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),
44 _lastDocumentHeight(-1)
46 document()->setDocumentMargin(0);
48 setAcceptRichText(false);
50 enableFindReplace(false);
54 setLineWrapEnabled(false);
57 connect(this, SIGNAL(textChanged()), this, SLOT(on_textChanged()));
59 _mircColorMap["00"] = "#ffffff";
60 _mircColorMap["01"] = "#000000";
61 _mircColorMap["02"] = "#000080";
62 _mircColorMap["03"] = "#008000";
63 _mircColorMap["04"] = "#ff0000";
64 _mircColorMap["05"] = "#800000";
65 _mircColorMap["06"] = "#800080";
66 _mircColorMap["07"] = "#ffa500";
67 _mircColorMap["08"] = "#ffff00";
68 _mircColorMap["09"] = "#00ff00";
69 _mircColorMap["10"] = "#008080";
70 _mircColorMap["11"] = "#00ffff";
71 _mircColorMap["12"] = "#4169e1";
72 _mircColorMap["13"] = "#ff00ff";
73 _mircColorMap["14"] = "#808080";
74 _mircColorMap["15"] = "#c0c0c0";
78 MultiLineEdit::~MultiLineEdit()
83 void MultiLineEdit::setCustomFont(const QFont &font)
90 void MultiLineEdit::setMode(Mode mode)
99 void MultiLineEdit::setLineWrapEnabled(bool enable)
101 setLineWrapMode(enable ? WidgetWidth : NoWrap);
106 void MultiLineEdit::setMinHeight(int lines)
108 if (lines == _minHeight)
116 void MultiLineEdit::setMaxHeight(int lines)
118 if (lines == _maxHeight)
126 void MultiLineEdit::setScrollBarsEnabled(bool enable)
128 if (_scrollBarsEnabled == enable)
131 _scrollBarsEnabled = enable;
136 void MultiLineEdit::updateScrollBars()
138 QFontMetrics fm(font());
139 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
140 if (_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
141 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
143 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
145 if (!_scrollBarsEnabled || isSingleLine())
146 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
148 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
152 void MultiLineEdit::resizeEvent(QResizeEvent *event)
154 QTextEdit::resizeEvent(event);
160 void MultiLineEdit::updateSizeHint()
162 QFontMetrics fm(font());
163 int minPixelHeight = fm.lineSpacing() * _minHeight;
164 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
165 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
167 // use the style to determine a decent size
168 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
169 QStyleOptionFrameV2 opt;
171 opt.rect = QRect(0, 0, 100, h);
172 opt.lineWidth = lineWidth();
173 opt.midLineWidth = midLineWidth();
174 opt.state |= QStyle::State_Sunken;
175 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), this);
176 if (s != _sizeHint) {
183 QSize MultiLineEdit::sizeHint() const
185 if (!_sizeHint.isValid()) {
186 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
187 that->updateSizeHint();
193 QSize MultiLineEdit::minimumSizeHint() const
199 void MultiLineEdit::setEmacsMode(bool enable)
205 void MultiLineEdit::setSpellCheckEnabled(bool enable)
208 setCheckSpellingEnabled(enable);
215 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *)
217 _pasteProtectionEnabled = enable;
221 void MultiLineEdit::historyMoveBack()
223 addToHistory(convertRichtextToMircCodes(), true);
232 void MultiLineEdit::historyMoveForward()
234 addToHistory(convertRichtextToMircCodes(), true);
236 if (_idx < _history.count()) {
238 if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
241 reset(); // equals clear() in this case
244 addToHistory(convertRichtextToMircCodes());
250 bool MultiLineEdit::addToHistory(const QString &text, bool temporary)
255 Q_ASSERT(0 <= _idx && _idx <= _history.count());
258 // if an entry of the history is changed, we remember it and show it again at this
259 // position until a line was actually sent
260 // sent lines get appended to the history
261 if (_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
262 _tempHistory[_idx] = text;
267 if (_history.isEmpty() || text != _history.last()) {
269 _tempHistory.clear();
277 bool MultiLineEdit::event(QEvent *e)
279 // We need to make sure that global shortcuts aren't eaten
280 if (e->type() == QEvent::ShortcutOverride) {
281 QKeyEvent *event = static_cast<QKeyEvent *>(e);
282 QKeySequence key = QKeySequence(event->key() | event->modifiers());
283 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
284 if (action->shortcuts().contains(key)) {
291 return MultiLineEditParent::event(e);
295 void MultiLineEdit::keyPressEvent(QKeyEvent *event)
297 if (event == QKeySequence::InsertLineSeparator) {
298 if (_mode == SingleLine) {
303 MultiLineEditParent::keyPressEvent(event);
307 switch (event->key()) {
309 if (event->modifiers() & Qt::ShiftModifier)
313 if (!(event->modifiers() & Qt::ControlModifier)) {
314 int pos = textCursor().position();
315 moveCursor(QTextCursor::Up);
316 if (pos == textCursor().position()) // already on top line -> history
325 if (event->modifiers() & Qt::ShiftModifier)
329 if (!(event->modifiers() & Qt::ControlModifier)) {
330 int pos = textCursor().position();
331 moveCursor(QTextCursor::Down);
332 if (pos == textCursor().position()) // already on bottom line -> history
333 historyMoveForward();
336 historyMoveForward();
347 // We don't want to have the tab key react even if no completer is installed
357 if (event->modifiers() & Qt::ControlModifier) {
358 switch (event->key()) {
361 moveCursor(QTextCursor::StartOfLine);
364 moveCursor(QTextCursor::EndOfLine);
367 moveCursor(QTextCursor::Right);
370 moveCursor(QTextCursor::Left);
378 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
386 else if (event->modifiers() & Qt::MetaModifier ||
387 event->modifiers() & Qt::AltModifier)
389 switch (event->key()) {
391 moveCursor(QTextCursor::WordRight);
394 moveCursor(QTextCursor::WordLeft);
397 moveCursor(QTextCursor::WordRight);
400 moveCursor(QTextCursor::WordLeft);
403 moveCursor(QTextCursor::Start);
405 case Qt::Key_Greater:
406 moveCursor(QTextCursor::End);
411 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
415 case Qt::Key_U: // uppercase word
416 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
417 textCursor().insertText(textCursor().selectedText().toUpper());
420 case Qt::Key_L: // lowercase word
421 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
422 textCursor().insertText(textCursor().selectedText().toLower());
427 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
428 QString const text = textCursor().selectedText();
429 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
435 moveCursor(QTextCursor::StartOfWord);
436 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
437 QString const word1 = textCursor().selectedText();
438 textCursor().clearSelection();
439 moveCursor(QTextCursor::WordRight);
440 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
441 QString const word2 = textCursor().selectedText();
442 if (!word2.isEmpty() && !word1.isEmpty()) {
443 textCursor().insertText(word1);
444 moveCursor(QTextCursor::WordLeft);
445 moveCursor(QTextCursor::WordLeft);
446 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
447 textCursor().insertText(word2);
448 moveCursor(QTextCursor::WordRight);
449 moveCursor(QTextCursor::EndOfWord);
461 KTextEdit::keyPressEvent(event);
463 QTextEdit::keyPressEvent(event);
468 QString MultiLineEdit::convertRichtextToMircCodes()
470 bool underline, bold, italic, color;
471 QString mircText, mircFgColor, mircBgColor;
472 QTextCursor cursor = textCursor();
473 QTextCursor peekcursor = textCursor();
474 cursor.movePosition(QTextCursor::Start);
476 underline = bold = italic = color = false;
478 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
479 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
480 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
483 mircText.append('\x03');
487 mircText.append('\x1f');
491 mircText.append('\x1d');
495 mircText.append('\x02');
497 mircText.append('\n');
500 if (!bold && cursor.charFormat().font().bold()) {
502 mircText.append('\x02');
504 if (!italic && cursor.charFormat().fontItalic()) {
506 mircText.append('\x1d');
508 if (!underline && cursor.charFormat().fontUnderline()) {
510 mircText.append('\x1f');
512 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
514 mircText.append('\x03');
515 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
516 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
518 if (mircFgColor.isEmpty()) {
519 mircFgColor = "01"; //use black if the current foreground color can't be converted
522 mircText.append(mircFgColor);
523 if (cursor.charFormat().background().isOpaque())
524 mircText.append("," + mircBgColor);
527 mircText.append(cursor.selectedText());
529 peekcursor.setPosition(cursor.position());
530 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
532 if (mircCodesChanged(cursor, peekcursor)) {
535 mircText.append('\x03');
539 mircText.append('\x1f');
543 mircText.append('\x1d');
547 mircText.append('\x02');
552 cursor.clearSelection();
556 mircText.append('\x03');
559 mircText.append('\x1f');
562 mircText.append('\x1d');
565 mircText.append('\x02');
571 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor)
573 bool changed = false;
574 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
576 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
578 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
580 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
582 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
588 QString MultiLineEdit::convertMircCodesToHtml(const QString &text)
591 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
597 posRight = mircCode.indexIn(text, posLeft);
600 words << text.mid(posLeft);
601 break; // no more mirc color codes
604 if (posLeft < posRight) {
605 words << text.mid(posLeft, posRight - posLeft);
609 posRight = text.indexOf(mircCode.cap(), posRight + 1);
610 words << text.mid(posLeft, posRight + 1 - posLeft);
611 posLeft = posRight + 1;
614 for (int i = 0; i < words.count(); i++) {
616 if (words[i].contains('\x02')) {
617 style.append(" font-weight:600;");
618 words[i].replace('\x02', "");
620 if (words[i].contains('\x1d')) {
621 style.append(" font-style:italic;");
622 words[i].replace('\x1d', "");
624 if (words[i].contains('\x1f')) {
625 style.append(" text-decoration: underline;");
626 words[i].replace('\x1f', "");
628 if (words[i].contains('\x03')) {
629 int pos = words[i].indexOf('\x03');
631 QString fg = words[i].mid(pos + 1, 2);
633 if (words[i][pos+3] == ',')
634 bg = words[i].mid(pos+4, 2);
636 style.append(" color:");
637 style.append(_mircColorMap[fg]);
641 style.append(" background-color:");
642 style.append(_mircColorMap[bg]);
646 words[i].replace(pos, len, "");
647 words[i].replace('\x03', "");
649 words[i].replace("&", "&");
650 words[i].replace("<", "<");
651 words[i].replace(">", ">");
652 words[i].replace("\"", """);
653 if (style.isEmpty()) {
654 words[i] = "<span>" + words[i] + "</span>";
657 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
660 return words.join("").replace("\n", "<br />");
664 void MultiLineEdit::on_returnPressed()
666 on_returnPressed(convertRichtextToMircCodes());
670 void MultiLineEdit::on_returnPressed(const QString &text)
672 if (!text.isEmpty()) {
673 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
677 emit textEntered(line);
680 _tempHistory.clear();
683 emit noTextEntered();
688 void MultiLineEdit::on_textChanged()
690 QString newText = text();
691 newText.replace("\r\n", "\n");
692 newText.replace('\r', '\n');
693 if (_mode == SingleLine) {
694 if (!pasteProtectionEnabled())
695 newText.replace('\n', ' ');
696 else if (newText.contains('\n')) {
697 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
700 if (lines.count() >= 4) {
701 QString msg = tr("Do you really want to paste %n line(s)?", "", lines.count());
703 for (int i = 0; i < 4; i++) {
704 #if QT_VERSION < 0x050000
705 msg += Qt::escape(lines[i].left(40));
707 msg += lines[i].left(40).toHtmlEscaped();
709 if (lines[i].count() > 40)
714 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
715 question.setDefaultButton(QMessageBox::No);
717 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
719 if (question.exec() != QMessageBox::Yes)
723 foreach(QString line, lines) {
731 _singleLine = (newText.indexOf('\n') < 0);
733 if (document()->size().height() != _lastDocumentHeight) {
734 _lastDocumentHeight = document()->size().height();
735 on_documentHeightChanged(_lastDocumentHeight);
738 ensureCursorVisible();
742 void MultiLineEdit::on_documentHeightChanged(qreal)
748 void MultiLineEdit::reset()
750 // every time the MultiLineEdit is cleared we also reset history index
751 _idx = _history.count();
753 QTextBlockFormat format = textCursor().blockFormat();
754 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
755 textCursor().setBlockFormat(format);
760 void MultiLineEdit::showHistoryEntry()
762 // if the user changed the history, display the changed line
763 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
764 QTextCursor cursor = textCursor();
765 QTextBlockFormat format = cursor.blockFormat();
766 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
767 cursor.setBlockFormat(format);
768 cursor.movePosition(QTextCursor::End);
769 setTextCursor(cursor);