Initial novacoin support
[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 from qrtextedit import QRTextEdit
22
23 import re
24 from decimal import Decimal
25 from electrum_nvc import bitcoin
26
27 RE_ADDRESS = '[1-9A-HJ-NP-Za-km-z]{26,}'
28 RE_ALIAS = '(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>'
29
30 frozen_style = "QWidget { background-color:none; border:none;}"
31 normal_style = "QPlainTextEdit { }"
32
33 class PayToEdit(QRTextEdit):
34
35     def __init__(self, win):
36         QRTextEdit.__init__(self)
37         self.win = win
38         self.amount_edit = win.amount_e
39         self.document().contentsChanged.connect(self.update_size)
40         self.heightMin = 0
41         self.heightMax = 150
42         self.c = None
43         self.textChanged.connect(self.check_text)
44         self.outputs = []
45         self.is_pr = False
46         self.scan_f = self.win.pay_from_URI
47         self.update_size()
48         self.payto_address = None
49
50     def lock_amount(self):
51         self.amount_edit.setFrozen(True)
52
53     def unlock_amount(self):
54         self.amount_edit.setFrozen(False)
55
56     def setFrozen(self, b):
57         self.setReadOnly(b)
58         self.setStyleSheet(frozen_style if b else normal_style)
59         self.button.setHidden(b)
60
61     def setGreen(self):
62         self.is_pr = True
63         self.setStyleSheet("QWidget { background-color:#80ff80;}")
64
65     def setExpired(self):
66         self.is_pr = True
67         self.setStyleSheet("QWidget { background-color:#ffcccc;}")
68
69     def parse_address_and_amount(self, line):
70         m = re.match('^OP_RETURN\s+"(.+)"$', line.strip())
71         if m:
72             type = 'op_return'
73             address = m.group(1)
74             amount = 0
75         else:
76             x, y = line.split(',')
77             type = 'address'
78             address = self.parse_address(x)
79             amount = self.parse_amount(y)
80         return type, address, amount
81
82
83     def parse_amount(self, x):
84         p = pow(10, self.amount_edit.decimal_point())
85         return int( p * Decimal(x.strip()))
86
87
88     def parse_address(self, line):
89         r = line.strip()
90         m = re.match('^'+RE_ALIAS+'$', r)
91         address = m.group(2) if m else r
92         assert bitcoin.is_address(address)
93         return address
94
95
96     def check_text(self):
97         if self.is_pr:
98             return
99
100         # filter out empty lines
101         lines = filter( lambda x: x, self.lines())
102         outputs = []
103         total = 0
104
105         self.payto_address = None
106
107         if len(lines) == 1:
108             try:
109                 self.payto_address = self.parse_address(lines[0])
110             except:
111                 pass
112
113             if self.payto_address:
114                 self.unlock_amount()
115                 return
116
117         for line in lines:
118             try:
119                 type, to_address, amount = self.parse_address_and_amount(line)
120             except:
121                 continue
122                 
123             outputs.append((type, to_address, amount))
124             total += amount
125
126         self.outputs = outputs
127         self.payto_address = None
128
129         if outputs:
130             self.amount_edit.setAmount(total)
131         else:
132             self.amount_edit.setText("")
133
134         self.amount_edit.textEdited.emit("")
135
136         if total or len(lines)>1:
137             self.lock_amount()
138         else:
139             self.unlock_amount()
140
141
142     def get_outputs(self):
143         if self.payto_address:
144             try:
145                 amount = self.amount_edit.get_amount()
146             except:
147                 amount = None
148
149             self.outputs = [('address', self.payto_address, amount)]
150
151         return self.outputs[:]
152
153
154     def lines(self):
155         return str(self.toPlainText()).split('\n')
156
157
158     def is_multiline(self):
159         return len(self.lines()) > 1
160
161
162     def update_size(self):
163         docHeight = self.document().size().height()
164         h = docHeight*17 + 11
165         if self.heightMin <= h <= self.heightMax:
166             self.setMinimumHeight(h)
167             self.setMaximumHeight(h)
168         self.verticalScrollBar().hide()
169
170
171     def setCompleter(self, completer):
172         self.c = completer
173         self.c.setWidget(self)
174         self.c.setCompletionMode(QCompleter.PopupCompletion)
175         self.c.activated.connect(self.insertCompletion)
176
177
178     def insertCompletion(self, completion):
179         if self.c.widget() != self:
180             return
181         tc = self.textCursor()
182         extra = completion.length() - self.c.completionPrefix().length()
183         tc.movePosition(QTextCursor.Left)
184         tc.movePosition(QTextCursor.EndOfWord)
185         tc.insertText(completion.right(extra))
186         self.setTextCursor(tc)
187  
188
189     def textUnderCursor(self):
190         tc = self.textCursor()
191         tc.select(QTextCursor.WordUnderCursor)
192         return tc.selectedText()
193
194
195     def keyPressEvent(self, e):
196         if self.isReadOnly():
197             return
198
199         if self.c.popup().isVisible():
200             if e.key() in [Qt.Key_Enter, Qt.Key_Return]:
201                 e.ignore()
202                 return
203
204         if e.key() in [Qt.Key_Tab]:
205             e.ignore()
206             return
207
208         if e.key() in [Qt.Key_Down, Qt.Key_Up] and not self.is_multiline():
209             e.ignore()
210             return
211
212         QPlainTextEdit.keyPressEvent(self, e)
213
214         ctrlOrShift = e.modifiers() and (Qt.ControlModifier or Qt.ShiftModifier)
215         if self.c is None or (ctrlOrShift and e.text().isEmpty()):
216             return
217
218         eow = QString("~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-=")
219         hasModifier = (e.modifiers() != Qt.NoModifier) and not ctrlOrShift;
220         completionPrefix = self.textUnderCursor()
221
222         if hasModifier or e.text().isEmpty() or completionPrefix.length() < 1 or eow.contains(e.text().right(1)):
223             self.c.popup().hide()
224             return
225
226         if completionPrefix != self.c.completionPrefix():
227             self.c.setCompletionPrefix(completionPrefix);
228             self.c.popup().setCurrentIndex(self.c.completionModel().index(0, 0))
229
230         cr = self.cursorRect()
231         cr.setWidth(self.c.popup().sizeHintForColumn(0) + self.c.popup().verticalScrollBar().sizeHint().width())
232         self.c.complete(cr)
233