Store the type of the current tab completion (user or channel) in the TabCompleter...
[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     _singleLine(true),
43     _minHeight(1),
44     _maxHeight(5),
45     _scrollBarsEnabled(true),
46     _lastDocumentHeight(-1)
47 {
48 #if QT_VERSION >= 0x040500
49   document()->setDocumentMargin(0); // new in Qt 4.5 and we really don't want it here
50 #endif
51
52   setAcceptRichText(false);
53 #ifdef HAVE_KDE
54   enableFindReplace(false);
55 #endif
56
57   setMode(SingleLine);
58   setWordWrapEnabled(false);
59   reset();
60
61   connect(this, SIGNAL(textChanged()), this, SLOT(on_textChanged()));
62 }
63
64 MultiLineEdit::~MultiLineEdit() {
65 }
66
67 void MultiLineEdit::setCustomFont(const QFont &font) {
68   setFont(font);
69   updateSizeHint();
70 }
71
72 void MultiLineEdit::setMode(Mode mode) {
73   if(mode == _mode)
74     return;
75
76   _mode = mode;
77 }
78
79 void MultiLineEdit::setMinHeight(int lines) {
80   if(lines == _minHeight)
81     return;
82
83   _minHeight = lines;
84   updateSizeHint();
85 }
86
87 void MultiLineEdit::setMaxHeight(int lines) {
88   if(lines == _maxHeight)
89     return;
90
91   _maxHeight = lines;
92   updateSizeHint();
93 }
94
95 void MultiLineEdit::setScrollBarsEnabled(bool enable) {
96   if(_scrollBarsEnabled == enable)
97     return;
98
99   _scrollBarsEnabled = enable;
100   updateScrollBars();
101 }
102
103 void MultiLineEdit::updateScrollBars() {
104   QFontMetrics fm(font());
105   int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
106   if(_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
107     setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
108   else
109     setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
110
111   if(!_scrollBarsEnabled || isSingleLine())
112     setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
113   else
114     setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
115 }
116
117 void MultiLineEdit::resizeEvent(QResizeEvent *event) {
118   QTextEdit::resizeEvent(event);
119   updateSizeHint();
120   updateScrollBars();
121 }
122
123 void MultiLineEdit::updateSizeHint() {
124   QFontMetrics fm(font());
125   int minPixelHeight = fm.lineSpacing() * _minHeight;
126   int maxPixelHeight = fm.lineSpacing() * _maxHeight;
127   int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
128
129   // use the style to determine a decent size
130   int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
131   QStyleOptionFrameV2 opt;
132   opt.initFrom(this);
133   opt.rect = QRect(0, 0, 100, h);
134   opt.lineWidth = lineWidth();
135   opt.midLineWidth = midLineWidth();
136   opt.state |= QStyle::State_Sunken;
137   QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), this);
138   if(s != _sizeHint) {
139     _sizeHint = s;
140     updateGeometry();
141   }
142 }
143
144 QSize MultiLineEdit::sizeHint() const {
145   if(!_sizeHint.isValid()) {
146     MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
147     that->updateSizeHint();
148   }
149   return _sizeHint;
150 }
151
152 QSize MultiLineEdit::minimumSizeHint() const {
153   return sizeHint();
154 }
155
156 void MultiLineEdit::setSpellCheckEnabled(bool enable) {
157 #ifdef HAVE_KDE
158   setCheckSpellingEnabled(enable);
159 #else
160   Q_UNUSED(enable)
161 #endif
162 }
163
164 void MultiLineEdit::setWordWrapEnabled(bool enable) {
165   setLineWrapMode(enable? WidgetWidth : NoWrap);
166   updateSizeHint();
167 }
168
169 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *) {
170   _pasteProtectionEnabled = enable;
171 }
172
173 void MultiLineEdit::historyMoveBack() {
174   addToHistory(text(), true);
175
176   if(idx > 0) {
177     idx--;
178     showHistoryEntry();
179   }
180 }
181
182 void MultiLineEdit::historyMoveForward() {
183   addToHistory(text(), true);
184
185   if(idx < history.count()) {
186     idx++;
187     if(idx < history.count() || tempHistory.contains(idx)) // tempHistory might have an entry for idx == history.count() + 1
188       showHistoryEntry();
189     else
190       reset();              // equals clear() in this case
191   } else {
192     addToHistory(text());
193     reset();
194   }
195 }
196
197 bool MultiLineEdit::addToHistory(const QString &text, bool temporary) {
198   if(text.isEmpty())
199     return false;
200
201   Q_ASSERT(0 <= idx && idx <= history.count());
202
203   if(temporary) {
204     // if an entry of the history is changed, we remember it and show it again at this
205     // position until a line was actually sent
206     // sent lines get appended to the history
207     if(history.isEmpty() || text != history[idx - (int)(idx == history.count())]) {
208       tempHistory[idx] = text;
209       return true;
210     }
211   } else {
212     if(history.isEmpty() || text != history.last()) {
213       history << text;
214       tempHistory.clear();
215       return true;
216     }
217   }
218   return false;
219 }
220
221 void MultiLineEdit::keyPressEvent(QKeyEvent *event) {
222   // Workaround the fact that Qt < 4.5 doesn't know InsertLineSeparator yet
223 #if QT_VERSION >= 0x040500
224   if(event == QKeySequence::InsertLineSeparator) {
225 #else
226
227 # ifdef Q_WS_MAC
228   if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::META) {
229 # else
230   if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::SHIFT) {
231 # endif
232 #endif
233
234     if(_mode == SingleLine) {
235       event->accept();
236       on_returnPressed();
237       return;
238     }
239 #ifdef HAVE_KDE
240     KTextEdit::keyPressEvent(event);
241 #else
242     QTextEdit::keyPressEvent(event);
243 #endif
244     return;
245   }
246
247   switch(event->key()) {
248   case Qt::Key_Up:
249     if(event->modifiers() & Qt::ShiftModifier)
250       break;
251     {
252       event->accept();
253       if(!(event->modifiers() & Qt::ControlModifier)) {
254         int pos = textCursor().position();
255         moveCursor(QTextCursor::Up);
256         if(pos == textCursor().position()) // already on top line -> history
257           historyMoveBack();
258       } else
259         historyMoveBack();
260       return;
261     }
262
263   case Qt::Key_Down:
264     if(event->modifiers() & Qt::ShiftModifier)
265       break;
266     {
267       event->accept();
268       if(!(event->modifiers() & Qt::ControlModifier)) {
269         int pos = textCursor().position();
270         moveCursor(QTextCursor::Down);
271         if(pos == textCursor().position()) // already on bottom line -> history
272           historyMoveForward();
273       } else
274         historyMoveForward();
275       return;
276     }
277
278   case Qt::Key_Return:
279   case Qt::Key_Enter:
280   case Qt::Key_Select:
281     event->accept();
282     on_returnPressed();
283     return;
284
285   // We don't want to have the tab key react even if no completer is installed
286   case Qt::Key_Tab:
287     event->accept();
288     return;
289
290   default:
291     ;
292   }
293
294
295 #ifdef HAVE_KDE
296   KTextEdit::keyPressEvent(event);
297 #else
298   QTextEdit::keyPressEvent(event);
299 #endif
300 }
301
302 void MultiLineEdit::on_returnPressed() {
303   on_returnPressed(text());
304 }
305
306 void MultiLineEdit::on_returnPressed(const QString & text) {
307   if(!text.isEmpty()) {
308     foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
309       if(line.isEmpty())
310         continue;
311       addToHistory(line);
312       emit textEntered(line);
313     }
314     reset();
315     tempHistory.clear();
316   } else {
317     emit noTextEntered();
318   }
319 }
320
321 void MultiLineEdit::on_textChanged() {
322   QString newText = text();
323   newText.replace("\r\n", "\n");
324   newText.replace('\r', '\n');
325   if(_mode == SingleLine) {
326     if(!pasteProtectionEnabled())
327       newText.replace('\n', ' ');
328     else if(newText.contains('\n')) {
329       QStringList lines = newText.split('\n', QString::SkipEmptyParts);
330       clear();
331
332       if(lines.count() >= 4) {
333         QString msg = tr("Do you really want to paste %n lines?", "", lines.count());
334         msg += "<p>";
335         for(int i = 0; i < 4; i++) {
336           msg += Qt::escape(lines[i].left(40));
337           if(lines[i].count() > 40)
338             msg += "...";
339           msg += "<br />";
340         }
341         msg += "...</p>";
342         QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
343         question.setDefaultButton(QMessageBox::No);
344 #ifdef Q_WS_MAC
345         question.setWindowFlags(question.windowFlags() | Qt::Sheet);
346 #endif
347         if(question.exec() != QMessageBox::Yes)
348           return;
349       }
350
351       foreach(QString line, lines) {
352         clear();
353         insert(line);
354         on_returnPressed();
355       }
356     }
357   }
358
359   _singleLine = (newText.indexOf('\n') < 0);
360
361   if(document()->size().height() != _lastDocumentHeight) {
362     _lastDocumentHeight = document()->size().height();
363     on_documentHeightChanged(_lastDocumentHeight);
364   }
365   updateSizeHint();
366   ensureCursorVisible();
367 }
368
369 void MultiLineEdit::on_documentHeightChanged(qreal) {
370   updateScrollBars();
371 }
372
373 void MultiLineEdit::reset() {
374   // every time the MultiLineEdit is cleared we also reset history index
375   idx = history.count();
376   clear();
377   QTextBlockFormat format = textCursor().blockFormat();
378   format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
379   textCursor().setBlockFormat(format);
380   updateScrollBars();
381 }
382
383 void MultiLineEdit::showHistoryEntry() {
384   // if the user changed the history, display the changed line
385   setPlainText(tempHistory.contains(idx) ? tempHistory[idx] : history[idx]);
386   QTextCursor cursor = textCursor();
387   QTextBlockFormat format = cursor.blockFormat();
388   format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
389   cursor.setBlockFormat(format);
390   cursor.movePosition(QTextCursor::End);
391   setTextCursor(cursor);
392   updateScrollBars();
393 }