1 /***************************************************************************
2 * Copyright (C) 2005-2010 by the Quassel Project *
3 * devel@quassel-irc.org *
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. *
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. *
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 ***************************************************************************/
21 #include <QApplication>
23 #include <QMessageBox>
26 #include "actioncollection.h"
27 #include "bufferview.h"
28 #include "graphicalui.h"
29 #include "multilineedit.h"
30 #include "tabcompleter.h"
32 const int leftMargin = 3;
34 MultiLineEdit::MultiLineEdit(QWidget *parent)
35 : MultiLineEditParent(parent),
41 _scrollBarsEnabled(true),
42 _pasteProtectionEnabled(true),
44 _lastDocumentHeight(-1)
46 #if QT_VERSION >= 0x040500
47 document()->setDocumentMargin(0); // new in Qt 4.5 and we really don't want it here
50 setAcceptRichText(false);
52 enableFindReplace(false);
56 setWordWrapEnabled(false);
59 connect(this, SIGNAL(textChanged()), this, SLOT(on_textChanged()));
61 _mircColorMap["00"] = "#ffffff";
62 _mircColorMap["01"] = "#000000";
63 _mircColorMap["02"] = "#000080";
64 _mircColorMap["03"] = "#008000";
65 _mircColorMap["04"] = "#ff0000";
66 _mircColorMap["05"] = "#800000";
67 _mircColorMap["06"] = "#800080";
68 _mircColorMap["07"] = "#ffa500";
69 _mircColorMap["08"] = "#ffff00";
70 _mircColorMap["09"] = "#00ff00";
71 _mircColorMap["10"] = "#008080";
72 _mircColorMap["11"] = "#00ffff";
73 _mircColorMap["12"] = "#4169e1";
74 _mircColorMap["13"] = "#ff00ff";
75 _mircColorMap["14"] = "#808080";
76 _mircColorMap["15"] = "#c0c0c0";
80 MultiLineEdit::~MultiLineEdit() {
83 void MultiLineEdit::setCustomFont(const QFont &font) {
88 void MultiLineEdit::setMode(Mode mode) {
95 void MultiLineEdit::setMinHeight(int lines) {
96 if(lines == _minHeight)
103 void MultiLineEdit::setMaxHeight(int lines) {
104 if(lines == _maxHeight)
111 void MultiLineEdit::setScrollBarsEnabled(bool enable) {
112 if(_scrollBarsEnabled == enable)
115 _scrollBarsEnabled = enable;
119 void MultiLineEdit::updateScrollBars() {
120 QFontMetrics fm(font());
121 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
122 if(_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
123 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
125 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
127 if(!_scrollBarsEnabled || isSingleLine())
128 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
130 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
133 void MultiLineEdit::resizeEvent(QResizeEvent *event) {
134 QTextEdit::resizeEvent(event);
139 void MultiLineEdit::updateSizeHint() {
140 QFontMetrics fm(font());
141 int minPixelHeight = fm.lineSpacing() * _minHeight;
142 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
143 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
145 // use the style to determine a decent size
146 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
147 QStyleOptionFrameV2 opt;
149 opt.rect = QRect(0, 0, 100, h);
150 opt.lineWidth = lineWidth();
151 opt.midLineWidth = midLineWidth();
152 opt.state |= QStyle::State_Sunken;
153 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), this);
160 QSize MultiLineEdit::sizeHint() const {
161 if(!_sizeHint.isValid()) {
162 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
163 that->updateSizeHint();
168 QSize MultiLineEdit::minimumSizeHint() const {
172 void MultiLineEdit::setEmacsMode(bool enable) {
176 void MultiLineEdit::setSpellCheckEnabled(bool enable) {
178 setCheckSpellingEnabled(enable);
184 void MultiLineEdit::setWordWrapEnabled(bool enable) {
185 setLineWrapMode(enable? WidgetWidth : NoWrap);
189 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *) {
190 _pasteProtectionEnabled = enable;
193 void MultiLineEdit::historyMoveBack() {
194 addToHistory(convertRichtextToMircCodes(), true);
202 void MultiLineEdit::historyMoveForward() {
203 addToHistory(convertRichtextToMircCodes(), true);
205 if(_idx < _history.count()) {
207 if(_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
210 reset(); // equals clear() in this case
212 addToHistory(convertRichtextToMircCodes());
217 bool MultiLineEdit::addToHistory(const QString &text, bool temporary) {
221 Q_ASSERT(0 <= _idx && _idx <= _history.count());
224 // if an entry of the history is changed, we remember it and show it again at this
225 // position until a line was actually sent
226 // sent lines get appended to the history
227 if(_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
228 _tempHistory[_idx] = text;
232 if(_history.isEmpty() || text != _history.last()) {
234 _tempHistory.clear();
241 bool MultiLineEdit::event(QEvent *e) {
242 // We need to make sure that global shortcuts aren't eaten
243 if(e->type() == QEvent::ShortcutOverride) {
244 QKeyEvent* event = static_cast<QKeyEvent *>(e);
245 QKeySequence key = QKeySequence(event->key() | event->modifiers());
246 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
247 if(action->shortcuts().contains(key)) {
254 return MultiLineEditParent::event(e);
257 void MultiLineEdit::keyPressEvent(QKeyEvent *event) {
258 // Workaround the fact that Qt < 4.5 doesn't know InsertLineSeparator yet
259 #if QT_VERSION >= 0x040500
260 if(event == QKeySequence::InsertLineSeparator) {
264 if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::META) {
266 if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::SHIFT) {
270 if(_mode == SingleLine) {
275 MultiLineEditParent::keyPressEvent(event);
279 switch(event->key()) {
281 if(event->modifiers() & Qt::ShiftModifier)
285 if(!(event->modifiers() & Qt::ControlModifier)) {
286 int pos = textCursor().position();
287 moveCursor(QTextCursor::Up);
288 if(pos == textCursor().position()) // already on top line -> history
296 if(event->modifiers() & Qt::ShiftModifier)
300 if(!(event->modifiers() & Qt::ControlModifier)) {
301 int pos = textCursor().position();
302 moveCursor(QTextCursor::Down);
303 if(pos == textCursor().position()) // already on bottom line -> history
304 historyMoveForward();
306 historyMoveForward();
317 // We don't want to have the tab key react even if no completer is installed
327 if(event->modifiers() & Qt::ControlModifier) {
328 switch(event->key()) {
331 moveCursor(QTextCursor::StartOfLine);
334 moveCursor(QTextCursor::EndOfLine);
337 moveCursor(QTextCursor::Right);
340 moveCursor(QTextCursor::Left);
348 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
356 else if(event->modifiers() & Qt::MetaModifier ||
357 event->modifiers() & Qt::AltModifier)
359 switch(event->key()) {
361 moveCursor(QTextCursor::WordRight);
364 moveCursor(QTextCursor::WordLeft);
367 moveCursor(QTextCursor::WordRight);
370 moveCursor(QTextCursor::WordLeft);
373 moveCursor(QTextCursor::Start);
375 case Qt::Key_Greater:
376 moveCursor(QTextCursor::End);
381 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
385 case Qt::Key_U: // uppercase word
386 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
387 textCursor().insertText(textCursor().selectedText().toUpper());
390 case Qt::Key_L: // lowercase word
391 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
392 textCursor().insertText(textCursor().selectedText().toLower());
395 case Qt::Key_C: { // capitalize word
396 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
397 QString const text = textCursor().selectedText();
398 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
402 case Qt::Key_T: { // transpose words
403 moveCursor(QTextCursor::StartOfWord);
404 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
405 QString const word1 = textCursor().selectedText();
406 textCursor().clearSelection();
407 moveCursor(QTextCursor::WordRight);
408 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
409 QString const word2 = textCursor().selectedText();
410 if(!word2.isEmpty() && !word1.isEmpty()) {
411 textCursor().insertText(word1);
412 moveCursor(QTextCursor::WordLeft);
413 moveCursor(QTextCursor::WordLeft);
414 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
415 textCursor().insertText(word2);
416 moveCursor(QTextCursor::WordRight);
417 moveCursor(QTextCursor::EndOfWord);
429 KTextEdit::keyPressEvent(event);
431 QTextEdit::keyPressEvent(event);
435 QString MultiLineEdit::convertRichtextToMircCodes() {
436 bool underline, bold, italic, color;
437 QString mircText, mircFgColor, mircBgColor;
438 QTextCursor cursor = textCursor();
439 QTextCursor peekcursor = textCursor();
440 cursor.movePosition(QTextCursor::Start);
442 underline = bold = italic = color = false;
444 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
446 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
447 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
450 mircText.append('\x03');
454 mircText.append('\x1f');
458 mircText.append('\x1d');
462 mircText.append('\x02');
464 mircText.append('\n');
467 if (!bold && cursor.charFormat().font().bold()) {
469 mircText.append('\x02');
471 if (!italic && cursor.charFormat().fontItalic()) {
473 mircText.append('\x1d');
475 if (!underline && cursor.charFormat().fontUnderline()) {
477 mircText.append('\x1f');
479 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
481 mircText.append('\x03');
482 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
483 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
485 if (mircFgColor.isEmpty()) {
486 mircFgColor = "01"; //use black if the current foreground color can't be converted
489 mircText.append(mircFgColor);
490 if (cursor.charFormat().background().isOpaque())
491 mircText.append("," + mircBgColor);
494 mircText.append(cursor.selectedText());
496 peekcursor.setPosition(cursor.position());
497 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
499 if (mircCodesChanged(cursor, peekcursor)) {
502 mircText.append('\x03');
506 mircText.append('\x1f');
510 mircText.append('\x1d');
514 mircText.append('\x02');
519 cursor.clearSelection();
523 mircText.append('\x03');
527 mircText.append('\x1f');
531 mircText.append('\x1d');
535 mircText.append('\x02');
541 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor) {
542 bool changed = false;
543 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
545 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
547 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
549 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
551 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
556 QString MultiLineEdit::convertMircCodesToHtml(const QString &text) {
558 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
564 posRight = mircCode.indexIn(text, posLeft);
567 words << text.mid(posLeft);
568 break; // no more mirc color codes
571 if (posLeft < posRight) {
572 words << text.mid(posLeft, posRight - posLeft);
576 posRight = text.indexOf(mircCode.cap(), posRight + 1);
577 words << text.mid(posLeft, posRight + 1 - posLeft);
578 posLeft = posRight + 1;
581 for (int i = 0; i < words.count(); i++) {
583 if (words[i].contains('\x02')) {
584 style.append(" font-weight:600;");
585 words[i].replace('\x02',"");
587 if (words[i].contains('\x1d')) {
588 style.append(" font-style:italic;");
589 words[i].replace('\x1d',"");
591 if (words[i].contains('\x1f')) {
592 style.append(" text-decoration: underline;");
593 words[i].replace('\x1f',"");
595 if (words[i].contains('\x03')) {
596 int pos = words[i].indexOf('\x03');
598 QString fg = words[i].mid(pos + 1,2);
600 if (words[i][pos+3] == ',')
601 bg = words[i].mid(pos+4,2);
603 style.append(" color:");
604 style.append(_mircColorMap[fg]);
608 style.append(" background-color:");
609 style.append(_mircColorMap[bg]);
613 words[i].replace(pos, len, "");
614 words[i].replace('\x03',"");
616 words[i].replace("&","&");
617 words[i].replace("<", "<");
618 words[i].replace(">", ">");
619 words[i].replace("\"", """);
620 if (style.isEmpty()) {
621 words[i] = "<span>" + words[i] + "</span>";
624 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
627 return words.join("").replace("\n","<br />");
630 void MultiLineEdit::on_returnPressed() {
631 on_returnPressed(convertRichtextToMircCodes());
634 void MultiLineEdit::on_returnPressed(const QString & text) {
635 if(!text.isEmpty()) {
636 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
640 emit textEntered(line);
643 _tempHistory.clear();
645 emit noTextEntered();
649 void MultiLineEdit::on_textChanged() {
650 QString newText = text();
651 newText.replace("\r\n", "\n");
652 newText.replace('\r', '\n');
653 if(_mode == SingleLine) {
654 if(!pasteProtectionEnabled())
655 newText.replace('\n', ' ');
656 else if(newText.contains('\n')) {
657 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
660 if(lines.count() >= 4) {
661 QString msg = tr("Do you really want to paste %n lines?", "", lines.count());
663 for(int i = 0; i < 4; i++) {
664 msg += Qt::escape(lines[i].left(40));
665 if(lines[i].count() > 40)
670 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
671 question.setDefaultButton(QMessageBox::No);
673 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
675 if(question.exec() != QMessageBox::Yes)
679 foreach(QString line, lines) {
687 _singleLine = (newText.indexOf('\n') < 0);
689 if(document()->size().height() != _lastDocumentHeight) {
690 _lastDocumentHeight = document()->size().height();
691 on_documentHeightChanged(_lastDocumentHeight);
694 ensureCursorVisible();
697 void MultiLineEdit::on_documentHeightChanged(qreal) {
701 void MultiLineEdit::reset() {
702 // every time the MultiLineEdit is cleared we also reset history index
703 _idx = _history.count();
705 QTextBlockFormat format = textCursor().blockFormat();
706 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
707 textCursor().setBlockFormat(format);
711 void MultiLineEdit::showHistoryEntry() {
712 // if the user changed the history, display the changed line
713 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
714 QTextCursor cursor = textCursor();
715 QTextBlockFormat format = cursor.blockFormat();
716 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
717 cursor.setBlockFormat(format);
718 cursor.movePosition(QTextCursor::End);
719 setTextCursor(cursor);