1 /***************************************************************************
2 * Copyright (C) 2005-2018 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>
22 #include <QMessageBox>
25 #include "actioncollection.h"
26 #include "bufferview.h"
27 #include "graphicalui.h"
28 #include "multilineedit.h"
29 #include "tabcompleter.h"
31 const int leftMargin = 3;
33 MultiLineEdit::MultiLineEdit(QWidget *parent)
34 : MultiLineEditParent(parent)
36 document()->setDocumentMargin(0);
38 setAcceptRichText(false);
40 enableFindReplace(false);
43 #if defined HAVE_SONNET && !defined HAVE_KDE
44 _spellCheckDecorator = new Sonnet::SpellCheckDecorator(this);
45 highlighter()->setActive(highlighter()->checkerEnabledByDefault());
49 setLineWrapEnabled(false);
52 // Prevent QTextHtmlImporter::appendNodeText from eating whitespace
53 document()->setDefaultStyleSheet("span { white-space: pre-wrap; }");
55 connect(this, &QTextEdit::textChanged, this, &MultiLineEdit::on_textChanged);
57 _mircColorMap["00"] = "#ffffff";
58 _mircColorMap["01"] = "#000000";
59 _mircColorMap["02"] = "#000080";
60 _mircColorMap["03"] = "#008000";
61 _mircColorMap["04"] = "#ff0000";
62 _mircColorMap["05"] = "#800000";
63 _mircColorMap["06"] = "#800080";
64 _mircColorMap["07"] = "#ffa500";
65 _mircColorMap["08"] = "#ffff00";
66 _mircColorMap["09"] = "#00ff00";
67 _mircColorMap["10"] = "#008080";
68 _mircColorMap["11"] = "#00ffff";
69 _mircColorMap["12"] = "#4169e1";
70 _mircColorMap["13"] = "#ff00ff";
71 _mircColorMap["14"] = "#808080";
72 _mircColorMap["15"] = "#c0c0c0";
76 #if defined HAVE_SONNET && !defined HAVE_KDE
77 Sonnet::Highlighter *MultiLineEdit::highlighter() const
79 return _spellCheckDecorator->highlighter();
83 void MultiLineEdit::setSpellCheckEnabled(bool enabled)
85 highlighter()->setActive(enabled);
87 highlighter()->slotRehighlight();
91 void MultiLineEdit::contextMenuEvent(QContextMenuEvent *event)
93 QMenu *menu = createStandardContextMenu();
96 auto action = menu->addAction(tr("Auto Spell Check"));
97 action->setCheckable(true);
98 action->setChecked(highlighter()->isActive());
99 connect(action, &QAction::toggled, this, &MultiLineEdit::setSpellCheckEnabled);
101 menu->exec(event->globalPos());
108 void MultiLineEdit::setCustomFont(const QFont &font)
115 void MultiLineEdit::setMode(Mode mode)
124 void MultiLineEdit::setLineWrapEnabled(bool enable)
126 setLineWrapMode(enable ? WidgetWidth : NoWrap);
131 void MultiLineEdit::setMinHeight(int lines)
133 if (lines == _minHeight)
141 void MultiLineEdit::setMaxHeight(int lines)
143 if (lines == _maxHeight)
151 void MultiLineEdit::setScrollBarsEnabled(bool enable)
153 if (_scrollBarsEnabled == enable)
156 _scrollBarsEnabled = enable;
161 void MultiLineEdit::updateScrollBars()
163 QFontMetrics fm(font());
164 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
165 if (_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
166 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
168 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
170 if (!_scrollBarsEnabled || isSingleLine())
171 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
173 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
177 void MultiLineEdit::resizeEvent(QResizeEvent *event)
179 QTextEdit::resizeEvent(event);
185 void MultiLineEdit::updateSizeHint()
187 QFontMetrics fm(font());
188 int minPixelHeight = fm.lineSpacing() * _minHeight;
189 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
190 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
192 // use the style to determine a decent size
193 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
195 QStyleOptionFrame opt;
197 opt.rect = QRect(0, 0, 100, h);
198 opt.lineWidth = lineWidth();
199 opt.midLineWidth = midLineWidth();
200 opt.state |= QStyle::State_Sunken;
201 QWidget *widget = this;
205 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), widget);
206 if (s != _sizeHint) {
213 QSize MultiLineEdit::sizeHint() const
215 if (!_sizeHint.isValid()) {
216 auto *that = const_cast<MultiLineEdit *>(this);
217 that->updateSizeHint();
223 QSize MultiLineEdit::minimumSizeHint() const
229 void MultiLineEdit::setEmacsMode(bool enable)
235 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *)
237 _pasteProtectionEnabled = enable;
241 void MultiLineEdit::historyMoveBack()
243 addToHistory(convertRichtextToMircCodes(), true);
252 void MultiLineEdit::historyMoveForward()
254 addToHistory(convertRichtextToMircCodes(), true);
256 if (_idx < _history.count()) {
258 if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
261 reset(); // equals clear() in this case
264 addToHistory(convertRichtextToMircCodes());
270 bool MultiLineEdit::addToHistory(const QString &text, bool temporary)
275 Q_ASSERT(0 <= _idx && _idx <= _history.count());
278 // if an entry of the history is changed, we remember it and show it again at this
279 // position until a line was actually sent
280 // sent lines get appended to the history
281 if (_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
282 _tempHistory[_idx] = text;
287 if (_history.isEmpty() || text != _history.last()) {
289 _tempHistory.clear();
297 bool MultiLineEdit::event(QEvent *e)
299 // We need to make sure that global shortcuts aren't eaten
300 if (e->type() == QEvent::ShortcutOverride) {
301 auto *event = static_cast<QKeyEvent *>(e);
302 QKeySequence key = QKeySequence(event->key() | event->modifiers());
303 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
304 if (action->shortcuts().contains(key)) {
311 return MultiLineEditParent::event(e);
315 void MultiLineEdit::keyPressEvent(QKeyEvent *event)
317 if (event == QKeySequence::InsertLineSeparator) {
318 if (_mode == SingleLine) {
323 MultiLineEditParent::keyPressEvent(event);
327 switch (event->key()) {
329 if (event->modifiers() & Qt::ShiftModifier)
333 if (!(event->modifiers() & Qt::ControlModifier)) {
334 int pos = textCursor().position();
335 moveCursor(QTextCursor::Up);
336 if (pos == textCursor().position()) // already on top line -> history
345 if (event->modifiers() & Qt::ShiftModifier)
349 if (!(event->modifiers() & Qt::ControlModifier)) {
350 int pos = textCursor().position();
351 moveCursor(QTextCursor::Down);
352 if (pos == textCursor().position()) // already on bottom line -> history
353 historyMoveForward();
356 historyMoveForward();
367 // We don't want to have the tab key react even if no completer is installed
377 if (event->modifiers() & Qt::ControlModifier) {
378 switch (event->key()) {
381 moveCursor(QTextCursor::StartOfLine);
384 moveCursor(QTextCursor::EndOfLine);
387 moveCursor(QTextCursor::Right);
390 moveCursor(QTextCursor::Left);
398 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
406 else if (event->modifiers() & Qt::MetaModifier ||
407 event->modifiers() & Qt::AltModifier)
409 switch (event->key()) {
411 moveCursor(QTextCursor::WordRight);
414 moveCursor(QTextCursor::WordLeft);
417 moveCursor(QTextCursor::WordRight);
420 moveCursor(QTextCursor::WordLeft);
423 moveCursor(QTextCursor::Start);
425 case Qt::Key_Greater:
426 moveCursor(QTextCursor::End);
431 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
435 case Qt::Key_U: // uppercase word
436 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
437 textCursor().insertText(textCursor().selectedText().toUpper());
440 case Qt::Key_L: // lowercase word
441 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
442 textCursor().insertText(textCursor().selectedText().toLower());
447 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
448 QString const text = textCursor().selectedText();
449 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
455 moveCursor(QTextCursor::StartOfWord);
456 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
457 QString const word1 = textCursor().selectedText();
458 textCursor().clearSelection();
459 moveCursor(QTextCursor::WordRight);
460 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
461 QString const word2 = textCursor().selectedText();
462 if (!word2.isEmpty() && !word1.isEmpty()) {
463 textCursor().insertText(word1);
464 moveCursor(QTextCursor::WordLeft);
465 moveCursor(QTextCursor::WordLeft);
466 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
467 textCursor().insertText(word2);
468 moveCursor(QTextCursor::WordRight);
469 moveCursor(QTextCursor::EndOfWord);
481 KTextEdit::keyPressEvent(event);
483 QTextEdit::keyPressEvent(event);
488 QString MultiLineEdit::convertRichtextToMircCodes()
490 bool underline, bold, italic, color;
491 QString mircText, mircFgColor, mircBgColor;
492 QTextCursor cursor = textCursor();
493 QTextCursor peekcursor = textCursor();
494 cursor.movePosition(QTextCursor::Start);
496 underline = bold = italic = color = false;
498 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
499 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
500 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
503 mircText.append('\x03');
507 mircText.append('\x1f');
511 mircText.append('\x1d');
515 mircText.append('\x02');
517 mircText.append('\n');
520 if (!bold && cursor.charFormat().font().bold()) {
522 mircText.append('\x02');
524 if (!italic && cursor.charFormat().fontItalic()) {
526 mircText.append('\x1d');
528 if (!underline && cursor.charFormat().fontUnderline()) {
530 mircText.append('\x1f');
532 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
534 mircText.append('\x03');
535 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
536 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
538 if (mircFgColor.isEmpty()) {
539 mircFgColor = "01"; //use black if the current foreground color can't be converted
542 mircText.append(mircFgColor);
543 if (cursor.charFormat().background().isOpaque())
544 mircText.append("," + mircBgColor);
547 mircText.append(cursor.selectedText());
549 peekcursor.setPosition(cursor.position());
550 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
552 if (mircCodesChanged(cursor, peekcursor)) {
555 mircText.append('\x03');
559 mircText.append('\x1f');
563 mircText.append('\x1d');
567 mircText.append('\x02');
572 cursor.clearSelection();
576 mircText.append('\x03');
579 mircText.append('\x1f');
582 mircText.append('\x1d');
585 mircText.append('\x02');
591 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor)
593 bool changed = false;
594 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
596 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
598 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
600 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
602 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
608 QString MultiLineEdit::convertMircCodesToHtml(const QString &text)
611 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
617 posRight = mircCode.indexIn(text, posLeft);
620 words << text.mid(posLeft);
621 break; // no more mirc color codes
624 if (posLeft < posRight) {
625 words << text.mid(posLeft, posRight - posLeft);
629 posRight = text.indexOf(mircCode.cap(), posRight + 1);
630 words << text.mid(posLeft, posRight + 1 - posLeft);
631 posLeft = posRight + 1;
634 for (int i = 0; i < words.count(); i++) {
636 if (words[i].contains('\x02')) {
637 style.append(" font-weight:600;");
638 words[i].replace('\x02', "");
640 if (words[i].contains('\x1d')) {
641 style.append(" font-style:italic;");
642 words[i].replace('\x1d', "");
644 if (words[i].contains('\x1f')) {
645 style.append(" text-decoration: underline;");
646 words[i].replace('\x1f', "");
648 if (words[i].contains('\x03')) {
649 int pos = words[i].indexOf('\x03');
651 QString fg = words[i].mid(pos + 1, 2);
653 if (words[i][pos+3] == ',')
654 bg = words[i].mid(pos+4, 2);
656 style.append(" color:");
657 style.append(_mircColorMap[fg]);
661 style.append(" background-color:");
662 style.append(_mircColorMap[bg]);
666 words[i].replace(pos, len, "");
667 words[i].replace('\x03', "");
669 words[i].replace("&", "&");
670 words[i].replace("<", "<");
671 words[i].replace(">", ">");
672 words[i].replace("\"", """);
673 if (style.isEmpty()) {
674 words[i] = "<span>" + words[i] + "</span>";
677 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
680 return words.join("").replace("\n", "<br />");
684 void MultiLineEdit::on_returnPressed()
686 on_returnPressed(convertRichtextToMircCodes());
690 void MultiLineEdit::on_returnPressed(QString text)
692 if (_completionSpace && text.endsWith(" ")) {
696 if (!text.isEmpty()) {
697 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
701 emit textEntered(line);
704 _tempHistory.clear();
707 emit noTextEntered();
712 void MultiLineEdit::on_textChanged()
714 _completionSpace = qMax(_completionSpace - 1, 0);
716 QString newText = text();
717 newText.replace("\r\n", "\n");
718 newText.replace('\r', '\n');
719 if (_mode == SingleLine) {
720 if (!pasteProtectionEnabled())
721 newText.replace('\n', ' ');
722 else if (newText.contains('\n')) {
723 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
726 if (lines.count() >= 4) {
727 QString msg = tr("Do you really want to paste %n line(s)?", "", lines.count());
729 for (int i = 0; i < 4; i++) {
730 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(" ");