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