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>
23 #include <QMessageBox>
26 #include "actioncollection.h"
27 #include "bufferview.h"
28 #include "graphicalui.h"
29 #include "multilineedit.h"
30 #include "tabcompleter.h"
32 const int leftMargin = 3;
34 MultiLineEdit::MultiLineEdit(QWidget *parent)
35 : MultiLineEditParent(parent),
41 _scrollBarsEnabled(true),
42 _pasteProtectionEnabled(true),
45 _lastDocumentHeight(-1)
47 document()->setDocumentMargin(0);
49 setAcceptRichText(false);
51 enableFindReplace(false);
55 setLineWrapEnabled(false);
58 // Prevent QTextHtmlImporter::appendNodeText from eating whitespace
59 document()->setDefaultStyleSheet("span { white-space: pre-wrap; }");
61 connect(this, SIGNAL(textChanged()), this, SLOT(on_textChanged()));
63 _mircColorMap["00"] = "#ffffff";
64 _mircColorMap["01"] = "#000000";
65 _mircColorMap["02"] = "#000080";
66 _mircColorMap["03"] = "#008000";
67 _mircColorMap["04"] = "#ff0000";
68 _mircColorMap["05"] = "#800000";
69 _mircColorMap["06"] = "#800080";
70 _mircColorMap["07"] = "#ffa500";
71 _mircColorMap["08"] = "#ffff00";
72 _mircColorMap["09"] = "#00ff00";
73 _mircColorMap["10"] = "#008080";
74 _mircColorMap["11"] = "#00ffff";
75 _mircColorMap["12"] = "#4169e1";
76 _mircColorMap["13"] = "#ff00ff";
77 _mircColorMap["14"] = "#808080";
78 _mircColorMap["15"] = "#c0c0c0";
82 MultiLineEdit::~MultiLineEdit()
87 void MultiLineEdit::setCustomFont(const QFont &font)
94 void MultiLineEdit::setMode(Mode mode)
103 void MultiLineEdit::setLineWrapEnabled(bool enable)
105 setLineWrapMode(enable ? WidgetWidth : NoWrap);
110 void MultiLineEdit::setMinHeight(int lines)
112 if (lines == _minHeight)
120 void MultiLineEdit::setMaxHeight(int lines)
122 if (lines == _maxHeight)
130 void MultiLineEdit::setScrollBarsEnabled(bool enable)
132 if (_scrollBarsEnabled == enable)
135 _scrollBarsEnabled = enable;
140 void MultiLineEdit::updateScrollBars()
142 QFontMetrics fm(font());
143 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
144 if (_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
145 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
147 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
149 if (!_scrollBarsEnabled || isSingleLine())
150 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
152 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
156 void MultiLineEdit::resizeEvent(QResizeEvent *event)
158 QTextEdit::resizeEvent(event);
164 void MultiLineEdit::updateSizeHint()
166 QFontMetrics fm(font());
167 int minPixelHeight = fm.lineSpacing() * _minHeight;
168 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
169 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
171 // use the style to determine a decent size
172 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
173 QStyleOptionFrameV2 opt;
175 opt.rect = QRect(0, 0, 100, h);
176 opt.lineWidth = lineWidth();
177 opt.midLineWidth = midLineWidth();
178 opt.state |= QStyle::State_Sunken;
179 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), this);
180 if (s != _sizeHint) {
187 QSize MultiLineEdit::sizeHint() const
189 if (!_sizeHint.isValid()) {
190 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
191 that->updateSizeHint();
197 QSize MultiLineEdit::minimumSizeHint() const
203 void MultiLineEdit::setEmacsMode(bool enable)
209 void MultiLineEdit::setSpellCheckEnabled(bool enable)
212 setCheckSpellingEnabled(enable);
219 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *)
221 _pasteProtectionEnabled = enable;
225 void MultiLineEdit::historyMoveBack()
227 addToHistory(convertRichtextToMircCodes(), true);
236 void MultiLineEdit::historyMoveForward()
238 addToHistory(convertRichtextToMircCodes(), true);
240 if (_idx < _history.count()) {
242 if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
245 reset(); // equals clear() in this case
248 addToHistory(convertRichtextToMircCodes());
254 bool MultiLineEdit::addToHistory(const QString &text, bool temporary)
259 Q_ASSERT(0 <= _idx && _idx <= _history.count());
262 // if an entry of the history is changed, we remember it and show it again at this
263 // position until a line was actually sent
264 // sent lines get appended to the history
265 if (_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
266 _tempHistory[_idx] = text;
271 if (_history.isEmpty() || text != _history.last()) {
273 _tempHistory.clear();
281 bool MultiLineEdit::event(QEvent *e)
283 // We need to make sure that global shortcuts aren't eaten
284 if (e->type() == QEvent::ShortcutOverride) {
285 QKeyEvent *event = static_cast<QKeyEvent *>(e);
286 QKeySequence key = QKeySequence(event->key() | event->modifiers());
287 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
288 if (action->shortcuts().contains(key)) {
295 return MultiLineEditParent::event(e);
299 void MultiLineEdit::keyPressEvent(QKeyEvent *event)
301 if (event == QKeySequence::InsertLineSeparator) {
302 if (_mode == SingleLine) {
307 MultiLineEditParent::keyPressEvent(event);
311 switch (event->key()) {
313 if (event->modifiers() & Qt::ShiftModifier)
317 if (!(event->modifiers() & Qt::ControlModifier)) {
318 int pos = textCursor().position();
319 moveCursor(QTextCursor::Up);
320 if (pos == textCursor().position()) // already on top line -> history
329 if (event->modifiers() & Qt::ShiftModifier)
333 if (!(event->modifiers() & Qt::ControlModifier)) {
334 int pos = textCursor().position();
335 moveCursor(QTextCursor::Down);
336 if (pos == textCursor().position()) // already on bottom line -> history
337 historyMoveForward();
340 historyMoveForward();
351 // We don't want to have the tab key react even if no completer is installed
361 if (event->modifiers() & Qt::ControlModifier) {
362 switch (event->key()) {
365 moveCursor(QTextCursor::StartOfLine);
368 moveCursor(QTextCursor::EndOfLine);
371 moveCursor(QTextCursor::Right);
374 moveCursor(QTextCursor::Left);
382 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
390 else if (event->modifiers() & Qt::MetaModifier ||
391 event->modifiers() & Qt::AltModifier)
393 switch (event->key()) {
395 moveCursor(QTextCursor::WordRight);
398 moveCursor(QTextCursor::WordLeft);
401 moveCursor(QTextCursor::WordRight);
404 moveCursor(QTextCursor::WordLeft);
407 moveCursor(QTextCursor::Start);
409 case Qt::Key_Greater:
410 moveCursor(QTextCursor::End);
415 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
419 case Qt::Key_U: // uppercase word
420 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
421 textCursor().insertText(textCursor().selectedText().toUpper());
424 case Qt::Key_L: // lowercase word
425 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
426 textCursor().insertText(textCursor().selectedText().toLower());
431 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
432 QString const text = textCursor().selectedText();
433 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
439 moveCursor(QTextCursor::StartOfWord);
440 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
441 QString const word1 = textCursor().selectedText();
442 textCursor().clearSelection();
443 moveCursor(QTextCursor::WordRight);
444 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
445 QString const word2 = textCursor().selectedText();
446 if (!word2.isEmpty() && !word1.isEmpty()) {
447 textCursor().insertText(word1);
448 moveCursor(QTextCursor::WordLeft);
449 moveCursor(QTextCursor::WordLeft);
450 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
451 textCursor().insertText(word2);
452 moveCursor(QTextCursor::WordRight);
453 moveCursor(QTextCursor::EndOfWord);
465 KTextEdit::keyPressEvent(event);
467 QTextEdit::keyPressEvent(event);
472 QString MultiLineEdit::convertRichtextToMircCodes()
474 bool underline, bold, italic, color;
475 QString mircText, mircFgColor, mircBgColor;
476 QTextCursor cursor = textCursor();
477 QTextCursor peekcursor = textCursor();
478 cursor.movePosition(QTextCursor::Start);
480 underline = bold = italic = color = false;
482 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
483 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
484 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
487 mircText.append('\x03');
491 mircText.append('\x1f');
495 mircText.append('\x1d');
499 mircText.append('\x02');
501 mircText.append('\n');
504 if (!bold && cursor.charFormat().font().bold()) {
506 mircText.append('\x02');
508 if (!italic && cursor.charFormat().fontItalic()) {
510 mircText.append('\x1d');
512 if (!underline && cursor.charFormat().fontUnderline()) {
514 mircText.append('\x1f');
516 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
518 mircText.append('\x03');
519 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
520 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
522 if (mircFgColor.isEmpty()) {
523 mircFgColor = "01"; //use black if the current foreground color can't be converted
526 mircText.append(mircFgColor);
527 if (cursor.charFormat().background().isOpaque())
528 mircText.append("," + mircBgColor);
531 mircText.append(cursor.selectedText());
533 peekcursor.setPosition(cursor.position());
534 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
536 if (mircCodesChanged(cursor, peekcursor)) {
539 mircText.append('\x03');
543 mircText.append('\x1f');
547 mircText.append('\x1d');
551 mircText.append('\x02');
556 cursor.clearSelection();
560 mircText.append('\x03');
563 mircText.append('\x1f');
566 mircText.append('\x1d');
569 mircText.append('\x02');
575 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor)
577 bool changed = false;
578 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
580 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
582 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
584 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
586 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
592 QString MultiLineEdit::convertMircCodesToHtml(const QString &text)
595 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
601 posRight = mircCode.indexIn(text, posLeft);
604 words << text.mid(posLeft);
605 break; // no more mirc color codes
608 if (posLeft < posRight) {
609 words << text.mid(posLeft, posRight - posLeft);
613 posRight = text.indexOf(mircCode.cap(), posRight + 1);
614 words << text.mid(posLeft, posRight + 1 - posLeft);
615 posLeft = posRight + 1;
618 for (int i = 0; i < words.count(); i++) {
620 if (words[i].contains('\x02')) {
621 style.append(" font-weight:600;");
622 words[i].replace('\x02', "");
624 if (words[i].contains('\x1d')) {
625 style.append(" font-style:italic;");
626 words[i].replace('\x1d', "");
628 if (words[i].contains('\x1f')) {
629 style.append(" text-decoration: underline;");
630 words[i].replace('\x1f', "");
632 if (words[i].contains('\x03')) {
633 int pos = words[i].indexOf('\x03');
635 QString fg = words[i].mid(pos + 1, 2);
637 if (words[i][pos+3] == ',')
638 bg = words[i].mid(pos+4, 2);
640 style.append(" color:");
641 style.append(_mircColorMap[fg]);
645 style.append(" background-color:");
646 style.append(_mircColorMap[bg]);
650 words[i].replace(pos, len, "");
651 words[i].replace('\x03', "");
653 words[i].replace("&", "&");
654 words[i].replace("<", "<");
655 words[i].replace(">", ">");
656 words[i].replace("\"", """);
657 if (style.isEmpty()) {
658 words[i] = "<span>" + words[i] + "</span>";
661 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
664 return words.join("").replace("\n", "<br />");
668 void MultiLineEdit::on_returnPressed()
670 on_returnPressed(convertRichtextToMircCodes());
674 void MultiLineEdit::on_returnPressed(QString text)
676 if (_completionSpace && text.endsWith(" ")) {
680 if (!text.isEmpty()) {
681 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
685 emit textEntered(line);
688 _tempHistory.clear();
691 emit noTextEntered();
696 void MultiLineEdit::on_textChanged()
698 _completionSpace = qMax(_completionSpace - 1, 0);
700 QString newText = text();
701 newText.replace("\r\n", "\n");
702 newText.replace('\r', '\n');
703 if (_mode == SingleLine) {
704 if (!pasteProtectionEnabled())
705 newText.replace('\n', ' ');
706 else if (newText.contains('\n')) {
707 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
710 if (lines.count() >= 4) {
711 QString msg = tr("Do you really want to paste %n line(s)?", "", lines.count());
713 for (int i = 0; i < 4; i++) {
714 #if QT_VERSION < 0x050000
715 msg += Qt::escape(lines[i].left(40));
717 msg += lines[i].left(40).toHtmlEscaped();
719 if (lines[i].count() > 40)
724 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
725 question.setDefaultButton(QMessageBox::No);
727 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
729 if (question.exec() != QMessageBox::Yes)
733 foreach(QString line, lines) {
741 _singleLine = (newText.indexOf('\n') < 0);
743 if (document()->size().height() != _lastDocumentHeight) {
744 _lastDocumentHeight = document()->size().height();
745 on_documentHeightChanged(_lastDocumentHeight);
748 ensureCursorVisible();
752 void MultiLineEdit::on_documentHeightChanged(qreal)
758 void MultiLineEdit::reset()
760 // every time the MultiLineEdit is cleared we also reset history index
761 _idx = _history.count();
763 QTextBlockFormat format = textCursor().blockFormat();
764 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
765 textCursor().setBlockFormat(format);
770 void MultiLineEdit::showHistoryEntry()
772 // if the user changed the history, display the changed line
773 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
774 QTextCursor cursor = textCursor();
775 QTextBlockFormat format = cursor.blockFormat();
776 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
777 cursor.setBlockFormat(format);
778 cursor.movePosition(QTextCursor::End);
779 setTextCursor(cursor);
784 void MultiLineEdit::addCompletionSpace()
786 // Inserting the space emits textChanged, which should not disable removal
787 _completionSpace = 2;
788 insertPlainText(" ");