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)
36 document()->setDocumentMargin(0);
38 setAcceptRichText(false);
40 enableFindReplace(false);
43 #if defined HAVE_SONNET && !defined HAVE_KDE
44 _spellCheckDecorator = new Sonnet::SpellCheckDecorator(this);
45 highlighter()->setActive(highlighter()->checkerEnabledByDefault());
49 setLineWrapEnabled(false);
52 // Prevent QTextHtmlImporter::appendNodeText from eating whitespace
53 document()->setDefaultStyleSheet("span { white-space: pre-wrap; }");
55 connect(this, SIGNAL(textChanged()), this, SLOT(on_textChanged()));
57 _mircColorMap["00"] = "#ffffff";
58 _mircColorMap["01"] = "#000000";
59 _mircColorMap["02"] = "#000080";
60 _mircColorMap["03"] = "#008000";
61 _mircColorMap["04"] = "#ff0000";
62 _mircColorMap["05"] = "#800000";
63 _mircColorMap["06"] = "#800080";
64 _mircColorMap["07"] = "#ffa500";
65 _mircColorMap["08"] = "#ffff00";
66 _mircColorMap["09"] = "#00ff00";
67 _mircColorMap["10"] = "#008080";
68 _mircColorMap["11"] = "#00ffff";
69 _mircColorMap["12"] = "#4169e1";
70 _mircColorMap["13"] = "#ff00ff";
71 _mircColorMap["14"] = "#808080";
72 _mircColorMap["15"] = "#c0c0c0";
76 MultiLineEdit::~MultiLineEdit()
80 #if defined HAVE_SONNET && !defined HAVE_KDE
81 Sonnet::Highlighter *MultiLineEdit::highlighter() const
83 return _spellCheckDecorator->highlighter();
87 void MultiLineEdit::setSpellCheckEnabled(bool enabled)
89 highlighter()->setActive(enabled);
91 highlighter()->slotRehighlight();
95 void MultiLineEdit::contextMenuEvent(QContextMenuEvent *event)
97 QMenu *menu = createStandardContextMenu();
100 auto action = menu->addAction(tr("Auto Spell Check"));
101 action->setCheckable(true);
102 action->setChecked(highlighter()->isActive());
103 connect(action, SIGNAL(toggled(bool)), this, SLOT(setSpellCheckEnabled(bool)));
105 menu->exec(event->globalPos());
112 void MultiLineEdit::setCustomFont(const QFont &font)
119 void MultiLineEdit::setMode(Mode mode)
128 void MultiLineEdit::setLineWrapEnabled(bool enable)
130 setLineWrapMode(enable ? WidgetWidth : NoWrap);
135 void MultiLineEdit::setMinHeight(int lines)
137 if (lines == _minHeight)
145 void MultiLineEdit::setMaxHeight(int lines)
147 if (lines == _maxHeight)
155 void MultiLineEdit::setScrollBarsEnabled(bool enable)
157 if (_scrollBarsEnabled == enable)
160 _scrollBarsEnabled = enable;
165 void MultiLineEdit::updateScrollBars()
167 QFontMetrics fm(font());
168 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
169 if (_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
170 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
172 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
174 if (!_scrollBarsEnabled || isSingleLine())
175 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
177 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
181 void MultiLineEdit::resizeEvent(QResizeEvent *event)
183 QTextEdit::resizeEvent(event);
189 void MultiLineEdit::updateSizeHint()
191 QFontMetrics fm(font());
192 int minPixelHeight = fm.lineSpacing() * _minHeight;
193 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
194 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
196 // use the style to determine a decent size
197 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
199 QStyleOptionFrame opt;
201 opt.rect = QRect(0, 0, 100, h);
202 opt.lineWidth = lineWidth();
203 opt.midLineWidth = midLineWidth();
204 opt.state |= QStyle::State_Sunken;
205 QWidget *widget = this;
209 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), widget);
210 if (s != _sizeHint) {
217 QSize MultiLineEdit::sizeHint() const
219 if (!_sizeHint.isValid()) {
220 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
221 that->updateSizeHint();
227 QSize MultiLineEdit::minimumSizeHint() const
233 void MultiLineEdit::setEmacsMode(bool enable)
239 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *)
241 _pasteProtectionEnabled = enable;
245 void MultiLineEdit::historyMoveBack()
247 addToHistory(convertRichtextToMircCodes(), true);
256 void MultiLineEdit::historyMoveForward()
258 addToHistory(convertRichtextToMircCodes(), true);
260 if (_idx < _history.count()) {
262 if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
265 reset(); // equals clear() in this case
268 addToHistory(convertRichtextToMircCodes());
274 bool MultiLineEdit::addToHistory(const QString &text, bool temporary)
279 Q_ASSERT(0 <= _idx && _idx <= _history.count());
282 // if an entry of the history is changed, we remember it and show it again at this
283 // position until a line was actually sent
284 // sent lines get appended to the history
285 if (_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
286 _tempHistory[_idx] = text;
291 if (_history.isEmpty() || text != _history.last()) {
293 _tempHistory.clear();
301 bool MultiLineEdit::event(QEvent *e)
303 // We need to make sure that global shortcuts aren't eaten
304 if (e->type() == QEvent::ShortcutOverride) {
305 QKeyEvent *event = static_cast<QKeyEvent *>(e);
306 QKeySequence key = QKeySequence(event->key() | event->modifiers());
307 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
308 if (action->shortcuts().contains(key)) {
315 return MultiLineEditParent::event(e);
319 void MultiLineEdit::keyPressEvent(QKeyEvent *event)
321 if (event == QKeySequence::InsertLineSeparator) {
322 if (_mode == SingleLine) {
327 MultiLineEditParent::keyPressEvent(event);
331 switch (event->key()) {
333 if (event->modifiers() & Qt::ShiftModifier)
337 if (!(event->modifiers() & Qt::ControlModifier)) {
338 int pos = textCursor().position();
339 moveCursor(QTextCursor::Up);
340 if (pos == textCursor().position()) // already on top line -> history
349 if (event->modifiers() & Qt::ShiftModifier)
353 if (!(event->modifiers() & Qt::ControlModifier)) {
354 int pos = textCursor().position();
355 moveCursor(QTextCursor::Down);
356 if (pos == textCursor().position()) // already on bottom line -> history
357 historyMoveForward();
360 historyMoveForward();
371 // We don't want to have the tab key react even if no completer is installed
381 if (event->modifiers() & Qt::ControlModifier) {
382 switch (event->key()) {
385 moveCursor(QTextCursor::StartOfLine);
388 moveCursor(QTextCursor::EndOfLine);
391 moveCursor(QTextCursor::Right);
394 moveCursor(QTextCursor::Left);
402 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
410 else if (event->modifiers() & Qt::MetaModifier ||
411 event->modifiers() & Qt::AltModifier)
413 switch (event->key()) {
415 moveCursor(QTextCursor::WordRight);
418 moveCursor(QTextCursor::WordLeft);
421 moveCursor(QTextCursor::WordRight);
424 moveCursor(QTextCursor::WordLeft);
427 moveCursor(QTextCursor::Start);
429 case Qt::Key_Greater:
430 moveCursor(QTextCursor::End);
435 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
439 case Qt::Key_U: // uppercase word
440 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
441 textCursor().insertText(textCursor().selectedText().toUpper());
444 case Qt::Key_L: // lowercase word
445 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
446 textCursor().insertText(textCursor().selectedText().toLower());
451 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
452 QString const text = textCursor().selectedText();
453 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
459 moveCursor(QTextCursor::StartOfWord);
460 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
461 QString const word1 = textCursor().selectedText();
462 textCursor().clearSelection();
463 moveCursor(QTextCursor::WordRight);
464 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
465 QString const word2 = textCursor().selectedText();
466 if (!word2.isEmpty() && !word1.isEmpty()) {
467 textCursor().insertText(word1);
468 moveCursor(QTextCursor::WordLeft);
469 moveCursor(QTextCursor::WordLeft);
470 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
471 textCursor().insertText(word2);
472 moveCursor(QTextCursor::WordRight);
473 moveCursor(QTextCursor::EndOfWord);
485 KTextEdit::keyPressEvent(event);
487 QTextEdit::keyPressEvent(event);
492 QString MultiLineEdit::convertRichtextToMircCodes()
494 bool underline, bold, italic, color;
495 QString mircText, mircFgColor, mircBgColor;
496 QTextCursor cursor = textCursor();
497 QTextCursor peekcursor = textCursor();
498 cursor.movePosition(QTextCursor::Start);
500 underline = bold = italic = color = false;
502 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
503 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
504 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
507 mircText.append('\x03');
511 mircText.append('\x1f');
515 mircText.append('\x1d');
519 mircText.append('\x02');
521 mircText.append('\n');
524 if (!bold && cursor.charFormat().font().bold()) {
526 mircText.append('\x02');
528 if (!italic && cursor.charFormat().fontItalic()) {
530 mircText.append('\x1d');
532 if (!underline && cursor.charFormat().fontUnderline()) {
534 mircText.append('\x1f');
536 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
538 mircText.append('\x03');
539 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
540 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
542 if (mircFgColor.isEmpty()) {
543 mircFgColor = "01"; //use black if the current foreground color can't be converted
546 mircText.append(mircFgColor);
547 if (cursor.charFormat().background().isOpaque())
548 mircText.append("," + mircBgColor);
551 mircText.append(cursor.selectedText());
553 peekcursor.setPosition(cursor.position());
554 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
556 if (mircCodesChanged(cursor, peekcursor)) {
559 mircText.append('\x03');
563 mircText.append('\x1f');
567 mircText.append('\x1d');
571 mircText.append('\x02');
576 cursor.clearSelection();
580 mircText.append('\x03');
583 mircText.append('\x1f');
586 mircText.append('\x1d');
589 mircText.append('\x02');
595 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor)
597 bool changed = false;
598 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
600 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
602 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
604 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
606 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
612 QString MultiLineEdit::convertMircCodesToHtml(const QString &text)
615 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
621 posRight = mircCode.indexIn(text, posLeft);
624 words << text.mid(posLeft);
625 break; // no more mirc color codes
628 if (posLeft < posRight) {
629 words << text.mid(posLeft, posRight - posLeft);
633 posRight = text.indexOf(mircCode.cap(), posRight + 1);
634 words << text.mid(posLeft, posRight + 1 - posLeft);
635 posLeft = posRight + 1;
638 for (int i = 0; i < words.count(); i++) {
640 if (words[i].contains('\x02')) {
641 style.append(" font-weight:600;");
642 words[i].replace('\x02', "");
644 if (words[i].contains('\x1d')) {
645 style.append(" font-style:italic;");
646 words[i].replace('\x1d', "");
648 if (words[i].contains('\x1f')) {
649 style.append(" text-decoration: underline;");
650 words[i].replace('\x1f', "");
652 if (words[i].contains('\x03')) {
653 int pos = words[i].indexOf('\x03');
655 QString fg = words[i].mid(pos + 1, 2);
657 if (words[i][pos+3] == ',')
658 bg = words[i].mid(pos+4, 2);
660 style.append(" color:");
661 style.append(_mircColorMap[fg]);
665 style.append(" background-color:");
666 style.append(_mircColorMap[bg]);
670 words[i].replace(pos, len, "");
671 words[i].replace('\x03', "");
673 words[i].replace("&", "&");
674 words[i].replace("<", "<");
675 words[i].replace(">", ">");
676 words[i].replace("\"", """);
677 if (style.isEmpty()) {
678 words[i] = "<span>" + words[i] + "</span>";
681 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
684 return words.join("").replace("\n", "<br />");
688 void MultiLineEdit::on_returnPressed()
690 on_returnPressed(convertRichtextToMircCodes());
694 void MultiLineEdit::on_returnPressed(QString text)
696 if (_completionSpace && text.endsWith(" ")) {
700 if (!text.isEmpty()) {
701 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
705 emit textEntered(line);
708 _tempHistory.clear();
711 emit noTextEntered();
716 void MultiLineEdit::on_textChanged()
718 _completionSpace = qMax(_completionSpace - 1, 0);
720 QString newText = text();
721 newText.replace("\r\n", "\n");
722 newText.replace('\r', '\n');
723 if (_mode == SingleLine) {
724 if (!pasteProtectionEnabled())
725 newText.replace('\n', ' ');
726 else if (newText.contains('\n')) {
727 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
730 if (lines.count() >= 4) {
731 QString msg = tr("Do you really want to paste %n line(s)?", "", lines.count());
733 for (int i = 0; i < 4; i++) {
734 msg += lines[i].left(40).toHtmlEscaped();
735 if (lines[i].count() > 40)
740 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
741 question.setDefaultButton(QMessageBox::No);
743 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
745 if (question.exec() != QMessageBox::Yes)
749 foreach(QString line, lines) {
757 _singleLine = (newText.indexOf('\n') < 0);
759 if (document()->size().height() != _lastDocumentHeight) {
760 _lastDocumentHeight = document()->size().height();
761 on_documentHeightChanged(_lastDocumentHeight);
764 ensureCursorVisible();
768 void MultiLineEdit::on_documentHeightChanged(qreal)
774 void MultiLineEdit::reset()
776 // every time the MultiLineEdit is cleared we also reset history index
777 _idx = _history.count();
779 QTextBlockFormat format = textCursor().blockFormat();
780 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
781 textCursor().setBlockFormat(format);
786 void MultiLineEdit::showHistoryEntry()
788 // if the user changed the history, display the changed line
789 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
790 QTextCursor cursor = textCursor();
791 QTextBlockFormat format = cursor.blockFormat();
792 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
793 cursor.setBlockFormat(format);
794 cursor.movePosition(QTextCursor::End);
795 setTextCursor(cursor);
800 void MultiLineEdit::addCompletionSpace()
802 // Inserting the space emits textChanged, which should not disable removal
803 _completionSpace = 2;
804 insertPlainText(" ");