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