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 QWidget *widget = this;
183 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), widget);
184 if (s != _sizeHint) {
191 QSize MultiLineEdit::sizeHint() const
193 if (!_sizeHint.isValid()) {
194 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
195 that->updateSizeHint();
201 QSize MultiLineEdit::minimumSizeHint() const
207 void MultiLineEdit::setEmacsMode(bool enable)
213 void MultiLineEdit::setSpellCheckEnabled(bool enable)
216 setCheckSpellingEnabled(enable);
223 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *)
225 _pasteProtectionEnabled = enable;
229 void MultiLineEdit::historyMoveBack()
231 addToHistory(convertRichtextToMircCodes(), true);
240 void MultiLineEdit::historyMoveForward()
242 addToHistory(convertRichtextToMircCodes(), true);
244 if (_idx < _history.count()) {
246 if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
249 reset(); // equals clear() in this case
252 addToHistory(convertRichtextToMircCodes());
258 bool MultiLineEdit::addToHistory(const QString &text, bool temporary)
263 Q_ASSERT(0 <= _idx && _idx <= _history.count());
266 // if an entry of the history is changed, we remember it and show it again at this
267 // position until a line was actually sent
268 // sent lines get appended to the history
269 if (_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
270 _tempHistory[_idx] = text;
275 if (_history.isEmpty() || text != _history.last()) {
277 _tempHistory.clear();
285 bool MultiLineEdit::event(QEvent *e)
287 // We need to make sure that global shortcuts aren't eaten
288 if (e->type() == QEvent::ShortcutOverride) {
289 QKeyEvent *event = static_cast<QKeyEvent *>(e);
290 QKeySequence key = QKeySequence(event->key() | event->modifiers());
291 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
292 if (action->shortcuts().contains(key)) {
299 return MultiLineEditParent::event(e);
303 void MultiLineEdit::keyPressEvent(QKeyEvent *event)
305 if (event == QKeySequence::InsertLineSeparator) {
306 if (_mode == SingleLine) {
311 MultiLineEditParent::keyPressEvent(event);
315 switch (event->key()) {
317 if (event->modifiers() & Qt::ShiftModifier)
321 if (!(event->modifiers() & Qt::ControlModifier)) {
322 int pos = textCursor().position();
323 moveCursor(QTextCursor::Up);
324 if (pos == textCursor().position()) // already on top line -> history
333 if (event->modifiers() & Qt::ShiftModifier)
337 if (!(event->modifiers() & Qt::ControlModifier)) {
338 int pos = textCursor().position();
339 moveCursor(QTextCursor::Down);
340 if (pos == textCursor().position()) // already on bottom line -> history
341 historyMoveForward();
344 historyMoveForward();
355 // We don't want to have the tab key react even if no completer is installed
365 if (event->modifiers() & Qt::ControlModifier) {
366 switch (event->key()) {
369 moveCursor(QTextCursor::StartOfLine);
372 moveCursor(QTextCursor::EndOfLine);
375 moveCursor(QTextCursor::Right);
378 moveCursor(QTextCursor::Left);
386 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
394 else if (event->modifiers() & Qt::MetaModifier ||
395 event->modifiers() & Qt::AltModifier)
397 switch (event->key()) {
399 moveCursor(QTextCursor::WordRight);
402 moveCursor(QTextCursor::WordLeft);
405 moveCursor(QTextCursor::WordRight);
408 moveCursor(QTextCursor::WordLeft);
411 moveCursor(QTextCursor::Start);
413 case Qt::Key_Greater:
414 moveCursor(QTextCursor::End);
419 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
423 case Qt::Key_U: // uppercase word
424 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
425 textCursor().insertText(textCursor().selectedText().toUpper());
428 case Qt::Key_L: // lowercase word
429 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
430 textCursor().insertText(textCursor().selectedText().toLower());
435 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
436 QString const text = textCursor().selectedText();
437 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
443 moveCursor(QTextCursor::StartOfWord);
444 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
445 QString const word1 = textCursor().selectedText();
446 textCursor().clearSelection();
447 moveCursor(QTextCursor::WordRight);
448 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
449 QString const word2 = textCursor().selectedText();
450 if (!word2.isEmpty() && !word1.isEmpty()) {
451 textCursor().insertText(word1);
452 moveCursor(QTextCursor::WordLeft);
453 moveCursor(QTextCursor::WordLeft);
454 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
455 textCursor().insertText(word2);
456 moveCursor(QTextCursor::WordRight);
457 moveCursor(QTextCursor::EndOfWord);
469 KTextEdit::keyPressEvent(event);
471 QTextEdit::keyPressEvent(event);
476 QString MultiLineEdit::convertRichtextToMircCodes()
478 bool underline, bold, italic, color;
479 QString mircText, mircFgColor, mircBgColor;
480 QTextCursor cursor = textCursor();
481 QTextCursor peekcursor = textCursor();
482 cursor.movePosition(QTextCursor::Start);
484 underline = bold = italic = color = false;
486 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
487 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
488 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
491 mircText.append('\x03');
495 mircText.append('\x1f');
499 mircText.append('\x1d');
503 mircText.append('\x02');
505 mircText.append('\n');
508 if (!bold && cursor.charFormat().font().bold()) {
510 mircText.append('\x02');
512 if (!italic && cursor.charFormat().fontItalic()) {
514 mircText.append('\x1d');
516 if (!underline && cursor.charFormat().fontUnderline()) {
518 mircText.append('\x1f');
520 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
522 mircText.append('\x03');
523 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
524 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
526 if (mircFgColor.isEmpty()) {
527 mircFgColor = "01"; //use black if the current foreground color can't be converted
530 mircText.append(mircFgColor);
531 if (cursor.charFormat().background().isOpaque())
532 mircText.append("," + mircBgColor);
535 mircText.append(cursor.selectedText());
537 peekcursor.setPosition(cursor.position());
538 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
540 if (mircCodesChanged(cursor, peekcursor)) {
543 mircText.append('\x03');
547 mircText.append('\x1f');
551 mircText.append('\x1d');
555 mircText.append('\x02');
560 cursor.clearSelection();
564 mircText.append('\x03');
567 mircText.append('\x1f');
570 mircText.append('\x1d');
573 mircText.append('\x02');
579 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor)
581 bool changed = false;
582 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
584 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
586 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
588 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
590 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
596 QString MultiLineEdit::convertMircCodesToHtml(const QString &text)
599 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
605 posRight = mircCode.indexIn(text, posLeft);
608 words << text.mid(posLeft);
609 break; // no more mirc color codes
612 if (posLeft < posRight) {
613 words << text.mid(posLeft, posRight - posLeft);
617 posRight = text.indexOf(mircCode.cap(), posRight + 1);
618 words << text.mid(posLeft, posRight + 1 - posLeft);
619 posLeft = posRight + 1;
622 for (int i = 0; i < words.count(); i++) {
624 if (words[i].contains('\x02')) {
625 style.append(" font-weight:600;");
626 words[i].replace('\x02', "");
628 if (words[i].contains('\x1d')) {
629 style.append(" font-style:italic;");
630 words[i].replace('\x1d', "");
632 if (words[i].contains('\x1f')) {
633 style.append(" text-decoration: underline;");
634 words[i].replace('\x1f', "");
636 if (words[i].contains('\x03')) {
637 int pos = words[i].indexOf('\x03');
639 QString fg = words[i].mid(pos + 1, 2);
641 if (words[i][pos+3] == ',')
642 bg = words[i].mid(pos+4, 2);
644 style.append(" color:");
645 style.append(_mircColorMap[fg]);
649 style.append(" background-color:");
650 style.append(_mircColorMap[bg]);
654 words[i].replace(pos, len, "");
655 words[i].replace('\x03', "");
657 words[i].replace("&", "&");
658 words[i].replace("<", "<");
659 words[i].replace(">", ">");
660 words[i].replace("\"", """);
661 if (style.isEmpty()) {
662 words[i] = "<span>" + words[i] + "</span>";
665 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
668 return words.join("").replace("\n", "<br />");
672 void MultiLineEdit::on_returnPressed()
674 on_returnPressed(convertRichtextToMircCodes());
678 void MultiLineEdit::on_returnPressed(QString text)
680 if (_completionSpace && text.endsWith(" ")) {
684 if (!text.isEmpty()) {
685 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
689 emit textEntered(line);
692 _tempHistory.clear();
695 emit noTextEntered();
700 void MultiLineEdit::on_textChanged()
702 _completionSpace = qMax(_completionSpace - 1, 0);
704 QString newText = text();
705 newText.replace("\r\n", "\n");
706 newText.replace('\r', '\n');
707 if (_mode == SingleLine) {
708 if (!pasteProtectionEnabled())
709 newText.replace('\n', ' ');
710 else if (newText.contains('\n')) {
711 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
714 if (lines.count() >= 4) {
715 QString msg = tr("Do you really want to paste %n line(s)?", "", lines.count());
717 for (int i = 0; i < 4; i++) {
718 #if QT_VERSION < 0x050000
719 msg += Qt::escape(lines[i].left(40));
721 msg += lines[i].left(40).toHtmlEscaped();
723 if (lines[i].count() > 40)
728 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
729 question.setDefaultButton(QMessageBox::No);
731 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
733 if (question.exec() != QMessageBox::Yes)
737 foreach(QString line, lines) {
745 _singleLine = (newText.indexOf('\n') < 0);
747 if (document()->size().height() != _lastDocumentHeight) {
748 _lastDocumentHeight = document()->size().height();
749 on_documentHeightChanged(_lastDocumentHeight);
752 ensureCursorVisible();
756 void MultiLineEdit::on_documentHeightChanged(qreal)
762 void MultiLineEdit::reset()
764 // every time the MultiLineEdit is cleared we also reset history index
765 _idx = _history.count();
767 QTextBlockFormat format = textCursor().blockFormat();
768 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
769 textCursor().setBlockFormat(format);
774 void MultiLineEdit::showHistoryEntry()
776 // if the user changed the history, display the changed line
777 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
778 QTextCursor cursor = textCursor();
779 QTextBlockFormat format = cursor.blockFormat();
780 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
781 cursor.setBlockFormat(format);
782 cursor.movePosition(QTextCursor::End);
783 setTextCursor(cursor);
788 void MultiLineEdit::addCompletionSpace()
790 // Inserting the space emits textChanged, which should not disable removal
791 _completionSpace = 2;
792 insertPlainText(" ");