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()
94 void MultiLineEdit::setCustomFont(const QFont &font)
101 void MultiLineEdit::setMode(Mode mode)
110 void MultiLineEdit::setLineWrapEnabled(bool enable)
112 setLineWrapMode(enable ? WidgetWidth : NoWrap);
117 void MultiLineEdit::setMinHeight(int lines)
119 if (lines == _minHeight)
127 void MultiLineEdit::setMaxHeight(int lines)
129 if (lines == _maxHeight)
137 void MultiLineEdit::setScrollBarsEnabled(bool enable)
139 if (_scrollBarsEnabled == enable)
142 _scrollBarsEnabled = enable;
147 void MultiLineEdit::updateScrollBars()
149 QFontMetrics fm(font());
150 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
151 if (_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
152 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
154 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
156 if (!_scrollBarsEnabled || isSingleLine())
157 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
159 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
163 void MultiLineEdit::resizeEvent(QResizeEvent *event)
165 QTextEdit::resizeEvent(event);
171 void MultiLineEdit::updateSizeHint()
173 QFontMetrics fm(font());
174 int minPixelHeight = fm.lineSpacing() * _minHeight;
175 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
176 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
178 // use the style to determine a decent size
179 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
180 QStyleOptionFrameV2 opt;
182 opt.rect = QRect(0, 0, 100, h);
183 opt.lineWidth = lineWidth();
184 opt.midLineWidth = midLineWidth();
185 opt.state |= QStyle::State_Sunken;
186 QWidget *widget = this;
190 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), widget);
191 if (s != _sizeHint) {
198 QSize MultiLineEdit::sizeHint() const
200 if (!_sizeHint.isValid()) {
201 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
202 that->updateSizeHint();
208 QSize MultiLineEdit::minimumSizeHint() const
214 void MultiLineEdit::setEmacsMode(bool enable)
220 void MultiLineEdit::setSpellCheckEnabled(bool enable)
223 setCheckSpellingEnabled(enable);
230 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *)
232 _pasteProtectionEnabled = enable;
236 void MultiLineEdit::historyMoveBack()
238 addToHistory(convertRichtextToMircCodes(), true);
247 void MultiLineEdit::historyMoveForward()
249 addToHistory(convertRichtextToMircCodes(), true);
251 if (_idx < _history.count()) {
253 if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
256 reset(); // equals clear() in this case
259 addToHistory(convertRichtextToMircCodes());
265 bool MultiLineEdit::addToHistory(const QString &text, bool temporary)
270 Q_ASSERT(0 <= _idx && _idx <= _history.count());
273 // if an entry of the history is changed, we remember it and show it again at this
274 // position until a line was actually sent
275 // sent lines get appended to the history
276 if (_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
277 _tempHistory[_idx] = text;
282 if (_history.isEmpty() || text != _history.last()) {
284 _tempHistory.clear();
292 bool MultiLineEdit::event(QEvent *e)
294 // We need to make sure that global shortcuts aren't eaten
295 if (e->type() == QEvent::ShortcutOverride) {
296 QKeyEvent *event = static_cast<QKeyEvent *>(e);
297 QKeySequence key = QKeySequence(event->key() | event->modifiers());
298 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
299 if (action->shortcuts().contains(key)) {
306 return MultiLineEditParent::event(e);
310 void MultiLineEdit::keyPressEvent(QKeyEvent *event)
312 if (event == QKeySequence::InsertLineSeparator) {
313 if (_mode == SingleLine) {
318 MultiLineEditParent::keyPressEvent(event);
322 switch (event->key()) {
324 if (event->modifiers() & Qt::ShiftModifier)
328 if (!(event->modifiers() & Qt::ControlModifier)) {
329 int pos = textCursor().position();
330 moveCursor(QTextCursor::Up);
331 if (pos == textCursor().position()) // already on top line -> history
340 if (event->modifiers() & Qt::ShiftModifier)
344 if (!(event->modifiers() & Qt::ControlModifier)) {
345 int pos = textCursor().position();
346 moveCursor(QTextCursor::Down);
347 if (pos == textCursor().position()) // already on bottom line -> history
348 historyMoveForward();
351 historyMoveForward();
362 // We don't want to have the tab key react even if no completer is installed
372 if (event->modifiers() & Qt::ControlModifier) {
373 switch (event->key()) {
376 moveCursor(QTextCursor::StartOfLine);
379 moveCursor(QTextCursor::EndOfLine);
382 moveCursor(QTextCursor::Right);
385 moveCursor(QTextCursor::Left);
393 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
401 else if (event->modifiers() & Qt::MetaModifier ||
402 event->modifiers() & Qt::AltModifier)
404 switch (event->key()) {
406 moveCursor(QTextCursor::WordRight);
409 moveCursor(QTextCursor::WordLeft);
412 moveCursor(QTextCursor::WordRight);
415 moveCursor(QTextCursor::WordLeft);
418 moveCursor(QTextCursor::Start);
420 case Qt::Key_Greater:
421 moveCursor(QTextCursor::End);
426 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
430 case Qt::Key_U: // uppercase word
431 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
432 textCursor().insertText(textCursor().selectedText().toUpper());
435 case Qt::Key_L: // lowercase word
436 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
437 textCursor().insertText(textCursor().selectedText().toLower());
442 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
443 QString const text = textCursor().selectedText();
444 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
450 moveCursor(QTextCursor::StartOfWord);
451 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
452 QString const word1 = textCursor().selectedText();
453 textCursor().clearSelection();
454 moveCursor(QTextCursor::WordRight);
455 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
456 QString const word2 = textCursor().selectedText();
457 if (!word2.isEmpty() && !word1.isEmpty()) {
458 textCursor().insertText(word1);
459 moveCursor(QTextCursor::WordLeft);
460 moveCursor(QTextCursor::WordLeft);
461 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
462 textCursor().insertText(word2);
463 moveCursor(QTextCursor::WordRight);
464 moveCursor(QTextCursor::EndOfWord);
476 KTextEdit::keyPressEvent(event);
478 QTextEdit::keyPressEvent(event);
483 QString MultiLineEdit::convertRichtextToMircCodes()
485 bool underline, bold, italic, color;
486 QString mircText, mircFgColor, mircBgColor;
487 QTextCursor cursor = textCursor();
488 QTextCursor peekcursor = textCursor();
489 cursor.movePosition(QTextCursor::Start);
491 underline = bold = italic = color = false;
493 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
494 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
495 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
498 mircText.append('\x03');
502 mircText.append('\x1f');
506 mircText.append('\x1d');
510 mircText.append('\x02');
512 mircText.append('\n');
515 if (!bold && cursor.charFormat().font().bold()) {
517 mircText.append('\x02');
519 if (!italic && cursor.charFormat().fontItalic()) {
521 mircText.append('\x1d');
523 if (!underline && cursor.charFormat().fontUnderline()) {
525 mircText.append('\x1f');
527 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
529 mircText.append('\x03');
530 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
531 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
533 if (mircFgColor.isEmpty()) {
534 mircFgColor = "01"; //use black if the current foreground color can't be converted
537 mircText.append(mircFgColor);
538 if (cursor.charFormat().background().isOpaque())
539 mircText.append("," + mircBgColor);
542 mircText.append(cursor.selectedText());
544 peekcursor.setPosition(cursor.position());
545 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
547 if (mircCodesChanged(cursor, peekcursor)) {
550 mircText.append('\x03');
554 mircText.append('\x1f');
558 mircText.append('\x1d');
562 mircText.append('\x02');
567 cursor.clearSelection();
571 mircText.append('\x03');
574 mircText.append('\x1f');
577 mircText.append('\x1d');
580 mircText.append('\x02');
586 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor)
588 bool changed = false;
589 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
591 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
593 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
595 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
597 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
603 QString MultiLineEdit::convertMircCodesToHtml(const QString &text)
606 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
612 posRight = mircCode.indexIn(text, posLeft);
615 words << text.mid(posLeft);
616 break; // no more mirc color codes
619 if (posLeft < posRight) {
620 words << text.mid(posLeft, posRight - posLeft);
624 posRight = text.indexOf(mircCode.cap(), posRight + 1);
625 words << text.mid(posLeft, posRight + 1 - posLeft);
626 posLeft = posRight + 1;
629 for (int i = 0; i < words.count(); i++) {
631 if (words[i].contains('\x02')) {
632 style.append(" font-weight:600;");
633 words[i].replace('\x02', "");
635 if (words[i].contains('\x1d')) {
636 style.append(" font-style:italic;");
637 words[i].replace('\x1d', "");
639 if (words[i].contains('\x1f')) {
640 style.append(" text-decoration: underline;");
641 words[i].replace('\x1f', "");
643 if (words[i].contains('\x03')) {
644 int pos = words[i].indexOf('\x03');
646 QString fg = words[i].mid(pos + 1, 2);
648 if (words[i][pos+3] == ',')
649 bg = words[i].mid(pos+4, 2);
651 style.append(" color:");
652 style.append(_mircColorMap[fg]);
656 style.append(" background-color:");
657 style.append(_mircColorMap[bg]);
661 words[i].replace(pos, len, "");
662 words[i].replace('\x03', "");
664 words[i].replace("&", "&");
665 words[i].replace("<", "<");
666 words[i].replace(">", ">");
667 words[i].replace("\"", """);
668 if (style.isEmpty()) {
669 words[i] = "<span>" + words[i] + "</span>";
672 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
675 return words.join("").replace("\n", "<br />");
679 void MultiLineEdit::on_returnPressed()
681 on_returnPressed(convertRichtextToMircCodes());
685 void MultiLineEdit::on_returnPressed(QString text)
687 if (_completionSpace && text.endsWith(" ")) {
691 if (!text.isEmpty()) {
692 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
696 emit textEntered(line);
699 _tempHistory.clear();
702 emit noTextEntered();
707 void MultiLineEdit::on_textChanged()
709 _completionSpace = qMax(_completionSpace - 1, 0);
711 QString newText = text();
712 newText.replace("\r\n", "\n");
713 newText.replace('\r', '\n');
714 if (_mode == SingleLine) {
715 if (!pasteProtectionEnabled())
716 newText.replace('\n', ' ');
717 else if (newText.contains('\n')) {
718 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
721 if (lines.count() >= 4) {
722 QString msg = tr("Do you really want to paste %n line(s)?", "", lines.count());
724 for (int i = 0; i < 4; i++) {
725 #if QT_VERSION < 0x050000
726 msg += Qt::escape(lines[i].left(40));
728 msg += lines[i].left(40).toHtmlEscaped();
730 if (lines[i].count() > 40)
735 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
736 question.setDefaultButton(QMessageBox::No);
738 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
740 if (question.exec() != QMessageBox::Yes)
744 foreach(QString line, lines) {
752 _singleLine = (newText.indexOf('\n') < 0);
754 if (document()->size().height() != _lastDocumentHeight) {
755 _lastDocumentHeight = document()->size().height();
756 on_documentHeightChanged(_lastDocumentHeight);
759 ensureCursorVisible();
763 void MultiLineEdit::on_documentHeightChanged(qreal)
769 void MultiLineEdit::reset()
771 // every time the MultiLineEdit is cleared we also reset history index
772 _idx = _history.count();
774 QTextBlockFormat format = textCursor().blockFormat();
775 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
776 textCursor().setBlockFormat(format);
781 void MultiLineEdit::showHistoryEntry()
783 // if the user changed the history, display the changed line
784 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
785 QTextCursor cursor = textCursor();
786 QTextBlockFormat format = cursor.blockFormat();
787 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
788 cursor.setBlockFormat(format);
789 cursor.movePosition(QTextCursor::End);
790 setTextCursor(cursor);
795 void MultiLineEdit::addCompletionSpace()
797 // Inserting the space emits textChanged, which should not disable removal
798 _completionSpace = 2;
799 insertPlainText(" ");