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),
40 _scrollBarsEnabled(true),
41 _pasteProtectionEnabled(true),
44 _lastDocumentHeight(-1)
46 document()->setDocumentMargin(0);
48 setAcceptRichText(false);
50 enableFindReplace(false);
53 #if defined HAVE_SONNET && !defined HAVE_KDE
54 _spellCheckDecorator = new Sonnet::SpellCheckDecorator(this);
55 highlighter()->setActive(highlighter()->checkerEnabledByDefault());
59 setLineWrapEnabled(false);
62 // Prevent QTextHtmlImporter::appendNodeText from eating whitespace
63 document()->setDefaultStyleSheet("span { white-space: pre-wrap; }");
65 connect(this, SIGNAL(textChanged()), this, SLOT(on_textChanged()));
67 _mircColorMap["00"] = "#ffffff";
68 _mircColorMap["01"] = "#000000";
69 _mircColorMap["02"] = "#000080";
70 _mircColorMap["03"] = "#008000";
71 _mircColorMap["04"] = "#ff0000";
72 _mircColorMap["05"] = "#800000";
73 _mircColorMap["06"] = "#800080";
74 _mircColorMap["07"] = "#ffa500";
75 _mircColorMap["08"] = "#ffff00";
76 _mircColorMap["09"] = "#00ff00";
77 _mircColorMap["10"] = "#008080";
78 _mircColorMap["11"] = "#00ffff";
79 _mircColorMap["12"] = "#4169e1";
80 _mircColorMap["13"] = "#ff00ff";
81 _mircColorMap["14"] = "#808080";
82 _mircColorMap["15"] = "#c0c0c0";
86 MultiLineEdit::~MultiLineEdit()
90 #if defined HAVE_SONNET && !defined HAVE_KDE
91 Sonnet::Highlighter *MultiLineEdit::highlighter() const
93 return _spellCheckDecorator->highlighter();
97 void MultiLineEdit::setSpellCheckEnabled(bool enabled)
99 highlighter()->setActive(enabled);
101 highlighter()->slotRehighlight();
105 void MultiLineEdit::contextMenuEvent(QContextMenuEvent *event)
107 QMenu *menu = createStandardContextMenu();
108 menu->addSeparator();
110 auto action = menu->addAction(tr("Auto Spell Check"));
111 action->setCheckable(true);
112 action->setChecked(highlighter()->isActive());
113 connect(action, SIGNAL(toggled(bool)), this, SLOT(setSpellCheckEnabled(bool)));
115 menu->exec(event->globalPos());
122 void MultiLineEdit::setCustomFont(const QFont &font)
129 void MultiLineEdit::setMode(Mode mode)
138 void MultiLineEdit::setLineWrapEnabled(bool enable)
140 setLineWrapMode(enable ? WidgetWidth : NoWrap);
145 void MultiLineEdit::setMinHeight(int lines)
147 if (lines == _minHeight)
155 void MultiLineEdit::setMaxHeight(int lines)
157 if (lines == _maxHeight)
165 void MultiLineEdit::setScrollBarsEnabled(bool enable)
167 if (_scrollBarsEnabled == enable)
170 _scrollBarsEnabled = enable;
175 void MultiLineEdit::updateScrollBars()
177 QFontMetrics fm(font());
178 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
179 if (_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
180 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
182 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
184 if (!_scrollBarsEnabled || isSingleLine())
185 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
187 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
191 void MultiLineEdit::resizeEvent(QResizeEvent *event)
193 QTextEdit::resizeEvent(event);
199 void MultiLineEdit::updateSizeHint()
201 QFontMetrics fm(font());
202 int minPixelHeight = fm.lineSpacing() * _minHeight;
203 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
204 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
206 // use the style to determine a decent size
207 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
209 QStyleOptionFrame opt;
211 opt.rect = QRect(0, 0, 100, h);
212 opt.lineWidth = lineWidth();
213 opt.midLineWidth = midLineWidth();
214 opt.state |= QStyle::State_Sunken;
215 QWidget *widget = this;
219 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), widget);
220 if (s != _sizeHint) {
227 QSize MultiLineEdit::sizeHint() const
229 if (!_sizeHint.isValid()) {
230 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
231 that->updateSizeHint();
237 QSize MultiLineEdit::minimumSizeHint() const
243 void MultiLineEdit::setEmacsMode(bool enable)
249 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *)
251 _pasteProtectionEnabled = enable;
255 void MultiLineEdit::historyMoveBack()
257 addToHistory(convertRichtextToMircCodes(), true);
266 void MultiLineEdit::historyMoveForward()
268 addToHistory(convertRichtextToMircCodes(), true);
270 if (_idx < _history.count()) {
272 if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
275 reset(); // equals clear() in this case
278 addToHistory(convertRichtextToMircCodes());
284 bool MultiLineEdit::addToHistory(const QString &text, bool temporary)
289 Q_ASSERT(0 <= _idx && _idx <= _history.count());
292 // if an entry of the history is changed, we remember it and show it again at this
293 // position until a line was actually sent
294 // sent lines get appended to the history
295 if (_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
296 _tempHistory[_idx] = text;
301 if (_history.isEmpty() || text != _history.last()) {
303 _tempHistory.clear();
311 bool MultiLineEdit::event(QEvent *e)
313 // We need to make sure that global shortcuts aren't eaten
314 if (e->type() == QEvent::ShortcutOverride) {
315 QKeyEvent *event = static_cast<QKeyEvent *>(e);
316 QKeySequence key = QKeySequence(event->key() | event->modifiers());
317 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
318 if (action->shortcuts().contains(key)) {
325 return MultiLineEditParent::event(e);
329 void MultiLineEdit::keyPressEvent(QKeyEvent *event)
331 if (event == QKeySequence::InsertLineSeparator) {
332 if (_mode == SingleLine) {
337 MultiLineEditParent::keyPressEvent(event);
341 switch (event->key()) {
343 if (event->modifiers() & Qt::ShiftModifier)
347 if (!(event->modifiers() & Qt::ControlModifier)) {
348 int pos = textCursor().position();
349 moveCursor(QTextCursor::Up);
350 if (pos == textCursor().position()) // already on top line -> history
359 if (event->modifiers() & Qt::ShiftModifier)
363 if (!(event->modifiers() & Qt::ControlModifier)) {
364 int pos = textCursor().position();
365 moveCursor(QTextCursor::Down);
366 if (pos == textCursor().position()) // already on bottom line -> history
367 historyMoveForward();
370 historyMoveForward();
381 // We don't want to have the tab key react even if no completer is installed
391 if (event->modifiers() & Qt::ControlModifier) {
392 switch (event->key()) {
395 moveCursor(QTextCursor::StartOfLine);
398 moveCursor(QTextCursor::EndOfLine);
401 moveCursor(QTextCursor::Right);
404 moveCursor(QTextCursor::Left);
412 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
420 else if (event->modifiers() & Qt::MetaModifier ||
421 event->modifiers() & Qt::AltModifier)
423 switch (event->key()) {
425 moveCursor(QTextCursor::WordRight);
428 moveCursor(QTextCursor::WordLeft);
431 moveCursor(QTextCursor::WordRight);
434 moveCursor(QTextCursor::WordLeft);
437 moveCursor(QTextCursor::Start);
439 case Qt::Key_Greater:
440 moveCursor(QTextCursor::End);
445 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
449 case Qt::Key_U: // uppercase word
450 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
451 textCursor().insertText(textCursor().selectedText().toUpper());
454 case Qt::Key_L: // lowercase word
455 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
456 textCursor().insertText(textCursor().selectedText().toLower());
461 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
462 QString const text = textCursor().selectedText();
463 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
469 moveCursor(QTextCursor::StartOfWord);
470 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
471 QString const word1 = textCursor().selectedText();
472 textCursor().clearSelection();
473 moveCursor(QTextCursor::WordRight);
474 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
475 QString const word2 = textCursor().selectedText();
476 if (!word2.isEmpty() && !word1.isEmpty()) {
477 textCursor().insertText(word1);
478 moveCursor(QTextCursor::WordLeft);
479 moveCursor(QTextCursor::WordLeft);
480 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
481 textCursor().insertText(word2);
482 moveCursor(QTextCursor::WordRight);
483 moveCursor(QTextCursor::EndOfWord);
495 KTextEdit::keyPressEvent(event);
497 QTextEdit::keyPressEvent(event);
502 QString MultiLineEdit::convertRichtextToMircCodes()
504 bool underline, bold, italic, color;
505 QString mircText, mircFgColor, mircBgColor;
506 QTextCursor cursor = textCursor();
507 QTextCursor peekcursor = textCursor();
508 cursor.movePosition(QTextCursor::Start);
510 underline = bold = italic = color = false;
512 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
513 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
514 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
517 mircText.append('\x03');
521 mircText.append('\x1f');
525 mircText.append('\x1d');
529 mircText.append('\x02');
531 mircText.append('\n');
534 if (!bold && cursor.charFormat().font().bold()) {
536 mircText.append('\x02');
538 if (!italic && cursor.charFormat().fontItalic()) {
540 mircText.append('\x1d');
542 if (!underline && cursor.charFormat().fontUnderline()) {
544 mircText.append('\x1f');
546 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
548 mircText.append('\x03');
549 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
550 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
552 if (mircFgColor.isEmpty()) {
553 mircFgColor = "01"; //use black if the current foreground color can't be converted
556 mircText.append(mircFgColor);
557 if (cursor.charFormat().background().isOpaque())
558 mircText.append("," + mircBgColor);
561 mircText.append(cursor.selectedText());
563 peekcursor.setPosition(cursor.position());
564 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
566 if (mircCodesChanged(cursor, peekcursor)) {
569 mircText.append('\x03');
573 mircText.append('\x1f');
577 mircText.append('\x1d');
581 mircText.append('\x02');
586 cursor.clearSelection();
590 mircText.append('\x03');
593 mircText.append('\x1f');
596 mircText.append('\x1d');
599 mircText.append('\x02');
605 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor)
607 bool changed = false;
608 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
610 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
612 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
614 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
616 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
622 QString MultiLineEdit::convertMircCodesToHtml(const QString &text)
625 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
631 posRight = mircCode.indexIn(text, posLeft);
634 words << text.mid(posLeft);
635 break; // no more mirc color codes
638 if (posLeft < posRight) {
639 words << text.mid(posLeft, posRight - posLeft);
643 posRight = text.indexOf(mircCode.cap(), posRight + 1);
644 words << text.mid(posLeft, posRight + 1 - posLeft);
645 posLeft = posRight + 1;
648 for (int i = 0; i < words.count(); i++) {
650 if (words[i].contains('\x02')) {
651 style.append(" font-weight:600;");
652 words[i].replace('\x02', "");
654 if (words[i].contains('\x1d')) {
655 style.append(" font-style:italic;");
656 words[i].replace('\x1d', "");
658 if (words[i].contains('\x1f')) {
659 style.append(" text-decoration: underline;");
660 words[i].replace('\x1f', "");
662 if (words[i].contains('\x03')) {
663 int pos = words[i].indexOf('\x03');
665 QString fg = words[i].mid(pos + 1, 2);
667 if (words[i][pos+3] == ',')
668 bg = words[i].mid(pos+4, 2);
670 style.append(" color:");
671 style.append(_mircColorMap[fg]);
675 style.append(" background-color:");
676 style.append(_mircColorMap[bg]);
680 words[i].replace(pos, len, "");
681 words[i].replace('\x03', "");
683 words[i].replace("&", "&");
684 words[i].replace("<", "<");
685 words[i].replace(">", ">");
686 words[i].replace("\"", """);
687 if (style.isEmpty()) {
688 words[i] = "<span>" + words[i] + "</span>";
691 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
694 return words.join("").replace("\n", "<br />");
698 void MultiLineEdit::on_returnPressed()
700 on_returnPressed(convertRichtextToMircCodes());
704 void MultiLineEdit::on_returnPressed(QString text)
706 if (_completionSpace && text.endsWith(" ")) {
710 if (!text.isEmpty()) {
711 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
715 emit textEntered(line);
718 _tempHistory.clear();
721 emit noTextEntered();
726 void MultiLineEdit::on_textChanged()
728 _completionSpace = qMax(_completionSpace - 1, 0);
730 QString newText = text();
731 newText.replace("\r\n", "\n");
732 newText.replace('\r', '\n');
733 if (_mode == SingleLine) {
734 if (!pasteProtectionEnabled())
735 newText.replace('\n', ' ');
736 else if (newText.contains('\n')) {
737 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
740 if (lines.count() >= 4) {
741 QString msg = tr("Do you really want to paste %n line(s)?", "", lines.count());
743 for (int i = 0; i < 4; i++) {
744 msg += lines[i].left(40).toHtmlEscaped();
745 if (lines[i].count() > 40)
750 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
751 question.setDefaultButton(QMessageBox::No);
753 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
755 if (question.exec() != QMessageBox::Yes)
759 foreach(QString line, lines) {
767 _singleLine = (newText.indexOf('\n') < 0);
769 if (document()->size().height() != _lastDocumentHeight) {
770 _lastDocumentHeight = document()->size().height();
771 on_documentHeightChanged(_lastDocumentHeight);
774 ensureCursorVisible();
778 void MultiLineEdit::on_documentHeightChanged(qreal)
784 void MultiLineEdit::reset()
786 // every time the MultiLineEdit is cleared we also reset history index
787 _idx = _history.count();
789 QTextBlockFormat format = textCursor().blockFormat();
790 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
791 textCursor().setBlockFormat(format);
796 void MultiLineEdit::showHistoryEntry()
798 // if the user changed the history, display the changed line
799 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
800 QTextCursor cursor = textCursor();
801 QTextBlockFormat format = cursor.blockFormat();
802 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
803 cursor.setBlockFormat(format);
804 cursor.movePosition(QTextCursor::End);
805 setTextCursor(cursor);
810 void MultiLineEdit::addCompletionSpace()
812 // Inserting the space emits textChanged, which should not disable removal
813 _completionSpace = 2;
814 insertPlainText(" ");