Update cs.ts
[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   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::enableScrollBars(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::enableSpellCheck(bool enable) {
155 #ifdef HAVE_KDE
156   setCheckSpellingEnabled(enable);
157 #else
158   Q_UNUSED(enable)
159 #endif
160 }
161
162 void MultiLineEdit::historyMoveBack() {
163   addToHistory(text(), true);
164
165   if(idx > 0) {
166     idx--;
167     showHistoryEntry();
168   }
169 }
170
171 void MultiLineEdit::historyMoveForward() {
172   addToHistory(text(), true);
173
174   if(idx < history.count()) {
175     idx++;
176     if(idx < history.count() || tempHistory.contains(idx)) // tempHistory might have an entry for idx == history.count() + 1
177       showHistoryEntry();
178     else
179       reset();              // equals clear() in this case
180   } else {
181     addToHistory(text());
182     reset();
183   }
184 }
185
186 bool MultiLineEdit::addToHistory(const QString &text, bool temporary) {
187   if(text.isEmpty())
188     return false;
189
190   Q_ASSERT(0 <= idx && idx <= history.count());
191
192   if(temporary) {
193     // if an entry of the history is changed, we remember it and show it again at this
194     // position until a line was actually sent
195     // sent lines get appended to the history
196     if(history.isEmpty() || text != history[idx - (int)(idx == history.count())]) {
197       tempHistory[idx] = text;
198       return true;
199     }
200   } else {
201     if(history.isEmpty() || text != history.last()) {
202       history << text;
203       tempHistory.clear();
204       return true;
205     }
206   }
207   return false;
208 }
209
210 void MultiLineEdit::keyPressEvent(QKeyEvent *event) {
211   // Workaround the fact that Qt < 4.5 doesn't know InsertLineSeparator yet
212 #if QT_VERSION >= 0x040500
213   if(event == QKeySequence::InsertLineSeparator) {
214 #else
215
216 # ifdef Q_WS_MAC
217   if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::META) {
218 # else
219   if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::SHIFT) {
220 # endif
221 #endif
222
223     if(_mode == SingleLine)
224       return;
225 #ifdef HAVE_KDE
226     KTextEdit::keyPressEvent(event);
227 #else
228     QTextEdit::keyPressEvent(event);
229 #endif
230     return;
231   }
232
233   switch(event->key()) {
234   case Qt::Key_Up:
235     if(event->modifiers() & Qt::ShiftModifier)
236       break;
237     {
238       event->accept();
239       if(!(event->modifiers() & Qt::ControlModifier)) {
240         int pos = textCursor().position();
241         moveCursor(QTextCursor::Up);
242         if(pos == textCursor().position()) // already on top line -> history
243           historyMoveBack();
244       } else
245         historyMoveBack();
246       return;
247     }
248
249   case Qt::Key_Down:
250     if(event->modifiers() & Qt::ShiftModifier)
251       break;
252     {
253       event->accept();
254       if(!(event->modifiers() & Qt::ControlModifier)) {
255         int pos = textCursor().position();
256         moveCursor(QTextCursor::Down);
257         if(pos == textCursor().position()) // already on bottom line -> history
258           historyMoveForward();
259       } else
260         historyMoveForward();
261       return;
262     }
263
264   case Qt::Key_Return:
265   case Qt::Key_Enter:
266   case Qt::Key_Select:
267     event->accept();
268     on_returnPressed();
269     return;
270
271   // We don't want to have the tab key react even if no completer is installed
272   case Qt::Key_Tab:
273     event->accept();
274     return;
275
276   default:
277     ;
278   }
279
280
281 #ifdef HAVE_KDE
282   KTextEdit::keyPressEvent(event);
283 #else
284   QTextEdit::keyPressEvent(event);
285 #endif
286 }
287
288 void MultiLineEdit::on_returnPressed() {
289   if(!text().isEmpty()) {
290     foreach(const QString &line, text().split('\n', QString::SkipEmptyParts)) {
291       if(line.isEmpty())
292         continue;
293       addToHistory(line);
294       emit textEntered(line);
295     }
296     reset();
297     tempHistory.clear();
298   }
299 }
300
301 void MultiLineEdit::on_textChanged() {
302   QString newText = text();
303   newText.replace("\r\n", "\n");
304   newText.replace('\r', '\n');
305   if(_mode == SingleLine)
306     newText.replace('\n', ' ');
307
308   _singleLine = (newText.indexOf('\n') < 0);
309
310   if(document()->size().height() != _lastDocumentHeight) {
311     _lastDocumentHeight = document()->size().height();
312     on_documentHeightChanged(_lastDocumentHeight);
313   }
314   computeSizeHint();
315 }
316
317 void MultiLineEdit::on_documentHeightChanged(qreal) {
318   updateScrollBars();
319 }
320
321 void MultiLineEdit::reset() {
322   // every time the MultiLineEdit is cleared we also reset history index
323   idx = history.count();
324   clear();
325   QTextBlockFormat format = textCursor().blockFormat();
326   format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
327   textCursor().setBlockFormat(format);
328   updateScrollBars();
329 }
330
331 void MultiLineEdit::showHistoryEntry() {
332   // if the user changed the history, display the changed line
333   setPlainText(tempHistory.contains(idx) ? tempHistory[idx] : history[idx]);
334   QTextCursor cursor = textCursor();
335   QTextBlockFormat format = cursor.blockFormat();
336   format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
337   cursor.setBlockFormat(format);
338   cursor.movePosition(QTextCursor::End);
339   setTextCursor(cursor);
340   updateScrollBars();
341 }