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 #if QT_VERSION < 0x050000
189 QStyleOptionFrameV2 opt;
191 QStyleOptionFrame opt;
194 opt.rect = QRect(0, 0, 100, h);
195 opt.lineWidth = lineWidth();
196 opt.midLineWidth = midLineWidth();
197 opt.state |= QStyle::State_Sunken;
198 QWidget *widget = this;
202 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), widget);
203 if (s != _sizeHint) {
210 QSize MultiLineEdit::sizeHint() const
212 if (!_sizeHint.isValid()) {
213 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
214 that->updateSizeHint();
220 QSize MultiLineEdit::minimumSizeHint() const
226 void MultiLineEdit::setEmacsMode(bool enable)
232 void MultiLineEdit::setSpellCheckEnabled(bool enable)
235 setCheckSpellingEnabled(enable);
242 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *)
244 _pasteProtectionEnabled = enable;
248 void MultiLineEdit::historyMoveBack()
250 addToHistory(convertRichtextToMircCodes(), true);
259 void MultiLineEdit::historyMoveForward()
261 addToHistory(convertRichtextToMircCodes(), true);
263 if (_idx < _history.count()) {
265 if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
268 reset(); // equals clear() in this case
271 addToHistory(convertRichtextToMircCodes());
277 bool MultiLineEdit::addToHistory(const QString &text, bool temporary)
282 Q_ASSERT(0 <= _idx && _idx <= _history.count());
285 // if an entry of the history is changed, we remember it and show it again at this
286 // position until a line was actually sent
287 // sent lines get appended to the history
288 if (_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
289 _tempHistory[_idx] = text;
294 if (_history.isEmpty() || text != _history.last()) {
296 _tempHistory.clear();
304 bool MultiLineEdit::event(QEvent *e)
306 // We need to make sure that global shortcuts aren't eaten
307 if (e->type() == QEvent::ShortcutOverride) {
308 QKeyEvent *event = static_cast<QKeyEvent *>(e);
309 QKeySequence key = QKeySequence(event->key() | event->modifiers());
310 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
311 if (action->shortcuts().contains(key)) {
318 return MultiLineEditParent::event(e);
322 void MultiLineEdit::keyPressEvent(QKeyEvent *event)
324 if (event == QKeySequence::InsertLineSeparator) {
325 if (_mode == SingleLine) {
330 MultiLineEditParent::keyPressEvent(event);
334 switch (event->key()) {
336 if (event->modifiers() & Qt::ShiftModifier)
340 if (!(event->modifiers() & Qt::ControlModifier)) {
341 int pos = textCursor().position();
342 moveCursor(QTextCursor::Up);
343 if (pos == textCursor().position()) // already on top line -> history
352 if (event->modifiers() & Qt::ShiftModifier)
356 if (!(event->modifiers() & Qt::ControlModifier)) {
357 int pos = textCursor().position();
358 moveCursor(QTextCursor::Down);
359 if (pos == textCursor().position()) // already on bottom line -> history
360 historyMoveForward();
363 historyMoveForward();
374 // We don't want to have the tab key react even if no completer is installed
384 if (event->modifiers() & Qt::ControlModifier) {
385 switch (event->key()) {
388 moveCursor(QTextCursor::StartOfLine);
391 moveCursor(QTextCursor::EndOfLine);
394 moveCursor(QTextCursor::Right);
397 moveCursor(QTextCursor::Left);
405 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
413 else if (event->modifiers() & Qt::MetaModifier ||
414 event->modifiers() & Qt::AltModifier)
416 switch (event->key()) {
418 moveCursor(QTextCursor::WordRight);
421 moveCursor(QTextCursor::WordLeft);
424 moveCursor(QTextCursor::WordRight);
427 moveCursor(QTextCursor::WordLeft);
430 moveCursor(QTextCursor::Start);
432 case Qt::Key_Greater:
433 moveCursor(QTextCursor::End);
438 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
442 case Qt::Key_U: // uppercase word
443 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
444 textCursor().insertText(textCursor().selectedText().toUpper());
447 case Qt::Key_L: // lowercase word
448 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
449 textCursor().insertText(textCursor().selectedText().toLower());
454 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
455 QString const text = textCursor().selectedText();
456 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
462 moveCursor(QTextCursor::StartOfWord);
463 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
464 QString const word1 = textCursor().selectedText();
465 textCursor().clearSelection();
466 moveCursor(QTextCursor::WordRight);
467 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
468 QString const word2 = textCursor().selectedText();
469 if (!word2.isEmpty() && !word1.isEmpty()) {
470 textCursor().insertText(word1);
471 moveCursor(QTextCursor::WordLeft);
472 moveCursor(QTextCursor::WordLeft);
473 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
474 textCursor().insertText(word2);
475 moveCursor(QTextCursor::WordRight);
476 moveCursor(QTextCursor::EndOfWord);
488 KTextEdit::keyPressEvent(event);
490 QTextEdit::keyPressEvent(event);
495 QString MultiLineEdit::convertRichtextToMircCodes()
497 bool underline, bold, italic, color;
498 QString mircText, mircFgColor, mircBgColor;
499 QTextCursor cursor = textCursor();
500 QTextCursor peekcursor = textCursor();
501 cursor.movePosition(QTextCursor::Start);
503 underline = bold = italic = color = false;
505 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
506 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
507 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
510 mircText.append('\x03');
514 mircText.append('\x1f');
518 mircText.append('\x1d');
522 mircText.append('\x02');
524 mircText.append('\n');
527 if (!bold && cursor.charFormat().font().bold()) {
529 mircText.append('\x02');
531 if (!italic && cursor.charFormat().fontItalic()) {
533 mircText.append('\x1d');
535 if (!underline && cursor.charFormat().fontUnderline()) {
537 mircText.append('\x1f');
539 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
541 mircText.append('\x03');
542 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
543 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
545 if (mircFgColor.isEmpty()) {
546 mircFgColor = "01"; //use black if the current foreground color can't be converted
549 mircText.append(mircFgColor);
550 if (cursor.charFormat().background().isOpaque())
551 mircText.append("," + mircBgColor);
554 mircText.append(cursor.selectedText());
556 peekcursor.setPosition(cursor.position());
557 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
559 if (mircCodesChanged(cursor, peekcursor)) {
562 mircText.append('\x03');
566 mircText.append('\x1f');
570 mircText.append('\x1d');
574 mircText.append('\x02');
579 cursor.clearSelection();
583 mircText.append('\x03');
586 mircText.append('\x1f');
589 mircText.append('\x1d');
592 mircText.append('\x02');
598 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor)
600 bool changed = false;
601 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
603 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
605 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
607 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
609 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
615 QString MultiLineEdit::convertMircCodesToHtml(const QString &text)
618 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
624 posRight = mircCode.indexIn(text, posLeft);
627 words << text.mid(posLeft);
628 break; // no more mirc color codes
631 if (posLeft < posRight) {
632 words << text.mid(posLeft, posRight - posLeft);
636 posRight = text.indexOf(mircCode.cap(), posRight + 1);
637 words << text.mid(posLeft, posRight + 1 - posLeft);
638 posLeft = posRight + 1;
641 for (int i = 0; i < words.count(); i++) {
643 if (words[i].contains('\x02')) {
644 style.append(" font-weight:600;");
645 words[i].replace('\x02', "");
647 if (words[i].contains('\x1d')) {
648 style.append(" font-style:italic;");
649 words[i].replace('\x1d', "");
651 if (words[i].contains('\x1f')) {
652 style.append(" text-decoration: underline;");
653 words[i].replace('\x1f', "");
655 if (words[i].contains('\x03')) {
656 int pos = words[i].indexOf('\x03');
658 QString fg = words[i].mid(pos + 1, 2);
660 if (words[i][pos+3] == ',')
661 bg = words[i].mid(pos+4, 2);
663 style.append(" color:");
664 style.append(_mircColorMap[fg]);
668 style.append(" background-color:");
669 style.append(_mircColorMap[bg]);
673 words[i].replace(pos, len, "");
674 words[i].replace('\x03', "");
676 words[i].replace("&", "&");
677 words[i].replace("<", "<");
678 words[i].replace(">", ">");
679 words[i].replace("\"", """);
680 if (style.isEmpty()) {
681 words[i] = "<span>" + words[i] + "</span>";
684 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
687 return words.join("").replace("\n", "<br />");
691 void MultiLineEdit::on_returnPressed()
693 on_returnPressed(convertRichtextToMircCodes());
697 void MultiLineEdit::on_returnPressed(QString text)
699 if (_completionSpace && text.endsWith(" ")) {
703 if (!text.isEmpty()) {
704 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
708 emit textEntered(line);
711 _tempHistory.clear();
714 emit noTextEntered();
719 void MultiLineEdit::on_textChanged()
721 _completionSpace = qMax(_completionSpace - 1, 0);
723 QString newText = text();
724 newText.replace("\r\n", "\n");
725 newText.replace('\r', '\n');
726 if (_mode == SingleLine) {
727 if (!pasteProtectionEnabled())
728 newText.replace('\n', ' ');
729 else if (newText.contains('\n')) {
730 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
733 if (lines.count() >= 4) {
734 QString msg = tr("Do you really want to paste %n line(s)?", "", lines.count());
736 for (int i = 0; i < 4; i++) {
737 #if QT_VERSION < 0x050000
738 msg += Qt::escape(lines[i].left(40));
740 msg += lines[i].left(40).toHtmlEscaped();
742 if (lines[i].count() > 40)
747 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
748 question.setDefaultButton(QMessageBox::No);
750 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
752 if (question.exec() != QMessageBox::Yes)
756 foreach(QString line, lines) {
764 _singleLine = (newText.indexOf('\n') < 0);
766 if (document()->size().height() != _lastDocumentHeight) {
767 _lastDocumentHeight = document()->size().height();
768 on_documentHeightChanged(_lastDocumentHeight);
771 ensureCursorVisible();
775 void MultiLineEdit::on_documentHeightChanged(qreal)
781 void MultiLineEdit::reset()
783 // every time the MultiLineEdit is cleared we also reset history index
784 _idx = _history.count();
786 QTextBlockFormat format = textCursor().blockFormat();
787 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
788 textCursor().setBlockFormat(format);
793 void MultiLineEdit::showHistoryEntry()
795 // if the user changed the history, display the changed line
796 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
797 QTextCursor cursor = textCursor();
798 QTextBlockFormat format = cursor.blockFormat();
799 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
800 cursor.setBlockFormat(format);
801 cursor.movePosition(QTextCursor::End);
802 setTextCursor(cursor);
807 void MultiLineEdit::addCompletionSpace()
809 // Inserting the space emits textChanged, which should not disable removal
810 _completionSpace = 2;
811 insertPlainText(" ");