removed C-left/right bindings (already available).
[quassel.git] / src / uisupport / multilineedit.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2010 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 "actioncollection.h"
27 #include "bufferview.h"
28 #include "graphicalui.h"
29 #include "multilineedit.h"
30 #include "tabcompleter.h"
31
32 const int leftMargin = 3;
33
34 MultiLineEdit::MultiLineEdit(QWidget *parent)
35   : MultiLineEditParent(parent),
36     _idx(0),
37     _mode(SingleLine),
38     _singleLine(true),
39     _minHeight(1),
40     _maxHeight(5),
41     _scrollBarsEnabled(true),
42     _pasteProtectionEnabled(true),
43     _lastDocumentHeight(-1)
44 {
45 #if QT_VERSION >= 0x040500
46   document()->setDocumentMargin(0); // new in Qt 4.5 and we really don't want it here
47 #endif
48
49   setAcceptRichText(false);
50 #ifdef HAVE_KDE
51   enableFindReplace(false);
52 #endif
53
54   setMode(SingleLine);
55   setWordWrapEnabled(false);
56   reset();
57
58   connect(this, SIGNAL(textChanged()), this, SLOT(on_textChanged()));
59
60   _mircColorMap["00"] = "#ffffff";
61   _mircColorMap["01"] = "#000000";
62   _mircColorMap["02"] = "#000080";
63   _mircColorMap["03"] = "#008000";
64   _mircColorMap["04"] = "#ff0000";
65   _mircColorMap["05"] = "#800000";
66   _mircColorMap["06"] = "#800080";
67   _mircColorMap["07"] = "#ffa500";
68   _mircColorMap["08"] = "#ffff00";
69   _mircColorMap["09"] = "#00ff00";
70   _mircColorMap["10"] = "#008080";
71   _mircColorMap["11"] = "#00ffff";
72   _mircColorMap["12"] = "#4169e1";
73   _mircColorMap["13"] = "#ff00ff";
74   _mircColorMap["14"] = "#808080";
75   _mircColorMap["15"] = "#c0c0c0";
76
77 }
78
79 MultiLineEdit::~MultiLineEdit() {
80 }
81
82 void MultiLineEdit::setCustomFont(const QFont &font) {
83   setFont(font);
84   updateSizeHint();
85 }
86
87 void MultiLineEdit::setMode(Mode mode) {
88   if(mode == _mode)
89     return;
90
91   _mode = mode;
92 }
93
94 void MultiLineEdit::setMinHeight(int lines) {
95   if(lines == _minHeight)
96     return;
97
98   _minHeight = lines;
99   updateSizeHint();
100 }
101
102 void MultiLineEdit::setMaxHeight(int lines) {
103   if(lines == _maxHeight)
104     return;
105
106   _maxHeight = lines;
107   updateSizeHint();
108 }
109
110 void MultiLineEdit::setScrollBarsEnabled(bool enable) {
111   if(_scrollBarsEnabled == enable)
112     return;
113
114   _scrollBarsEnabled = enable;
115   updateScrollBars();
116 }
117
118 void MultiLineEdit::updateScrollBars() {
119   QFontMetrics fm(font());
120   int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
121   if(_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
122     setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
123   else
124     setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
125
126   if(!_scrollBarsEnabled || isSingleLine())
127     setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
128   else
129     setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
130 }
131
132 void MultiLineEdit::resizeEvent(QResizeEvent *event) {
133   QTextEdit::resizeEvent(event);
134   updateSizeHint();
135   updateScrollBars();
136 }
137
138 void MultiLineEdit::updateSizeHint() {
139   QFontMetrics fm(font());
140   int minPixelHeight = fm.lineSpacing() * _minHeight;
141   int maxPixelHeight = fm.lineSpacing() * _maxHeight;
142   int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
143
144   // use the style to determine a decent size
145   int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
146   QStyleOptionFrameV2 opt;
147   opt.initFrom(this);
148   opt.rect = QRect(0, 0, 100, h);
149   opt.lineWidth = lineWidth();
150   opt.midLineWidth = midLineWidth();
151   opt.state |= QStyle::State_Sunken;
152   QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), this);
153   if(s != _sizeHint) {
154     _sizeHint = s;
155     updateGeometry();
156   }
157 }
158
159 QSize MultiLineEdit::sizeHint() const {
160   if(!_sizeHint.isValid()) {
161     MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
162     that->updateSizeHint();
163   }
164   return _sizeHint;
165 }
166
167 QSize MultiLineEdit::minimumSizeHint() const {
168   return sizeHint();
169 }
170
171 void MultiLineEdit::setEmacsMode(bool enable) {
172   _emacsMode = enable;
173 }
174
175 void MultiLineEdit::setSpellCheckEnabled(bool enable) {
176 #ifdef HAVE_KDE
177   setCheckSpellingEnabled(enable);
178 #else
179   Q_UNUSED(enable)
180 #endif
181 }
182
183 void MultiLineEdit::setWordWrapEnabled(bool enable) {
184   setLineWrapMode(enable? WidgetWidth : NoWrap);
185   updateSizeHint();
186 }
187
188 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *) {
189   _pasteProtectionEnabled = enable;
190 }
191
192 void MultiLineEdit::historyMoveBack() {
193   addToHistory(convertRichtextToMircCodes(), true);
194
195   if(_idx > 0) {
196     _idx--;
197     showHistoryEntry();
198   }
199 }
200
201 void MultiLineEdit::historyMoveForward() {
202   addToHistory(convertRichtextToMircCodes(), true);
203
204   if(_idx < _history.count()) {
205     _idx++;
206     if(_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
207       showHistoryEntry();
208     else
209       reset();              // equals clear() in this case
210   } else {
211     addToHistory(convertRichtextToMircCodes());
212     reset();
213   }
214 }
215
216 bool MultiLineEdit::addToHistory(const QString &text, bool temporary) {
217   if(text.isEmpty())
218     return false;
219
220   Q_ASSERT(0 <= _idx && _idx <= _history.count());
221
222   if(temporary) {
223     // if an entry of the history is changed, we remember it and show it again at this
224     // position until a line was actually sent
225     // sent lines get appended to the history
226     if(_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
227       _tempHistory[_idx] = text;
228       return true;
229     }
230   } else {
231     if(_history.isEmpty() || text != _history.last()) {
232       _history << text;
233       _tempHistory.clear();
234       return true;
235     }
236   }
237   return false;
238 }
239
240 bool MultiLineEdit::event(QEvent *e) {
241   // We need to make sure that global shortcuts aren't eaten
242   if(e->type() == QEvent::ShortcutOverride) {
243     QKeyEvent* event = static_cast<QKeyEvent *>(e);
244     QKeySequence key = QKeySequence(event->key() | event->modifiers());
245     foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
246       if(action->shortcuts().contains(key)) {
247         e->ignore();
248         return false;
249       }
250     }
251   }
252
253   return MultiLineEditParent::event(e);
254 }
255
256 void MultiLineEdit::keyPressEvent(QKeyEvent *event) {
257   // Workaround the fact that Qt < 4.5 doesn't know InsertLineSeparator yet
258 #if QT_VERSION >= 0x040500
259   if(event == QKeySequence::InsertLineSeparator) {
260 #else
261
262 # ifdef Q_WS_MAC
263   if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::META) {
264 # else
265   if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::SHIFT) {
266 # endif
267 #endif
268
269     if(_mode == SingleLine) {
270       event->accept();
271       on_returnPressed();
272       return;
273     }
274     MultiLineEditParent::keyPressEvent(event);
275     return;
276   }
277
278   switch(event->key()) {
279   case Qt::Key_Up:
280     if(event->modifiers() & Qt::ShiftModifier)
281       break;
282     {
283       event->accept();
284       if(!(event->modifiers() & Qt::ControlModifier)) {
285         int pos = textCursor().position();
286         moveCursor(QTextCursor::Up);
287         if(pos == textCursor().position()) // already on top line -> history
288           historyMoveBack();
289       } else
290         historyMoveBack();
291       return;
292     }
293
294   case Qt::Key_Down:
295     if(event->modifiers() & Qt::ShiftModifier)
296       break;
297     {
298       event->accept();
299       if(!(event->modifiers() & Qt::ControlModifier)) {
300         int pos = textCursor().position();
301         moveCursor(QTextCursor::Down);
302         if(pos == textCursor().position()) // already on bottom line -> history
303           historyMoveForward();
304       } else
305         historyMoveForward();
306       return;
307     }
308
309   case Qt::Key_Return:
310   case Qt::Key_Enter:
311   case Qt::Key_Select:
312     event->accept();
313     on_returnPressed();
314     return;
315
316   // We don't want to have the tab key react even if no completer is installed
317   case Qt::Key_Tab:
318     event->accept();
319     return;
320
321   default:
322     ;
323   }
324
325   if(_emacsMode) {
326     if(event->modifiers() & Qt::ControlModifier) {
327       switch(event->key()) {
328         // move
329       case Qt::Key_A:
330         moveCursor(QTextCursor::StartOfLine);
331         return;
332       case Qt::Key_E:
333         moveCursor(QTextCursor::EndOfLine);
334         return;
335       case Qt::Key_F:
336         moveCursor(QTextCursor::Right);
337         return;
338       case Qt::Key_B:
339         moveCursor(QTextCursor::Left);
340         return;
341
342         // modify
343       case Qt::Key_Y:
344         paste();
345         return;
346       case Qt::Key_K:
347         moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
348         cut();
349         return;
350       }
351     }
352     else if(event->modifiers() & Qt::MetaModifier) {
353       switch(event->key()) {
354       case Qt::Key_Right:
355         moveCursor(QTextCursor::WordRight);
356         return;
357       case Qt::Key_Left:
358         moveCursor(QTextCursor::WordLeft);
359         return;
360       case Qt::Key_F:
361         moveCursor(QTextCursor::WordRight);
362         return;
363       case Qt::Key_B:
364         moveCursor(QTextCursor::WordLeft);
365         return;
366       case Qt::Key_Less:
367         moveCursor(QTextCursor::Start);
368         return;
369       case Qt::Key_Greater:
370         moveCursor(QTextCursor::End);
371         return;
372       }
373     }
374   }
375
376 #ifdef HAVE_KDE
377   KTextEdit::keyPressEvent(event);
378 #else
379   QTextEdit::keyPressEvent(event);
380 #endif
381 }
382
383 QString MultiLineEdit::convertRichtextToMircCodes() {
384   bool underline, bold, italic, color;
385   QString mircText, mircFgColor, mircBgColor;
386   QTextCursor cursor = textCursor();
387   QTextCursor peekcursor = textCursor();
388   cursor.movePosition(QTextCursor::Start);
389
390   underline = bold = italic = color = false;
391
392   while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
393
394     if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
395       || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
396       if (color) {
397         color = false;
398         mircText.append('\x03');
399       }
400       if (underline) {
401         underline = false;
402         mircText.append('\x1f');
403       }
404       if (italic) {
405         italic = false;
406         mircText.append('\x1d');
407       }
408       if (bold) {
409         bold = false;
410         mircText.append('\x02');
411       }
412       mircText.append('\n');
413     }
414     else {
415       if (!bold && cursor.charFormat().font().bold()) {
416         bold = true;
417         mircText.append('\x02');
418       }
419       if (!italic && cursor.charFormat().fontItalic()) {
420         italic = true;
421         mircText.append('\x1d');
422       }
423       if (!underline && cursor.charFormat().fontUnderline()) {
424         underline = true;
425         mircText.append('\x1f');
426       }
427       if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
428         color = true;
429         mircText.append('\x03');
430         mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
431         mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
432
433         if (mircFgColor.isEmpty()) {
434             mircFgColor = "01"; //use black if the current foreground color can't be converted
435         }
436
437         mircText.append(mircFgColor);
438         if (cursor.charFormat().background().isOpaque())
439           mircText.append("," + mircBgColor);
440       }
441
442       mircText.append(cursor.selectedText());
443
444       peekcursor.setPosition(cursor.position());
445       peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
446
447       if (mircCodesChanged(cursor, peekcursor)) {
448         if (color) {
449           color = false;
450           mircText.append('\x03');
451         }
452         if (underline) {
453           underline = false;
454           mircText.append('\x1f');
455         }
456         if (italic) {
457           italic = false;
458           mircText.append('\x1d');
459         }
460         if (bold) {
461           bold = false;
462           mircText.append('\x02');
463         }
464       }
465     }
466
467     cursor.clearSelection();
468   }
469   if (color) {
470     color = false;
471     mircText.append('\x03');
472   }
473   if (underline) {
474     underline = false;
475     mircText.append('\x1f');
476   }
477   if (italic) {
478     italic = false;
479     mircText.append('\x1d');
480   }
481   if (bold) {
482     bold = false;
483     mircText.append('\x02');
484   }
485
486   return mircText;
487 }
488
489 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor) {
490   bool changed = false;
491   if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
492     changed = true;
493   if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
494     changed = true;
495   if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
496     changed = true;
497   if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
498     changed = true;
499   if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
500     changed = true;
501   return changed;
502 }
503
504 QString MultiLineEdit::convertMircCodesToHtml(const QString &text) {
505   QStringList words;
506   QRegExp mircCode = QRegExp("(\ 2|\1d|\1f|\ 3)", Qt::CaseSensitive);
507
508   int posLeft = 0;
509   int posRight = 0;
510
511   for(;;) {
512     posRight = mircCode.indexIn(text, posLeft);
513
514     if(posRight < 0) {
515       words << text.mid(posLeft);
516       break; // no more mirc color codes
517     }
518
519     if (posLeft < posRight) {
520       words << text.mid(posLeft, posRight - posLeft);
521       posLeft = posRight;
522     }
523
524     posRight = text.indexOf(mircCode.cap(), posRight + 1);
525     words << text.mid(posLeft, posRight + 1 - posLeft);
526     posLeft = posRight + 1;
527   }
528
529   for (int i = 0; i < words.count(); i++) {
530       QString style;
531       if (words[i].contains('\x02')) {
532         style.append(" font-weight:600;");
533         words[i].replace('\x02',"");
534       }
535       if (words[i].contains('\x1d')) {
536         style.append(" font-style:italic;");
537         words[i].replace('\x1d',"");
538       }
539       if (words[i].contains('\x1f')) {
540         style.append(" text-decoration: underline;");
541         words[i].replace('\x1f',"");
542       }
543       if (words[i].contains('\x03')) {
544         int pos = words[i].indexOf('\x03');
545         int len = 3;
546         QString fg = words[i].mid(pos + 1,2);
547         QString bg;
548         if (words[i][pos+3] == ',')
549           bg = words[i].mid(pos+4,2);
550
551         style.append(" color:");
552         style.append(_mircColorMap[fg]);
553         style.append(";");
554
555         if (!bg.isEmpty()) {
556           style.append(" background-color:");
557           style.append(_mircColorMap[bg]);
558           style.append(";");
559           len = 6;
560         }
561         words[i].replace(pos, len, "");
562         words[i].replace('\x03',"");
563       }
564       words[i].replace("&","&amp;");
565       words[i].replace("<", "&lt;");
566       words[i].replace(">", "&gt;");
567       words[i].replace("\"", "&quot;");
568       if (style.isEmpty()) {
569         words[i] = "<span>" + words[i] + "</span>";
570       }
571       else {
572         words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
573       }
574   }
575   return words.join("").replace("\n","<br />");
576 }
577
578 void MultiLineEdit::on_returnPressed() {
579   on_returnPressed(convertRichtextToMircCodes());
580 }
581
582 void MultiLineEdit::on_returnPressed(const QString & text) {
583   if(!text.isEmpty()) {
584     foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
585       if(line.isEmpty())
586         continue;
587       addToHistory(line);
588       emit textEntered(line);
589     }
590     reset();
591     _tempHistory.clear();
592   } else {
593     emit noTextEntered();
594   }
595 }
596
597 void MultiLineEdit::on_textChanged() {
598   QString newText = text();
599   newText.replace("\r\n", "\n");
600   newText.replace('\r', '\n');
601   if(_mode == SingleLine) {
602     if(!pasteProtectionEnabled())
603       newText.replace('\n', ' ');
604     else if(newText.contains('\n')) {
605       QStringList lines = newText.split('\n', QString::SkipEmptyParts);
606       clear();
607
608       if(lines.count() >= 4) {
609         QString msg = tr("Do you really want to paste %n lines?", "", lines.count());
610         msg += "<p>";
611         for(int i = 0; i < 4; i++) {
612           msg += Qt::escape(lines[i].left(40));
613           if(lines[i].count() > 40)
614             msg += "...";
615           msg += "<br />";
616         }
617         msg += "...</p>";
618         QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
619         question.setDefaultButton(QMessageBox::No);
620 #ifdef Q_WS_MAC
621         question.setWindowFlags(question.windowFlags() | Qt::Sheet);
622 #endif
623         if(question.exec() != QMessageBox::Yes)
624           return;
625       }
626
627       foreach(QString line, lines) {
628         clear();
629         insert(line);
630         on_returnPressed();
631       }
632     }
633   }
634
635   _singleLine = (newText.indexOf('\n') < 0);
636
637   if(document()->size().height() != _lastDocumentHeight) {
638     _lastDocumentHeight = document()->size().height();
639     on_documentHeightChanged(_lastDocumentHeight);
640   }
641   updateSizeHint();
642   ensureCursorVisible();
643 }
644
645 void MultiLineEdit::on_documentHeightChanged(qreal) {
646   updateScrollBars();
647 }
648
649 void MultiLineEdit::reset() {
650   // every time the MultiLineEdit is cleared we also reset history index
651   _idx = _history.count();
652   clear();
653   QTextBlockFormat format = textCursor().blockFormat();
654   format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
655   textCursor().setBlockFormat(format);
656   updateScrollBars();
657 }
658
659 void MultiLineEdit::showHistoryEntry() {
660   // if the user changed the history, display the changed line
661   setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
662   QTextCursor cursor = textCursor();
663   QTextBlockFormat format = cursor.blockFormat();
664   format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
665   cursor.setBlockFormat(format);
666   cursor.movePosition(QTextCursor::End);
667   setTextCursor(cursor);
668   updateScrollBars();
669 }