Added base unit 'bits'.
[electrum-nvc.git] / gui / qt / amountedit.py
1 # -*- coding: utf-8 -*-
2
3 from PyQt4.QtCore import *
4 from PyQt4.QtGui import *
5
6 from decimal import Decimal
7
8 class MyLineEdit(QLineEdit):
9     frozen = pyqtSignal()
10
11     def setFrozen(self, b):
12         self.setReadOnly(b)
13         self.setFrame(not b)
14         self.frozen.emit()
15
16 class AmountEdit(MyLineEdit):
17
18     def __init__(self, base_unit, is_int = False, parent=None):
19         QLineEdit.__init__(self, parent)
20         self.base_unit = base_unit
21         self.textChanged.connect(self.numbify)
22         self.is_int = is_int
23         self.is_shortcut = False
24         self.help_palette = QPalette()
25
26     def decimal_point(self):
27         return 8
28
29     def numbify(self):
30         text = unicode(self.text()).strip()
31         if text == '!':
32             self.is_shortcut = True
33         pos = self.cursorPosition()
34         chars = '0123456789'
35         if not self.is_int: chars +='.'
36         s = ''.join([i for i in text if i in chars])
37         if not self.is_int:
38             if '.' in s:
39                 p = s.find('.')
40                 s = s.replace('.','')
41                 s = s[:p] + '.' + s[p:p+self.decimal_point()]
42         self.setText(s)
43         self.setCursorPosition(pos)
44
45     def paintEvent(self, event):
46         QLineEdit.paintEvent(self, event)
47         if self.base_unit:
48             panel = QStyleOptionFrameV2()
49             self.initStyleOption(panel)
50             textRect = self.style().subElementRect(QStyle.SE_LineEditContents, panel, self)
51             textRect.adjust(2, 0, -10, 0)
52             painter = QPainter(self)
53             painter.setPen(self.help_palette.brush(QPalette.Disabled, QPalette.Text).color())
54             painter.drawText(textRect, Qt.AlignRight | Qt.AlignVCenter, self.base_unit())
55
56
57
58 class BTCAmountEdit(AmountEdit):
59
60     def __init__(self, decimal_point, is_int = False, parent=None):
61         AmountEdit.__init__(self, self._base_unit, is_int, parent)
62         self.decimal_point = decimal_point
63
64     def _base_unit(self):
65         p = self.decimal_point()
66         assert p in [2, 5, 8]
67         if p == 8:
68             return 'BTC'
69         if p == 5:
70             return 'mBTC'
71         if p == 2:
72             return 'bits'
73         raise Exception('Unknown base unit')
74
75     def get_amount(self):
76         try:
77             x = Decimal(str(self.text()))
78         except:
79             return None
80         p = pow(10, self.decimal_point())
81         return int( p * x )
82
83     def setAmount(self, amount):
84         if amount is None:
85             self.setText("")
86             return
87
88         p = pow(10, self.decimal_point())
89         x = amount / Decimal(p)
90         self.setText(str(x))
91