1 /*
2    Drawpile - a collaborative drawing program.
3 
4    Copyright (C) 2013-2014 Calle Laakkonen
5 
6    Drawpile 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    Drawpile 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 Drawpile.  If not, see <http://www.gnu.org/licenses/>.
18 */
19 #include <QKeyEvent>
20 
21 #include "chatlineedit.h"
22 
ChatLineEdit(QWidget * parent)23 ChatLineEdit::ChatLineEdit(QWidget *parent) :
24 	QLineEdit(parent), _historypos(0)
25 {
26 }
27 
pushHistory(const QString & text)28 void ChatLineEdit::pushHistory(const QString &text)
29 {
30 	// Disallow consecutive duplicates
31 	if(!_history.isEmpty() && _history.last() == text)
32 		return;
33 
34 	// Add to history list while limiting its size
35 	_history.append(text);
36 	if(_history.count() > 50)
37 		_history.removeFirst();
38 
39 	++_historypos;
40 }
41 
keyPressEvent(QKeyEvent * event)42 void ChatLineEdit::keyPressEvent(QKeyEvent *event)
43 {
44 	if(event->key() == Qt::Key_Up) {
45 		if(_historypos>0) {
46 			if(_historypos==_history.count())
47 				_current = text();
48 			--_historypos;
49 			setText(_history[_historypos]);
50 		}
51 	} else if(event->key() == Qt::Key_Down) {
52 		if(_historypos<_history.count()-1) {
53 			++_historypos;
54 			setText(_history[_historypos]);
55 		} else if(_historypos==_history.count()-1) {
56 			++_historypos;
57 			setText(_current);
58 		}
59 	} else if(event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) {
60 		QString txt = trimmedText();
61 		if(!txt.isEmpty()) {
62 			pushHistory(txt);
63 			_historypos = _history.count();
64 			setText(QString());
65 			emit returnPressed(txt);
66 		}
67 	} else {
68 		QLineEdit::keyPressEvent(event);
69 	}
70 }
71 
trimmedText() const72 QString ChatLineEdit::trimmedText() const
73 {
74 	QString str = text();
75 
76 	// Remove trailing whitespace
77 	int chop = str.length();
78 	while(chop>0 && str.at(chop-1).isSpace())
79 		--chop;
80 
81 	if(chop==0)
82 		return QString();
83 	str.truncate(chop);
84 
85 	return str;
86 }
87