1 /***************************************************************************
2 * Copyright (C) 2005-2015 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 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), this);
187 if (s != _sizeHint) {
194 QSize MultiLineEdit::sizeHint() const
196 if (!_sizeHint.isValid()) {
197 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
198 that->updateSizeHint();
204 QSize MultiLineEdit::minimumSizeHint() const
210 void MultiLineEdit::setEmacsMode(bool enable)
216 void MultiLineEdit::setSpellCheckEnabled(bool enable)
219 setCheckSpellingEnabled(enable);
226 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *)
228 _pasteProtectionEnabled = enable;
232 void MultiLineEdit::historyMoveBack()
234 addToHistory(convertRichtextToMircCodes(), true);
243 void MultiLineEdit::historyMoveForward()
245 addToHistory(convertRichtextToMircCodes(), true);
247 if (_idx < _history.count()) {
249 if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
252 reset(); // equals clear() in this case
255 addToHistory(convertRichtextToMircCodes());
261 bool MultiLineEdit::addToHistory(const QString &text, bool temporary)
266 Q_ASSERT(0 <= _idx && _idx <= _history.count());
269 // if an entry of the history is changed, we remember it and show it again at this
270 // position until a line was actually sent
271 // sent lines get appended to the history
272 if (_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
273 _tempHistory[_idx] = text;
278 if (_history.isEmpty() || text != _history.last()) {
280 _tempHistory.clear();
288 bool MultiLineEdit::event(QEvent *e)
290 // We need to make sure that global shortcuts aren't eaten
291 if (e->type() == QEvent::ShortcutOverride) {
292 QKeyEvent *event = static_cast<QKeyEvent *>(e);
293 QKeySequence key = QKeySequence(event->key() | event->modifiers());
294 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
295 if (action->shortcuts().contains(key)) {
302 return MultiLineEditParent::event(e);
306 void MultiLineEdit::keyPressEvent(QKeyEvent *event)
308 if (event == QKeySequence::InsertLineSeparator) {
309 if (_mode == SingleLine) {
314 MultiLineEditParent::keyPressEvent(event);
318 switch (event->key()) {
320 if (event->modifiers() & Qt::ShiftModifier)
324 if (!(event->modifiers() & Qt::ControlModifier)) {
325 int pos = textCursor().position();
326 moveCursor(QTextCursor::Up);
327 if (pos == textCursor().position()) // already on top line -> history
336 if (event->modifiers() & Qt::ShiftModifier)
340 if (!(event->modifiers() & Qt::ControlModifier)) {
341 int pos = textCursor().position();
342 moveCursor(QTextCursor::Down);
343 if (pos == textCursor().position()) // already on bottom line -> history
344 historyMoveForward();
347 historyMoveForward();
358 // We don't want to have the tab key react even if no completer is installed
368 if (event->modifiers() & Qt::ControlModifier) {
369 switch (event->key()) {
372 moveCursor(QTextCursor::StartOfLine);
375 moveCursor(QTextCursor::EndOfLine);
378 moveCursor(QTextCursor::Right);
381 moveCursor(QTextCursor::Left);
389 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
397 else if (event->modifiers() & Qt::MetaModifier ||
398 event->modifiers() & Qt::AltModifier)
400 switch (event->key()) {
402 moveCursor(QTextCursor::WordRight);
405 moveCursor(QTextCursor::WordLeft);
408 moveCursor(QTextCursor::WordRight);
411 moveCursor(QTextCursor::WordLeft);
414 moveCursor(QTextCursor::Start);
416 case Qt::Key_Greater:
417 moveCursor(QTextCursor::End);
422 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
426 case Qt::Key_U: // uppercase word
427 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
428 textCursor().insertText(textCursor().selectedText().toUpper());
431 case Qt::Key_L: // lowercase word
432 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
433 textCursor().insertText(textCursor().selectedText().toLower());
438 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
439 QString const text = textCursor().selectedText();
440 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
446 moveCursor(QTextCursor::StartOfWord);
447 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
448 QString const word1 = textCursor().selectedText();
449 textCursor().clearSelection();
450 moveCursor(QTextCursor::WordRight);
451 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
452 QString const word2 = textCursor().selectedText();
453 if (!word2.isEmpty() && !word1.isEmpty()) {
454 textCursor().insertText(word1);
455 moveCursor(QTextCursor::WordLeft);
456 moveCursor(QTextCursor::WordLeft);
457 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
458 textCursor().insertText(word2);
459 moveCursor(QTextCursor::WordRight);
460 moveCursor(QTextCursor::EndOfWord);
472 KTextEdit::keyPressEvent(event);
474 QTextEdit::keyPressEvent(event);
479 QString MultiLineEdit::convertRichtextToMircCodes()
481 bool underline, bold, italic, color;
482 QString mircText, mircFgColor, mircBgColor;
483 QTextCursor cursor = textCursor();
484 QTextCursor peekcursor = textCursor();
485 cursor.movePosition(QTextCursor::Start);
487 underline = bold = italic = color = false;
489 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
490 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
491 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
494 mircText.append('\x03');
498 mircText.append('\x1f');
502 mircText.append('\x1d');
506 mircText.append('\x02');
508 mircText.append('\n');
511 if (!bold && cursor.charFormat().font().bold()) {
513 mircText.append('\x02');
515 if (!italic && cursor.charFormat().fontItalic()) {
517 mircText.append('\x1d');
519 if (!underline && cursor.charFormat().fontUnderline()) {
521 mircText.append('\x1f');
523 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
525 mircText.append('\x03');
526 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
527 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
529 if (mircFgColor.isEmpty()) {
530 mircFgColor = "01"; //use black if the current foreground color can't be converted
533 mircText.append(mircFgColor);
534 if (cursor.charFormat().background().isOpaque())
535 mircText.append("," + mircBgColor);
538 mircText.append(cursor.selectedText());
540 peekcursor.setPosition(cursor.position());
541 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
543 if (mircCodesChanged(cursor, peekcursor)) {
546 mircText.append('\x03');
550 mircText.append('\x1f');
554 mircText.append('\x1d');
558 mircText.append('\x02');
563 cursor.clearSelection();
567 mircText.append('\x03');
570 mircText.append('\x1f');
573 mircText.append('\x1d');
576 mircText.append('\x02');
582 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor)
584 bool changed = false;
585 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
587 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
589 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
591 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
593 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
599 QString MultiLineEdit::convertMircCodesToHtml(const QString &text)
602 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
608 posRight = mircCode.indexIn(text, posLeft);
611 words << text.mid(posLeft);
612 break; // no more mirc color codes
615 if (posLeft < posRight) {
616 words << text.mid(posLeft, posRight - posLeft);
620 posRight = text.indexOf(mircCode.cap(), posRight + 1);
621 words << text.mid(posLeft, posRight + 1 - posLeft);
622 posLeft = posRight + 1;
625 for (int i = 0; i < words.count(); i++) {
627 if (words[i].contains('\x02')) {
628 style.append(" font-weight:600;");
629 words[i].replace('\x02', "");
631 if (words[i].contains('\x1d')) {
632 style.append(" font-style:italic;");
633 words[i].replace('\x1d', "");
635 if (words[i].contains('\x1f')) {
636 style.append(" text-decoration: underline;");
637 words[i].replace('\x1f', "");
639 if (words[i].contains('\x03')) {
640 int pos = words[i].indexOf('\x03');
642 QString fg = words[i].mid(pos + 1, 2);
644 if (words[i][pos+3] == ',')
645 bg = words[i].mid(pos+4, 2);
647 style.append(" color:");
648 style.append(_mircColorMap[fg]);
652 style.append(" background-color:");
653 style.append(_mircColorMap[bg]);
657 words[i].replace(pos, len, "");
658 words[i].replace('\x03', "");
660 words[i].replace("&", "&");
661 words[i].replace("<", "<");
662 words[i].replace(">", ">");
663 words[i].replace("\"", """);
664 if (style.isEmpty()) {
665 words[i] = "<span>" + words[i] + "</span>";
668 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
671 return words.join("").replace("\n", "<br />");
675 void MultiLineEdit::on_returnPressed()
677 on_returnPressed(convertRichtextToMircCodes());
681 void MultiLineEdit::on_returnPressed(QString text)
683 if (_completionSpace && text.endsWith(" ")) {
687 if (!text.isEmpty()) {
688 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
692 emit textEntered(line);
695 _tempHistory.clear();
698 emit noTextEntered();
703 void MultiLineEdit::on_textChanged()
705 _completionSpace = qMax(_completionSpace - 1, 0);
707 QString newText = text();
708 newText.replace("\r\n", "\n");
709 newText.replace('\r', '\n');
710 if (_mode == SingleLine) {
711 if (!pasteProtectionEnabled())
712 newText.replace('\n', ' ');
713 else if (newText.contains('\n')) {
714 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
717 if (lines.count() >= 4) {
718 QString msg = tr("Do you really want to paste %n line(s)?", "", lines.count());
720 for (int i = 0; i < 4; i++) {
721 #if QT_VERSION < 0x050000
722 msg += Qt::escape(lines[i].left(40));
724 msg += lines[i].left(40).toHtmlEscaped();
726 if (lines[i].count() > 40)
731 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
732 question.setDefaultButton(QMessageBox::No);
734 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
736 if (question.exec() != QMessageBox::Yes)
740 foreach(QString line, lines) {
748 _singleLine = (newText.indexOf('\n') < 0);
750 if (document()->size().height() != _lastDocumentHeight) {
751 _lastDocumentHeight = document()->size().height();
752 on_documentHeightChanged(_lastDocumentHeight);
755 ensureCursorVisible();
759 void MultiLineEdit::on_documentHeightChanged(qreal)
765 void MultiLineEdit::reset()
767 // every time the MultiLineEdit is cleared we also reset history index
768 _idx = _history.count();
770 QTextBlockFormat format = textCursor().blockFormat();
771 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
772 textCursor().setBlockFormat(format);
777 void MultiLineEdit::showHistoryEntry()
779 // if the user changed the history, display the changed line
780 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
781 QTextCursor cursor = textCursor();
782 QTextBlockFormat format = cursor.blockFormat();
783 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
784 cursor.setBlockFormat(format);
785 cursor.movePosition(QTextCursor::End);
786 setTextCursor(cursor);
791 void MultiLineEdit::addCompletionSpace()
793 // Inserting the space emits textChanged, which should not disable removal
794 _completionSpace = 2;
795 insertPlainText(" ");