new widget: QRTextEdit
[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
49     def qr_input(self):
50         from electrum.plugins import run_hook
51         run_hook('scan_qr_hook', lambda x: self.win.pay_from_URI(x))
52
53     def lock_amount(self):
54         self.amount_edit.setFrozen(True)
55
56     def unlock_amount(self):
57         self.amount_edit.setFrozen(False)
58
59     def setFrozen(self, b):
60         self.setReadOnly(b)
61         self.setStyleSheet(frozen_style if b else normal_style)
62
63     def setGreen(self):
64         self.is_pr = True
65         self.setStyleSheet("QWidget { background-color:#80ff80;}")
66
67     def setExpired(self):
68         self.is_pr = True
69         self.setStyleSheet("QWidget { background-color:#ffcccc;}")
70
71     def parse_address_and_amount(self, line):
72         x, y = line.split(',')
73         address = self.parse_address(x)
74         amount = self.parse_amount(y)
75         return address, amount
76
77
78     def parse_amount(self, x):
79         p = pow(10, self.amount_edit.decimal_point())
80         return int( p * Decimal(x.strip()))
81
82
83     def parse_address(self, line):
84         r = line.strip()
85         m = re.match('^'+RE_ALIAS+'$', r)
86         address = m.group(2) if m else r
87         assert bitcoin.is_address(address)
88         return address
89
90
91     def check_text(self):
92         if self.is_pr:
93             return
94
95         # filter out empty lines
96         lines = filter( lambda x: x, self.lines())
97         outputs = []
98         total = 0
99
100         self.payto_address = None
101
102         if len(lines) == 1:
103             try:
104                 self.payto_address = self.parse_address(lines[0])
105             except:
106                 pass
107
108             if self.payto_address:
109                 self.unlock_amount()
110                 return
111
112         for line in lines:
113             try:
114                 to_address, amount = self.parse_address_and_amount(line)
115             except:
116                 continue
117                 
118             outputs.append((to_address, amount))
119             total += amount
120
121         self.outputs = outputs
122         self.payto_address = None
123
124         if total:
125             self.amount_edit.setAmount(total)
126         else:
127             self.amount_edit.setText("")
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