1 /***************************************************************************
2 * Copyright (C) 2005-2016 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>
26 # include <Sonnet/SpellCheckDecorator>
29 #include "actioncollection.h"
30 #include "bufferview.h"
31 #include "graphicalui.h"
32 #include "multilineedit.h"
33 #include "tabcompleter.h"
35 const int leftMargin = 3;
37 MultiLineEdit::MultiLineEdit(QWidget *parent)
38 : MultiLineEditParent(parent),
44 _scrollBarsEnabled(true),
45 _pasteProtectionEnabled(true),
48 _lastDocumentHeight(-1)
50 document()->setDocumentMargin(0);
52 setAcceptRichText(false);
54 enableFindReplace(false);
58 new Sonnet::SpellCheckDecorator(this);
62 setLineWrapEnabled(false);
65 // Prevent QTextHtmlImporter::appendNodeText from eating whitespace
66 document()->setDefaultStyleSheet("span { white-space: pre-wrap; }");
68 connect(this, SIGNAL(textChanged()), this, SLOT(on_textChanged()));
70 _mircColorMap["00"] = "#ffffff";
71 _mircColorMap["01"] = "#000000";
72 _mircColorMap["02"] = "#000080";
73 _mircColorMap["03"] = "#008000";
74 _mircColorMap["04"] = "#ff0000";
75 _mircColorMap["05"] = "#800000";
76 _mircColorMap["06"] = "#800080";
77 _mircColorMap["07"] = "#ffa500";
78 _mircColorMap["08"] = "#ffff00";
79 _mircColorMap["09"] = "#00ff00";
80 _mircColorMap["10"] = "#008080";
81 _mircColorMap["11"] = "#00ffff";
82 _mircColorMap["12"] = "#4169e1";
83 _mircColorMap["13"] = "#ff00ff";
84 _mircColorMap["14"] = "#808080";
85 _mircColorMap["15"] = "#c0c0c0";
89 MultiLineEdit::~MultiLineEdit()
93 #if defined HAVE_KF5 || defined HAVE_KDE4
94 void MultiLineEdit::createHighlighter()
96 KTextEdit::createHighlighter();
98 highlighter()->setAutomatic(false);
102 void MultiLineEdit::setCustomFont(const QFont &font)
109 void MultiLineEdit::setMode(Mode mode)
118 void MultiLineEdit::setLineWrapEnabled(bool enable)
120 setLineWrapMode(enable ? WidgetWidth : NoWrap);
125 void MultiLineEdit::setMinHeight(int lines)
127 if (lines == _minHeight)
135 void MultiLineEdit::setMaxHeight(int lines)
137 if (lines == _maxHeight)
145 void MultiLineEdit::setScrollBarsEnabled(bool enable)
147 if (_scrollBarsEnabled == enable)
150 _scrollBarsEnabled = enable;
155 void MultiLineEdit::updateScrollBars()
157 QFontMetrics fm(font());
158 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
159 if (_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
160 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
162 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
164 if (!_scrollBarsEnabled || isSingleLine())
165 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
167 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
171 void MultiLineEdit::resizeEvent(QResizeEvent *event)
173 QTextEdit::resizeEvent(event);
179 void MultiLineEdit::updateSizeHint()
181 QFontMetrics fm(font());
182 int minPixelHeight = fm.lineSpacing() * _minHeight;
183 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
184 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
186 // use the style to determine a decent size
187 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
188 QStyleOptionFrameV2 opt;
190 opt.rect = QRect(0, 0, 100, h);
191 opt.lineWidth = lineWidth();
192 opt.midLineWidth = midLineWidth();
193 opt.state |= QStyle::State_Sunken;
194 QWidget *widget = this;
198 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), widget);
199 if (s != _sizeHint) {
206 QSize MultiLineEdit::sizeHint() const
208 if (!_sizeHint.isValid()) {
209 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
210 that->updateSizeHint();
216 QSize MultiLineEdit::minimumSizeHint() const
222 void MultiLineEdit::setEmacsMode(bool enable)
228 void MultiLineEdit::setSpellCheckEnabled(bool enable)
231 setCheckSpellingEnabled(enable);
238 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *)
240 _pasteProtectionEnabled = enable;
244 void MultiLineEdit::historyMoveBack()
246 addToHistory(convertRichtextToMircCodes(), true);
255 void MultiLineEdit::historyMoveForward()
257 addToHistory(convertRichtextToMircCodes(), true);
259 if (_idx < _history.count()) {
261 if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
264 reset(); // equals clear() in this case
267 addToHistory(convertRichtextToMircCodes());
273 bool MultiLineEdit::addToHistory(const QString &text, bool temporary)
278 Q_ASSERT(0 <= _idx && _idx <= _history.count());
281 // if an entry of the history is changed, we remember it and show it again at this
282 // position until a line was actually sent
283 // sent lines get appended to the history
284 if (_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
285 _tempHistory[_idx] = text;
290 if (_history.isEmpty() || text != _history.last()) {
292 _tempHistory.clear();
300 bool MultiLineEdit::event(QEvent *e)
302 // We need to make sure that global shortcuts aren't eaten
303 if (e->type() == QEvent::ShortcutOverride) {
304 QKeyEvent *event = static_cast<QKeyEvent *>(e);
305 QKeySequence key = QKeySequence(event->key() | event->modifiers());
306 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
307 if (action->shortcuts().contains(key)) {
314 return MultiLineEditParent::event(e);
318 void MultiLineEdit::keyPressEvent(QKeyEvent *event)
320 if (event == QKeySequence::InsertLineSeparator) {
321 if (_mode == SingleLine) {
326 MultiLineEditParent::keyPressEvent(event);
330 switch (event->key()) {
332 if (event->modifiers() & Qt::ShiftModifier)
336 if (!(event->modifiers() & Qt::ControlModifier)) {
337 int pos = textCursor().position();
338 moveCursor(QTextCursor::Up);
339 if (pos == textCursor().position()) // already on top line -> history
348 if (event->modifiers() & Qt::ShiftModifier)
352 if (!(event->modifiers() & Qt::ControlModifier)) {
353 int pos = textCursor().position();
354 moveCursor(QTextCursor::Down);
355 if (pos == textCursor().position()) // already on bottom line -> history
356 historyMoveForward();
359 historyMoveForward();
370 // We don't want to have the tab key react even if no completer is installed
380 if (event->modifiers() & Qt::ControlModifier) {
381 switch (event->key()) {
384 moveCursor(QTextCursor::StartOfLine);
387 moveCursor(QTextCursor::EndOfLine);
390 moveCursor(QTextCursor::Right);
393 moveCursor(QTextCursor::Left);
401 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
409 else if (event->modifiers() & Qt::MetaModifier ||
410 event->modifiers() & Qt::AltModifier)
412 switch (event->key()) {
414 moveCursor(QTextCursor::WordRight);
417 moveCursor(QTextCursor::WordLeft);
420 moveCursor(QTextCursor::WordRight);
423 moveCursor(QTextCursor::WordLeft);
426 moveCursor(QTextCursor::Start);
428 case Qt::Key_Greater:
429 moveCursor(QTextCursor::End);
434 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
438 case Qt::Key_U: // uppercase word
439 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
440 textCursor().insertText(textCursor().selectedText().toUpper());
443 case Qt::Key_L: // lowercase word
444 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
445 textCursor().insertText(textCursor().selectedText().toLower());
450 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
451 QString const text = textCursor().selectedText();
452 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
458 moveCursor(QTextCursor::StartOfWord);
459 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
460 QString const word1 = textCursor().selectedText();
461 textCursor().clearSelection();
462 moveCursor(QTextCursor::WordRight);
463 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
464 QString const word2 = textCursor().selectedText();
465 if (!word2.isEmpty() && !word1.isEmpty()) {
466 textCursor().insertText(word1);
467 moveCursor(QTextCursor::WordLeft);
468 moveCursor(QTextCursor::WordLeft);
469 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
470 textCursor().insertText(word2);
471 moveCursor(QTextCursor::WordRight);
472 moveCursor(QTextCursor::EndOfWord);
484 KTextEdit::keyPressEvent(event);
486 QTextEdit::keyPressEvent(event);
491 QString MultiLineEdit::convertRichtextToMircCodes()
493 bool underline, bold, italic, color;
494 QString mircText, mircFgColor, mircBgColor;
495 QTextCursor cursor = textCursor();
496 QTextCursor peekcursor = textCursor();
497 cursor.movePosition(QTextCursor::Start);
499 underline = bold = italic = color = false;
501 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
502 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
503 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
506 mircText.append('\x03');
510 mircText.append('\x1f');
514 mircText.append('\x1d');
518 mircText.append('\x02');
520 mircText.append('\n');
523 if (!bold && cursor.charFormat().font().bold()) {
525 mircText.append('\x02');
527 if (!italic && cursor.charFormat().fontItalic()) {
529 mircText.append('\x1d');
531 if (!underline && cursor.charFormat().fontUnderline()) {
533 mircText.append('\x1f');
535 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
537 mircText.append('\x03');
538 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
539 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
541 if (mircFgColor.isEmpty()) {
542 mircFgColor = "01"; //use black if the current foreground color can't be converted
545 mircText.append(mircFgColor);
546 if (cursor.charFormat().background().isOpaque())
547 mircText.append("," + mircBgColor);
550 mircText.append(cursor.selectedText());
552 peekcursor.setPosition(cursor.position());
553 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
555 if (mircCodesChanged(cursor, peekcursor)) {
558 mircText.append('\x03');
562 mircText.append('\x1f');
566 mircText.append('\x1d');
570 mircText.append('\x02');
575 cursor.clearSelection();
579 mircText.append('\x03');
582 mircText.append('\x1f');
585 mircText.append('\x1d');
588 mircText.append('\x02');
594 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor)
596 bool changed = false;
597 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
599 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
601 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
603 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
605 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
611 QString MultiLineEdit::convertMircCodesToHtml(const QString &text)
614 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
620 posRight = mircCode.indexIn(text, posLeft);
623 words << text.mid(posLeft);
624 break; // no more mirc color codes
627 if (posLeft < posRight) {
628 words << text.mid(posLeft, posRight - posLeft);
632 posRight = text.indexOf(mircCode.cap(), posRight + 1);
633 words << text.mid(posLeft, posRight + 1 - posLeft);
634 posLeft = posRight + 1;
637 for (int i = 0; i < words.count(); i++) {
639 if (words[i].contains('\x02')) {
640 style.append(" font-weight:600;");
641 words[i].replace('\x02', "");
643 if (words[i].contains('\x1d')) {
644 style.append(" font-style:italic;");
645 words[i].replace('\x1d', "");
647 if (words[i].contains('\x1f')) {
648 style.append(" text-decoration: underline;");
649 words[i].replace('\x1f', "");
651 if (words[i].contains('\x03')) {
652 int pos = words[i].indexOf('\x03');
654 QString fg = words[i].mid(pos + 1, 2);
656 if (words[i][pos+3] == ',')
657 bg = words[i].mid(pos+4, 2);
659 style.append(" color:");
660 style.append(_mircColorMap[fg]);
664 style.append(" background-color:");
665 style.append(_mircColorMap[bg]);
669 words[i].replace(pos, len, "");
670 words[i].replace('\x03', "");
672 words[i].replace("&", "&");
673 words[i].replace("<", "<");
674 words[i].replace(">", ">");
675 words[i].replace("\"", """);
676 if (style.isEmpty()) {
677 words[i] = "<span>" + words[i] + "</span>";
680 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
683 return words.join("").replace("\n", "<br />");
687 void MultiLineEdit::on_returnPressed()
689 on_returnPressed(convertRichtextToMircCodes());
693 void MultiLineEdit::on_returnPressed(QString text)
695 if (_completionSpace && text.endsWith(" ")) {
699 if (!text.isEmpty()) {
700 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
704 emit textEntered(line);
707 _tempHistory.clear();
710 emit noTextEntered();
715 void MultiLineEdit::on_textChanged()
717 _completionSpace = qMax(_completionSpace - 1, 0);
719 QString newText = text();
720 newText.replace("\r\n", "\n");
721 newText.replace('\r', '\n');
722 if (_mode == SingleLine) {
723 if (!pasteProtectionEnabled())
724 newText.replace('\n', ' ');
725 else if (newText.contains('\n')) {
726 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
729 if (lines.count() >= 4) {
730 QString msg = tr("Do you really want to paste %n line(s)?", "", lines.count());
732 for (int i = 0; i < 4; i++) {
733 #if QT_VERSION < 0x050000
734 msg += Qt::escape(lines[i].left(40));
736 msg += lines[i].left(40).toHtmlEscaped();
738 if (lines[i].count() > 40)
743 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
744 question.setDefaultButton(QMessageBox::No);
746 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
748 if (question.exec() != QMessageBox::Yes)
752 foreach(QString line, lines) {
760 _singleLine = (newText.indexOf('\n') < 0);
762 if (document()->size().height() != _lastDocumentHeight) {
763 _lastDocumentHeight = document()->size().height();
764 on_documentHeightChanged(_lastDocumentHeight);
767 ensureCursorVisible();
771 void MultiLineEdit::on_documentHeightChanged(qreal)
777 void MultiLineEdit::reset()
779 // every time the MultiLineEdit is cleared we also reset history index
780 _idx = _history.count();
782 QTextBlockFormat format = textCursor().blockFormat();
783 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
784 textCursor().setBlockFormat(format);
789 void MultiLineEdit::showHistoryEntry()
791 // if the user changed the history, display the changed line
792 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
793 QTextCursor cursor = textCursor();
794 QTextBlockFormat format = cursor.blockFormat();
795 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
796 cursor.setBlockFormat(format);
797 cursor.movePosition(QTextCursor::End);
798 setTextCursor(cursor);
803 void MultiLineEdit::addCompletionSpace()
805 // Inserting the space emits textChanged, which should not disable removal
806 _completionSpace = 2;
807 insertPlainText(" ");