-
Notifications
You must be signed in to change notification settings - Fork 0
/
armorymodels.py
1529 lines (1257 loc) · 58.6 KB
/
armorymodels.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
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
################################################################################
# #
# Copyright (C) 2011-2015, Armory Technologies, Inc. #
# Distributed under the GNU Affero General Public License (AGPL v3) #
# See LICENSE or http://www.gnu.org/licenses/agpl.html #
# #
################################################################################
from os import path
import os
import platform
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from CppBlockUtils import *
from armoryengine.ALL import *
from qtdefines import *
from armoryengine.MultiSigUtils import calcLockboxID
from copy import deepcopy
sys.path.append('..')
sys.path.append('../cppForSwig')
WLTVIEWCOLS = enum('Visible', 'ID', 'Name', 'Secure', 'Bal')
LEDGERCOLS = enum('NumConf', 'UnixTime', 'DateStr', 'TxDir', 'WltName', 'Comment', \
'Amount', 'isOther', 'WltID', 'TxHash', 'isCoinbase', 'toSelf', \
'optInRBF', 'isChainedZC')
ADDRESSCOLS = enum('ChainIdx', 'Address', 'Comment', 'NumTx', 'Balance')
ADDRBOOKCOLS = enum('Address', 'WltID', 'NumSent', 'Comment')
TXINCOLS = enum('WltID', 'Sender', 'Btc', 'OutPt', 'OutIdx', 'FromBlk', \
'ScrType', 'Sequence', 'Script', 'AddrStr')
TXOUTCOLS = enum('WltID', 'Recip', 'Btc', 'ScrType', 'Script', 'AddrStr')
PROMCOLS = enum('PromID', 'Label', 'PayAmt', 'FeeAmt')
PAGE_LOAD_OFFSET = 10
class AllWalletsDispModel(QAbstractTableModel):
# The columns enumeration
def __init__(self, mainWindow):
super(AllWalletsDispModel, self).__init__()
self.main = mainWindow
def rowCount(self, index=QModelIndex()):
return len(self.main.walletMap)
def columnCount(self, index=QModelIndex()):
return 5
def data(self, index, role=Qt.DisplayRole):
bdmState = TheBDM.getState()
COL = WLTVIEWCOLS
row,col = index.row(), index.column()
wlt = self.main.walletMap[self.main.walletIDList[row]]
wltID = wlt.uniqueIDB58
if role==Qt.DisplayRole:
if col==COL.Visible:
return self.main.walletVisibleList[row]
elif col==COL.ID:
return QVariant(wltID)
elif col==COL.Name:
return QVariant(wlt.labelName.ljust(32))
elif col==COL.Secure:
wtype,typestr = determineWalletType(wlt, self.main)
return QVariant(typestr)
elif col==COL.Bal:
if not bdmState==BDM_BLOCKCHAIN_READY:
return QVariant('(...)')
if wlt.isEnabled == True:
bal = wlt.getBalance('Total')
if bal==-1:
return QVariant('(...)')
else:
dispStr = coin2str(bal, maxZeros=2)
return QVariant(dispStr)
else:
dispStr = 'Scanning: %d%%' % (self.main.walletSideScanProgress[wltID])
return QVariant(dispStr)
elif role==Qt.TextAlignmentRole:
if col in (COL.ID, COL.Name):
return QVariant(int(Qt.AlignLeft | Qt.AlignVCenter))
elif col in (COL.Secure,):
return QVariant(int(Qt.AlignHCenter | Qt.AlignVCenter))
elif col in (COL.Bal,):
if not bdmState==BDM_BLOCKCHAIN_READY:
return QVariant(int(Qt.AlignHCenter | Qt.AlignVCenter))
else:
return QVariant(int(Qt.AlignLeft | Qt.AlignVCenter))
elif role==Qt.BackgroundColorRole:
t = determineWalletType(wlt, self.main)[0]
if t==WLTTYPES.WatchOnly:
return QVariant( Colors.TblWltOther )
elif t==WLTTYPES.Offline:
return QVariant( Colors.TblWltOffline )
else:
return QVariant( Colors.TblWltMine )
elif role==Qt.FontRole:
if col==COL.Bal:
return GETFONT('Fixed')
return QVariant()
def headerData(self, section, orientation, role=Qt.DisplayRole):
colLabels = ['', self.tr('ID'), self.tr('Wallet Name'), self.tr('Security'), self.tr('Balance')]
if role==Qt.DisplayRole:
if orientation==Qt.Horizontal:
return QVariant( colLabels[section])
elif role==Qt.TextAlignmentRole:
return QVariant( int(Qt.AlignHCenter | Qt.AlignVCenter) )
def flags(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
wlt = self.main.walletMap[self.main.walletIDList[index.row()]]
rowFlag = Qt.ItemIsEnabled | Qt.ItemIsSelectable
if wlt.isEnabled is False:
return Qt.ItemFlags()
return rowFlag
################################################################################
class AllWalletsCheckboxDelegate(QStyledItemDelegate):
"""
Taken from http://stackoverflow.com/a/3366899/1610471
"""
EYESIZE = 20
def __init__(self, parent=None):
super(AllWalletsCheckboxDelegate, self).__init__(parent)
#############################################################################
def paint(self, painter, option, index):
bgcolor = QColor(index.model().data(index, Qt.BackgroundColorRole))
if option.state & QStyle.State_Selected:
bgcolor = QApplication.palette().highlight().color()
if index.column() == WLTVIEWCOLS.Visible:
isVisible = index.model().data(index)
image=None
painter.fillRect(option.rect, bgcolor)
if isVisible:
image = QImage(':/visible2.png').scaled(self.EYESIZE,self.EYESIZE)
pixmap = QPixmap.fromImage(image)
painter.drawPixmap(option.rect, pixmap)
else:
QStyledItemDelegate.paint(self, painter, option, index)
#############################################################################
def sizeHint(self, option, index):
if index.column()==WLTVIEWCOLS.Visible:
return QSize(self.EYESIZE,self.EYESIZE)
return QStyledItemDelegate.sizeHint(self, option, index)
################################################################################
class TableEntry():
def __init__(self, id=-1, table=[]):
self.id = id
self.table = table
################################################################################
class LedgerDispModelSimple(QAbstractTableModel):
""" Displays an Nx10 table of pre-formatted/processed ledger entries """
def __init__(self, ledgerTable, parent=None, main=None, isLboxModel=False):
super(LedgerDispModelSimple, self).__init__()
self.parent = parent
self.main = main
self.ledger = ledgerTable
self.isLboxModel = isLboxModel
self.bottomPage = TableEntry(1, [])
self.currentPage = TableEntry(0, [])
self.topPage = TableEntry(-1, [])
self.getPageLedger = None
self.convertLedger = None
self.ledgerDelegate = None
def rowCount(self, index=QModelIndex()):
return len(self.ledger)
def columnCount(self, index=QModelIndex()):
return 13
def data(self, index, role=Qt.DisplayRole):
COL = LEDGERCOLS
row,col = index.row(), index.column()
rowData = self.ledger[row]
nConf = rowData[LEDGERCOLS.NumConf]
wltID = rowData[LEDGERCOLS.WltID]
wlt = self.main.walletMap.get(wltID)
optInRBF = rowData[LEDGERCOLS.optInRBF]
isChainedZC = rowData[LEDGERCOLS.isChainedZC]
amount = float(rowData[LEDGERCOLS.Amount])
toSelf = rowData[LEDGERCOLS.toSelf]
flagged = (optInRBF) and amount < 0 or toSelf
highlighted = optInRBF or isChainedZC
if wlt:
wtype = determineWalletType(self.main.walletMap[wltID], self.main)[0]
else:
wtype = WLTTYPES.WatchOnly
if role==Qt.DisplayRole:
return QVariant(rowData[col])
elif role==Qt.TextAlignmentRole:
if col in (COL.NumConf, COL.TxDir):
return QVariant(int(Qt.AlignHCenter | Qt.AlignVCenter))
elif col in (COL.Comment, COL.DateStr):
return QVariant(int(Qt.AlignLeft | Qt.AlignVCenter))
elif col in (COL.Amount,):
return QVariant(int(Qt.AlignRight | Qt.AlignVCenter))
elif role==Qt.DecorationRole:
pass
elif role==Qt.BackgroundColorRole:
if optInRBF is True:
if flagged:
return QVariant( Colors.myRBF)
else:
return QVariant( Colors.optInRBF )
elif isChainedZC is True:
return QVariant( Colors.chainedZC )
elif wtype==WLTTYPES.WatchOnly:
return QVariant( Colors.TblWltOther )
elif wtype==WLTTYPES.Offline:
return QVariant( Colors.TblWltOffline )
else:
return QVariant( Colors.TblWltMine )
elif role==Qt.ForegroundRole:
if highlighted:
return QVariant(Colors.HighlightFG)
elif nConf < 2:
return QVariant(Colors.TextNoConfirm)
elif nConf <= 4:
return QVariant(Colors.TextSomeConfirm)
if col==COL.Amount:
#toSelf = self.index(index.row(), COL.toSelf).data().toBool()
toSelf = rowData[COL.toSelf]
if toSelf:
return QVariant(Colors.Mid)
amt = float(rowData[COL.Amount])
if amt>0: return QVariant(Colors.TextGreen)
elif amt<0: return QVariant(Colors.TextRed)
else: return QVariant(Colors.Foreground)
elif role==Qt.FontRole:
if col==COL.Amount:
f = GETFONT('Fixed')
f.setWeight(QFont.Bold)
return f
elif role==Qt.ToolTipRole:
if col in (COL.NumConf, COL.DateStr):
nConf = rowData[COL.NumConf]
isCB = rowData[COL.isCoinbase]
isConfirmed = (nConf>119 if isCB else nConf>5)
if isConfirmed:
return QVariant(self.tr('Transaction confirmed!\n(%1 confirmations)').arg(nConf))
else:
tooltipStr = ''
if isCB:
tooltipStr = self.tr('%1/120 confirmations').arg(nConf)
tooltipStr += ( self.tr('\n\nThis is a "generation" transaction from\n'
'Bitcoin mining. These transactions take\n'
'120 confirmations (approximately one day)\n'
'before they are available to be spent.'))
elif flagged:
tooltipStr = self.tr("You have create this transaction as RBF (Replaceable By Fee).<br><br>"
"This means you have the opportunity to bump the fee on this transaction"
" if it fails to confirm quickly enough.<br><br>"
"To bump the fee, right click on the ledger entry and pick <u>\"Bump the fee\"</u>")
elif optInRBF:
tooltipStr = self.tr("This transaction has been RBF flagged (Replaceable By Fee)<br><br>"
"It means the network will accept and broadcast a double spend of"
" the underlying outputs as long as the double spend pays a higher fee.<br><br>"
"Do not consider a RBF transaction as a valid payment until it receives"
" at least 1 confirmation.")
elif isChainedZC:
tooltipStr = self.tr("This transaction spends ZC (zero confirmation) outputs<br><br>"
"Transactions built on top of yet to confirm transactions are at"
" risk of being invalidated for as long as the parent transaction"
" remains unconfirmed.<br><br>"
"It is recommended to wait for at least 1 confirmation before"
" accepting these as valid payment.")
else:
tooltipStr = self.tr('%1/6 confirmations').arg(rowData[COL.NumConf])
tooltipStr += self.tr( '\n\nFor small transactions, 2 or 3 '
'confirmations is usually acceptable. '
'For larger transactions, you should '
'wait for 6 confirmations before '
'trusting that the transaction is valid.')
return QVariant(tooltipStr)
if col==COL.TxDir:
#toSelf = self.index(index.row(), COL.toSelf).data().toBool()
toSelf = rowData[COL.toSelf]
if toSelf:
return QVariant(self.tr('Bitcoins sent and received by the same wallet'))
else:
#txdir = str(index.model().data(index).toString()).strip()
txdir = rowData[COL.TxDir]
if rowData[COL.isCoinbase]:
return QVariant(self.tr('You mined these Bitcoins!'))
if float(txdir.strip())<0:
return QVariant(self.tr('Bitcoins sent'))
else:
return QVariant(self.tr('Bitcoins received'))
if col==COL.Amount:
if self.main.settings.get('DispRmFee'):
return QVariant(self.tr('The net effect on the balance of this wallet '
'<b>not including transaction fees.</b> '
'You can change this behavior in the Armory '
'preferences window.'))
else:
return QVariant(self.tr('The net effect on the balance of this wallet, '
'including transaction fees.'))
return QVariant()
def headerData(self, section, orientation, role=Qt.DisplayRole):
COL = LEDGERCOLS
if role==Qt.DisplayRole:
if orientation==Qt.Horizontal:
if section==COL.NumConf: return QVariant()
if section==COL.DateStr: return QVariant(self.tr('Date'))
if section==COL.WltName: return QVariant(self.tr('Lockbox')) if self.isLboxModel else QVariant(self.tr('Wallet'))
if section==COL.Comment: return QVariant(self.tr('Comments'))
if section==COL.TxDir: return QVariant()
if section==COL.Amount: return QVariant(self.tr('Amount'))
if section==COL.isOther: return QVariant(self.tr('Other Owner'))
if section==COL.WltID: return QVariant(self.tr('Wallet ID'))
if section==COL.TxHash: return QVariant(self.tr('Tx Hash (LE)'))
elif role==Qt.TextAlignmentRole:
return QVariant( int(Qt.AlignHCenter | Qt.AlignVCenter) )
def setLedgerDelegate(self, delegate):
self.ledgerDelegate = delegate
def setConvertLedgerMethod(self, method):
self.convertLedger = method
def getMoreData(self, atBottom):
#return 0 if self.ledger didn't change
if atBottom == True:
#Try to grab the next page. If it throws, there is no more data
#so we can simply return
try:
newLedger = self.ledgerDelegate.getHistoryPage(self.bottomPage.id +1)
toTable = self.convertLedger(newLedger)
except:
return 0
self.previousOffset = -len(self.topPage.table)
#get the length of the ledger we're not dumping
prevPageCount = len(self.currentPage.table) + \
len(self.bottomPage.table)
#Swap pages downwards
self.topPage = deepcopy(self.currentPage)
self.currentPage = deepcopy(self.bottomPage)
self.bottomPage.id += 1
self.bottomPage.table = toTable
#figure out the bottom of the previous view in
#relation with the new one
pageCount = prevPageCount + len(self.bottomPage.table)
if pageCount == 0:
ratio = 0
else:
ratio = float(prevPageCount) / float(pageCount)
else:
try:
newLedger = self.ledgerDelegate.getHistoryPage(self.topPage.id -1)
toTable = self.convertLedger(newLedger)
except:
return 0
self.previousOffset = len(self.topPage.table)
prevPageCount = len(self.currentPage.table) + \
len(self.topPage.table)
self.bottomPage = deepcopy(self.currentPage)
self.currentPage = deepcopy(self.topPage)
self.topPage.id -= 1
self.topPage.table = toTable
pageCount = prevPageCount + len(self.topPage.table)
ratio = 1 - float(prevPageCount) / float(pageCount)
#call reset, which will pull the missing ledgerTable from C++
self.reset()
return ratio
def reset(self, hard=False):
#if either top or current page is index 0, update it
#also if any of the pages has no ledger, pull and convert it
if hard == True:
self.topPage.id = -1
self.topPage.table = []
self.currentPage.id = 0
self.currentPage.table = []
self.bottomPage.id = 1
self.bottomPage.table = []
if self.topPage.id == 0 or len(self.topPage.table) == 0:
try:
newLedger = self.ledgerDelegate.getHistoryPage(self.topPage.id)
toTable = self.convertLedger(newLedger)
self.topPage.table = toTable
except:
pass
if self.currentPage.id == 0 or len(self.currentPage.table) == 0:
try:
newLedger = self.ledgerDelegate.getHistoryPage(self.currentPage.id)
toTable = self.convertLedger(newLedger)
self.currentPage.table = toTable
except:
pass
if len(self.bottomPage.table) == 0:
try:
newLedger = self.ledgerDelegate.getHistoryPage(self.bottomPage.id)
toTable = self.convertLedger(newLedger)
self.bottomPage.table = toTable
except:
pass
self.ledger = []
self.ledger.extend(self.topPage.table)
self.ledger.extend(self.currentPage.table)
self.ledger.extend(self.bottomPage.table)
#call the parent reset() which will update the view
super(QAbstractTableModel, self).reset()
def centerAtHeight(self, blk):
#return the index for that block height in the new ledger
centerId = self.ledgerDelegate.getPageIdForBlockHeight(blk)
self.bottomPage = TableEntry(centerId +1, [])
self.currentPage = TableEntry(centerId, [])
self.topPage = TableEntry(centerId -1, [])
self.reset()
blockDiff = 2**32
blockReturn = 0
for leID in range(0, len(self.ledger)):
block = TheBDM.getTopBlockHeight() - self.ledger[leID][0] -1
diff = abs(block - blk)
if blockDiff >= diff :
blockDiff = diff
blockReturn = leID
return blockReturn
def updateIndexComment(self, index, comment):
#this allows the code to update comments without the need
#to reload the entire model
row = index.row()
rowData = self.ledger[row]
rowData[LEDGERCOLS.Comment] = comment
################################################################################
class CalendarDialog(ArmoryDialog):
def __init__(self, parent, main):
super(CalendarDialog, self).__init__(parent, main)
self.parent = parent
self.main = main
self.calendarWidget = QCalendarWidget(self)
self.layout = QGridLayout()
self.layout.addWidget(self.calendarWidget, 0, 0)
self.setLayout(self.layout)
self.adjustSize()
self.calendarWidget.selectionChanged.connect(self.accept)
################################################################################
class ArmoryBlockAndDateSelector():
def __init__(self, parent, main, controlFrame):
self.parent = parent
self.main = main
self.ledgerDelegate = None
self.Height = 0
self.Width = 0
self.Block = 0
self.Date = 0
self.isExpanded = False
self.doHide = False
self.isEditingBlockHeight = False
self.frmBlockAndDate = QFrame()
self.frmBlockAndDateLayout = QGridLayout()
self.frmBlockAndDateLayout.setAlignment(Qt.AlignLeft | Qt.AlignBottom)
self.lblBlock = QLabel(self.main.tr("<a href=edtBlock>Block:</a>"))
self.lblBlock.linkActivated.connect(self.linkClicked)
self.lblBlock.adjustSize()
self.lblBlockValue = QLabel("")
self.lblBlockValue.adjustSize()
self.lblDate = QLabel(self.main.tr("<a href=edtDate>Date:</a>"))
self.lblDate.linkActivated.connect(self.linkClicked)
self.lblDate.adjustSize()
self.lblDateValue = QLabel("")
self.lblDateValue.adjustSize()
self.lblTop = QLabel(self.main.tr("<a href=goToTop>Top</a>"))
self.lblTop.linkActivated.connect(self.goToTop)
self.lblTop.adjustSize()
self.calendarDlg = CalendarDialog(self.parent, self.main)
self.edtBlock = QLineEdit()
edtFontMetrics = self.edtBlock.fontMetrics()
fontRect = edtFontMetrics.boundingRect("00000000")
self.edtBlock.setFixedWidth(fontRect.width())
self.edtBlock.setVisible(False)
self.edtBlock.editingFinished.connect(self.blkEditingFinished)
self.frmBlock = QFrame()
self.frmBlockLayout = QGridLayout()
self.frmBlockLayout.addWidget(self.lblBlock, 0, 0)
self.frmBlockLayout.addWidget(self.lblBlockValue, 0, 1)
self.frmBlockLayout.addWidget(self.edtBlock, 0, 1)
self.frmBlockLayout.addWidget(self.lblTop, 0, 2)
self.frmBlock.setLayout(self.frmBlockLayout)
self.frmBlock.adjustSize()
self.frmBlockAndDateLayout.addWidget(self.lblBlock, 0, 0)
self.frmBlockAndDateLayout.addWidget(self.lblBlockValue, 0, 1)
self.frmBlockAndDateLayout.addWidget(self.edtBlock, 0, 1)
self.frmBlockAndDateLayout.addWidget(self.lblTop, 0, 2)
self.frmBlockAndDateLayout.addWidget(self.lblDate, 1, 0)
self.frmBlockAndDateLayout.addWidget(self.lblDateValue, 1, 1)
self.frmBlockAndDate.setLayout(self.frmBlockAndDateLayout)
self.frmBlockAndDate.setBackgroundRole(QPalette.Window)
self.frmBlockAndDate.setAutoFillBackground(True)
self.frmBlockAndDate.setFrameStyle(QFrame.Panel | QFrame.Raised);
self.frmBlockAndDate.setVisible(False)
self.frmBlockAndDate.setMouseTracking(True)
self.frmBlockAndDate.leaveEvent = self.triggerHideBlockAndDate
self.frmBlockAndDate.enterEvent = self.resetHideBlockAndDate
self.dateBlockSelectButton = QPushButton('Goto')
self.dateBlockSelectButton.setStyleSheet('QPushButton { font-size : 10px }')
self.dateBlockSelectButton.setMaximumSize(60, 20)
self.main.connect(self.dateBlockSelectButton, \
SIGNAL('clicked()'), self.showBlockDateController)
self.frmLayout = QGridLayout()
self.frmLayout.addWidget(self.dateBlockSelectButton)
self.frmLayout.addWidget(self.frmBlockAndDate)
self.frmLayout.connect(self.frmLayout, SIGNAL('hideIt'), self.hideBlockAndDate)
self.frmLayout.setAlignment(Qt.AlignCenter | Qt.AlignTop)
self.frmLayout.setMargin(0)
self.dateBlockSelectButton.setVisible(True)
controlFrame.setLayout(self.frmLayout)
def linkClicked(self, link):
if link == 'edtBlock':
self.editBlockHeight()
elif link == 'edtDate':
self.editDate()
def updateLabel(self, block):
self.Block = block
try:
self.Date = TheBDM.bdv().getBlockTimeByHeight(block)
datefmt = self.main.getPreferredDateFormat()
dateStr = unixTimeToFormatStr(self.Date, datefmt)
except:
dateStr = "N/A"
self.lblBlockValue.setText(str(block) )
self.lblBlockValue.adjustSize()
self.lblDateValue.setText(dateStr)
self.lblDateValue.adjustSize()
self.frmBlockAndDate.adjustSize()
if self.isExpanded == True:
fontRect = self.frmBlockAndDate.geometry()
else:
fontRect = self.dateBlockSelectButton.geometry()
self.Width = fontRect.width()
self.Height = fontRect.height()
def getLayoutSize(self):
return QSize(self.Width, self.Height)
def pressEvent(self, mEvent):
if mEvent.button() == Qt.LeftButton:
self.lblClicked()
def showBlockDateController(self):
self.isExpanded = True
self.dateBlockSelectButton.setVisible(False)
self.frmBlockAndDate.setVisible(True)
self.updateLabel(self.Block)
def prepareToHideThread(self):
self.doHide = True
time.sleep(1)
self.frmLayout.emit(SIGNAL('hideIt'))
def triggerHideBlockAndDate(self, mEvent):
hideThread = PyBackgroundThread(self.prepareToHideThread)
hideThread.start()
def hideBlockAndDate(self):
if self.isExpanded == True and self.doHide == True:
self.frmBlockAndDate.setVisible(False)
self.dateBlockSelectButton.setVisible(True)
self.isExpanded = False
self.updateLabel(self.Block)
def resetHideBlockAndDate(self, mEvent):
self.doHide = False
def editBlockHeight(self):
if self.isEditingBlockHeight == False:
self.edtBlock.setText(self.lblBlockValue.text())
self.lblBlockValue.setVisible(False)
self.edtBlock.setVisible(True)
self.isEditingBlockHeight = True
self.frmBlockAndDate.adjustSize()
else:
self.lblBlockValue.setVisible(True)
self.edtBlock.setVisible(False)
self.isEditingBlockHeight = False
self.frmBlockAndDate.adjustSize()
def editDate(self):
if self.isEditingBlockHeight == True:
self.editBlockHeight()
if self.calendarDlg.exec_() == True:
self.dateChanged()
def blkEditingFinished(self):
try:
blk = int(self.edtBlock.text())
self.Block = self.ledgerDelegate.getBlockInVicinity(blk)
self.Date = TheBDM.bdv().getBlockTimeByHeight(self.Block)
except:
pass
self.editBlockHeight()
self.updateLabel(self.Block)
self.parent.emit(SIGNAL('centerView'), self.Block)
def dateChanged(self):
try:
ddate = self.calendarDlg.calendarWidget.selectedDate().toPyDate()
self.Date = int(time.mktime(ddate.timetuple()))
self.Block = TheBDM.bdv().getClosestBlockHeightForTime(self.Date)
except:
pass
self.updateLabel(self.Block)
self.parent.emit(SIGNAL('centerView'), self.Block)
def goToTop(self):
if self.isEditingBlockHeight == True:
self.editBlockHeight()
self.parent.emit(SIGNAL('goToTop'))
def hide(self):
self.dateBlockSelectButton.setVisible(False)
def show(self):
if self.isExpanded == False:
self.dateBlockSelectButton.setVisible(True)
################################################################################
class ArmoryTableView(QTableView):
def __init__(self, parent, main, controlFrame):
super(ArmoryTableView, self).__init__()
self.parent = parent
self.main = main
self.BlockAndDateSelector = ArmoryBlockAndDateSelector(self, self.main, controlFrame)
self.verticalScrollBar().rangeChanged.connect(self.scrollBarRangeChanged)
self.vBarRatio = 0
# self.verticalScrollBar().setVisible(False)
self.setSelectionMode(QAbstractItemView.SingleSelection)
self.prevIndex = -1
self.connect(self, SIGNAL('centerView'), self.centerViewAtBlock)
self.connect(self, SIGNAL('goToTop'), self.goToTop)
def verticalScrollbarValueChanged(self, dx):
if dx > self.verticalScrollBar().maximum() - PAGE_LOAD_OFFSET:
#at the bottom of the scroll area
ratio = self.ledgerModel.getMoreData(True)
if ratio != 0:
self.vBarRatio = ratio
elif dx < PAGE_LOAD_OFFSET:
#at the top of the scroll area
ratio = self.ledgerModel.getMoreData(False)
if ratio != 0:
self.vBarRatio = ratio
self.updateBlockAndDateLabel()
def setModel(self, model):
QTableView.setModel(self, model)
self.ledgerModel = model
if model is not None:
self.BlockAndDateSelector.ledgerDelegate = self.ledgerModel.ledgerDelegate
def scrollBarRangeChanged(self, rangeMin, rangeMax):
pos = int(self.vBarRatio * rangeMax)
self.verticalScrollBar().setValue(pos)
self.updateBlockAndDateLabel()
def selectionChanged(self, itemSelected, itemDeselected):
if itemSelected.last().bottom() +2 >= len(self.ledgerModel.ledger):
ratio = self.ledgerModel.getMoreData(True)
if ratio != 0:
self.vBarRatio = ratio
elif itemSelected.last().top() -2 <= 0:
ratio = self.ledgerModel.getMoreData(False)
if ratio != 0:
self.vBarRatio = ratio
super(ArmoryTableView, self).selectionChanged(itemSelected, itemDeselected)
self.updateBlockAndDateLabel()
def moveCursor(self, action, modifier):
self.prevIndex = self.currentIndex().row()
if action == QAbstractItemView.MoveUp:
if self.currentIndex().row() > 0:
return self.ledgerModel.index(self.currentIndex().row() -1, 0)
elif action == QAbstractItemView.MoveDown:
if self.currentIndex().row() < self.ledgerModel.rowCount() -1:
return self.ledgerModel.index(self.currentIndex().row() +1, 0)
return self.currentIndex()
def reset(self):
#save the previous selection
super(ArmoryTableView, self).reset()
if self.prevIndex != -1:
self.setCurrentIndex(\
self.ledgerModel.index(self.ledgerModel.previousOffset + self.prevIndex, 0))
self.updateBlockAndDateLabel()
def centerViewAtBlock(self, Blk):
itemIndex = self.ledgerModel.centerAtHeight(Blk)
self.vBarRatio = float(itemIndex) / float(self.ledgerModel.rowCount())
self.verticalScrollBar().setValue(\
self.vBarRatio * self.verticalScrollBar().maximum())
def updateBlockAndDateLabel(self):
try:
sbMax = self.verticalScrollBar().maximum()
if sbMax == 0:
self.BlockAndDateSelector.hide()
else:
self.BlockAndDateSelector.show()
ratio = float(self.verticalScrollBar().value()) \
/ float(self.verticalScrollBar().maximum())
leID = int(ratio * float(self.ledgerModel.rowCount()))
block = TheBDM.getTopBlockHeight() - self.ledgerModel.ledger[leID][0] +1
self.BlockAndDateSelector.updateLabel(block)
except:
pass
def goToTop(self):
self.ledgerModel.reset(True)
self.vBarRatio = 0
self.verticalScrollBar().setValue(0)
################################################################################
class LedgerDispSortProxy(QSortFilterProxyModel):
"""
Acts as a proxy that re-maps indices to the table view so that data
appears sorted, without actually touching the model
"""
def lessThan(self, idxLeft, idxRight):
COL = LEDGERCOLS
thisCol = self.sortColumn()
def getDouble(idx, col):
return float(self.sourceModel().ledger[idx.row()][col])
def getInt(idx, col):
return int(self.sourceModel().ledger[idx.row()][col])
#LEDGERCOLS = enum('NumConf', 'UnixTime', 'DateStr', 'TxDir', 'WltName', 'Comment', \
#'Amount', 'isOther', 'WltID', 'TxHash', 'toSelf', 'DoubleSpend')
if thisCol==COL.NumConf:
lConf = getInt(idxLeft, COL.NumConf)
rConf = getInt(idxRight, COL.NumConf)
if lConf==rConf:
tLeft = getDouble(idxLeft, COL.UnixTime)
tRight = getDouble(idxRight, COL.UnixTime)
return (tLeft<tRight)
return (lConf>rConf)
if thisCol==COL.DateStr:
tLeft = getDouble(idxLeft, COL.UnixTime)
tRight = getDouble(idxRight, COL.UnixTime)
return (tLeft<tRight)
if thisCol==COL.Amount:
btcLeft = getDouble(idxLeft, COL.Amount)
btcRight = getDouble(idxRight, COL.Amount)
return (abs(btcLeft) < abs(btcRight))
else:
return super(LedgerDispSortProxy, self).lessThan(idxLeft, idxRight)
################################################################################
class LedgerDispDelegate(QStyledItemDelegate):
COL = LEDGERCOLS
def __init__(self, parent=None):
super(LedgerDispDelegate, self).__init__(parent)
def paint(self, painter, option, index):
bgcolor = QColor(index.model().data(index, Qt.BackgroundColorRole))
if option.state & QStyle.State_Selected:
bgcolor = QApplication.palette().highlight().color()
#bgcolor = Colors.Background
#if option.state & QStyle.State_Selected:
#bgcolor = Colors.Highlight
if index.column() == self.COL.NumConf:
nConf = index.model().data(index).toInt()[0]
isCoinbase = index.model().index(index.row(), self.COL.isCoinbase).data().toBool()
image=None
if isCoinbase:
if nConf<120:
effectiveNConf = int(6*float(nConf)/120.)
image = QImage(':/conf%dt_nonum.png'%effectiveNConf)
else:
image = QImage(':/conf6t.png')
else:
if nConf<6:
image = QImage(':/conf%dt.png'%nConf)
else:
image = QImage(':/conf6t.png')
painter.fillRect(option.rect, bgcolor)
pixmap = QPixmap.fromImage(image)
#pixmap.scaled(70, 30, Qt.KeepAspectRatio)
painter.drawPixmap(option.rect, pixmap)
elif index.column() == self.COL.TxDir:
# This is frustrating... QVariant doesn't support 64-bit ints
# So I have to pass the amt as string, then convert here to long
toSelf = index.model().index(index.row(), self.COL.toSelf).data().toBool()
isCoinbase = index.model().index(index.row(), self.COL.isCoinbase).data().toBool()
image = QImage()
# isCoinbase still needs to be flagged in the C++ utils
if isCoinbase:
image = QImage(':/moneyCoinbase.png')
elif toSelf:
image = QImage(':/moneySelf.png')
else:
txdir = str(index.model().data(index).toString()).strip()
if txdir[0].startswith('-'):
image = QImage(':/moneyOut.png')
else:
image = QImage(':/moneyIn.png')
painter.fillRect(option.rect, bgcolor)
pixmap = QPixmap.fromImage(image)
#pixmap.scaled(70, 30, Qt.KeepAspectRatio)
painter.drawPixmap(option.rect, pixmap)
else:
QStyledItemDelegate.paint(self, painter, option, index)
def sizeHint(self, option, index):
if index.column()==self.COL.NumConf:
return QSize(28,28)
elif index.column()==self.COL.TxDir:
return QSize(28,28)
return QStyledItemDelegate.sizeHint(self, option, index)
################################################################################
class WalletAddrDispModel(QAbstractTableModel):
def __init__(self, wlt, mainWindow):
super(WalletAddrDispModel, self).__init__()
self.main = mainWindow
self.wlt = wlt
self.noChange = False
self.usedOnly = False
self.notEmpty = False
self.filterAddrList()
def setFilter(self, filt1=False, filt2=False, filt3=False):
self.notEmpty = filt1
self.noChange = filt2
self.usedOnly = filt3
self.filterAddrList()
def filterAddrList(self):
addrList = self.wlt.getLinearAddrList()
if self.notEmpty and TheBDM.getState()==BDM_BLOCKCHAIN_READY:
hasBalance = lambda a: (self.wlt.getAddrBalance(a.getAddr160(), 'Full')>0)
addrList = filter(hasBalance, addrList)
if self.noChange:
notChange = lambda a: (self.wlt.getCommentForAddress(a.getAddr160()) != CHANGE_ADDR_DESCR_STRING)
addrList = filter(notChange, addrList)
if self.usedOnly and TheBDM.getState()==BDM_BLOCKCHAIN_READY:
isUsed = lambda a: (self.wlt.getAddrTotalTxnCount(Hash160ToScrAddr(a.getAddr160())))
addrList = filter(isUsed, addrList)
self.addr160List = [a.getAddr160() for a in addrList]
@TimeThisFunction
def reset(self):
self.filterAddrList()
super(WalletAddrDispModel, self).reset()
def rowCount(self, index=QModelIndex()):
return len(self.addr160List)
def columnCount(self, index=QModelIndex()):
return 5
def data(self, index, role=Qt.DisplayRole):
COL = ADDRESSCOLS
row,col = index.row(), index.column()
if row>=len(self.addr160List):
return QVariant('')
addr = self.wlt.addrMap[self.addr160List[row]]
addr_index = addr.chainIndex
try:
if addr_index == -2:
addr_index = self.wlt.cppWallet.getAssetIndexForAddr(addr.getAddr160())
index_import = self.wlt.cppWallet.convertToImportIndex(addr_index)