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),
45 _lastDocumentHeight(-1)
47 document()->setDocumentMargin(0);
49 setAcceptRichText(false);
51 enableFindReplace(false);
55 setLineWrapEnabled(false);
58 // Prevent QTextHtmlImporter::appendNodeText from eating whitespace
59 document()->setDefaultStyleSheet("span { white-space: pre-wrap; }");
61 connect(this, SIGNAL(textChanged()), this, SLOT(on_textChanged()));
63 _mircColorMap["00"] = "#ffffff";
64 _mircColorMap["01"] = "#000000";
65 _mircColorMap["02"] = "#000080";
66 _mircColorMap["03"] = "#008000";
67 _mircColorMap["04"] = "#ff0000";
68 _mircColorMap["05"] = "#800000";
69 _mircColorMap["06"] = "#800080";
70 _mircColorMap["07"] = "#ffa500";
71 _mircColorMap["08"] = "#ffff00";
72 _mircColorMap["09"] = "#00ff00";
73 _mircColorMap["10"] = "#008080";
74 _mircColorMap["11"] = "#00ffff";
75 _mircColorMap["12"] = "#4169e1";
76 _mircColorMap["13"] = "#ff00ff";
77 _mircColorMap["14"] = "#808080";
78 _mircColorMap["15"] = "#c0c0c0";
82 MultiLineEdit::~MultiLineEdit()
86 #if defined HAVE_KF5 || defined HAVE_KDE4
87 void MultiLineEdit::createHighlighter()
89 KTextEdit::createHighlighter();
91 highlighter()->setAutomatic(false);
95 void MultiLineEdit::setCustomFont(const QFont &font)
102 void MultiLineEdit::setMode(Mode mode)
111 void MultiLineEdit::setLineWrapEnabled(bool enable)
113 setLineWrapMode(enable ? WidgetWidth : NoWrap);
118 void MultiLineEdit::setMinHeight(int lines)
120 if (lines == _minHeight)
128 void MultiLineEdit::setMaxHeight(int lines)
130 if (lines == _maxHeight)
138 void MultiLineEdit::setScrollBarsEnabled(bool enable)
140 if (_scrollBarsEnabled == enable)
143 _scrollBarsEnabled = enable;
148 void MultiLineEdit::updateScrollBars()
150 QFontMetrics fm(font());
151 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
152 if (_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
153 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
155 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
157 if (!_scrollBarsEnabled || isSingleLine())
158 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
160 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
164 void MultiLineEdit::resizeEvent(QResizeEvent *event)
166 QTextEdit::resizeEvent(event);
172 void MultiLineEdit::updateSizeHint()
174 QFontMetrics fm(font());
175 int minPixelHeight = fm.lineSpacing() * _minHeight;
176 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
177 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
179 // use the style to determine a decent size
180 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
181 QStyleOptionFrameV2 opt;
183 opt.rect = QRect(0, 0, 100, h);
184 opt.lineWidth = lineWidth();
185 opt.midLineWidth = midLineWidth();
186 opt.state |= QStyle::State_Sunken;
187 QWidget *widget = this;
191 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), widget);
192 if (s != _sizeHint) {
199 QSize MultiLineEdit::sizeHint() const
201 if (!_sizeHint.isValid()) {
202 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
203 that->updateSizeHint();
209 QSize MultiLineEdit::minimumSizeHint() const
215 void MultiLineEdit::setEmacsMode(bool enable)
221 void MultiLineEdit::setSpellCheckEnabled(bool enable)
224 setCheckSpellingEnabled(enable);
231 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *)
233 _pasteProtectionEnabled = enable;
237 void MultiLineEdit::historyMoveBack()
239 addToHistory(convertRichtextToMircCodes(), true);
248 void MultiLineEdit::historyMoveForward()
250 addToHistory(convertRichtextToMircCodes(), true);
252 if (_idx < _history.count()) {
254 if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
257 reset(); // equals clear() in this case
260 addToHistory(convertRichtextToMircCodes());
266 bool MultiLineEdit::addToHistory(const QString &text, bool temporary)
271 Q_ASSERT(0 <= _idx && _idx <= _history.count());
274 // if an entry of the history is changed, we remember it and show it again at this
275 // position until a line was actually sent
276 // sent lines get appended to the history
277 if (_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
278 _tempHistory[_idx] = text;
283 if (_history.isEmpty() || text != _history.last()) {
285 _tempHistory.clear();
293 bool MultiLineEdit::event(QEvent *e)
295 // We need to make sure that global shortcuts aren't eaten
296 if (e->type() == QEvent::ShortcutOverride) {
297 QKeyEvent *event = static_cast<QKeyEvent *>(e);
298 QKeySequence key = QKeySequence(event->key() | event->modifiers());
299 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
300 if (action->shortcuts().contains(key)) {
307 return MultiLineEditParent::event(e);
311 void MultiLineEdit::keyPressEvent(QKeyEvent *event)
313 if (event == QKeySequence::InsertLineSeparator) {
314 if (_mode == SingleLine) {
319 MultiLineEditParent::keyPressEvent(event);
323 switch (event->key()) {
325 if (event->modifiers() & Qt::ShiftModifier)
329 if (!(event->modifiers() & Qt::ControlModifier)) {
330 int pos = textCursor().position();
331 moveCursor(QTextCursor::Up);
332 if (pos == textCursor().position()) // already on top line -> history
341 if (event->modifiers() & Qt::ShiftModifier)
345 if (!(event->modifiers() & Qt::ControlModifier)) {
346 int pos = textCursor().position();
347 moveCursor(QTextCursor::Down);
348 if (pos == textCursor().position()) // already on bottom line -> history
349 historyMoveForward();
352 historyMoveForward();
363 // We don't want to have the tab key react even if no completer is installed
373 if (event->modifiers() & Qt::ControlModifier) {
374 switch (event->key()) {
377 moveCursor(QTextCursor::StartOfLine);
380 moveCursor(QTextCursor::EndOfLine);
383 moveCursor(QTextCursor::Right);
386 moveCursor(QTextCursor::Left);
394 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
402 else if (event->modifiers() & Qt::MetaModifier ||
403 event->modifiers() & Qt::AltModifier)
405 switch (event->key()) {
407 moveCursor(QTextCursor::WordRight);
410 moveCursor(QTextCursor::WordLeft);
413 moveCursor(QTextCursor::WordRight);
416 moveCursor(QTextCursor::WordLeft);
419 moveCursor(QTextCursor::Start);
421 case Qt::Key_Greater:
422 moveCursor(QTextCursor::End);
427 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
431 case Qt::Key_U: // uppercase word
432 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
433 textCursor().insertText(textCursor().selectedText().toUpper());
436 case Qt::Key_L: // lowercase word
437 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
438 textCursor().insertText(textCursor().selectedText().toLower());
443 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
444 QString const text = textCursor().selectedText();
445 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
451 moveCursor(QTextCursor::StartOfWord);
452 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
453 QString const word1 = textCursor().selectedText();
454 textCursor().clearSelection();
455 moveCursor(QTextCursor::WordRight);
456 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
457 QString const word2 = textCursor().selectedText();
458 if (!word2.isEmpty() && !word1.isEmpty()) {
459 textCursor().insertText(word1);
460 moveCursor(QTextCursor::WordLeft);
461 moveCursor(QTextCursor::WordLeft);
462 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
463 textCursor().insertText(word2);
464 moveCursor(QTextCursor::WordRight);
465 moveCursor(QTextCursor::EndOfWord);
477 KTextEdit::keyPressEvent(event);
479 QTextEdit::keyPressEvent(event);
484 QString MultiLineEdit::convertRichtextToMircCodes()
486 bool underline, bold, italic, color;
487 QString mircText, mircFgColor, mircBgColor;
488 QTextCursor cursor = textCursor();
489 QTextCursor peekcursor = textCursor();
490 cursor.movePosition(QTextCursor::Start);
492 underline = bold = italic = color = false;
494 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
495 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
496 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
499 mircText.append('\x03');
503 mircText.append('\x1f');
507 mircText.append('\x1d');
511 mircText.append('\x02');
513 mircText.append('\n');
516 if (!bold && cursor.charFormat().font().bold()) {
518 mircText.append('\x02');
520 if (!italic && cursor.charFormat().fontItalic()) {
522 mircText.append('\x1d');
524 if (!underline && cursor.charFormat().fontUnderline()) {
526 mircText.append('\x1f');
528 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
530 mircText.append('\x03');
531 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
532 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
534 if (mircFgColor.isEmpty()) {
535 mircFgColor = "01"; //use black if the current foreground color can't be converted
538 mircText.append(mircFgColor);
539 if (cursor.charFormat().background().isOpaque())
540 mircText.append("," + mircBgColor);
543 mircText.append(cursor.selectedText());
545 peekcursor.setPosition(cursor.position());
546 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
548 if (mircCodesChanged(cursor, peekcursor)) {
551 mircText.append('\x03');
555 mircText.append('\x1f');
559 mircText.append('\x1d');
563 mircText.append('\x02');
568 cursor.clearSelection();
572 mircText.append('\x03');
575 mircText.append('\x1f');
578 mircText.append('\x1d');
581 mircText.append('\x02');
587 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor)
589 bool changed = false;
590 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
592 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
594 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
596 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
598 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
604 QString MultiLineEdit::convertMircCodesToHtml(const QString &text)
607 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
613 posRight = mircCode.indexIn(text, posLeft);
616 words << text.mid(posLeft);
617 break; // no more mirc color codes
620 if (posLeft < posRight) {
621 words << text.mid(posLeft, posRight - posLeft);
625 posRight = text.indexOf(mircCode.cap(), posRight + 1);
626 words << text.mid(posLeft, posRight + 1 - posLeft);
627 posLeft = posRight + 1;
630 for (int i = 0; i < words.count(); i++) {
632 if (words[i].contains('\x02')) {
633 style.append(" font-weight:600;");
634 words[i].replace('\x02', "");
636 if (words[i].contains('\x1d')) {
637 style.append(" font-style:italic;");
638 words[i].replace('\x1d', "");
640 if (words[i].contains('\x1f')) {
641 style.append(" text-decoration: underline;");
642 words[i].replace('\x1f', "");
644 if (words[i].contains('\x03')) {
645 int pos = words[i].indexOf('\x03');
647 QString fg = words[i].mid(pos + 1, 2);
649 if (words[i][pos+3] == ',')
650 bg = words[i].mid(pos+4, 2);
652 style.append(" color:");
653 style.append(_mircColorMap[fg]);
657 style.append(" background-color:");
658 style.append(_mircColorMap[bg]);
662 words[i].replace(pos, len, "");
663 words[i].replace('\x03', "");
665 words[i].replace("&", "&");
666 words[i].replace("<", "<");
667 words[i].replace(">", ">");
668 words[i].replace("\"", """);
669 if (style.isEmpty()) {
670 words[i] = "<span>" + words[i] + "</span>";
673 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
676 return words.join("").replace("\n", "<br />");
680 void MultiLineEdit::on_returnPressed()
682 on_returnPressed(convertRichtextToMircCodes());
686 void MultiLineEdit::on_returnPressed(QString text)
688 if (_completionSpace && text.endsWith(" ")) {
692 if (!text.isEmpty()) {
693 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
697 emit textEntered(line);
700 _tempHistory.clear();
703 emit noTextEntered();
708 void MultiLineEdit::on_textChanged()
710 _completionSpace = qMax(_completionSpace - 1, 0);
712 QString newText = text();
713 newText.replace("\r\n", "\n");
714 newText.replace('\r', '\n');
715 if (_mode == SingleLine) {
716 if (!pasteProtectionEnabled())
717 newText.replace('\n', ' ');
718 else if (newText.contains('\n')) {
719 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
722 if (lines.count() >= 4) {
723 QString msg = tr("Do you really want to paste %n line(s)?", "", lines.count());
725 for (int i = 0; i < 4; i++) {
726 #if QT_VERSION < 0x050000
727 msg += Qt::escape(lines[i].left(40));
729 msg += lines[i].left(40).toHtmlEscaped();
731 if (lines[i].count() > 40)
736 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
737 question.setDefaultButton(QMessageBox::No);
739 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
741 if (question.exec() != QMessageBox::Yes)
745 foreach(QString line, lines) {
753 _singleLine = (newText.indexOf('\n') < 0);
755 if (document()->size().height() != _lastDocumentHeight) {
756 _lastDocumentHeight = document()->size().height();
757 on_documentHeightChanged(_lastDocumentHeight);
760 ensureCursorVisible();
764 void MultiLineEdit::on_documentHeightChanged(qreal)
770 void MultiLineEdit::reset()
772 // every time the MultiLineEdit is cleared we also reset history index
773 _idx = _history.count();
775 QTextBlockFormat format = textCursor().blockFormat();
776 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
777 textCursor().setBlockFormat(format);
782 void MultiLineEdit::showHistoryEntry()
784 // if the user changed the history, display the changed line
785 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
786 QTextCursor cursor = textCursor();
787 QTextBlockFormat format = cursor.blockFormat();
788 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
789 cursor.setBlockFormat(format);
790 cursor.movePosition(QTextCursor::End);
791 setTextCursor(cursor);
796 void MultiLineEdit::addCompletionSpace()
798 // Inserting the space emits textChanged, which should not disable removal
799 _completionSpace = 2;
800 insertPlainText(" ");