-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathutil.py
More file actions
1528 lines (1283 loc) · 52.8 KB
/
Copy pathutil.py
File metadata and controls
1528 lines (1283 loc) · 52.8 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
from abc import ABC, ABCMeta
import os.path
import time
import sys
import platform
import queue
import os
import webbrowser
import ctypes
from functools import partial, lru_cache
from typing import (NamedTuple, Callable, Optional, TYPE_CHECKING, List, Any, Sequence, Tuple, Union)
from PyQt6 import QtCore
from PyQt6.QtGui import (QFont, QColor, QCursor, QPixmap, QImage,
QPalette, QIcon, QFontMetrics, QPainter, QContextMenuEvent, QMovie)
from PyQt6.QtCore import (Qt, pyqtSignal, QCoreApplication, QSize, QRect, QPoint, QObject)
from PyQt6.QtWidgets import (QPushButton, QLabel, QMessageBox, QHBoxLayout, QVBoxLayout, QLineEdit,
QStyle, QDialog, QGroupBox, QButtonGroup, QRadioButton,
QFileDialog, QWidget, QToolButton, QPlainTextEdit, QApplication, QToolTip,
QGraphicsEffect, QGraphicsScene, QGraphicsPixmapItem, QLayoutItem, QLayout, QMenu,
QFrame, QAbstractButton)
from electrum.i18n import _
from electrum.util import (FileImportFailed, FileExportFailed, resource_path, EventListener,
get_logger, UserCancelled, UserFacingException, ChoiceItem)
from electrum.invoices import (PR_UNPAID, PR_PAID, PR_EXPIRED, PR_INFLIGHT, PR_UNKNOWN, PR_FAILED, PR_ROUTING,
PR_UNCONFIRMED, PR_BROADCASTING, PR_BROADCAST)
from electrum.qrreader import MissingQrDetectionLib, QrCodeResult
from electrum.submarine_swaps import pubkey_to_rgb_color
from electrum.gui.common_qt.util import TaskThread
if TYPE_CHECKING:
from .main_window import ElectrumWindow
from .paytoedit import PayToEdit
from electrum.simple_config import SimpleConfig
from electrum.simple_config import ConfigVarWithConfig
if platform.system() == 'Windows':
MONOSPACE_FONT = 'Lucida Console'
elif platform.system() == 'Darwin':
MONOSPACE_FONT = 'Monaco'
else:
MONOSPACE_FONT = 'monospace'
_logger = get_logger(__name__)
dialogs = []
pr_icons = {
PR_UNKNOWN: "warning.png",
PR_UNPAID: "unpaid.png",
PR_PAID: "confirmed.png",
PR_EXPIRED: "expired.png",
PR_INFLIGHT: "unconfirmed.png",
PR_FAILED: "warning.png",
PR_ROUTING: "unconfirmed.png",
PR_UNCONFIRMED: "unconfirmed.png",
PR_BROADCASTING: "unconfirmed.png",
PR_BROADCAST: "unconfirmed.png",
}
# filter tx files in QFileDialog:
TRANSACTION_FILE_EXTENSION_FILTER_ANY = "Transaction (*.txn *.psbt);;All files (*)"
TRANSACTION_FILE_EXTENSION_FILTER_ONLY_PARTIAL_TX = "Partial Transaction (*.psbt)"
TRANSACTION_FILE_EXTENSION_FILTER_ONLY_COMPLETE_TX = "Complete Transaction (*.txn)"
TRANSACTION_FILE_EXTENSION_FILTER_SEPARATE = (f"{TRANSACTION_FILE_EXTENSION_FILTER_ONLY_PARTIAL_TX};;"
f"{TRANSACTION_FILE_EXTENSION_FILTER_ONLY_COMPLETE_TX};;"
f"All files (*)")
class EnterButton(QPushButton):
def __init__(self, text, func):
QPushButton.__init__(self, text)
self.func = func
self.clicked.connect(func)
self._orig_text = text
def keyPressEvent(self, e):
if e.key() in [Qt.Key.Key_Return, Qt.Key.Key_Enter]:
self.func()
def restore_original_text(self):
self.setText(self._orig_text)
class ThreadedButton(QPushButton):
def __init__(self, text, task, on_success=None, on_error=None):
QPushButton.__init__(self, text)
self.task = task
self.on_success = on_success
self.on_error = on_error
self.clicked.connect(self.run_task)
def run_task(self):
self.setEnabled(False)
self.thread = TaskThread(self)
self.thread.add(self.task, self.on_success, self.done, self.on_error)
def done(self):
self.setEnabled(True)
self.thread.stop()
class WWLabel(QLabel):
"""Word-wrapping label"""
def __init__(self, text="", parent=None):
QLabel.__init__(self, text, parent)
self.setWordWrap(True)
self.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
class RichLabel(WWLabel):
"""Word-wrapping label with link activation"""
def __init__(self, text='', parent=None):
WWLabel.__init__(self, text, parent)
self.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
self.setOpenExternalLinks(True)
class AmountLabel(QLabel):
def __init__(self, *args, **kwargs):
QLabel.__init__(self, *args, **kwargs)
self.setFont(QFont(MONOSPACE_FONT))
self.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
class Spinner(QLabel):
def __init__(self, *args, **kwargs):
QLabel.__init__(self, *args, **kwargs)
self.spinner = QMovie(icon_path('spinner.gif'))
self.spinner.setScaledSize(QSize(20, 20))
self.spinner.frameChanged.connect(lambda: self.setPixmap(self.spinner.currentPixmap()))
self.setVisible(False)
def setVisible(self, visible):
if visible:
self.spinner.start()
else:
self.spinner.stop()
super().setVisible(visible)
class HelpMixin:
def __init__(self, help_text: str, *, help_title: str | None = None):
assert isinstance(self, QWidget), "HelpMixin must be a QWidget instance!"
self.help_text = help_text
self._help_title = help_title or _('Help')
if isinstance(self, QLabel):
self.setTextInteractionFlags(
(self.textInteractionFlags() | Qt.TextInteractionFlag.TextSelectableByMouse)
& ~Qt.TextInteractionFlag.TextSelectableByKeyboard)
def show_help(self):
custom_message_box(
icon=QMessageBox.Icon.Information,
parent=self,
title=self._help_title,
text=self.help_text,
rich_text=True,
)
class HelpLabel(HelpMixin, QLabel):
def __init__(self, text: str, help_text: str):
QLabel.__init__(self, text)
HelpMixin.__init__(self, help_text)
self.app = QCoreApplication.instance()
self.font = self.font()
@classmethod
def from_configvar(cls, cv: 'ConfigVarWithConfig') -> 'HelpLabel':
return HelpLabel(cv.get_short_desc() + ':', cv.get_long_desc())
def mouseReleaseEvent(self, x):
self.show_help()
def enterEvent(self, event):
self.font.setUnderline(True)
self.setFont(self.font)
self.app.setOverrideCursor(QCursor(Qt.CursorShape.PointingHandCursor))
return QLabel.enterEvent(self, event)
def leaveEvent(self, event):
self.font.setUnderline(False)
self.setFont(self.font)
self.app.setOverrideCursor(QCursor(Qt.CursorShape.ArrowCursor))
return QLabel.leaveEvent(self, event)
class HelpButton(HelpMixin, QToolButton):
def __init__(self, text: str):
QToolButton.__init__(self)
HelpMixin.__init__(self, text)
self.setText('?')
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.setFixedWidth(round(2.2 * char_width_in_lineedit()))
self.clicked.connect(self.show_help)
class InfoButton(HelpMixin, QPushButton):
def __init__(self, text: str):
QPushButton.__init__(self, _('Info'))
HelpMixin.__init__(self, text, help_title=_('Info'))
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.setFixedWidth(6 * char_width_in_lineedit())
self.clicked.connect(self.show_help)
class Buttons(QHBoxLayout):
def __init__(self, *buttons):
QHBoxLayout.__init__(self)
self.addStretch(1)
for b in buttons:
if b is None:
continue
self.addWidget(b)
class CloseButton(QPushButton):
def __init__(self, dialog):
QPushButton.__init__(self, _("Close"))
self.clicked.connect(dialog.close)
self.setDefault(True)
class CopyButton(QPushButton):
def __init__(self, text_getter, app):
QPushButton.__init__(self, _("Copy"))
self.clicked.connect(lambda: app.clipboard().setText(text_getter()))
class CopyCloseButton(QPushButton):
def __init__(self, text_getter, app, dialog):
QPushButton.__init__(self, _("Copy and Close"))
self.clicked.connect(lambda: app.clipboard().setText(text_getter()))
self.clicked.connect(dialog.close)
self.setDefault(True)
class OkButton(QPushButton):
def __init__(self, dialog, label=None):
QPushButton.__init__(self, label or _("OK"))
self.clicked.connect(dialog.accept)
self.setDefault(True)
class CancelButton(QPushButton):
def __init__(self, dialog, label=None):
QPushButton.__init__(self, label or _("Cancel"))
self.clicked.connect(dialog.reject)
class MessageBoxMixin(object):
def top_level_window_recurse(self, window=None, test_func=None):
window = window or self
classes = (WindowModalDialog, QMessageBox)
if test_func is None:
test_func = lambda x: True
for n, child in enumerate(window.children()):
# Test for visibility as old closed dialogs may not be GC-ed.
# Only accept children that confirm to test_func.
if isinstance(child, classes) and child.isVisible() \
and test_func(child):
return self.top_level_window_recurse(child, test_func=test_func)
return window
def top_level_window(self, test_func=None):
return self.top_level_window_recurse(test_func)
def question(self, msg, parent=None, title=None, icon=None, **kwargs) -> bool:
yes, no = QMessageBox.StandardButton.Yes, QMessageBox.StandardButton.No
return yes == self.msg_box(icon=icon or QMessageBox.Icon.Question,
parent=parent,
title=title or '',
text=msg,
buttons=yes | no,
defaultButton=no,
**kwargs)
def show_warning(self, msg, parent=None, title=None, **kwargs):
return self.msg_box(QMessageBox.Icon.Warning, parent,
title or _('Warning'), msg, **kwargs)
def show_error(self, msg, parent=None, **kwargs):
return self.msg_box(QMessageBox.Icon.Warning, parent,
_('Error'), msg, **kwargs)
def show_critical(self, msg, parent=None, title=None, **kwargs):
return self.msg_box(QMessageBox.Icon.Critical, parent,
title or _('Critical Error'), msg, **kwargs)
def show_message(self, msg, parent=None, title=None, icon=QMessageBox.Icon.Information, **kwargs):
return self.msg_box(icon, parent, title or _('Information'), msg, **kwargs)
def msg_box(
self,
icon: Union[QMessageBox.Icon, QPixmap],
parent: QWidget,
title: str,
text: str,
*,
buttons: Union[QMessageBox.StandardButton,
List[Union[QMessageBox.StandardButton, Tuple[QAbstractButton, QMessageBox.ButtonRole, int]]]] = QMessageBox.StandardButton.Ok,
defaultButton: QMessageBox.StandardButton = QMessageBox.StandardButton.NoButton,
rich_text: bool = False,
checkbox: Optional[bool] = None
):
parent = parent or self.top_level_window()
return custom_message_box(
icon=icon, parent=parent, title=title, text=text, buttons=buttons, defaultButton=defaultButton,
rich_text=rich_text, checkbox=checkbox
)
def query_choice(
self,
msg: Optional[str],
choices: Sequence['ChoiceItem'],
*,
title: Optional[str] = None,
default_key: Optional[Any] = None,
) -> Optional[Any]:
"""Returns ChoiceItem.key (for selected item), or None if the user cancels the dialog.
Needed by QtHandler for hardware wallets.
"""
if title is None:
title = _('Question')
dialog = WindowModalDialog(self.top_level_window(), title=title)
dialog.setMinimumWidth(400)
choice_widget = ChoiceWidget(message=msg, choices=choices, default_key=default_key)
vbox = QVBoxLayout(dialog)
vbox.addWidget(choice_widget)
cancel_button = CancelButton(dialog)
vbox.addLayout(Buttons(cancel_button, OkButton(dialog)))
cancel_button.setFocus()
if not dialog.exec():
return None
return choice_widget.selected_key
def password_dialog(self, msg=None, parent=None):
from .password_dialog import PasswordDialog
parent = parent or self
d = PasswordDialog(parent, msg)
return d.run()
def custom_message_box(
*,
icon: Union[QMessageBox.Icon, QPixmap],
parent: QWidget,
title: str,
text: str,
buttons: Union[QMessageBox.StandardButton,
List[Union[QMessageBox.StandardButton, Tuple[QAbstractButton, QMessageBox.ButtonRole, int]]]] = QMessageBox.StandardButton.Ok,
defaultButton: QMessageBox.StandardButton = QMessageBox.StandardButton.NoButton,
rich_text: bool = False,
checkbox: Optional[bool] = None
) -> int:
custom_buttons = []
standard_buttons = QMessageBox.StandardButton.NoButton
if buttons:
if not isinstance(buttons, list):
buttons = [buttons]
for button in buttons:
if isinstance(button, QMessageBox.StandardButton):
standard_buttons |= button
else:
custom_buttons.append(button)
if type(icon) is QPixmap:
d = QMessageBox(QMessageBox.Icon.Information, title, str(text), standard_buttons, parent)
d.setIconPixmap(icon)
else:
d = QMessageBox(icon, title, str(text), standard_buttons, parent)
for button, role, _ in custom_buttons:
d.addButton(button, role)
d.setWindowModality(Qt.WindowModality.WindowModal)
d.setDefaultButton(defaultButton)
if rich_text:
d.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse | Qt.TextInteractionFlag.LinksAccessibleByMouse)
# set AutoText instead of RichText
# AutoText lets Qt figure out whether to render as rich text.
# e.g. if text is actually plain text and uses "\n" newlines;
# and we set RichText here, newlines would be swallowed
d.setTextFormat(Qt.TextFormat.AutoText)
else:
d.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
d.setTextFormat(Qt.TextFormat.PlainText)
if checkbox is not None:
d.setCheckBox(checkbox)
result = d.exec()
for button, _, value in custom_buttons:
if button == d.clickedButton():
return value
return result
class WindowModalDialog(QDialog, MessageBoxMixin):
'''Handy wrapper; window modal dialogs are better for our multi-window
daemon model as other wallet windows can still be accessed.'''
def __init__(self, parent, title=None):
QDialog.__init__(self, parent)
self.setWindowModality(Qt.WindowModality.WindowModal)
if title:
self.setWindowTitle(title)
class WaitingDialog(WindowModalDialog):
'''Shows a please wait dialog whilst running a task. It is not
necessary to maintain a reference to this dialog.'''
def __init__(self, parent: QWidget, message: str, task, on_success=None, on_error=None, on_cancel=None):
assert parent
if isinstance(parent, MessageBoxMixin):
parent = parent.top_level_window()
WindowModalDialog.__init__(self, parent, _("Please wait"))
self.message_label = QLabel(message)
vbox = QVBoxLayout(self)
vbox.addWidget(self.message_label)
if on_cancel:
self.cancel_button = CancelButton(self)
self.cancel_button.clicked.connect(on_cancel)
vbox.addLayout(Buttons(self.cancel_button))
self.accepted.connect(self.on_accepted)
self.show()
self.thread = TaskThread(self)
self.thread.finished.connect(self.deleteLater) # see #3956
self.thread.add(task, on_success, self.accept, on_error)
def wait(self):
self.thread.wait()
def on_accepted(self):
self.thread.stop()
def update(self, msg):
print(msg)
self.message_label.setText(msg)
class RunCoroutineDialog(WaitingDialog):
def __init__(self, parent: QWidget, message: str, coroutine):
from electrum import util
import asyncio
import concurrent.futures
loop = util.get_asyncio_loop()
assert util.get_running_loop() != loop, 'must not be called from asyncio thread'
self._exception = None
self._result = None
self._future = asyncio.run_coroutine_threadsafe(coroutine, loop)
def task():
try:
self._result = self._future.result()
except concurrent.futures.CancelledError:
self._exception = UserCancelled
except Exception as e:
self._exception = e
WaitingDialog.__init__(self, parent, message, task, on_cancel=self._future.cancel)
def run(self):
self.exec()
if self._exception:
raise self._exception
else:
return self._result
def line_dialog(parent, title, label, ok_label, default=None):
dialog = WindowModalDialog(parent, title)
dialog.setMinimumWidth(500)
l = QVBoxLayout()
dialog.setLayout(l)
l.addWidget(QLabel(label))
txt = QLineEdit()
if default:
txt.setText(default)
l.addWidget(txt)
l.addLayout(Buttons(CancelButton(dialog), OkButton(dialog, ok_label)))
if dialog.exec():
return txt.text()
def text_dialog(
*,
parent,
title,
header_layout,
ok_label,
default=None,
allow_multi=False,
config: 'SimpleConfig',
):
from .qrtextedit import ScanQRTextEdit
dialog = WindowModalDialog(parent, title)
dialog.setMinimumWidth(600)
l = QVBoxLayout()
dialog.setLayout(l)
if isinstance(header_layout, str):
l.addWidget(QLabel(header_layout))
else:
l.addLayout(header_layout)
txt = ScanQRTextEdit(allow_multi=allow_multi, config=config)
if default:
txt.setText(default)
l.addWidget(txt)
l.addLayout(Buttons(CancelButton(dialog), OkButton(dialog, ok_label)))
if dialog.exec():
return txt.toPlainText()
class ChoiceWidget(QWidget):
"""Renders a list of ChoiceItems as a radiobuttons group.
Callers can pre-select an item by key, through the 'default_key' parameter.
The selected item is made available by index (selected_index),
by key (selected_key) and by Choice (selected_item).
"""
itemSelected = pyqtSignal([int], arguments=['index'])
def __init__(
self,
*,
message: Optional[str] = None,
choices: Sequence[ChoiceItem] = None,
default_key: Optional[Any] = None,
):
QWidget.__init__(self)
vbox = QVBoxLayout()
self.setLayout(vbox)
if choices is None:
choices = []
self.selected_index = -1 # type: int
self.selected_item = None # type: Optional[ChoiceItem]
self.selected_key = None # type: Optional[Any]
self.choices = choices # type: Sequence[ChoiceItem]
if message and len(message) > 50:
vbox.addWidget(WWLabel(message))
message = ""
gb2 = QGroupBox(message)
vbox.addWidget(gb2)
vbox2 = QVBoxLayout()
gb2.setLayout(vbox2)
self.group = group = QButtonGroup()
assert isinstance(choices, list)
for i, c in enumerate(choices):
assert isinstance(c, ChoiceItem), f"{c=!r}"
button = QRadioButton(gb2)
button.setText(c.label)
vbox2.addWidget(button)
group.addButton(button)
group.setId(button, i)
if (i == 0 and default_key is None) or c.key == default_key:
self.selected_index = i
self.selected_item = c
self.selected_key = c.key
button.setChecked(True)
group.buttonClicked.connect(self.on_selected)
def on_selected(self, button):
self.selected_index = self.group.id(button)
self.selected_item = self.choices[self.selected_index]
self.selected_key = self.choices[self.selected_index].key
self.itemSelected.emit(self.selected_index)
def select(self, key):
for i, c in enumerate(self.choices):
if key == c.key:
self.group.button(i).click()
class ResizableStackedWidget(QWidget):
"""Simple alternative to QStackedWidget, as QStackedWidget always resizes to the largest
widget in the stack, leaving ugly scrollbars where they're not needed."""
def __init__(self, parent):
super().__init__(parent)
self.setLayout(QVBoxLayout())
self.widgets = []
self.current_index = -1
def sizeHint(self) -> QSize:
if not self.count() or not self.currentWidget():
return super().sizeHint()
return self.currentWidget().sizeHint()
def addWidget(self, widget: QWidget) -> int:
self.widgets.append(widget)
self.layout().addWidget(widget)
if len(self.widgets) == 1: # first widget?
self.current_index = 0
self.showCurrentWidget()
return len(self.widgets) - 1
def removeWidget(self, widget: QWidget):
i = self.widgets.index(widget)
self.widgets.remove(widget)
self.layout().removeWidget(widget)
if self.current_index >= i:
self.current_index -= 1
if self.current_index == self.count() - 1:
self.showCurrentWidget()
def setCurrentIndex(self, index: int):
assert isinstance(index, int)
assert 0 <= index < len(self.widgets), f'invalid widget index {index}'
self.current_index = index
self.showCurrentWidget()
def currentWidget(self) -> Optional[QWidget]:
if self.current_index < 0:
return None
return self.widgets[self.current_index]
def showCurrentWidget(self):
if not self.widgets:
return
for i, k in enumerate(self.widgets):
if i == self.current_index:
k.show()
else:
k.hide()
def count(self) -> int:
return len(self.widgets)
class VLine(QFrame):
"""Vertical line separator"""
def __init__(self):
super(VLine, self).__init__()
self.setFrameShape(QFrame.Shape.VLine)
self.setFrameShadow(QFrame.Shadow.Sunken)
self.setLineWidth(1)
def address_field(addresses, *, btn_text: str | None = None):
if btn_text is None:
btn_text = _('Get wallet address')
hbox = QHBoxLayout()
address_e = QLineEdit()
if addresses and len(addresses) > 0:
address_e.setText(addresses[0])
else:
addresses = []
def func():
try:
i = addresses.index(str(address_e.text())) + 1
i = i % len(addresses)
address_e.setText(addresses[i])
except ValueError:
# the user might have changed address_e to an
# address not in the wallet (or to something that isn't an address)
if addresses and len(addresses) > 0:
address_e.setText(addresses[0])
button = QPushButton(btn_text)
button.clicked.connect(func)
hbox.addWidget(button)
hbox.addWidget(address_e)
return hbox, address_e
def filename_field(parent, config, defaultname, select_msg):
vbox = QVBoxLayout()
vbox.addWidget(QLabel(_("Format")))
gb = QGroupBox("format", parent)
b1 = QRadioButton(gb)
b1.setText(_("CSV"))
b1.setChecked(True)
b2 = QRadioButton(gb)
b2.setText(_("json"))
vbox.addWidget(b1)
vbox.addWidget(b2)
hbox = QHBoxLayout()
directory = config.IO_DIRECTORY
path = os.path.join(directory, defaultname)
filename_e = QLineEdit()
filename_e.setText(path)
def func():
text = filename_e.text()
_filter = "*.csv" if defaultname.endswith(".csv") else "*.json" if defaultname.endswith(".json") else None
p = getSaveFileName(
parent=None,
title=select_msg,
filename=text,
filter=_filter,
config=config,
)
if p:
filename_e.setText(p)
button = QPushButton(_('File'))
button.clicked.connect(func)
hbox.addWidget(button)
hbox.addWidget(filename_e)
vbox.addLayout(hbox)
def set_csv(v):
text = filename_e.text()
text = text.replace(".json",".csv") if v else text.replace(".csv",".json")
filename_e.setText(text)
b1.clicked.connect(lambda: set_csv(True))
b2.clicked.connect(lambda: set_csv(False))
return vbox, filename_e, b1
def get_icon_qrcode() -> QIcon:
name = "qrcode_white.png" if ColorScheme.dark_scheme else "qrcode.png"
return read_QIcon(name)
def get_icon_camera() -> QIcon:
name = "camera_white.png" if ColorScheme.dark_scheme else "camera_dark.png"
return read_QIcon(name)
def pubkey_to_q_icon(server_pubkey: str) -> QIcon:
color = QColor(*pubkey_to_rgb_color(server_pubkey))
color_pixmap = QPixmap(100, 100)
color_pixmap.fill(color)
return QIcon(color_pixmap)
def add_input_actions_to_context_menu(gih: 'GenericInputHandler', m: QMenu) -> None:
if gih.on_qr_from_camera_input_btn:
m.addAction(get_icon_camera(), _("Read QR code with camera"), gih.on_qr_from_camera_input_btn)
if gih.on_qr_from_screenshot_input_btn:
m.addAction(read_QIcon("picture_in_picture.png"), _("Read QR code from screen"), gih.on_qr_from_screenshot_input_btn)
if gih.on_qr_from_file_input_btn:
m.addAction(read_QIcon("qr_file.png"), _("Read QR code from file"), gih.on_qr_from_file_input_btn)
if gih.on_input_file:
m.addAction(read_QIcon("file.png"), _("Read text from file"), gih.on_input_file)
def scan_qr_from_screenshot() -> QrCodeResult:
from .qrreader import scan_qr_from_image
screenshots = [screen.grabWindow(0).toImage()
for screen in QApplication.instance().screens()]
if all(screen.allGray() for screen in screenshots):
raise UserFacingException(_("Failed to take screenshot."))
scanned_qr = None
for screenshot in screenshots:
try:
scan_result = scan_qr_from_image(screenshot)
except MissingQrDetectionLib as e:
raise UserFacingException(_("Unable to scan image.") + "\n" + repr(e))
if len(scan_result) > 0:
if (scanned_qr is not None) or len(scan_result) > 1:
raise UserFacingException(_("More than one QR code was found on the screen."))
scanned_qr = scan_result
if scanned_qr is None:
raise UserFacingException(_("No QR code was found on the screen."))
assert len(scanned_qr) == 1, f"{len(scanned_qr)=}, expected 1"
return scanned_qr[0]
class GenericInputHandler:
on_qr_from_camera_input_btn: Callable[[], None] = None
on_qr_from_screenshot_input_btn: Callable[[], None] = None
on_qr_from_file_input_btn: Callable[[], None] = None
on_input_file: Callable[[], None] = None
def input_qr_from_camera(
self,
*,
config: 'SimpleConfig',
allow_multi: bool = False,
show_error: Callable[[str], None],
setText: Callable[[str], None] = None,
parent: QWidget = None,
) -> None:
if setText is None:
setText = self.setText
def cb(success: bool, error: str, data: Optional[str]):
if not success:
if error:
show_error(error)
return
if not data:
data = ''
try:
if allow_multi:
text = self.text()
if data in text:
return
if text and not text.endswith('\n'):
text += '\n'
text += data
text += '\n'
setText(text)
else:
new_text = data
setText(new_text)
except Exception as e:
show_error(_('Invalid payment identifier in QR') + ':\n' + repr(e))
from .qrreader import scan_qrcode_from_camera
if parent is None:
parent = self if isinstance(self, QWidget) else None
scan_qrcode_from_camera(parent=parent, config=config, callback=cb)
def input_qr_from_screenshot(
self,
*,
allow_multi: bool = False,
show_error: Callable[[str], None],
setText: Callable[[str], None] = None,
) -> None:
if setText is None:
setText = self.setText
try:
scanned_qr = scan_qr_from_screenshot()
except UserFacingException as e:
show_error(str(e))
return
data = scanned_qr.data
try:
if allow_multi:
text = self.text()
if data in text:
return
if text and not text.endswith('\n'):
text += '\n'
text += data
text += '\n'
setText(text)
else:
new_text = data
setText(new_text)
except Exception as e:
show_error(_('Invalid payment identifier in QR') + ':\n' + repr(e))
def input_file(
self,
*,
config: 'SimpleConfig',
show_error: Callable[[str], None],
setText: Callable[[str], None] = None,
) -> None:
if setText is None:
setText = self.setText
fileName = getOpenFileName(
parent=None,
title='select file',
# trying to open non-text things like pdfs makes electrum freeze
filter="Text files (*.txt *.csv);;All files (*)",
config=config,
)
if not fileName:
return
try:
try:
with open(fileName, "r") as f:
data = f.read()
except UnicodeError as e:
with open(fileName, "rb") as f:
data = f.read()
data = data.hex()
except BaseException as e:
show_error(_('Error opening file') + ':\n' + repr(e))
else:
try:
setText(data)
except Exception as e:
show_error(_('Invalid payment identifier in file') + ':\n' + repr(e))
def input_qr_from_file(
self,
*,
allow_multi: bool = False,
config: 'SimpleConfig',
show_error: Callable[[str], None],
setText: Callable[[str], None] = None,
):
from .qrreader import scan_qr_from_image
if setText is None:
setText = self.setText
file_name = getOpenFileName(
parent=None,
title=_("Select image file"),
config=config,
filter="Image files (*.png *.jpg *.jpeg *.bmp);;",
)
if not file_name:
return
image = QImage(file_name)
if image.isNull():
show_error(_("Failed to open image file."))
return
try:
scan_result: Sequence[QrCodeResult] = scan_qr_from_image(image)
except MissingQrDetectionLib as e:
show_error(_("Unable to scan image.") + "\n" + repr(e))
return
if len(scan_result) < 1:
show_error(_("No QR code was found in the image."))
return
if len(scan_result) > 1 and not allow_multi:
show_error(_("More than one QR code was found in the image."))
return
if len(scan_result) > 1:
result_text = "\n".join([r.data for r in scan_result])
else:
result_text = scan_result[0].data
try:
setText(result_text)
except Exception as e:
show_error(_("Couldn't set result") + ':\n' + repr(e))
def input_paste_from_clipboard(
self,
*,
setText: Callable[[str], None] = None,
) -> None:
if setText is None:
setText = self.setText
app = QApplication.instance()
setText(app.clipboard().text())
class OverlayControlMixin(GenericInputHandler):
STYLE_SHEET_COMMON = '''
QPushButton { border-width: 1px; padding: 0px; margin: 0px; }
'''
STYLE_SHEET_LIGHT = '''
QPushButton { border: 1px solid transparent; }
QPushButton:hover { border: 1px solid #3daee9; }
'''
def __init__(self, middle: bool = False):
GenericInputHandler.__init__(self)
assert isinstance(self, QWidget)
assert isinstance(self, OverlayControlMixin) # only here for type-hints in IDE
self.middle = middle
self.overlay_widget = QWidget(self)
style_sheet = self.STYLE_SHEET_COMMON
if not ColorScheme.dark_scheme:
style_sheet = style_sheet + self.STYLE_SHEET_LIGHT
self.overlay_widget.setStyleSheet(style_sheet)
self.overlay_layout = QHBoxLayout(self.overlay_widget)
self.overlay_layout.setContentsMargins(0, 0, 0, 0)
self.overlay_layout.setSpacing(1)
self._updateOverlayPos()
def resizeEvent(self, e):
super().resizeEvent(e)
self._updateOverlayPos()
def _updateOverlayPos(self):
frame_width = self.style().pixelMetric(QStyle.PixelMetric.PM_DefaultFrameWidth)
overlay_size = self.overlay_widget.sizeHint()
x = self.rect().right() - frame_width - overlay_size.width()
y = self.rect().bottom() - overlay_size.height()
middle = self.middle
if hasattr(self, 'document'):
# Keep the buttons centered if we have less than 2 lines in the editor
line_spacing = QFontMetrics(self.document().defaultFont()).lineSpacing()
if self.rect().height() < (line_spacing * 2):
middle = True
y = (y / 2) + frame_width if middle else y - frame_width
if hasattr(self, 'verticalScrollBar') and self.verticalScrollBar().isVisible():
scrollbar_width = self.style().pixelMetric(QStyle.PixelMetric.PM_ScrollBarExtent)
x -= scrollbar_width
self.overlay_widget.move(int(x), int(y))
def addWidget(self, widget: QWidget):
# The old code positioned the items the other way around, so we just insert at position 0 instead
self.overlay_layout.insertWidget(0, widget)
def addButton(self, icon: QIcon, on_click, tooltip: str) -> QPushButton:
button = QPushButton(self.overlay_widget)
button.setToolTip(tooltip)
button.setIcon(icon)
button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
button.clicked.connect(on_click)
self.addWidget(button)
return button
def addCopyButton(self):
def on_copy():
app = QApplication.instance()
app.clipboard().setText(self.text())
QToolTip.showText(QCursor.pos(), _("Text copied to clipboard"), self)