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