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