Build on Qt 4.4 again
[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   // Workaround the fact that Qt < 4.5 doesn't know InsertLineSeparator yet
205 #if QT_VERSION >= 0x040500
206   if(event == QKeySequence::InsertLineSeparator) {
207 #else
208
209 # ifdef Q_WS_MAC
210   if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::META) {
211 # else
212   if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::SHIFT) {
213 # endif
214 #endif
215
216     if(_mode == SingleLine)
217       return;
218 #ifdef HAVE_KDE
219     KTextEdit::keyPressEvent(event);
220 #else
221     QTextEdit::keyPressEvent(event);
222 #endif
223     return;
224   }
225
226   switch(event->key()) {
227   case Qt::Key_Up: {
228     event->accept();
229     if(!(event->modifiers() & Qt::ControlModifier)) {
230       int pos = textCursor().position();
231       moveCursor(QTextCursor::Up);
232       if(pos == textCursor().position()) // already on top line -> history
233         historyMoveBack();
234     } else
235       historyMoveBack();
236     break;
237   }
238
239   case Qt::Key_Down: {
240     event->accept();
241     if(!(event->modifiers() & Qt::ControlModifier)) {
242       int pos = textCursor().position();
243       moveCursor(QTextCursor::Down);
244       if(pos == textCursor().position()) // already on bottom line -> history
245         historyMoveForward();
246     } else
247       historyMoveForward();
248     break;
249   }
250
251   case Qt::Key_Return:
252   case Qt::Key_Enter:
253   case Qt::Key_Select:
254     event->accept();
255     on_returnPressed();
256     break;
257
258   // We don't want to have the tab key react if no completer is installed 
259   case Qt::Key_Tab:
260     event->accept();
261     break;
262
263   default:
264 #ifdef HAVE_KDE
265     KTextEdit::keyPressEvent(event);
266 #else
267     QTextEdit::keyPressEvent(event);
268 #endif
269   }
270 }
271
272 void MultiLineEdit::on_returnPressed() {
273   if(!text().isEmpty()) {
274     foreach(const QString &line, text().split('\n', QString::SkipEmptyParts)) {
275       if(line.isEmpty())
276         continue;
277       addToHistory(line);
278       emit textEntered(line);
279     }
280     reset();
281     tempHistory.clear();
282   }
283 }
284
285 void MultiLineEdit::on_textChanged() {
286   QString newText = text();
287   newText.replace("\r\n", "\n");
288   newText.replace('\r', '\n');
289   if(_mode == SingleLine)
290     newText.replace('\n', ' ');
291
292   if(document()->size().height() != _lastDocumentHeight) {
293     _lastDocumentHeight = document()->size().height();
294     on_documentHeightChanged(_lastDocumentHeight);
295   }
296   updateGeometry();
297 }
298
299 void MultiLineEdit::on_documentHeightChanged(qreal) {
300   updateScrollBars();
301 }
302
303 void MultiLineEdit::reset() {
304   // every time the MultiLineEdit is cleared we also reset history index
305   idx = history.count();
306   clear();
307   QTextBlockFormat format = textCursor().blockFormat();
308   format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
309   textCursor().setBlockFormat(format);
310 }
311
312 void MultiLineEdit::showHistoryEntry() {
313   // if the user changed the history, display the changed line
314   setPlainText(tempHistory.contains(idx) ? tempHistory[idx] : history[idx]);
315   QTextCursor cursor = textCursor();
316   QTextBlockFormat format = cursor.blockFormat();
317   format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
318   cursor.setBlockFormat(format);
319   cursor.movePosition(QTextCursor::End);
320   setTextCursor(cursor);
321 }