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 connect(this, SIGNAL(textChanged()), this, SLOT(on_textChanged()));
60 _mircColorMap["00"] = "#ffffff";
61 _mircColorMap["01"] = "#000000";
62 _mircColorMap["02"] = "#000080";
63 _mircColorMap["03"] = "#008000";
64 _mircColorMap["04"] = "#ff0000";
65 _mircColorMap["05"] = "#800000";
66 _mircColorMap["06"] = "#800080";
67 _mircColorMap["07"] = "#ffa500";
68 _mircColorMap["08"] = "#ffff00";
69 _mircColorMap["09"] = "#00ff00";
70 _mircColorMap["10"] = "#008080";
71 _mircColorMap["11"] = "#00ffff";
72 _mircColorMap["12"] = "#4169e1";
73 _mircColorMap["13"] = "#ff00ff";
74 _mircColorMap["14"] = "#808080";
75 _mircColorMap["15"] = "#c0c0c0";
79 MultiLineEdit::~MultiLineEdit()
84 void MultiLineEdit::setCustomFont(const QFont &font)
91 void MultiLineEdit::setMode(Mode mode)
100 void MultiLineEdit::setLineWrapEnabled(bool enable)
102 setLineWrapMode(enable ? WidgetWidth : NoWrap);
107 void MultiLineEdit::setMinHeight(int lines)
109 if (lines == _minHeight)
117 void MultiLineEdit::setMaxHeight(int lines)
119 if (lines == _maxHeight)
127 void MultiLineEdit::setScrollBarsEnabled(bool enable)
129 if (_scrollBarsEnabled == enable)
132 _scrollBarsEnabled = enable;
137 void MultiLineEdit::updateScrollBars()
139 QFontMetrics fm(font());
140 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
141 if (_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
142 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
144 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
146 if (!_scrollBarsEnabled || isSingleLine())
147 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
149 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
153 void MultiLineEdit::resizeEvent(QResizeEvent *event)
155 QTextEdit::resizeEvent(event);
161 void MultiLineEdit::updateSizeHint()
163 QFontMetrics fm(font());
164 int minPixelHeight = fm.lineSpacing() * _minHeight;
165 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
166 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
168 // use the style to determine a decent size
169 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
170 QStyleOptionFrameV2 opt;
172 opt.rect = QRect(0, 0, 100, h);
173 opt.lineWidth = lineWidth();
174 opt.midLineWidth = midLineWidth();
175 opt.state |= QStyle::State_Sunken;
176 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), this);
177 if (s != _sizeHint) {
184 QSize MultiLineEdit::sizeHint() const
186 if (!_sizeHint.isValid()) {
187 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
188 that->updateSizeHint();
194 QSize MultiLineEdit::minimumSizeHint() const
200 void MultiLineEdit::setEmacsMode(bool enable)
206 void MultiLineEdit::setSpellCheckEnabled(bool enable)
209 setCheckSpellingEnabled(enable);
216 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *)
218 _pasteProtectionEnabled = enable;
222 void MultiLineEdit::historyMoveBack()
224 addToHistory(convertRichtextToMircCodes(), true);
233 void MultiLineEdit::historyMoveForward()
235 addToHistory(convertRichtextToMircCodes(), true);
237 if (_idx < _history.count()) {
239 if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
242 reset(); // equals clear() in this case
245 addToHistory(convertRichtextToMircCodes());
251 bool MultiLineEdit::addToHistory(const QString &text, bool temporary)
256 Q_ASSERT(0 <= _idx && _idx <= _history.count());
259 // if an entry of the history is changed, we remember it and show it again at this
260 // position until a line was actually sent
261 // sent lines get appended to the history
262 if (_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
263 _tempHistory[_idx] = text;
268 if (_history.isEmpty() || text != _history.last()) {
270 _tempHistory.clear();
278 bool MultiLineEdit::event(QEvent *e)
280 // We need to make sure that global shortcuts aren't eaten
281 if (e->type() == QEvent::ShortcutOverride) {
282 QKeyEvent *event = static_cast<QKeyEvent *>(e);
283 QKeySequence key = QKeySequence(event->key() | event->modifiers());
284 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
285 if (action->shortcuts().contains(key)) {
292 return MultiLineEditParent::event(e);
296 void MultiLineEdit::keyPressEvent(QKeyEvent *event)
298 if (event == QKeySequence::InsertLineSeparator) {
299 if (_mode == SingleLine) {
304 MultiLineEditParent::keyPressEvent(event);
308 switch (event->key()) {
310 if (event->modifiers() & Qt::ShiftModifier)
314 if (!(event->modifiers() & Qt::ControlModifier)) {
315 int pos = textCursor().position();
316 moveCursor(QTextCursor::Up);
317 if (pos == textCursor().position()) // already on top line -> history
326 if (event->modifiers() & Qt::ShiftModifier)
330 if (!(event->modifiers() & Qt::ControlModifier)) {
331 int pos = textCursor().position();
332 moveCursor(QTextCursor::Down);
333 if (pos == textCursor().position()) // already on bottom line -> history
334 historyMoveForward();
337 historyMoveForward();
348 // We don't want to have the tab key react even if no completer is installed
358 if (event->modifiers() & Qt::ControlModifier) {
359 switch (event->key()) {
362 moveCursor(QTextCursor::StartOfLine);
365 moveCursor(QTextCursor::EndOfLine);
368 moveCursor(QTextCursor::Right);
371 moveCursor(QTextCursor::Left);
379 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
387 else if (event->modifiers() & Qt::MetaModifier ||
388 event->modifiers() & Qt::AltModifier)
390 switch (event->key()) {
392 moveCursor(QTextCursor::WordRight);
395 moveCursor(QTextCursor::WordLeft);
398 moveCursor(QTextCursor::WordRight);
401 moveCursor(QTextCursor::WordLeft);
404 moveCursor(QTextCursor::Start);
406 case Qt::Key_Greater:
407 moveCursor(QTextCursor::End);
412 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
416 case Qt::Key_U: // uppercase word
417 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
418 textCursor().insertText(textCursor().selectedText().toUpper());
421 case Qt::Key_L: // lowercase word
422 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
423 textCursor().insertText(textCursor().selectedText().toLower());
428 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
429 QString const text = textCursor().selectedText();
430 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
436 moveCursor(QTextCursor::StartOfWord);
437 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
438 QString const word1 = textCursor().selectedText();
439 textCursor().clearSelection();
440 moveCursor(QTextCursor::WordRight);
441 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
442 QString const word2 = textCursor().selectedText();
443 if (!word2.isEmpty() && !word1.isEmpty()) {
444 textCursor().insertText(word1);
445 moveCursor(QTextCursor::WordLeft);
446 moveCursor(QTextCursor::WordLeft);
447 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
448 textCursor().insertText(word2);
449 moveCursor(QTextCursor::WordRight);
450 moveCursor(QTextCursor::EndOfWord);
462 KTextEdit::keyPressEvent(event);
464 QTextEdit::keyPressEvent(event);
469 QString MultiLineEdit::convertRichtextToMircCodes()
471 bool underline, bold, italic, color;
472 QString mircText, mircFgColor, mircBgColor;
473 QTextCursor cursor = textCursor();
474 QTextCursor peekcursor = textCursor();
475 cursor.movePosition(QTextCursor::Start);
477 underline = bold = italic = color = false;
479 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
480 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
481 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
484 mircText.append('\x03');
488 mircText.append('\x1f');
492 mircText.append('\x1d');
496 mircText.append('\x02');
498 mircText.append('\n');
501 if (!bold && cursor.charFormat().font().bold()) {
503 mircText.append('\x02');
505 if (!italic && cursor.charFormat().fontItalic()) {
507 mircText.append('\x1d');
509 if (!underline && cursor.charFormat().fontUnderline()) {
511 mircText.append('\x1f');
513 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
515 mircText.append('\x03');
516 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
517 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
519 if (mircFgColor.isEmpty()) {
520 mircFgColor = "01"; //use black if the current foreground color can't be converted
523 mircText.append(mircFgColor);
524 if (cursor.charFormat().background().isOpaque())
525 mircText.append("," + mircBgColor);
528 mircText.append(cursor.selectedText());
530 peekcursor.setPosition(cursor.position());
531 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
533 if (mircCodesChanged(cursor, peekcursor)) {
536 mircText.append('\x03');
540 mircText.append('\x1f');
544 mircText.append('\x1d');
548 mircText.append('\x02');
553 cursor.clearSelection();
557 mircText.append('\x03');
560 mircText.append('\x1f');
563 mircText.append('\x1d');
566 mircText.append('\x02');
572 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor)
574 bool changed = false;
575 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
577 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
579 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
581 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
583 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
589 QString MultiLineEdit::convertMircCodesToHtml(const QString &text)
592 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
598 posRight = mircCode.indexIn(text, posLeft);
601 words << text.mid(posLeft);
602 break; // no more mirc color codes
605 if (posLeft < posRight) {
606 words << text.mid(posLeft, posRight - posLeft);
610 posRight = text.indexOf(mircCode.cap(), posRight + 1);
611 words << text.mid(posLeft, posRight + 1 - posLeft);
612 posLeft = posRight + 1;
615 for (int i = 0; i < words.count(); i++) {
617 if (words[i].contains('\x02')) {
618 style.append(" font-weight:600;");
619 words[i].replace('\x02', "");
621 if (words[i].contains('\x1d')) {
622 style.append(" font-style:italic;");
623 words[i].replace('\x1d', "");
625 if (words[i].contains('\x1f')) {
626 style.append(" text-decoration: underline;");
627 words[i].replace('\x1f', "");
629 if (words[i].contains('\x03')) {
630 int pos = words[i].indexOf('\x03');
632 QString fg = words[i].mid(pos + 1, 2);
634 if (words[i][pos+3] == ',')
635 bg = words[i].mid(pos+4, 2);
637 style.append(" color:");
638 style.append(_mircColorMap[fg]);
642 style.append(" background-color:");
643 style.append(_mircColorMap[bg]);
647 words[i].replace(pos, len, "");
648 words[i].replace('\x03', "");
650 words[i].replace("&", "&");
651 words[i].replace("<", "<");
652 words[i].replace(">", ">");
653 words[i].replace("\"", """);
654 if (style.isEmpty()) {
655 words[i] = "<span>" + words[i] + "</span>";
658 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
661 return words.join("").replace("\n", "<br />");
665 void MultiLineEdit::on_returnPressed()
667 on_returnPressed(convertRichtextToMircCodes());
671 void MultiLineEdit::on_returnPressed(QString text)
673 if (_completionSpace && text.endsWith(" ")) {
677 if (!text.isEmpty()) {
678 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
682 emit textEntered(line);
685 _tempHistory.clear();
688 emit noTextEntered();
693 void MultiLineEdit::on_textChanged()
695 _completionSpace = qMax(_completionSpace - 1, 0);
697 QString newText = text();
698 newText.replace("\r\n", "\n");
699 newText.replace('\r', '\n');
700 if (_mode == SingleLine) {
701 if (!pasteProtectionEnabled())
702 newText.replace('\n', ' ');
703 else if (newText.contains('\n')) {
704 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
707 if (lines.count() >= 4) {
708 QString msg = tr("Do you really want to paste %n line(s)?", "", lines.count());
710 for (int i = 0; i < 4; i++) {
711 #if QT_VERSION < 0x050000
712 msg += Qt::escape(lines[i].left(40));
714 msg += lines[i].left(40).toHtmlEscaped();
716 if (lines[i].count() > 40)
721 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
722 question.setDefaultButton(QMessageBox::No);
724 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
726 if (question.exec() != QMessageBox::Yes)
730 foreach(QString line, lines) {
738 _singleLine = (newText.indexOf('\n') < 0);
740 if (document()->size().height() != _lastDocumentHeight) {
741 _lastDocumentHeight = document()->size().height();
742 on_documentHeightChanged(_lastDocumentHeight);
745 ensureCursorVisible();
749 void MultiLineEdit::on_documentHeightChanged(qreal)
755 void MultiLineEdit::reset()
757 // every time the MultiLineEdit is cleared we also reset history index
758 _idx = _history.count();
760 QTextBlockFormat format = textCursor().blockFormat();
761 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
762 textCursor().setBlockFormat(format);
767 void MultiLineEdit::showHistoryEntry()
769 // if the user changed the history, display the changed line
770 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
771 QTextCursor cursor = textCursor();
772 QTextBlockFormat format = cursor.blockFormat();
773 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
774 cursor.setBlockFormat(format);
775 cursor.movePosition(QTextCursor::End);
776 setTextCursor(cursor);
781 void MultiLineEdit::addCompletionSpace()
783 // Inserting the space emits textChanged, which should not disable removal
784 _completionSpace = 2;
785 insertPlainText(" ");