1 /***************************************************************************
2 * Copyright (C) 2005-2015 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 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 document()->setDocumentMargin(0);
48 setAcceptRichText(false);
50 enableFindReplace(false);
54 setLineWrapEnabled(false);
57 // Prevent QTextHtmlImporter::appendNodeText from eating whitespace
58 document()->setDefaultStyleSheet("span { white-space: pre-wrap; }");
60 connect(this, SIGNAL(textChanged()), this, SLOT(on_textChanged()));
62 _mircColorMap["00"] = "#ffffff";
63 _mircColorMap["01"] = "#000000";
64 _mircColorMap["02"] = "#000080";
65 _mircColorMap["03"] = "#008000";
66 _mircColorMap["04"] = "#ff0000";
67 _mircColorMap["05"] = "#800000";
68 _mircColorMap["06"] = "#800080";
69 _mircColorMap["07"] = "#ffa500";
70 _mircColorMap["08"] = "#ffff00";
71 _mircColorMap["09"] = "#00ff00";
72 _mircColorMap["10"] = "#008080";
73 _mircColorMap["11"] = "#00ffff";
74 _mircColorMap["12"] = "#4169e1";
75 _mircColorMap["13"] = "#ff00ff";
76 _mircColorMap["14"] = "#808080";
77 _mircColorMap["15"] = "#c0c0c0";
81 MultiLineEdit::~MultiLineEdit()
86 void MultiLineEdit::setCustomFont(const QFont &font)
93 void MultiLineEdit::setMode(Mode mode)
102 void MultiLineEdit::setLineWrapEnabled(bool enable)
104 setLineWrapMode(enable ? WidgetWidth : NoWrap);
109 void MultiLineEdit::setMinHeight(int lines)
111 if (lines == _minHeight)
119 void MultiLineEdit::setMaxHeight(int lines)
121 if (lines == _maxHeight)
129 void MultiLineEdit::setScrollBarsEnabled(bool enable)
131 if (_scrollBarsEnabled == enable)
134 _scrollBarsEnabled = enable;
139 void MultiLineEdit::updateScrollBars()
141 QFontMetrics fm(font());
142 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
143 if (_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
144 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
146 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
148 if (!_scrollBarsEnabled || isSingleLine())
149 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
151 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
155 void MultiLineEdit::resizeEvent(QResizeEvent *event)
157 QTextEdit::resizeEvent(event);
163 void MultiLineEdit::updateSizeHint()
165 QFontMetrics fm(font());
166 int minPixelHeight = fm.lineSpacing() * _minHeight;
167 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
168 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
170 // use the style to determine a decent size
171 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
172 QStyleOptionFrameV2 opt;
174 opt.rect = QRect(0, 0, 100, h);
175 opt.lineWidth = lineWidth();
176 opt.midLineWidth = midLineWidth();
177 opt.state |= QStyle::State_Sunken;
178 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), this);
179 if (s != _sizeHint) {
186 QSize MultiLineEdit::sizeHint() const
188 if (!_sizeHint.isValid()) {
189 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
190 that->updateSizeHint();
196 QSize MultiLineEdit::minimumSizeHint() const
202 void MultiLineEdit::setEmacsMode(bool enable)
208 void MultiLineEdit::setSpellCheckEnabled(bool enable)
211 setCheckSpellingEnabled(enable);
218 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *)
220 _pasteProtectionEnabled = enable;
224 void MultiLineEdit::historyMoveBack()
226 addToHistory(convertRichtextToMircCodes(), true);
235 void MultiLineEdit::historyMoveForward()
237 addToHistory(convertRichtextToMircCodes(), true);
239 if (_idx < _history.count()) {
241 if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
244 reset(); // equals clear() in this case
247 addToHistory(convertRichtextToMircCodes());
253 bool MultiLineEdit::addToHistory(const QString &text, bool temporary)
258 Q_ASSERT(0 <= _idx && _idx <= _history.count());
261 // if an entry of the history is changed, we remember it and show it again at this
262 // position until a line was actually sent
263 // sent lines get appended to the history
264 if (_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
265 _tempHistory[_idx] = text;
270 if (_history.isEmpty() || text != _history.last()) {
272 _tempHistory.clear();
280 bool MultiLineEdit::event(QEvent *e)
282 // We need to make sure that global shortcuts aren't eaten
283 if (e->type() == QEvent::ShortcutOverride) {
284 QKeyEvent *event = static_cast<QKeyEvent *>(e);
285 QKeySequence key = QKeySequence(event->key() | event->modifiers());
286 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
287 if (action->shortcuts().contains(key)) {
294 return MultiLineEditParent::event(e);
298 void MultiLineEdit::keyPressEvent(QKeyEvent *event)
300 if (event == QKeySequence::InsertLineSeparator) {
301 if (_mode == SingleLine) {
306 MultiLineEditParent::keyPressEvent(event);
310 switch (event->key()) {
312 if (event->modifiers() & Qt::ShiftModifier)
316 if (!(event->modifiers() & Qt::ControlModifier)) {
317 int pos = textCursor().position();
318 moveCursor(QTextCursor::Up);
319 if (pos == textCursor().position()) // already on top line -> history
328 if (event->modifiers() & Qt::ShiftModifier)
332 if (!(event->modifiers() & Qt::ControlModifier)) {
333 int pos = textCursor().position();
334 moveCursor(QTextCursor::Down);
335 if (pos == textCursor().position()) // already on bottom line -> history
336 historyMoveForward();
339 historyMoveForward();
350 // We don't want to have the tab key react even if no completer is installed
360 if (event->modifiers() & Qt::ControlModifier) {
361 switch (event->key()) {
364 moveCursor(QTextCursor::StartOfLine);
367 moveCursor(QTextCursor::EndOfLine);
370 moveCursor(QTextCursor::Right);
373 moveCursor(QTextCursor::Left);
381 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
389 else if (event->modifiers() & Qt::MetaModifier ||
390 event->modifiers() & Qt::AltModifier)
392 switch (event->key()) {
394 moveCursor(QTextCursor::WordRight);
397 moveCursor(QTextCursor::WordLeft);
400 moveCursor(QTextCursor::WordRight);
403 moveCursor(QTextCursor::WordLeft);
406 moveCursor(QTextCursor::Start);
408 case Qt::Key_Greater:
409 moveCursor(QTextCursor::End);
414 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
418 case Qt::Key_U: // uppercase word
419 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
420 textCursor().insertText(textCursor().selectedText().toUpper());
423 case Qt::Key_L: // lowercase word
424 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
425 textCursor().insertText(textCursor().selectedText().toLower());
430 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
431 QString const text = textCursor().selectedText();
432 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
438 moveCursor(QTextCursor::StartOfWord);
439 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
440 QString const word1 = textCursor().selectedText();
441 textCursor().clearSelection();
442 moveCursor(QTextCursor::WordRight);
443 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
444 QString const word2 = textCursor().selectedText();
445 if (!word2.isEmpty() && !word1.isEmpty()) {
446 textCursor().insertText(word1);
447 moveCursor(QTextCursor::WordLeft);
448 moveCursor(QTextCursor::WordLeft);
449 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
450 textCursor().insertText(word2);
451 moveCursor(QTextCursor::WordRight);
452 moveCursor(QTextCursor::EndOfWord);
464 KTextEdit::keyPressEvent(event);
466 QTextEdit::keyPressEvent(event);
471 QString MultiLineEdit::convertRichtextToMircCodes()
473 bool underline, bold, italic, color;
474 QString mircText, mircFgColor, mircBgColor;
475 QTextCursor cursor = textCursor();
476 QTextCursor peekcursor = textCursor();
477 cursor.movePosition(QTextCursor::Start);
479 underline = bold = italic = color = false;
481 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
482 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
483 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
486 mircText.append('\x03');
490 mircText.append('\x1f');
494 mircText.append('\x1d');
498 mircText.append('\x02');
500 mircText.append('\n');
503 if (!bold && cursor.charFormat().font().bold()) {
505 mircText.append('\x02');
507 if (!italic && cursor.charFormat().fontItalic()) {
509 mircText.append('\x1d');
511 if (!underline && cursor.charFormat().fontUnderline()) {
513 mircText.append('\x1f');
515 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
517 mircText.append('\x03');
518 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
519 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
521 if (mircFgColor.isEmpty()) {
522 mircFgColor = "01"; //use black if the current foreground color can't be converted
525 mircText.append(mircFgColor);
526 if (cursor.charFormat().background().isOpaque())
527 mircText.append("," + mircBgColor);
530 mircText.append(cursor.selectedText());
532 peekcursor.setPosition(cursor.position());
533 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
535 if (mircCodesChanged(cursor, peekcursor)) {
538 mircText.append('\x03');
542 mircText.append('\x1f');
546 mircText.append('\x1d');
550 mircText.append('\x02');
555 cursor.clearSelection();
559 mircText.append('\x03');
562 mircText.append('\x1f');
565 mircText.append('\x1d');
568 mircText.append('\x02');
574 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor)
576 bool changed = false;
577 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
579 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
581 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
583 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
585 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
591 QString MultiLineEdit::convertMircCodesToHtml(const QString &text)
594 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
600 posRight = mircCode.indexIn(text, posLeft);
603 words << text.mid(posLeft);
604 break; // no more mirc color codes
607 if (posLeft < posRight) {
608 words << text.mid(posLeft, posRight - posLeft);
612 posRight = text.indexOf(mircCode.cap(), posRight + 1);
613 words << text.mid(posLeft, posRight + 1 - posLeft);
614 posLeft = posRight + 1;
617 for (int i = 0; i < words.count(); i++) {
619 if (words[i].contains('\x02')) {
620 style.append(" font-weight:600;");
621 words[i].replace('\x02', "");
623 if (words[i].contains('\x1d')) {
624 style.append(" font-style:italic;");
625 words[i].replace('\x1d', "");
627 if (words[i].contains('\x1f')) {
628 style.append(" text-decoration: underline;");
629 words[i].replace('\x1f', "");
631 if (words[i].contains('\x03')) {
632 int pos = words[i].indexOf('\x03');
634 QString fg = words[i].mid(pos + 1, 2);
636 if (words[i][pos+3] == ',')
637 bg = words[i].mid(pos+4, 2);
639 style.append(" color:");
640 style.append(_mircColorMap[fg]);
644 style.append(" background-color:");
645 style.append(_mircColorMap[bg]);
649 words[i].replace(pos, len, "");
650 words[i].replace('\x03', "");
652 words[i].replace("&", "&");
653 words[i].replace("<", "<");
654 words[i].replace(">", ">");
655 words[i].replace("\"", """);
656 if (style.isEmpty()) {
657 words[i] = "<span>" + words[i] + "</span>";
660 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
663 return words.join("").replace("\n", "<br />");
667 void MultiLineEdit::on_returnPressed()
669 on_returnPressed(convertRichtextToMircCodes());
673 void MultiLineEdit::on_returnPressed(const QString &text)
675 if (!text.isEmpty()) {
676 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
680 emit textEntered(line);
683 _tempHistory.clear();
686 emit noTextEntered();
691 void MultiLineEdit::on_textChanged()
693 QString newText = text();
694 newText.replace("\r\n", "\n");
695 newText.replace('\r', '\n');
696 if (_mode == SingleLine) {
697 if (!pasteProtectionEnabled())
698 newText.replace('\n', ' ');
699 else if (newText.contains('\n')) {
700 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
703 if (lines.count() >= 4) {
704 QString msg = tr("Do you really want to paste %n line(s)?", "", lines.count());
706 for (int i = 0; i < 4; i++) {
707 #if QT_VERSION < 0x050000
708 msg += Qt::escape(lines[i].left(40));
710 msg += lines[i].left(40).toHtmlEscaped();
712 if (lines[i].count() > 40)
717 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
718 question.setDefaultButton(QMessageBox::No);
720 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
722 if (question.exec() != QMessageBox::Yes)
726 foreach(QString line, lines) {
734 _singleLine = (newText.indexOf('\n') < 0);
736 if (document()->size().height() != _lastDocumentHeight) {
737 _lastDocumentHeight = document()->size().height();
738 on_documentHeightChanged(_lastDocumentHeight);
741 ensureCursorVisible();
745 void MultiLineEdit::on_documentHeightChanged(qreal)
751 void MultiLineEdit::reset()
753 // every time the MultiLineEdit is cleared we also reset history index
754 _idx = _history.count();
756 QTextBlockFormat format = textCursor().blockFormat();
757 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
758 textCursor().setBlockFormat(format);
763 void MultiLineEdit::showHistoryEntry()
765 // if the user changed the history, display the changed line
766 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
767 QTextCursor cursor = textCursor();
768 QTextBlockFormat format = cursor.blockFormat();
769 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
770 cursor.setBlockFormat(format);
771 cursor.movePosition(QTextCursor::End);
772 setTextCursor(cursor);