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