parse payto text
[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 parse_line(self, line):
55         recipient, amount = line.split(',')
56         amount = Decimal(amount.strip())
57         recipient = recipient.strip()
58         m = re.match(RE_ALIAS, recipient)
59         to_address = m.group(2) if m else recipient
60         assert bitcoin.is_address(to_address)
61         return to_address, amount
62
63
64     def check_text(self):
65         # filter out empty lines
66         lines = filter( lambda x: x, self.lines())
67         outputs = []
68         total = 0
69
70         for line in lines:
71             try:
72                 to_address, amount = self.parse_line(line)
73             except:
74                 continue
75             outputs.append((to_address, amount))
76             total += amount
77
78         self.outputs = outputs
79
80         self.amount_edit.setText(str(total) if total else "")
81         if total or len(lines)>1:
82             self.lock_amount()
83         else:
84             self.unlock_amount()
85
86     def lines(self):
87         return str(self.toPlainText()).split('\n')
88
89
90     def is_multiline(self):
91         return len(self.lines()) > 1
92
93
94     def update_size(self):
95         docHeight = self.document().size().height()
96         if self.heightMin <= docHeight <= self.heightMax:
97             self.setMinimumHeight(docHeight + 2)
98             self.setMaximumHeight(docHeight + 2)
99
100
101     def setCompleter(self, completer):
102         self.c = completer
103         self.c.setWidget(self)
104         self.c.setCompletionMode(QCompleter.PopupCompletion)
105         self.c.activated.connect(self.insertCompletion)
106
107
108     def insertCompletion(self, completion):
109         if self.c.widget() != self:
110             return
111         tc = self.textCursor()
112         extra = completion.length() - self.c.completionPrefix().length()
113         tc.movePosition(QTextCursor.Left)
114         tc.movePosition(QTextCursor.EndOfWord)
115         tc.insertText(completion.right(extra))
116         self.setTextCursor(tc)
117         self.check_text()
118  
119
120     def textUnderCursor(self):
121         tc = self.textCursor()
122         tc.select(QTextCursor.WordUnderCursor)
123         return tc.selectedText()
124
125
126     def keyPressEvent(self, e):
127         if self.c.popup().isVisible():
128             if e.key() in [Qt.Key_Enter, Qt.Key_Return]:
129                 e.ignore()
130                 return
131
132         if e.key() in [Qt.Key_Tab]:
133             e.ignore()
134             return
135
136         if e.key() in [Qt.Key_Down, Qt.Key_Up] and not self.is_multiline():
137             e.ignore()
138             return
139
140         isShortcut = (e.modifiers() and Qt.ControlModifier) and e.key() == Qt.Key_E
141
142         if not self.c or not isShortcut:
143             QTextEdit.keyPressEvent(self, e)
144             self.check_text()
145
146
147         ctrlOrShift = e.modifiers() and (Qt.ControlModifier or Qt.ShiftModifier)
148         if self.c is None or (ctrlOrShift and e.text().isEmpty()):
149             return
150
151         eow = QString("~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-=")
152         hasModifier = (e.modifiers() != Qt.NoModifier) and not ctrlOrShift;
153         completionPrefix = self.textUnderCursor()
154
155         if not isShortcut and (hasModifier or e.text().isEmpty() or completionPrefix.length() < 1 or eow.contains(e.text().right(1)) ):
156             self.c.popup().hide()
157             return
158
159         if completionPrefix != self.c.completionPrefix():
160             self.c.setCompletionPrefix(completionPrefix);
161             self.c.popup().setCurrentIndex(self.c.completionModel().index(0, 0))
162
163         cr = self.cursorRect()
164         cr.setWidth(self.c.popup().sizeHintForColumn(0) + self.c.popup().verticalScrollBar().sizeHint().width())
165         self.c.complete(cr)
166
167