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