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()
91 #if defined HAVE_SONNET && !defined HAVE_KDE
92 Sonnet::Highlighter *MultiLineEdit::highlighter() const
94 return _spellCheckDecorator->highlighter();
98 void MultiLineEdit::setSpellCheckEnabled(bool enabled)
100 highlighter()->setActive(enabled);
102 highlighter()->slotRehighlight();
106 void MultiLineEdit::contextMenuEvent(QContextMenuEvent *event)
108 QMenu *menu = createStandardContextMenu();
109 menu->addSeparator();
111 auto action = menu->addAction(tr("Auto Spell Check"));
112 action->setCheckable(true);
113 action->setChecked(highlighter()->isActive());
114 connect(action, SIGNAL(toggled(bool)), this, SLOT(setSpellCheckEnabled(bool)));
116 menu->exec(event->globalPos());
123 void MultiLineEdit::setCustomFont(const QFont &font)
130 void MultiLineEdit::setMode(Mode mode)
139 void MultiLineEdit::setLineWrapEnabled(bool enable)
141 setLineWrapMode(enable ? WidgetWidth : NoWrap);
146 void MultiLineEdit::setMinHeight(int lines)
148 if (lines == _minHeight)
156 void MultiLineEdit::setMaxHeight(int lines)
158 if (lines == _maxHeight)
166 void MultiLineEdit::setScrollBarsEnabled(bool enable)
168 if (_scrollBarsEnabled == enable)
171 _scrollBarsEnabled = enable;
176 void MultiLineEdit::updateScrollBars()
178 QFontMetrics fm(font());
179 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
180 if (_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
181 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
183 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
185 if (!_scrollBarsEnabled || isSingleLine())
186 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
188 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
192 void MultiLineEdit::resizeEvent(QResizeEvent *event)
194 QTextEdit::resizeEvent(event);
200 void MultiLineEdit::updateSizeHint()
202 QFontMetrics fm(font());
203 int minPixelHeight = fm.lineSpacing() * _minHeight;
204 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
205 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
207 // use the style to determine a decent size
208 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
209 #if QT_VERSION < 0x050000
210 QStyleOptionFrameV2 opt;
212 QStyleOptionFrame opt;
215 opt.rect = QRect(0, 0, 100, h);
216 opt.lineWidth = lineWidth();
217 opt.midLineWidth = midLineWidth();
218 opt.state |= QStyle::State_Sunken;
219 QWidget *widget = this;
223 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), widget);
224 if (s != _sizeHint) {
231 QSize MultiLineEdit::sizeHint() const
233 if (!_sizeHint.isValid()) {
234 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
235 that->updateSizeHint();
241 QSize MultiLineEdit::minimumSizeHint() const
247 void MultiLineEdit::setEmacsMode(bool enable)
253 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *)
255 _pasteProtectionEnabled = enable;
259 void MultiLineEdit::historyMoveBack()
261 addToHistory(convertRichtextToMircCodes(), true);
270 void MultiLineEdit::historyMoveForward()
272 addToHistory(convertRichtextToMircCodes(), true);
274 if (_idx < _history.count()) {
276 if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
279 reset(); // equals clear() in this case
282 addToHistory(convertRichtextToMircCodes());
288 bool MultiLineEdit::addToHistory(const QString &text, bool temporary)
293 Q_ASSERT(0 <= _idx && _idx <= _history.count());
296 // if an entry of the history is changed, we remember it and show it again at this
297 // position until a line was actually sent
298 // sent lines get appended to the history
299 if (_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
300 _tempHistory[_idx] = text;
305 if (_history.isEmpty() || text != _history.last()) {
307 _tempHistory.clear();
315 bool MultiLineEdit::event(QEvent *e)
317 // We need to make sure that global shortcuts aren't eaten
318 if (e->type() == QEvent::ShortcutOverride) {
319 QKeyEvent *event = static_cast<QKeyEvent *>(e);
320 QKeySequence key = QKeySequence(event->key() | event->modifiers());
321 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
322 if (action->shortcuts().contains(key)) {
329 return MultiLineEditParent::event(e);
333 void MultiLineEdit::keyPressEvent(QKeyEvent *event)
335 if (event == QKeySequence::InsertLineSeparator) {
336 if (_mode == SingleLine) {
341 MultiLineEditParent::keyPressEvent(event);
345 switch (event->key()) {
347 if (event->modifiers() & Qt::ShiftModifier)
351 if (!(event->modifiers() & Qt::ControlModifier)) {
352 int pos = textCursor().position();
353 moveCursor(QTextCursor::Up);
354 if (pos == textCursor().position()) // already on top line -> history
363 if (event->modifiers() & Qt::ShiftModifier)
367 if (!(event->modifiers() & Qt::ControlModifier)) {
368 int pos = textCursor().position();
369 moveCursor(QTextCursor::Down);
370 if (pos == textCursor().position()) // already on bottom line -> history
371 historyMoveForward();
374 historyMoveForward();
385 // We don't want to have the tab key react even if no completer is installed
395 if (event->modifiers() & Qt::ControlModifier) {
396 switch (event->key()) {
399 moveCursor(QTextCursor::StartOfLine);
402 moveCursor(QTextCursor::EndOfLine);
405 moveCursor(QTextCursor::Right);
408 moveCursor(QTextCursor::Left);
416 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
424 else if (event->modifiers() & Qt::MetaModifier ||
425 event->modifiers() & Qt::AltModifier)
427 switch (event->key()) {
429 moveCursor(QTextCursor::WordRight);
432 moveCursor(QTextCursor::WordLeft);
435 moveCursor(QTextCursor::WordRight);
438 moveCursor(QTextCursor::WordLeft);
441 moveCursor(QTextCursor::Start);
443 case Qt::Key_Greater:
444 moveCursor(QTextCursor::End);
449 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
453 case Qt::Key_U: // uppercase word
454 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
455 textCursor().insertText(textCursor().selectedText().toUpper());
458 case Qt::Key_L: // lowercase word
459 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
460 textCursor().insertText(textCursor().selectedText().toLower());
465 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
466 QString const text = textCursor().selectedText();
467 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
473 moveCursor(QTextCursor::StartOfWord);
474 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
475 QString const word1 = textCursor().selectedText();
476 textCursor().clearSelection();
477 moveCursor(QTextCursor::WordRight);
478 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
479 QString const word2 = textCursor().selectedText();
480 if (!word2.isEmpty() && !word1.isEmpty()) {
481 textCursor().insertText(word1);
482 moveCursor(QTextCursor::WordLeft);
483 moveCursor(QTextCursor::WordLeft);
484 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
485 textCursor().insertText(word2);
486 moveCursor(QTextCursor::WordRight);
487 moveCursor(QTextCursor::EndOfWord);
499 KTextEdit::keyPressEvent(event);
501 QTextEdit::keyPressEvent(event);
506 QString MultiLineEdit::convertRichtextToMircCodes()
508 bool underline, bold, italic, color;
509 QString mircText, mircFgColor, mircBgColor;
510 QTextCursor cursor = textCursor();
511 QTextCursor peekcursor = textCursor();
512 cursor.movePosition(QTextCursor::Start);
514 underline = bold = italic = color = false;
516 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
517 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
518 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
521 mircText.append('\x03');
525 mircText.append('\x1f');
529 mircText.append('\x1d');
533 mircText.append('\x02');
535 mircText.append('\n');
538 if (!bold && cursor.charFormat().font().bold()) {
540 mircText.append('\x02');
542 if (!italic && cursor.charFormat().fontItalic()) {
544 mircText.append('\x1d');
546 if (!underline && cursor.charFormat().fontUnderline()) {
548 mircText.append('\x1f');
550 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
552 mircText.append('\x03');
553 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
554 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
556 if (mircFgColor.isEmpty()) {
557 mircFgColor = "01"; //use black if the current foreground color can't be converted
560 mircText.append(mircFgColor);
561 if (cursor.charFormat().background().isOpaque())
562 mircText.append("," + mircBgColor);
565 mircText.append(cursor.selectedText());
567 peekcursor.setPosition(cursor.position());
568 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
570 if (mircCodesChanged(cursor, peekcursor)) {
573 mircText.append('\x03');
577 mircText.append('\x1f');
581 mircText.append('\x1d');
585 mircText.append('\x02');
590 cursor.clearSelection();
594 mircText.append('\x03');
597 mircText.append('\x1f');
600 mircText.append('\x1d');
603 mircText.append('\x02');
609 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor)
611 bool changed = false;
612 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
614 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
616 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
618 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
620 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
626 QString MultiLineEdit::convertMircCodesToHtml(const QString &text)
629 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
635 posRight = mircCode.indexIn(text, posLeft);
638 words << text.mid(posLeft);
639 break; // no more mirc color codes
642 if (posLeft < posRight) {
643 words << text.mid(posLeft, posRight - posLeft);
647 posRight = text.indexOf(mircCode.cap(), posRight + 1);
648 words << text.mid(posLeft, posRight + 1 - posLeft);
649 posLeft = posRight + 1;
652 for (int i = 0; i < words.count(); i++) {
654 if (words[i].contains('\x02')) {
655 style.append(" font-weight:600;");
656 words[i].replace('\x02', "");
658 if (words[i].contains('\x1d')) {
659 style.append(" font-style:italic;");
660 words[i].replace('\x1d', "");
662 if (words[i].contains('\x1f')) {
663 style.append(" text-decoration: underline;");
664 words[i].replace('\x1f', "");
666 if (words[i].contains('\x03')) {
667 int pos = words[i].indexOf('\x03');
669 QString fg = words[i].mid(pos + 1, 2);
671 if (words[i][pos+3] == ',')
672 bg = words[i].mid(pos+4, 2);
674 style.append(" color:");
675 style.append(_mircColorMap[fg]);
679 style.append(" background-color:");
680 style.append(_mircColorMap[bg]);
684 words[i].replace(pos, len, "");
685 words[i].replace('\x03', "");
687 words[i].replace("&", "&");
688 words[i].replace("<", "<");
689 words[i].replace(">", ">");
690 words[i].replace("\"", """);
691 if (style.isEmpty()) {
692 words[i] = "<span>" + words[i] + "</span>";
695 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
698 return words.join("").replace("\n", "<br />");
702 void MultiLineEdit::on_returnPressed()
704 on_returnPressed(convertRichtextToMircCodes());
708 void MultiLineEdit::on_returnPressed(QString text)
710 if (_completionSpace && text.endsWith(" ")) {
714 if (!text.isEmpty()) {
715 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
719 emit textEntered(line);
722 _tempHistory.clear();
725 emit noTextEntered();
730 void MultiLineEdit::on_textChanged()
732 _completionSpace = qMax(_completionSpace - 1, 0);
734 QString newText = text();
735 newText.replace("\r\n", "\n");
736 newText.replace('\r', '\n');
737 if (_mode == SingleLine) {
738 if (!pasteProtectionEnabled())
739 newText.replace('\n', ' ');
740 else if (newText.contains('\n')) {
741 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
744 if (lines.count() >= 4) {
745 QString msg = tr("Do you really want to paste %n line(s)?", "", lines.count());
747 for (int i = 0; i < 4; i++) {
748 #if QT_VERSION < 0x050000
749 msg += Qt::escape(lines[i].left(40));
751 msg += lines[i].left(40).toHtmlEscaped();
753 if (lines[i].count() > 40)
758 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
759 question.setDefaultButton(QMessageBox::No);
761 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
763 if (question.exec() != QMessageBox::Yes)
767 foreach(QString line, lines) {
775 _singleLine = (newText.indexOf('\n') < 0);
777 if (document()->size().height() != _lastDocumentHeight) {
778 _lastDocumentHeight = document()->size().height();
779 on_documentHeightChanged(_lastDocumentHeight);
782 ensureCursorVisible();
786 void MultiLineEdit::on_documentHeightChanged(qreal)
792 void MultiLineEdit::reset()
794 // every time the MultiLineEdit is cleared we also reset history index
795 _idx = _history.count();
797 QTextBlockFormat format = textCursor().blockFormat();
798 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
799 textCursor().setBlockFormat(format);
804 void MultiLineEdit::showHistoryEntry()
806 // if the user changed the history, display the changed line
807 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
808 QTextCursor cursor = textCursor();
809 QTextBlockFormat format = cursor.blockFormat();
810 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
811 cursor.setBlockFormat(format);
812 cursor.movePosition(QTextCursor::End);
813 setTextCursor(cursor);
818 void MultiLineEdit::addCompletionSpace()
820 // Inserting the space emits textChanged, which should not disable removal
821 _completionSpace = 2;
822 insertPlainText(" ");