read amounts
[electrum-nvc.git] / gui / qt / paytoedit.py
1 #!/usr/bin/env python
2 #
3 # Electrum - lightweight Bitcoin client
4 # Copyright (C) 2012 thomasv@gitorious
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19 from PyQt4.QtCore import *
20 from PyQt4.QtGui import *
21
22 import re
23 from decimal import Decimal
24 from electrum import bitcoin
25
26 RE_ADDRESS = '[1-9A-HJ-NP-Za-km-z]{26,}'
27 RE_ALIAS = '(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>'
28
29 class PayToEdit(QTextEdit):
30
31     def __init__(self, amount_edit):
32         QTextEdit.__init__(self)
33         self.amount_edit = amount_edit
34         self.document().contentsChanged.connect(self.update_size)
35         self.heightMin = 0
36         self.heightMax = 150
37         self.setMinimumHeight(27)
38         self.setMaximumHeight(27)
39         #self.setStyleSheet("QTextEdit { border-style:solid; border-width: 1px;}")
40         self.c = None
41
42
43     def lock_amount(self):
44         e = self.amount_edit
45         e.setReadOnly(True)
46         e.setFrame(False)
47
48     def unlock_amount(self):
49         e = self.amount_edit
50         e.setReadOnly(False)
51         e.setFrame(True)
52
53
54     def parse_address_and_amount(self, line):
55         x, y = line.split(',')
56         address = self.parse_address(x)
57         amount = self.parse_amount(y)
58         return address, amount
59
60
61     def parse_amount(self, x):
62         p = pow(10, self.amount_edit.decimal_point())
63         return int( p * Decimal(x.strip()))
64
65
66     def parse_address(self, line):
67         r = line.strip()
68         m = re.match('^'+RE_ALIAS+'$', r)
69         address = m.group(2) if m else r
70         assert bitcoin.is_address(address)
71         return address
72
73
74     def check_text(self):
75         # filter out empty lines
76         lines = filter( lambda x: x, self.lines())
77         outputs = []
78         total = 0
79
80         if len(lines) == 1:
81             try:
82                 self.payto_address = self.parse_address(lines[0])
83             except:
84                 self.payto_address = None
85
86             if self.payto_address:
87                 print "unlock", self.payto_address
88                 self.unlock_amount()
89                 return
90
91         for line in lines:
92             try:
93                 to_address, amount = self.parse_address_and_amount(line)
94             except:
95                 continue
96                 
97             outputs.append((to_address, amount))
98             total += amount
99
100         self.outputs = outputs
101         self.payto_address = None
102
103         if total:
104             self.amount_edit.setAmount(total)
105         else:
106             self.amount_edit.setText("")
107
108         if total or len(lines)>1:
109             self.lock_amount()
110         else:
111             self.unlock_amount()
112
113
114
115     def get_outputs(self):
116
117         if self.payto_address:
118             
119             if not bitcoin.is_address(self.payto_address):
120                 QMessageBox.warning(self, _('Error'), _('Invalid Bitcoin Address') + ':\n' + to_address, _('OK'))
121                 return
122
123             try:
124                 amount = self.amount_edit.get_amount()
125             except Exception:
126                 QMessageBox.warning(self, _('Error'), _('Invalid Amount'), _('OK'))
127                 return
128
129             outputs = [(self.payto_address, amount)]
130             return outputs
131
132         return self.outputs
133
134
135     def lines(self):
136         return str(self.toPlainText()).split('\n')
137
138
139     def is_multiline(self):
140         return len(self.lines()) > 1
141
142
143     def update_size(self):
144         docHeight = self.document().size().height()
145         if self.heightMin <= docHeight <= self.heightMax:
146             self.setMinimumHeight(docHeight + 2)
147             self.setMaximumHeight(docHeight + 2)
148
149
150     def setCompleter(self, completer):
151         self.c = completer
152         self.c.setWidget(self)
153         self.c.setCompletionMode(QCompleter.PopupCompletion)
154         self.c.activated.connect(self.insertCompletion)
155
156
157     def insertCompletion(self, completion):
158         if self.c.widget() != self:
159             return
160         tc = self.textCursor()
161         extra = completion.length() - self.c.completionPrefix().length()
162         tc.movePosition(QTextCursor.Left)
163         tc.movePosition(QTextCursor.EndOfWord)
164         tc.insertText(completion.right(extra))
165         self.setTextCursor(tc)
166         self.check_text()
167  
168
169     def textUnderCursor(self):
170         tc = self.textCursor()
171         tc.select(QTextCursor.WordUnderCursor)
172         return tc.selectedText()
173
174
175     def keyPressEvent(self, e):
176         if self.c.popup().isVisible():
177             if e.key() in [Qt.Key_Enter, Qt.Key_Return]:
178                 e.ignore()
179                 return
180
181         if e.key() in [Qt.Key_Tab]:
182             e.ignore()
183             return
184
185         if e.key() in [Qt.Key_Down, Qt.Key_Up] and not self.is_multiline():
186             e.ignore()
187             return
188
189         isShortcut = (e.modifiers() and Qt.ControlModifier) and e.key() == Qt.Key_E
190
191         if not self.c or not isShortcut:
192             QTextEdit.keyPressEvent(self, e)
193             self.check_text()
194
195
196         ctrlOrShift = e.modifiers() and (Qt.ControlModifier or Qt.ShiftModifier)
197         if self.c is None or (ctrlOrShift and e.text().isEmpty()):
198             return
199
200         eow = QString("~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-=")
201         hasModifier = (e.modifiers() != Qt.NoModifier) and not ctrlOrShift;
202         completionPrefix = self.textUnderCursor()
203
204         if not isShortcut and (hasModifier or e.text().isEmpty() or completionPrefix.length() < 1 or eow.contains(e.text().right(1)) ):
205             self.c.popup().hide()
206             return
207
208         if completionPrefix != self.c.completionPrefix():
209             self.c.setCompletionPrefix(completionPrefix);
210             self.c.popup().setCurrentIndex(self.c.completionModel().index(0, 0))
211
212         cr = self.cursorRect()
213         cr.setWidth(self.c.popup().sizeHintForColumn(0) + self.c.popup().verticalScrollBar().sizeHint().width())
214         self.c.complete(cr)
215
216