-
Notifications
You must be signed in to change notification settings - Fork 617
/
armorymodels.py
1618 lines (1327 loc) · 60.9 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', 'DoubleSpend')
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 = ['', tr('ID'), tr('Wallet Name'), tr('Security'), 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
# This might work for checkbox-in-tableview
#QStandardItemModel* tableModel = new QStandardItemModel();
#// create text item
#tableModel->setItem(0, 0, new QStandardItem("text item"));
#// create check box item
#QStandardItem* item0 = new QStandardItem(true);
#item0->setCheckable(true);
#item0->setCheckState(Qt::Checked);
#item0->setText("some text");
#tableModel->setItem(0, 1, item0);
#// set model
#ui->tableView->setModel(tableModel);
# Perhaps delegate for rich text in QTableViews
#void SpinBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
#{
#QTextDocument document;
#QVariant value = index.data(Qt::DisplayRole);
#if (value.isValid() && !value.isNull()) {
#QString text("<span style='background-color: lightgreen'>This</span> is highlighted.");
#text.append(" (");
#text.append(value.toString());
#text.append(")");
#document.setHtml(text);
#painter->translate(option.rect.topLeft());
#document.drawContents(painter);
#painter->translate(-option.rect.topLeft());
#}
# This was an almost-successful attempt to use a delegate to manage visibility
# Will kind of hack around it, using a simpler delegate and a QTableView
# signal to do the toggling
'''
class AllWalletsCheckboxDelegate(QStyledItemDelegate):
"""
Taken from http://stackoverflow.com/a/3366899/1610471
"""
def __init__(self, parent=None):
super(AllWalletsCheckboxDelegate, self).__init__(parent)
def createEditor(self, parent, option, index):
""" Without this, an editor is created if the user clicks in this cell."""
return None
def paint(self, painter, option, index):
if not index.column() == WLTVIEWCOLS.Visible:
QStyledItemDelegate.paint(self, painter, option, index)
else:
# Paint a checkbox without the label.
checked = bool(index.model().data(index, Qt.DisplayRole))
check_box_style_option = QStyleOptionButton()
if (index.flags() & Qt.ItemIsEditable) > 0:
check_box_style_option.state |= QStyle.State_Enabled
else:
check_box_style_option.state |= QStyle.State_ReadOnly
if checked:
check_box_style_option.state |= QStyle.State_On
else:
check_box_style_option.state |= QStyle.State_Off
check_box_style_option.rect = self.getCheckboxRect(option)
#if not index.model().hasFlag(index, Qt.ItemIsEditable):
#check_box_style_option.state |= QStyle.State_ReadOnly
QApplication.style().drawControl(QStyle.CE_CheckBox,
check_box_style_option,
painter)
def editorEvent(self, event, model, option, index):
"""
Change the data in the model and the state of the checkbox
if the user presses the left mousebutton or presses
Key_Space or Key_Select and this cell is editable. Otherwise do nothing.
"""
if index.column()==WLTVIEWCOLS.Visible:
#if not (index.flags() & Qt.ItemIsEditable) > 0:
#return False
# Do not change the checkbox-state
if event.type() == QEvent.MouseButtonRelease or \
event.type() == QEvent.MouseButtonDblClick:
if event.button() != Qt.LeftButton or \
not self.getCheckboxRect(option).contains(event.pos()):
return False
if event.type() == QEvent.MouseButtonDblClick:
return True
elif event.type() == QEvent.KeyPress:
if event.key() != Qt.Key_Space and \
event.key() != Qt.Key_Select:
return False
else:
return False
# Change the checkbox-state
self.setModelData(None, model, index)
return True
else:
return False
def setModelData(self, editor, model, index):
""" The user wanted to change the old state in the opposite """
newValue = not bool(index.model().data(index, Qt.DisplayRole))
model.setData(index, newValue, Qt.EditRole)
def getCheckboxRect(self, option):
check_box_style_option = QStyleOptionButton()
check_box_rect = QApplication.style().subElementRect( \
QStyle.SE_CheckBoxIndicator, check_box_style_option, None)
check_box_point = QPoint( option.rect.x() +
option.rect.width() / 2 -
check_box_rect.width() / 2,
option.rect.y() +
option.rect.height() / 2 -
check_box_rect.height() / 2)
return QRect(check_box_point, check_box_rect.size())
def sizeHint(self, option, index):
if index.column()==WLTVIEWCOLS.Visible:
return QSize(28,28)
return QStyledItemDelegate.sizeHint(self, option, index)
'''
################################################################################
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
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)
if wlt:
wtype = determineWalletType(self.main.walletMap[wltID], self.main)[0]
else:
wtype = WLTTYPES.WatchOnly
#LEDGERCOLS = enum( 'NumConf', 'UnixTime','DateStr', 'TxDir',
# 'WltName', 'Comment', 'Amount', 'isOther',
# 'WltID', 'TxHash', 'isCoinbase', 'toSelf',
# 'DoubleSpend')
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 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 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('Transaction confirmed!\n(%d confirmations)'%nConf)
else:
tooltipStr = ''
if isCB:
tooltipStr = '%d/120 confirmations'%nConf
tooltipStr += ( '\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.')
else:
tooltipStr = '%d/6 confirmations'%rowData[COL.NumConf]
tooltipStr += ( '\n\nFor small transactions, 2 or 3\n'
'confirmations is usually acceptable.\n'
'For larger transactions, you should\n'
'wait for 6 confirmations before\n'
'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('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('You mined these Bitcoins!')
if float(txdir.strip())<0:
return QVariant('Bitcoins sent')
else:
return QVariant('Bitcoins received')
if col==COL.Amount:
if self.main.settings.get('DispRmFee'):
return QVariant('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('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('Date')
if section==COL.WltName: return QVariant('Lockbox') if self.isLboxModel else QVariant('Wallet')
if section==COL.Comment: return QVariant('Comments')
if section==COL.TxDir: return QVariant()
if section==COL.Amount: return QVariant('Amount')
if section==COL.isOther: return QVariant('Other Owner')
if section==COL.WltID: return QVariant('Wallet ID')
if section==COL.TxHash: return QVariant('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
################################################################################
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("<a href=edtBlock>Block:</a>")
self.lblBlock.linkActivated.connect(self.linkClicked)
self.lblBlock.adjustSize()
self.lblBlockValue = QLabel("")
self.lblBlockValue.adjustSize()
self.lblDate = QLabel("<a href=edtDate>Date:</a>")
self.lblDate.linkActivated.connect(self.linkClicked)
self.lblDate.adjustSize()
self.lblDateValue = QLabel("")
self.lblDateValue.adjustSize()
self.lblTop = QLabel("<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
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()