forked from etotheipi/BitcoinArmory
-
Notifications
You must be signed in to change notification settings - Fork 1
/
qtdefines.py
955 lines (739 loc) · 29.9 KB
/
qtdefines.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
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
################################################################################
# #
# Copyright (C) 2011-2013, Armory Technologies, Inc. #
# Distributed under the GNU Affero General Public License (AGPL v3) #
# See LICENSE or http://www.gnu.org/licenses/agpl.html #
# #
################################################################################
from armoryengine import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from armorycolors import Colors, htmlColor
from tempfile import mkstemp
SETTINGS_PATH = os.path.join(ARMORY_HOME_DIR, 'ArmorySettings.txt')
USERMODE = enum('Standard', 'Advanced', 'Expert')
SATOSHIMODE = enum('Auto', 'User')
NETWORKMODE = enum('Offline', 'Full', 'Disconnected')
WLTTYPES = enum('Plain', 'Crypt', 'WatchOnly', 'Offline')
WLTFIELDS = enum('Name', 'Descr', 'WltID', 'NumAddr', 'Secure', \
'BelongsTo', 'Crypto', 'Time', 'Mem', 'Version')
MSGBOX = enum('Good','Info', 'Question', 'Warning', 'Critical', 'Error')
MSGBOX = enum('Good','Info', 'Question', 'Warning', 'Critical', 'Error')
DASHBTNS = enum('Close', 'Browse', 'Install', 'Instruct', 'Settings')
STYLE_SUNKEN = QFrame.Box | QFrame.Sunken
STYLE_RAISED = QFrame.Box | QFrame.Raised
STYLE_PLAIN = QFrame.Box | QFrame.Plain
STYLE_STYLED = QFrame.StyledPanel | QFrame.Raised
STYLE_NONE = QFrame.NoFrame
CHANGE_ADDR_DESCR_STRING = '[[ Change received ]]'
HTTP_VERSION_FILE = 'http://bitcoinarmory.com/versions.txt'
################################################################################
def tr(txt):
"""
This is a common convention for implementing translations, where all
translatable strings are put int the _(...) function, and that method
does some fancy stuff to present the translation if needed.
This is being implemented here, to not only do translations in the
future, but also to clean up the typical text fields I use. I've
ended up with a program full of stuff like this:
myLabel = QRichLabel( \
'This text is split across mulitple lines '
'with a space after each one, and single '
'quotes on either side.')
Instead it should really look like:
myLabel = QRichLabel( _('''
This text is split across mulitple lines
and it will acquire a space after each line
as well as include newlines because it's HTML
and uses <br>. ''' ))
"""
txt = toUnicode(txt)
lines = [l.strip() for l in txt.split('\n')]
outText = (' '.join(lines)).strip()
# Eventually we do something cool with this transalate function.
TRANSLATE = lambda x: x
return TRANSLATE(outText)
################################################################################
def HLINE(style=QFrame.Plain):
qf = QFrame()
qf.setFrameStyle(QFrame.HLine | style)
return qf
def VLINE(style=QFrame.Plain):
qf = QFrame()
qf.setFrameStyle(QFrame.VLine | style)
return qf
# Setup fixed-width and var-width fonts
def GETFONT(ftype, sz=10, bold=False, italic=False):
fnt = None
if ftype.lower().startswith('fix'):
if OS_WINDOWS:
fnt = QFont("Courier", sz)
else:
fnt = QFont("DejaVu Sans Mono", sz)
elif ftype.lower().startswith('var'):
fnt = QFont("Verdana", sz)
#if OS_WINDOWS:
#fnt = QFont("Tahoma", sz)
#else:
#fnt = QFont("Sans", sz)
elif ftype.lower().startswith('money'):
if OS_WINDOWS:
fnt = QFont("Courier", sz)
else:
fnt = QFont("DejaVu Sans Mono", sz)
else:
fnt = QFont(ftype, sz)
if bold:
fnt.setWeight(QFont.Bold)
if italic:
fnt.setItalic(True)
return fnt
def UnicodeErrorBox(parent):
QMessageBox.warning(parent, 'ASCII Error', \
toUnicode('Armory does not currently support non-ASCII characters in '
'most text fields (like \xc2\xa3\xc2\xa5\xc3\xa1\xc3\xb6\xc3\xa9). '
'Please use only letters found '
'on an English(US) keyboard. This will be fixed in an upcoming '
'release'), QMessageBox.Ok)
#######
def UserModeStr(mode):
if mode==USERMODE.Standard:
return 'Standard'
elif mode==USERMODE.Advanced:
return 'Advanced'
elif mode==USERMODE.Expert:
return 'Expert'
#######
def tightSizeNChar(obj, nChar):
"""
Approximates the size of a row text of mixed characters
This is only aproximate, since variable-width fonts will vary
depending on the specific text
"""
try:
fm = QFontMetricsF(QFont(obj.font()))
except AttributeError:
fm = QFontMetricsF(QFont(obj))
szWidth,szHeight = fm.boundingRect('abcfgijklm').width(), fm.height()
szWidth = int(szWidth * nChar/10.0 + 0.5)
return szWidth, szHeight
#######
def tightSizeStr(obj, theStr):
""" Measure a specific string """
try:
fm = QFontMetricsF(QFont(obj.font()))
except AttributeError:
fm = QFontMetricsF(QFont(obj))
szWidth,szHeight = fm.boundingRect(theStr).width(), fm.height()
return szWidth, szHeight
#######
def relaxedSizeStr(obj, theStr):
"""
Approximates the size of a row text, nchars long, adds some margin
"""
try:
fm = QFontMetricsF(QFont(obj.font()))
except AttributeError:
fm = QFontMetricsF(QFont(obj))
szWidth,szHeight = fm.boundingRect(theStr).width(), fm.height()
return (10 + szWidth*1.05), 1.5*szHeight
#######
def relaxedSizeNChar(obj, nChar):
"""
Approximates the size of a row text, nchars long, adds some margin
"""
try:
fm = QFontMetricsF(QFont(obj.font()))
except AttributeError:
fm = QFontMetricsF(QFont(obj))
szWidth,szHeight = fm.boundingRect('abcfg ijklm').width(), fm.height()
szWidth = int(szWidth * nChar/10.0 + 0.5)
return (10 + szWidth*1.05), 1.5*szHeight
#############################################################################
def determineWalletType(wlt, wndw):
if wlt.watchingOnly:
if wndw.getWltSetting(wlt.uniqueIDB58,'IsMine'):
return [WLTTYPES.Offline, 'Offline']
else:
return [WLTTYPES.WatchOnly, 'Watching-Only']
elif wlt.useEncryption:
return [WLTTYPES.Crypt, 'Encrypted']
else:
return [WLTTYPES.Plain, 'No Encryption']
#############################################################################
def initialColResize(tblViewObj, sizeList):
"""
We assume that all percentages are below 1, all fixed >1.
TODO: This seems to almost work. providing exactly 100% input will
actually result in somewhere between 75% and 125% (approx).
For now, I have to experiment with initial values a few times
before getting it to a satisfactory initial size.
"""
totalWidth = tblViewObj.width()
fixedCols, pctCols = [],[]
nCols = tblViewObj.model().columnCount()
for col,colVal in enumerate(sizeList):
if colVal > 1:
fixedCols.append( (col, colVal) )
else:
pctCols.append( (col, colVal) )
for c,sz in fixedCols:
tblViewObj.horizontalHeader().resizeSection(c, sz)
totalFixed = sum([sz[1] for sz in fixedCols])
szRemain = totalWidth-totalFixed
for c,pct in pctCols:
tblViewObj.horizontalHeader().resizeSection(c, pct*szRemain)
tblViewObj.horizontalHeader().setStretchLastSection(True)
class QRichLabel(QLabel):
def __init__(self, txt, doWrap=True, \
hAlign=Qt.AlignLeft, \
vAlign=Qt.AlignVCenter, \
**kwargs):
super(QRichLabel, self).__init__(txt)
self.setTextFormat(Qt.RichText)
self.setWordWrap(doWrap)
self.setAlignment(hAlign | vAlign)
self.setText(txt, **kwargs)
def setText(self, text, color=None, size=None, bold=None, italic=None):
text = unicode(text)
if color:
text = '<font color="%s">%s</font>' % (htmlColor(color), text)
if size:
if isinstance(size, int):
text = '<font size=%d>%s</font>' % (size, text)
else:
text = '<font size="%s">%s</font>' % (size, text)
if bold:
text = '<b>%s</b>' % text
if italic:
text = '<i>%s</i>' % text
super(QRichLabel, self).setText(text)
def setBold(self):
self.setText('<b>' + self.text() + '</b>')
def setItalic(self):
self.setText('<i>' + self.text() + '</i>')
class QMoneyLabel(QRichLabel):
def __init__(self, nSatoshi, ndec=8, maxZeros=2, wColor=True, wBold=False):
QLabel.__init__(self, coin2str(nSatoshi))
self.setValueText(nSatoshi, ndec, maxZeros, wColor, wBold)
def setValueText(self, nSatoshi, ndec=None, maxZeros=None, wColor=None, wBold=None):
"""
When we set the text of the QMoneyLabel, remember previous values unless
explicitly respecified
"""
if not ndec==None:
self.ndec = ndec
if not maxZeros==None:
self.max0 = maxZeros
if not wColor==None:
self.colr = wColor
if not wBold==None:
self.bold = wBold
theFont = GETFONT("Fixed", 10)
if self.bold:
theFont.setWeight(QFont.Bold)
self.setFont(theFont)
self.setWordWrap(False)
valStr = coin2str(nSatoshi, ndec=self.ndec, maxZeros=self.max0)
goodMoney = htmlColor('MoneyPos')
badMoney = htmlColor('MoneyNeg')
if nSatoshi < 0 and self.colr:
self.setText('<font color=%s>%s</font>' % (badMoney, valStr))
elif nSatoshi > 0 and self.colr:
self.setText('<font color=%s>%s</font>' % (goodMoney, valStr))
else:
self.setText('%s' % valStr)
self.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
def setLayoutStretchRows(layout, *args):
for i,st in enumerate(args):
layout.setRowStretch(i, st)
def setLayoutStretchCols(layout, *args):
for i,st in enumerate(args):
layout.setColumnStretch(i, st)
# Use this for QHBoxLayout and QVBoxLayout, where you don't specify dimension
def setLayoutStretch(layout, *args):
for i,st in enumerate(args):
layout.setStretch(i, st)
################################################################################
def QPixmapButton(img):
btn = QPushButton('')
px = QPixmap(img)
btn.setIcon( QIcon(px))
btn.setIconSize(px.rect().size())
return btn
################################################################################
def QAcceptButton():
return QPixmapButton('img/btnaccept.png')
def QCancelButton():
return QPixmapButton('img/btncancel.png')
def QBackButton():
return QPixmapButton('img/btnback.png')
def QOkButton():
return QPixmapButton('img/btnok.png')
def QDoneButton():
return QPixmapButton('img/btndone.png')
################################################################################
class QLabelButton(QLabel):
mousePressOn = set()
def __init__(self, txt):
colorStr = htmlColor('LBtnNormalFG')
QLabel.__init__(self, '<font color=%s>%s</u></font>' % (colorStr, txt))
self.plainText = txt
self.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
def sizeHint(self):
w,h = relaxedSizeStr(self, self.plainText)
return QSize(w,1.2*h)
def mousePressEvent(self, ev):
# Prevent click-bleed-through to dialogs being opened
txt = toBytes(unicode(self.text()))
self.mousePressOn.add(txt)
def mouseReleaseEvent(self, ev):
txt = toBytes(unicode(self.text()))
if txt in self.mousePressOn:
self.mousePressOn.remove(txt)
self.emit(SIGNAL('clicked()'))
def enterEvent(self, ev):
ssStr = "QLabel { background-color : %s }" % htmlColor('LBtnHoverBG')
self.setStyleSheet(ssStr)
def leaveEvent(self, ev):
ssStr = "QLabel { background-color : %s }" % htmlColor('LBtnNormalBG')
self.setStyleSheet(ssStr)
################################################################################
def createToolTipObject(tiptext, iconSz=2):
"""
The <u></u> is to signal to Qt that it should be interpretted as HTML/Rich
text even if no HTML tags are used. This appears to be necessary for Qt
to wrap the tooltip text
"""
fgColor = htmlColor('ToolTipQ')
lbl = QLabel('<font size=%d color=%s>(?)</font>' % (iconSz, fgColor))
lbl.setToolTip('<u></u>' + tiptext)
lbl.setMaximumWidth(relaxedSizeStr(lbl, '(?)')[0])
lbl.connect(lbl, SIGNAL('clicked()'), lambda: printlbl)
return lbl
################################################################################
def MsgBoxCustom(wtype, title, msg, wCancel=False, yesStr=None, noStr=None):
"""
Creates a message box with custom button text and icon
"""
class dlgWarn(QDialog):
def __init__(self, dtype, dtitle, wmsg, withCancel=False, yesStr=None, noStr=None):
super(dlgWarn, self).__init__(None)
msgIcon = QLabel()
fpix = ''
if dtype==MSGBOX.Good:
fpix = ':/MsgBox_good48.png'
if dtype==MSGBOX.Info:
fpix = ':/MsgBox_info48.png'
if dtype==MSGBOX.Question:
fpix = ':/MsgBox_question64.png'
if dtype==MSGBOX.Warning:
fpix = ':/MsgBox_warning48.png'
if dtype==MSGBOX.Critical:
fpix = ':/MsgBox_critical64.png'
if dtype==MSGBOX.Error:
fpix = ':/MsgBox_error64.png'
if len(fpix)>0:
msgIcon.setPixmap(QPixmap(fpix))
msgIcon.setAlignment(Qt.AlignHCenter | Qt.AlignTop)
lblMsg = QLabel(msg)
lblMsg.setTextFormat(Qt.RichText)
lblMsg.setWordWrap(True)
lblMsg.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
w,h = tightSizeNChar(lblMsg, 70)
lblMsg.setMinimumSize( w, 3.2*h )
buttonbox = QDialogButtonBox()
if dtype==MSGBOX.Question:
if not yesStr: yesStr = '&Yes'
if not noStr: noStr = '&No'
btnYes = QPushButton(yesStr)
btnNo = QPushButton(noStr)
self.connect(btnYes, SIGNAL('clicked()'), self.accept)
self.connect(btnNo, SIGNAL('clicked()'), self.reject)
buttonbox.addButton(btnYes,QDialogButtonBox.AcceptRole)
buttonbox.addButton(btnNo, QDialogButtonBox.RejectRole)
else:
if not yesStr: yesStr = '&OK'
if not noStr: noStr = '&Cancel'
btnOk = QPushButton(yesStr)
btnCancel = QPushButton(noStr)
self.connect(btnOk, SIGNAL('clicked()'), self.accept)
self.connect(btnCancel, SIGNAL('clicked()'), self.reject)
buttonbox.addButton(btnOk, QDialogButtonBox.AcceptRole)
if withCancel or noStr:
buttonbox.addButton(btnCancel, QDialogButtonBox.RejectRole)
spacer = QSpacerItem(20, 10, QSizePolicy.Fixed, QSizePolicy.Expanding)
layout = QGridLayout()
layout.addItem( spacer, 0,0, 1,2)
layout.addWidget(msgIcon, 1,0, 1,1)
layout.addWidget(lblMsg, 1,1, 1,1)
layout.addWidget(buttonbox, 3,0, 1,2)
layout.setSpacing(20)
self.setLayout(layout)
self.setWindowTitle(dtitle)
dlg = dlgWarn(wtype, title, msg, wCancel, yesStr, noStr)
result = dlg.exec_()
return result
################################################################################
def MsgBoxWithDNAA(wtype, title, msg, dnaaMsg, wCancel=False, \
yesStr='Yes', noStr='No', dnaaStartChk=False):
"""
Creates a warning/question/critical dialog, but with a "Do not ask again"
checkbox. Will return a pair (response, DNAA-is-checked)
"""
class dlgWarn(QDialog):
def __init__(self, dtype, dtitle, wmsg, dmsg=None, withCancel=False):
super(dlgWarn, self).__init__(None)
msgIcon = QLabel()
fpix = ''
if dtype==MSGBOX.Info:
fpix = ':/MsgBox_info48.png'
if not dmsg: dmsg = 'Do not show this message again'
if dtype==MSGBOX.Question:
fpix = ':/MsgBox_question64.png'
if not dmsg: dmsg = 'Do not ask again'
if dtype==MSGBOX.Warning:
fpix = ':/MsgBox_warning48.png'
if not dmsg: dmsg = 'Do not show this warning again'
if dtype==MSGBOX.Critical:
fpix = ':/MsgBox_critical64.png'
if not dmsg: dmsg = None # should always show crits
if dtype==MSGBOX.Error:
fpix = ':/MsgBox_error64.png'
if not dmsg: dmsg = None # should always show errors
if len(fpix)>0:
msgIcon.setPixmap(QPixmap(fpix))
msgIcon.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
self.chkDnaa = QCheckBox(dmsg)
self.chkDnaa.setChecked(dnaaStartChk)
lblMsg = QLabel(msg)
lblMsg.setTextFormat(Qt.RichText)
lblMsg.setWordWrap(True)
lblMsg.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
w,h = tightSizeNChar(lblMsg, 50)
lblMsg.setMinimumSize( w, 3.2*h )
lblMsg.setOpenExternalLinks(True)
buttonbox = QDialogButtonBox()
if dtype==MSGBOX.Question:
btnYes = QPushButton(yesStr)
btnNo = QPushButton(noStr)
self.connect(btnYes, SIGNAL('clicked()'), self.accept)
self.connect(btnNo, SIGNAL('clicked()'), self.reject)
buttonbox.addButton(btnYes,QDialogButtonBox.AcceptRole)
buttonbox.addButton(btnNo, QDialogButtonBox.RejectRole)
else:
btnOk = QPushButton('Ok')
self.connect(btnOk, SIGNAL('clicked()'), self.accept)
buttonbox.addButton(btnOk, QDialogButtonBox.AcceptRole)
if withCancel:
btnOk = QPushButton('Cancel')
self.connect(btnOk, SIGNAL('clicked()'), self.reject)
buttonbox.addButton(btnOk, QDialogButtonBox.RejectRole)
spacer = QSpacerItem(20, 10, QSizePolicy.Fixed, QSizePolicy.Expanding)
layout = QGridLayout()
layout.addItem( spacer, 0,0, 1,2)
layout.addWidget(msgIcon, 1,0, 1,1)
layout.addWidget(lblMsg, 1,1, 1,1)
layout.addWidget(self.chkDnaa, 2,0, 1,2)
layout.addWidget(buttonbox, 3,0, 1,2)
layout.setSpacing(20)
self.setLayout(layout)
self.setWindowTitle(dtitle)
dlg = dlgWarn(wtype, title, msg, dnaaMsg, wCancel)
result = dlg.exec_()
return (result, dlg.chkDnaa.isChecked())
def makeLayoutFrame(dirStr, widgetList, style=QFrame.NoFrame):
frm = QFrame()
frm.setFrameStyle(style)
frmLayout = QHBoxLayout()
if dirStr.lower().startswith('vert'):
frmLayout = QVBoxLayout()
for w in widgetList:
if isinstance(w,str) and w.lower()=='stretch':
frmLayout.addStretch()
elif isinstance(w,str) and w.lower().startswith('space'):
# expect "spacer(30)"
first = w.index('(')+1
last = w.index(')')
wid,hgt = int(w[first:last]), 1
if dirStr.lower().startswith('vert'):
wid,hgt = hgt,wid
frmLayout.addItem( QSpacerItem(wid,hgt) )
elif isinstance(w,str) and w.lower().startswith('line'):
frmLine = QFrame()
if dirStr.lower().startswith('vert'):
frmLine.setFrameStyle(QFrame.HLine | QFrame.Plain)
else:
frmLine.setFrameStyle(QFrame.VLine | QFrame.Plain)
frmLayout.addWidget(frmLine)
elif isinstance(w,str) and w.lower().startswith('strut'):
first = w.index('(')+1
last = w.index(')')
strutSz = int(w[first:last])
frmLayout.addStrut(strutSz)
elif isinstance(w,QSpacerItem):
frmLayout.addItem(w)
else:
frmLayout.addWidget(w)
frmLayout.setContentsMargins(5,5,5,5)
frm.setLayout(frmLayout)
return frm
def addFrame(widget, style=STYLE_SUNKEN):
return makeLayoutFrame('Horiz', [widget], style)
def makeVertFrame(widgetList, style=QFrame.NoFrame):
return makeLayoutFrame('Vert', widgetList, style)
def makeHorizFrame(widgetList, style=QFrame.NoFrame):
return makeLayoutFrame('Horiz', widgetList, style)
def QImageLabel(imgfn, size=None, stretch='NoStretch'):
lbl = QLabel()
if size==None:
px = QPixmap(imgfn)
else:
px = QPixmap(imgfn).scaled(*size) # expect size=(W,H)
lbl.setPixmap(px)
return lbl
def restoreTableView(qtbl, hexBytes):
try:
binunpack = BinaryUnpacker(hex_to_binary(hexBytes))
hexByte = binunpack.get(UINT8)
binLen = binunpack.get(UINT8)
toRestore = []
for i in range(binLen):
sz = binunpack.get(UINT16)
if sz>0:
toRestore.append([i,sz])
for i,c in toRestore[:-1]:
qtbl.setColumnWidth(i, c)
except Exception, e:
print 'ERROR!'
pass
# Don't want to crash the program just because couldn't load tbl data
def saveTableView(qtbl):
nCol = qtbl.model().columnCount()
sz = [None]*nCol
for i in range(nCol):
sz[i] = qtbl.columnWidth(i)
# Use 'ff' as a kind of magic byte for this data. Most importantly
# we want to guarantee that the settings file will interpret this
# as hex data -- I once had an unlucky hex string written out with
# all digits and then intepretted as an integer on the next load :(
first = int_to_hex(nCol)
rest = [int_to_hex(s, widthBytes=2) for s in sz]
return 'ff' + first + ''.join(rest)
################################################################################
class ArmoryDialog(QDialog):
def __init__(self, parent=None, main=None):
super(ArmoryDialog, self).__init__(parent)
self.parent = parent
self.main = main
self.setFont(GETFONT('var'))
self.setWindowFlags(Qt.Window)
if USE_TESTNET:
self.setWindowTitle('Armory - Protoshares Wallet Management [TESTNET]')
self.setWindowIcon(QIcon(':/armory_icon_green_32x32.png'))
else:
self.setWindowTitle('Armory - Protoshares Wallet Management')
self.setWindowIcon(QIcon(':/armory_icon_32x32.png'))
################################################################################
class QRCodeWidget(QWidget):
def __init__(self, asciiToEncode='', prefSize=160, errLevel='L', parent=None):
super(QRCodeWidget, self).__init__()
self.parent = parent
self.qrmtrx = None
self.setAsciiData(asciiToEncode, prefSize, errLevel, repaint=False)
def setAsciiData(self, newAscii, prefSize=160, errLevel='L', repaint=True):
if len(newAscii)==0:
self.qrmtrx = [[0]]
self.modCt = 1
self.pxScale= 1
return
self.theData = newAscii
self.qrmtrx, self.modCt = CreateQRMatrix(self.theData, errLevel)
self.setPreferredSize(prefSize)
def getModuleCount1D(self):
return self.modCt
def setPreferredSize(self, px, policy='Approx'):
self.pxScale,rem = divmod(int(px), int(self.modCt))
if policy.lower().startswith('approx'):
if rem>self.modCt/2.0:
self.pxScale += 1
elif policy.lower().startswith('atleast'):
if rem>0:
self.pxScale += 1
elif policy.lower().startswith('max'):
pass
else:
LOGERROR('Bad size policy in set qr size')
return self.pxScale*self.modCt
return
def getSize(self):
return self.pxScale*self.modCt
def sizeHint(self):
sz1d = self.pxScale*self.modCt
return QSize(sz1d, sz1d)
def paintEvent(self, e):
qp = QPainter()
qp.begin(self)
self.drawWidget(qp)
qp.end()
def drawWidget(self, qp):
# In case this is not a white background, draw the white boxes
qp.setPen(QColor(255,255,255))
qp.setBrush(QColor(255,255,255))
for r in range(self.modCt):
for c in range(self.modCt):
if not self.qrmtrx[r][c]:
qp.drawRect(*[a*self.pxScale for a in [r,c,1,1]])
# Draw the black tiles
qp.setPen(QColor(0,0,0))
qp.setBrush(QColor(0,0,0))
for r in range(self.modCt):
for c in range(self.modCt):
if self.qrmtrx[r][c]:
qp.drawRect(*[a*self.pxScale for a in [r,c,1,1]])
def mouseDoubleClickEvent(self, *args):
DlgInflatedQR(self.parent, self.theData).exec_()
# Create a very simple dialog and execute it
class DlgInflatedQR(ArmoryDialog):
def __init__(self, parent, dataToQR):
super(DlgInflatedQR, self).__init__(parent)
sz = QApplication.desktop().size()
w,h = sz.width(), sz.height()
qrSize = int(min(w,h)*0.8)
qrDisp = QRCodeWidget(dataToQR, prefSize=qrSize)
def closeDlg(*args):
self.accept()
qrDisp.mouseDoubleClickEvent = closeDlg
self.mouseDoubleClickEvent = closeDlg
lbl = QRichLabel('<b>Double-click or press ESC to close</b>')
lbl.setAlignment(Qt.AlignTop | Qt.AlignHCenter)
frmQR = makeHorizFrame(['Stretch', qrDisp, 'Stretch'])
frmFull = makeVertFrame(['Stretch',frmQR, lbl, 'Stretch'])
layout = QVBoxLayout()
layout.addWidget(frmFull)
self.setLayout(layout)
self.showFullScreen()
# Pure-python BMP creator taken from:
#
# http://pseentertainmentcorp.com/smf/index.php?topic=2034.0
#
# This will take a 2D array of ones-and-zeros and convert it to a binary
# bitmap image, which will be stored in a temporary file. This temporary
# file can be used for display and copy-and-paste into email.
def bmp_binary(header, pixels):
'''It takes a header (based on default_bmp_header),
the pixel data (from structs, as produced by get_color and row_padding),
and writes it to filename'''
header_str = ""
header_str += struct.pack('<B', header['mn1'])
header_str += struct.pack('<B', header['mn2'])
header_str += struct.pack('<L', header['filesize'])
header_str += struct.pack('<H', header['undef1'])
header_str += struct.pack('<H', header['undef2'])
header_str += struct.pack('<L', header['offset'])
header_str += struct.pack('<L', header['headerlength'])
header_str += struct.pack('<L', header['width'])
header_str += struct.pack('<L', header['height'])
header_str += struct.pack('<H', header['colorplanes'])
header_str += struct.pack('<H', header['colordepth'])
header_str += struct.pack('<L', header['compression'])
header_str += struct.pack('<L', header['imagesize'])
header_str += struct.pack('<L', header['res_hor'])
header_str += struct.pack('<L', header['res_vert'])
header_str += struct.pack('<L', header['palette'])
header_str += struct.pack('<L', header['importantcolors'])
return header_str + pixels
def bmp_write(header, pixels, filename):
out = open(filename, 'wb')
out.write(bmp_binary(header, pixels))
out.close()
def bmp_row_padding(width, colordepth):
'''returns any necessary row padding'''
byte_length = width*colordepth/8
# how many bytes are needed to make byte_length evenly divisible by 4?
padding = (4-byte_length)%4
padbytes = ''
for i in range(padding):
x = struct.pack('<B',0)
padbytes += x
return padbytes
def bmp_pack_color(red, green, blue):
'''accepts values from 0-255 for each value, returns a packed string'''
return struct.pack('<BBB',blue,green,red)
###################################
BMP_TEMPFILE = -1
def createBitmap(imgMtrx2D, writeToFile=-1, returnBinary=True):
try:
h,w = len(imgMtrx2D), len(imgMtrx2D[0])
except:
LOGERROR('Error creating BMP object')
raise
header = {'mn1':66,
'mn2':77,
'filesize':0,
'undef1':0,
'undef2':0,
'offset':54,
'headerlength':40,
'width':w,
'height':h,
'colorplanes':0,
'colordepth':24,
'compression':0,
'imagesize':0,
'res_hor':0,
'res_vert':0,
'palette':0,
'importantcolors':0}
pixels = ''
black = bmp_pack_color( 0, 0, 0)
white = bmp_pack_color(255,255,255)
for row in range(header['height']-1,-1,-1):# (BMPs are L to R from the bottom L row)
for col in range(header['width']):
pixels += black if imgMtrx2D[row][col] else white
pixels += bmp_row_padding(header['width'], header['colordepth'])
if returnBinary:
return bmp_binary(header,pixels)
elif writeToFile==BMP_TEMPFILE:
handle,temppath = mkstemp(suffix='.bmp')
bmp_write(header, pixels, temppath)
return temppath
else:
try:
bmp_write(header, pixels, writeToFile)
return True
except:
return False
def selectFileForQLineEdit(parent, qObj, title="Select File", existing=False, \
ffilter=[]):
types = list(ffilter)
types.append('All files (*)')
typesStr = ';; '.join(types)
if not OS_MACOSX:
fullPath = unicode(QFileDialog.getOpenFileName(parent, \
title, ARMORY_HOME_DIR, typesStr))
else:
fullPath = unicode(QFileDialog.getOpenFileName(parent, \
title, ARMORY_HOME_DIR, typesStr, options=QFileDialog.DontUseNativeDialog))
if fullPath:
qObj.setText( fullPath)
def selectDirectoryForQLineEdit(par, qObj, title="Select Directory"):
initPath = ARMORY_HOME_DIR
currText = unicode(qObj.text()).strip()
if len(currText)>0:
if os.path.exists(currText):
initPath = currText
if not OS_MACOSX:
fullPath = unicode(QFileDialog.getExistingDirectory(par, title, initPath))
else:
fullPath = unicode(QFileDialog.getExistingDirectory(par, title, initPath, \
options=QFileDialog.DontUseNativeDialog))
if fullPath:
qObj.setText( fullPath)
def createDirectorySelectButton(parent, targetWidget, title="Select Directory"):
btn = QPushButton('')
ico = QIcon(QPixmap(':/folder24.png'))
btn.setIcon(ico)
fn = lambda: selectDirectoryForQLineEdit(parent, targetWidget, title)
parent.connect(btn, SIGNAL('clicked()'), fn)
return btn