Introduce multi-line editing for the inputline
[quassel.git] / src / uisupport / multilineedit.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005/06 by the Quassel Project                          *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
19  ***************************************************************************/
20
21 #include <QApplication>
22 #include <QMenu>
23 #include <QMessageBox>
24 #include <QScrollBar>
25
26 #include "bufferview.h"
27 #include "graphicalui.h"
28 #include "multilineedit.h"
29 #include "tabcompleter.h"
30
31 const int leftMargin = 3;
32
33 MultiLineEdit::MultiLineEdit(QWidget *parent)
34   :
35 #ifdef HAVE_KDE
36     KTextEdit(parent),
37 #else
38     QTextEdit(parent),
39 #endif
40     idx(0),
41     _mode(SingleLine),
42     _wrapMode(QTextOption::NoWrap),
43     _numLines(1),
44     _minHeight(1),
45     _maxHeight(5),
46     _scrollBarsEnabled(true),
47     _lastDocumentHeight(-1)
48 {
49 #if QT_VERSION >= 0x040500
50   document()->setDocumentMargin(0); // new in Qt 4.5 and we really don't want it here
51 #endif
52
53   setAcceptRichText(false);
54   setWordWrapMode(QTextOption::NoWrap);
55 #ifdef HAVE_KDE
56   enableFindReplace(false);
57 #endif
58
59   setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
60   setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
61
62   setMode(SingleLine);
63
64   reset();
65
66   connect(this, SIGNAL(textChanged()), this, SLOT(on_textChanged()));
67 }
68
69 MultiLineEdit::~MultiLineEdit() {
70 }
71
72 void MultiLineEdit::setCustomFont(const QFont &font) {
73   setFont(font);
74   updateGeometry();
75 }
76
77 void MultiLineEdit::setMode(Mode mode) {
78   if(mode == _mode)
79     return;
80
81   _mode = mode;
82 }
83
84 void MultiLineEdit::setWrapMode(QTextOption::WrapMode wrapMode) {
85   if(_wrapMode == wrapMode)
86     return;
87
88   _wrapMode = wrapMode;
89   setWordWrapMode(wrapMode);
90 }
91
92 void MultiLineEdit::setMinHeight(int lines) {
93   if(lines == _minHeight)
94     return;
95
96   _minHeight = lines;
97   updateGeometry();
98 }
99
100 void MultiLineEdit::setMaxHeight(int lines) {
101   if(lines == _maxHeight)
102     return;
103
104   _maxHeight = lines;
105   updateGeometry();
106 }
107
108 void MultiLineEdit::enableScrollBars(bool enable) {
109   if(_scrollBarsEnabled == enable)
110     return;
111
112   _scrollBarsEnabled = enable;
113   if(enable && numLines() > 1) {
114     // the vertical scrollbar must be enabled/disabled manually;
115     // ScrollBarAsNeeded leads to flicker because of the dynamic widget resize
116     setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
117   } else {
118     setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
119   }
120   updateScrollBars();
121 }
122
123 void MultiLineEdit::updateScrollBars() {
124   QFontMetrics fm(font());
125   int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
126   if(_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
127     setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
128   else
129     setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
130 }
131
132 void MultiLineEdit::resizeEvent(QResizeEvent *event) {
133   updateScrollBars();
134   QTextEdit::resizeEvent(event);
135 }
136
137 QSize MultiLineEdit::sizeHint() const {
138   QFontMetrics fm(font());
139   int _minPixelHeight = fm.lineSpacing() * _minHeight;
140   int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
141
142   // use the style to determine a decent size
143   int h = qMin(qMax((int)document()->size().height(), _minPixelHeight), _maxPixelHeight) + 2 * frameWidth();
144   QStyleOptionFrameV2 opt;
145   opt.initFrom(this);
146   opt.rect = QRect(0, 0, 100, h);
147   opt.lineWidth = lineWidth();
148   opt.midLineWidth = midLineWidth();
149   opt.state |= QStyle::State_Sunken;
150   QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), this);
151   return s;
152 }
153
154 QSize MultiLineEdit::minimumSizeHint() const {
155   return sizeHint();
156 }
157
158 void MultiLineEdit::historyMoveBack() {
159   addToHistory(text(), true);
160
161   if(idx > 0) {
162     idx--;
163     showHistoryEntry();
164   }
165 }
166
167 void MultiLineEdit::historyMoveForward() {
168   addToHistory(text(), true);
169
170   if(idx < history.count()) {
171     idx++;
172     if(idx < history.count() || tempHistory.contains(idx)) // tempHistory might have an entry for idx == history.count() + 1
173       showHistoryEntry();
174     else
175       reset();              // equals clear() in this case
176   }
177 }
178
179 bool MultiLineEdit::addToHistory(const QString &text, bool temporary) {
180   if(text.isEmpty())
181     return false;
182
183   Q_ASSERT(0 <= idx && idx <= history.count());
184
185   if(temporary) {
186     // if an entry of the history is changed, we remember it and show it again at this
187     // position until a line was actually sent
188     // sent lines get appended to the history
189     if(history.isEmpty() || text != history[idx - (int)(idx == history.count())]) {
190       tempHistory[idx] = text;
191       return true;
192     }
193   } else {
194     if(history.isEmpty() || text != history.last()) {
195       history << text;
196       tempHistory.clear();
197       return true;
198     }
199   }
200   return false;
201 }
202
203 void MultiLineEdit::keyPressEvent(QKeyEvent *event) {
204   if(event == QKeySequence::InsertLineSeparator) {
205     if(_mode == SingleLine)
206       return;
207 #ifdef HAVE_KDE
208     KTextEdit::keyPressEvent(event);
209 #else
210     QTextEdit::keyPressEvent(event);
211 #endif
212     return;
213   }
214
215   switch(event->key()) {
216   case Qt::Key_Up: {
217     event->accept();
218     if(!(event->modifiers() & Qt::ControlModifier)) {
219       int pos = textCursor().position();
220       moveCursor(QTextCursor::Up);
221       if(pos == textCursor().position()) // already on top line -> history
222         historyMoveBack();
223     } else
224       historyMoveBack();
225     break;
226   }
227
228   case Qt::Key_Down: {
229     event->accept();
230     if(!(event->modifiers() & Qt::ControlModifier)) {
231       int pos = textCursor().position();
232       moveCursor(QTextCursor::Down);
233       if(pos == textCursor().position()) // already on bottom line -> history
234         historyMoveForward();
235     } else
236       historyMoveForward();
237     break;
238   }
239
240   case Qt::Key_Return:
241   case Qt::Key_Enter:
242   case Qt::Key_Select:
243     event->accept();
244     on_returnPressed();
245     break;
246
247   // We don't want to have the tab key react if no completer is installed 
248   case Qt::Key_Tab:
249     event->accept();
250     break;
251
252   default:
253 #ifdef HAVE_KDE
254     KTextEdit::keyPressEvent(event);
255 #else
256     QTextEdit::keyPressEvent(event);
257 #endif
258   }
259 }
260
261 void MultiLineEdit::on_returnPressed() {
262   if(!text().isEmpty()) {
263     foreach(const QString &line, text().split('\n', QString::SkipEmptyParts)) {
264       if(line.isEmpty())
265         continue;
266       addToHistory(line);
267       emit textEntered(line);
268     }
269     reset();
270     tempHistory.clear();
271   }
272 }
273
274 void MultiLineEdit::on_textChanged() {
275   QString newText = text();
276   newText.replace("\r\n", "\n");
277   newText.replace('\r', '\n');
278   if(_mode == SingleLine)
279     newText.replace('\n', ' ');
280
281   if(document()->size().height() != _lastDocumentHeight) {
282     _lastDocumentHeight = document()->size().height();
283     on_documentHeightChanged(_lastDocumentHeight);
284   }
285   updateGeometry();
286 }
287
288 void MultiLineEdit::on_documentHeightChanged(qreal) {
289   updateScrollBars();
290 }
291
292 void MultiLineEdit::reset() {
293   // every time the MultiLineEdit is cleared we also reset history index
294   idx = history.count();
295   clear();
296   QTextBlockFormat format = textCursor().blockFormat();
297   format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
298   textCursor().setBlockFormat(format);
299 }
300
301 void MultiLineEdit::showHistoryEntry() {
302   // if the user changed the history, display the changed line
303   setPlainText(tempHistory.contains(idx) ? tempHistory[idx] : history[idx]);
304   QTextCursor cursor = textCursor();
305   QTextBlockFormat format = cursor.blockFormat();
306   format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
307   cursor.setBlockFormat(format);
308   cursor.movePosition(QTextCursor::End);
309   setTextCursor(cursor);
310 }