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 "multilineedit.h"
23 #include <QApplication>
24 #include <QMessageBox>
27 #include "actioncollection.h"
28 #include "bufferview.h"
29 #include "graphicalui.h"
30 #include "tabcompleter.h"
32 const int leftMargin = 3;
34 MultiLineEdit::MultiLineEdit(QWidget* parent)
35 : MultiLineEditParent(parent)
37 document()->setDocumentMargin(0);
39 setAcceptRichText(false);
41 enableFindReplace(false);
44 #if defined HAVE_SONNET && !defined HAVE_KDE
45 _spellCheckDecorator = new Sonnet::SpellCheckDecorator(this);
46 highlighter()->setActive(highlighter()->checkerEnabledByDefault());
50 setLineWrapEnabled(false);
53 // Prevent QTextHtmlImporter::appendNodeText from eating whitespace
54 document()->setDefaultStyleSheet("span { white-space: pre-wrap; }");
56 connect(this, &QTextEdit::textChanged, this, &MultiLineEdit::on_textChanged);
58 _mircColorMap["00"] = "#ffffff";
59 _mircColorMap["01"] = "#000000";
60 _mircColorMap["02"] = "#000080";
61 _mircColorMap["03"] = "#008000";
62 _mircColorMap["04"] = "#ff0000";
63 _mircColorMap["05"] = "#800000";
64 _mircColorMap["06"] = "#800080";
65 _mircColorMap["07"] = "#ffa500";
66 _mircColorMap["08"] = "#ffff00";
67 _mircColorMap["09"] = "#00ff00";
68 _mircColorMap["10"] = "#008080";
69 _mircColorMap["11"] = "#00ffff";
70 _mircColorMap["12"] = "#4169e1";
71 _mircColorMap["13"] = "#ff00ff";
72 _mircColorMap["14"] = "#808080";
73 _mircColorMap["15"] = "#c0c0c0";
76 #if defined HAVE_SONNET && !defined HAVE_KDE
77 Sonnet::Highlighter* MultiLineEdit::highlighter() const
79 return _spellCheckDecorator->highlighter();
82 void MultiLineEdit::setSpellCheckEnabled(bool enabled)
84 highlighter()->setActive(enabled);
86 highlighter()->slotRehighlight();
90 void MultiLineEdit::contextMenuEvent(QContextMenuEvent* event)
92 QMenu* menu = createStandardContextMenu();
95 auto action = menu->addAction(tr("Auto Spell Check"));
96 action->setCheckable(true);
97 action->setChecked(highlighter()->isActive());
98 connect(action, &QAction::toggled, this, &MultiLineEdit::setSpellCheckEnabled);
100 menu->exec(event->globalPos());
106 void MultiLineEdit::setCustomFont(const QFont& font)
112 void MultiLineEdit::setMode(Mode mode)
120 void MultiLineEdit::setLineWrapEnabled(bool enable)
122 setLineWrapMode(enable ? WidgetWidth : NoWrap);
126 void MultiLineEdit::setMinHeight(int lines)
128 if (lines == _minHeight)
135 void MultiLineEdit::setMaxHeight(int lines)
137 if (lines == _maxHeight)
144 void MultiLineEdit::setScrollBarsEnabled(bool enable)
146 if (_scrollBarsEnabled == enable)
149 _scrollBarsEnabled = enable;
153 void MultiLineEdit::updateScrollBars()
155 QFontMetrics fm(font());
156 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
157 if (_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
158 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
160 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
162 if (!_scrollBarsEnabled || isSingleLine())
163 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
165 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
168 void MultiLineEdit::resizeEvent(QResizeEvent* event)
170 QTextEdit::resizeEvent(event);
175 void MultiLineEdit::updateSizeHint()
177 QFontMetrics fm(font());
178 int minPixelHeight = fm.lineSpacing() * _minHeight;
179 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
180 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
182 // use the style to determine a decent size
183 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
185 QStyleOptionFrame opt;
187 opt.rect = QRect(0, 0, 100, h);
188 opt.lineWidth = lineWidth();
189 opt.midLineWidth = midLineWidth();
190 opt.state |= QStyle::State_Sunken;
191 QWidget* widget = this;
195 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), widget);
196 if (s != _sizeHint) {
202 QSize MultiLineEdit::sizeHint() const
204 if (!_sizeHint.isValid()) {
205 auto* that = const_cast<MultiLineEdit*>(this);
206 that->updateSizeHint();
211 QSize MultiLineEdit::minimumSizeHint() const
216 void MultiLineEdit::setEmacsMode(bool enable)
221 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget*)
223 _pasteProtectionEnabled = enable;
226 void MultiLineEdit::historyMoveBack()
228 addToHistory(convertRichtextToMircCodes(), true);
236 void MultiLineEdit::historyMoveForward()
238 addToHistory(convertRichtextToMircCodes(), true);
240 if (_idx < _history.count()) {
242 if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
245 reset(); // equals clear() in this case
248 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();
279 bool MultiLineEdit::event(QEvent* e)
281 // We need to make sure that global shortcuts aren't eaten
282 if (e->type() == QEvent::ShortcutOverride) {
283 auto* event = static_cast<QKeyEvent*>(e);
284 QKeySequence key = QKeySequence(event->key() | event->modifiers());
285 foreach (QAction* action, GraphicalUi::actionCollection()->actions()) {
286 if (action->shortcuts().contains(key)) {
293 return MultiLineEditParent::event(e);
296 void MultiLineEdit::keyPressEvent(QKeyEvent* event)
298 if (event == QKeySequence::InsertLineSeparator) {
299 if (_mode == SingleLine) {
304 MultiLineEditParent::keyPressEvent(event);
308 switch (event->key()) {
310 if (event->modifiers() & Qt::ShiftModifier)
314 if (!(event->modifiers() & Qt::ControlModifier)) {
315 int pos = textCursor().position();
316 moveCursor(QTextCursor::Up);
317 if (pos == textCursor().position()) // already on top line -> history
326 if (event->modifiers() & Qt::ShiftModifier)
330 if (!(event->modifiers() & Qt::ControlModifier)) {
331 int pos = textCursor().position();
332 moveCursor(QTextCursor::Down);
333 if (pos == textCursor().position()) // already on bottom line -> history
334 historyMoveForward();
337 historyMoveForward();
348 // We don't want to have the tab key react even if no completer is installed
358 if (event->modifiers() & Qt::ControlModifier) {
359 switch (event->key()) {
362 moveCursor(QTextCursor::StartOfLine);
365 moveCursor(QTextCursor::EndOfLine);
368 moveCursor(QTextCursor::Right);
371 moveCursor(QTextCursor::Left);
379 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
387 else if (event->modifiers() & Qt::MetaModifier || event->modifiers() & Qt::AltModifier) {
388 switch (event->key()) {
390 moveCursor(QTextCursor::WordRight);
393 moveCursor(QTextCursor::WordLeft);
396 moveCursor(QTextCursor::WordRight);
399 moveCursor(QTextCursor::WordLeft);
402 moveCursor(QTextCursor::Start);
404 case Qt::Key_Greater:
405 moveCursor(QTextCursor::End);
410 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
414 case Qt::Key_U: // uppercase word
415 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
416 textCursor().insertText(textCursor().selectedText().toUpper());
419 case Qt::Key_L: // lowercase word
420 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
421 textCursor().insertText(textCursor().selectedText().toLower());
424 case Qt::Key_C: { // capitalize word
425 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
426 QString const text = textCursor().selectedText();
427 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
431 case Qt::Key_T: { // transpose words
432 moveCursor(QTextCursor::StartOfWord);
433 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
434 QString const word1 = textCursor().selectedText();
435 textCursor().clearSelection();
436 moveCursor(QTextCursor::WordRight);
437 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
438 QString const word2 = textCursor().selectedText();
439 if (!word2.isEmpty() && !word1.isEmpty()) {
440 textCursor().insertText(word1);
441 moveCursor(QTextCursor::WordLeft);
442 moveCursor(QTextCursor::WordLeft);
443 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
444 textCursor().insertText(word2);
445 moveCursor(QTextCursor::WordRight);
446 moveCursor(QTextCursor::EndOfWord);
458 KTextEdit::keyPressEvent(event);
460 QTextEdit::keyPressEvent(event);
464 QString MultiLineEdit::convertRichtextToMircCodes()
466 bool underline, bold, italic, color;
467 QString mircText, mircFgColor, mircBgColor;
468 QTextCursor cursor = textCursor();
469 QTextCursor peekcursor = textCursor();
470 cursor.movePosition(QTextCursor::Start);
472 underline = bold = italic = color = false;
474 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
475 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
476 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
479 mircText.append('\x03');
483 mircText.append('\x1f');
487 mircText.append('\x1d');
491 mircText.append('\x02');
493 mircText.append('\n');
496 if (!bold && cursor.charFormat().font().bold()) {
498 mircText.append('\x02');
500 if (!italic && cursor.charFormat().fontItalic()) {
502 mircText.append('\x1d');
504 if (!underline && cursor.charFormat().fontUnderline()) {
506 mircText.append('\x1f');
508 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
510 mircText.append('\x03');
511 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
512 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
514 if (mircFgColor.isEmpty()) {
515 mircFgColor = "01"; // use black if the current foreground color can't be converted
518 mircText.append(mircFgColor);
519 if (cursor.charFormat().background().isOpaque())
520 mircText.append("," + mircBgColor);
523 mircText.append(cursor.selectedText());
525 peekcursor.setPosition(cursor.position());
526 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
528 if (mircCodesChanged(cursor, peekcursor)) {
531 mircText.append('\x03');
535 mircText.append('\x1f');
539 mircText.append('\x1d');
543 mircText.append('\x02');
548 cursor.clearSelection();
552 mircText.append('\x03');
555 mircText.append('\x1f');
558 mircText.append('\x1d');
561 mircText.append('\x02');
566 bool MultiLineEdit::mircCodesChanged(QTextCursor& cursor, QTextCursor& peekcursor)
568 bool changed = false;
569 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
571 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
573 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
575 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
577 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
582 QString MultiLineEdit::convertMircCodesToHtml(const QString& text)
585 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
591 posRight = mircCode.indexIn(text, posLeft);
594 words << text.mid(posLeft);
595 break; // no more mirc color codes
598 if (posLeft < posRight) {
599 words << text.mid(posLeft, posRight - posLeft);
603 posRight = text.indexOf(mircCode.cap(), posRight + 1);
604 words << text.mid(posLeft, posRight + 1 - posLeft);
605 posLeft = posRight + 1;
608 for (int i = 0; i < words.count(); i++) {
610 if (words[i].contains('\x02')) {
611 style.append(" font-weight:600;");
612 words[i].replace('\x02', "");
614 if (words[i].contains('\x1d')) {
615 style.append(" font-style:italic;");
616 words[i].replace('\x1d', "");
618 if (words[i].contains('\x1f')) {
619 style.append(" text-decoration: underline;");
620 words[i].replace('\x1f', "");
622 if (words[i].contains('\x03')) {
623 int pos = words[i].indexOf('\x03');
625 QString fg = words[i].mid(pos + 1, 2);
627 if (words[i][pos + 3] == ',')
628 bg = words[i].mid(pos + 4, 2);
630 style.append(" color:");
631 style.append(_mircColorMap[fg]);
635 style.append(" background-color:");
636 style.append(_mircColorMap[bg]);
640 words[i].replace(pos, len, "");
641 words[i].replace('\x03', "");
643 words[i].replace("&", "&");
644 words[i].replace("<", "<");
645 words[i].replace(">", ">");
646 words[i].replace("\"", """);
647 if (style.isEmpty()) {
648 words[i] = "<span>" + words[i] + "</span>";
651 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
654 return words.join("").replace("\n", "<br />");
657 void MultiLineEdit::on_returnPressed()
659 on_returnPressed(convertRichtextToMircCodes());
662 void MultiLineEdit::on_returnPressed(QString text)
664 if (_completionSpace && text.endsWith(" ")) {
668 if (!text.isEmpty()) {
669 foreach (const QString& line, text.split('\n', QString::SkipEmptyParts)) {
673 emit textEntered(line);
676 _tempHistory.clear();
679 emit noTextEntered();
683 void MultiLineEdit::on_textChanged()
685 _completionSpace = qMax(_completionSpace - 1, 0);
687 QString newText = text();
688 newText.replace("\r\n", "\n");
689 newText.replace('\r', '\n');
690 if (_mode == SingleLine) {
691 if (!pasteProtectionEnabled())
692 newText.replace('\n', ' ');
693 else if (newText.contains('\n')) {
694 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
697 if (lines.count() >= 4) {
698 QString msg = tr("Do you really want to paste %n line(s)?", "", lines.count());
700 for (int i = 0; i < 4; i++) {
701 msg += lines[i].left(40).toHtmlEscaped();
702 if (lines[i].count() > 40)
707 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes | QMessageBox::No);
708 question.setDefaultButton(QMessageBox::No);
710 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
712 if (question.exec() != QMessageBox::Yes)
716 foreach (QString line, lines) {
724 _singleLine = (newText.indexOf('\n') < 0);
726 if (document()->size().height() != _lastDocumentHeight) {
727 _lastDocumentHeight = document()->size().height();
728 on_documentHeightChanged(_lastDocumentHeight);
731 ensureCursorVisible();
734 void MultiLineEdit::on_documentHeightChanged(qreal)
739 void MultiLineEdit::reset()
741 // every time the MultiLineEdit is cleared we also reset history index
742 _idx = _history.count();
744 QTextBlockFormat format = textCursor().blockFormat();
745 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
746 textCursor().setBlockFormat(format);
750 void MultiLineEdit::showHistoryEntry()
752 // if the user changed the history, display the changed line
753 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
754 QTextCursor cursor = textCursor();
755 QTextBlockFormat format = cursor.blockFormat();
756 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
757 cursor.setBlockFormat(format);
758 cursor.movePosition(QTextCursor::End);
759 setTextCursor(cursor);
763 void MultiLineEdit::addCompletionSpace()
765 // Inserting the space emits textChanged, which should not disable removal
766 _completionSpace = 2;
767 insertPlainText(" ");