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