don't show qrcode button in payto if it is a payment request
[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         self.payto_address = None
51
52     def lock_amount(self):
53         self.amount_edit.setFrozen(True)
54
55     def unlock_amount(self):
56         self.amount_edit.setFrozen(False)
57
58     def setFrozen(self, b):
59         self.setReadOnly(b)
60         self.setStyleSheet(frozen_style if b else normal_style)
61         self.button.setHidden(b)
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         self.amount_edit.textEdited.emit("")
130
131         if total or len(lines)>1:
132             self.lock_amount()
133         else:
134             self.unlock_amount()
135
136
137     def get_outputs(self):
138         if self.payto_address:
139             try:
140                 amount = self.amount_edit.get_amount()
141             except:
142                 amount = None
143
144             self.outputs = [(self.payto_address, amount)]
145
146         return self.outputs[:]
147
148
149     def lines(self):
150         return str(self.toPlainText()).split('\n')
151
152
153     def is_multiline(self):
154         return len(self.lines()) > 1
155
156
157     def update_size(self):
158         docHeight = self.document().size().height()
159         if self.heightMin <= docHeight <= self.heightMax:
160             self.setMinimumHeight(docHeight + 2)
161             self.setMaximumHeight(docHeight + 2)
162
163
164     def setCompleter(self, completer):
165         self.c = completer
166         self.c.setWidget(self)
167         self.c.setCompletionMode(QCompleter.PopupCompletion)
168         self.c.activated.connect(self.insertCompletion)
169
170
171     def insertCompletion(self, completion):
172         if self.c.widget() != self:
173             return
174         tc = self.textCursor()
175         extra = completion.length() - self.c.completionPrefix().length()
176         tc.movePosition(QTextCursor.Left)
177         tc.movePosition(QTextCursor.EndOfWord)
178         tc.insertText(completion.right(extra))
179         self.setTextCursor(tc)
180  
181
182     def textUnderCursor(self):
183         tc = self.textCursor()
184         tc.select(QTextCursor.WordUnderCursor)
185         return tc.selectedText()
186
187
188     def keyPressEvent(self, e):
189         if self.isReadOnly():
190             return
191
192         if self.c.popup().isVisible():
193             if e.key() in [Qt.Key_Enter, Qt.Key_Return]:
194                 e.ignore()
195                 return
196
197         if e.key() in [Qt.Key_Tab]:
198             e.ignore()
199             return
200
201         if e.key() in [Qt.Key_Down, Qt.Key_Up] and not self.is_multiline():
202             e.ignore()
203             return
204
205         isShortcut = (e.modifiers() and Qt.ControlModifier) and e.key() == Qt.Key_E
206
207         if not self.c or not isShortcut:
208             QTextEdit.keyPressEvent(self, e)
209
210
211         ctrlOrShift = e.modifiers() and (Qt.ControlModifier or Qt.ShiftModifier)
212         if self.c is None or (ctrlOrShift and e.text().isEmpty()):
213             return
214
215         eow = QString("~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-=")
216         hasModifier = (e.modifiers() != Qt.NoModifier) and not ctrlOrShift;
217         completionPrefix = self.textUnderCursor()
218
219         if not isShortcut and (hasModifier or e.text().isEmpty() or completionPrefix.length() < 1 or eow.contains(e.text().right(1)) ):
220             self.c.popup().hide()
221             return
222
223         if completionPrefix != self.c.completionPrefix():
224             self.c.setCompletionPrefix(completionPrefix);
225             self.c.popup().setCurrentIndex(self.c.completionModel().index(0, 0))
226
227         cr = self.cursorRect()
228         cr.setWidth(self.c.popup().sizeHintForColumn(0) + self.c.popup().verticalScrollBar().sizeHint().width())
229         self.c.complete(cr)
230
231