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),
47 _lastDocumentHeight(-1)
49 document()->setDocumentMargin(0);
51 setAcceptRichText(false);
53 enableFindReplace(false);
57 new Sonnet::SpellCheckDecorator(this);
61 setLineWrapEnabled(false);
64 connect(this, SIGNAL(textChanged()), this, SLOT(on_textChanged()));
66 _mircColorMap["00"] = "#ffffff";
67 _mircColorMap["01"] = "#000000";
68 _mircColorMap["02"] = "#000080";
69 _mircColorMap["03"] = "#008000";
70 _mircColorMap["04"] = "#ff0000";
71 _mircColorMap["05"] = "#800000";
72 _mircColorMap["06"] = "#800080";
73 _mircColorMap["07"] = "#ffa500";
74 _mircColorMap["08"] = "#ffff00";
75 _mircColorMap["09"] = "#00ff00";
76 _mircColorMap["10"] = "#008080";
77 _mircColorMap["11"] = "#00ffff";
78 _mircColorMap["12"] = "#4169e1";
79 _mircColorMap["13"] = "#ff00ff";
80 _mircColorMap["14"] = "#808080";
81 _mircColorMap["15"] = "#c0c0c0";
85 MultiLineEdit::~MultiLineEdit()
90 void MultiLineEdit::setCustomFont(const QFont &font)
97 void MultiLineEdit::setMode(Mode mode)
106 void MultiLineEdit::setLineWrapEnabled(bool enable)
108 setLineWrapMode(enable ? WidgetWidth : NoWrap);
113 void MultiLineEdit::setMinHeight(int lines)
115 if (lines == _minHeight)
123 void MultiLineEdit::setMaxHeight(int lines)
125 if (lines == _maxHeight)
133 void MultiLineEdit::setScrollBarsEnabled(bool enable)
135 if (_scrollBarsEnabled == enable)
138 _scrollBarsEnabled = enable;
143 void MultiLineEdit::updateScrollBars()
145 QFontMetrics fm(font());
146 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
147 if (_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
148 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
150 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
152 if (!_scrollBarsEnabled || isSingleLine())
153 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
155 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
159 void MultiLineEdit::resizeEvent(QResizeEvent *event)
161 QTextEdit::resizeEvent(event);
167 void MultiLineEdit::updateSizeHint()
169 QFontMetrics fm(font());
170 int minPixelHeight = fm.lineSpacing() * _minHeight;
171 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
172 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
174 // use the style to determine a decent size
175 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
176 QStyleOptionFrameV2 opt;
178 opt.rect = QRect(0, 0, 100, h);
179 opt.lineWidth = lineWidth();
180 opt.midLineWidth = midLineWidth();
181 opt.state |= QStyle::State_Sunken;
182 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), this);
183 if (s != _sizeHint) {
190 QSize MultiLineEdit::sizeHint() const
192 if (!_sizeHint.isValid()) {
193 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
194 that->updateSizeHint();
200 QSize MultiLineEdit::minimumSizeHint() const
206 void MultiLineEdit::setEmacsMode(bool enable)
212 void MultiLineEdit::setSpellCheckEnabled(bool enable)
215 setCheckSpellingEnabled(enable);
222 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *)
224 _pasteProtectionEnabled = enable;
228 void MultiLineEdit::historyMoveBack()
230 addToHistory(convertRichtextToMircCodes(), true);
239 void MultiLineEdit::historyMoveForward()
241 addToHistory(convertRichtextToMircCodes(), true);
243 if (_idx < _history.count()) {
245 if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
248 reset(); // equals clear() in this case
251 addToHistory(convertRichtextToMircCodes());
257 bool MultiLineEdit::addToHistory(const QString &text, bool temporary)
262 Q_ASSERT(0 <= _idx && _idx <= _history.count());
265 // if an entry of the history is changed, we remember it and show it again at this
266 // position until a line was actually sent
267 // sent lines get appended to the history
268 if (_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
269 _tempHistory[_idx] = text;
274 if (_history.isEmpty() || text != _history.last()) {
276 _tempHistory.clear();
284 bool MultiLineEdit::event(QEvent *e)
286 // We need to make sure that global shortcuts aren't eaten
287 if (e->type() == QEvent::ShortcutOverride) {
288 QKeyEvent *event = static_cast<QKeyEvent *>(e);
289 QKeySequence key = QKeySequence(event->key() | event->modifiers());
290 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
291 if (action->shortcuts().contains(key)) {
298 return MultiLineEditParent::event(e);
302 void MultiLineEdit::keyPressEvent(QKeyEvent *event)
304 if (event == QKeySequence::InsertLineSeparator) {
305 if (_mode == SingleLine) {
310 MultiLineEditParent::keyPressEvent(event);
314 switch (event->key()) {
316 if (event->modifiers() & Qt::ShiftModifier)
320 if (!(event->modifiers() & Qt::ControlModifier)) {
321 int pos = textCursor().position();
322 moveCursor(QTextCursor::Up);
323 if (pos == textCursor().position()) // already on top line -> history
332 if (event->modifiers() & Qt::ShiftModifier)
336 if (!(event->modifiers() & Qt::ControlModifier)) {
337 int pos = textCursor().position();
338 moveCursor(QTextCursor::Down);
339 if (pos == textCursor().position()) // already on bottom line -> history
340 historyMoveForward();
343 historyMoveForward();
354 // We don't want to have the tab key react even if no completer is installed
364 if (event->modifiers() & Qt::ControlModifier) {
365 switch (event->key()) {
368 moveCursor(QTextCursor::StartOfLine);
371 moveCursor(QTextCursor::EndOfLine);
374 moveCursor(QTextCursor::Right);
377 moveCursor(QTextCursor::Left);
385 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
393 else if (event->modifiers() & Qt::MetaModifier ||
394 event->modifiers() & Qt::AltModifier)
396 switch (event->key()) {
398 moveCursor(QTextCursor::WordRight);
401 moveCursor(QTextCursor::WordLeft);
404 moveCursor(QTextCursor::WordRight);
407 moveCursor(QTextCursor::WordLeft);
410 moveCursor(QTextCursor::Start);
412 case Qt::Key_Greater:
413 moveCursor(QTextCursor::End);
418 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
422 case Qt::Key_U: // uppercase word
423 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
424 textCursor().insertText(textCursor().selectedText().toUpper());
427 case Qt::Key_L: // lowercase word
428 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
429 textCursor().insertText(textCursor().selectedText().toLower());
434 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
435 QString const text = textCursor().selectedText();
436 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
442 moveCursor(QTextCursor::StartOfWord);
443 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
444 QString const word1 = textCursor().selectedText();
445 textCursor().clearSelection();
446 moveCursor(QTextCursor::WordRight);
447 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
448 QString const word2 = textCursor().selectedText();
449 if (!word2.isEmpty() && !word1.isEmpty()) {
450 textCursor().insertText(word1);
451 moveCursor(QTextCursor::WordLeft);
452 moveCursor(QTextCursor::WordLeft);
453 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
454 textCursor().insertText(word2);
455 moveCursor(QTextCursor::WordRight);
456 moveCursor(QTextCursor::EndOfWord);
468 KTextEdit::keyPressEvent(event);
470 QTextEdit::keyPressEvent(event);
475 QString MultiLineEdit::convertRichtextToMircCodes()
477 bool underline, bold, italic, color;
478 QString mircText, mircFgColor, mircBgColor;
479 QTextCursor cursor = textCursor();
480 QTextCursor peekcursor = textCursor();
481 cursor.movePosition(QTextCursor::Start);
483 underline = bold = italic = color = false;
485 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
486 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
487 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
490 mircText.append('\x03');
494 mircText.append('\x1f');
498 mircText.append('\x1d');
502 mircText.append('\x02');
504 mircText.append('\n');
507 if (!bold && cursor.charFormat().font().bold()) {
509 mircText.append('\x02');
511 if (!italic && cursor.charFormat().fontItalic()) {
513 mircText.append('\x1d');
515 if (!underline && cursor.charFormat().fontUnderline()) {
517 mircText.append('\x1f');
519 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
521 mircText.append('\x03');
522 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
523 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
525 if (mircFgColor.isEmpty()) {
526 mircFgColor = "01"; //use black if the current foreground color can't be converted
529 mircText.append(mircFgColor);
530 if (cursor.charFormat().background().isOpaque())
531 mircText.append("," + mircBgColor);
534 mircText.append(cursor.selectedText());
536 peekcursor.setPosition(cursor.position());
537 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
539 if (mircCodesChanged(cursor, peekcursor)) {
542 mircText.append('\x03');
546 mircText.append('\x1f');
550 mircText.append('\x1d');
554 mircText.append('\x02');
559 cursor.clearSelection();
563 mircText.append('\x03');
566 mircText.append('\x1f');
569 mircText.append('\x1d');
572 mircText.append('\x02');
578 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor)
580 bool changed = false;
581 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
583 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
585 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
587 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
589 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
595 QString MultiLineEdit::convertMircCodesToHtml(const QString &text)
598 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
604 posRight = mircCode.indexIn(text, posLeft);
607 words << text.mid(posLeft);
608 break; // no more mirc color codes
611 if (posLeft < posRight) {
612 words << text.mid(posLeft, posRight - posLeft);
616 posRight = text.indexOf(mircCode.cap(), posRight + 1);
617 words << text.mid(posLeft, posRight + 1 - posLeft);
618 posLeft = posRight + 1;
621 for (int i = 0; i < words.count(); i++) {
623 if (words[i].contains('\x02')) {
624 style.append(" font-weight:600;");
625 words[i].replace('\x02', "");
627 if (words[i].contains('\x1d')) {
628 style.append(" font-style:italic;");
629 words[i].replace('\x1d', "");
631 if (words[i].contains('\x1f')) {
632 style.append(" text-decoration: underline;");
633 words[i].replace('\x1f', "");
635 if (words[i].contains('\x03')) {
636 int pos = words[i].indexOf('\x03');
638 QString fg = words[i].mid(pos + 1, 2);
640 if (words[i][pos+3] == ',')
641 bg = words[i].mid(pos+4, 2);
643 style.append(" color:");
644 style.append(_mircColorMap[fg]);
648 style.append(" background-color:");
649 style.append(_mircColorMap[bg]);
653 words[i].replace(pos, len, "");
654 words[i].replace('\x03', "");
656 words[i].replace("&", "&");
657 words[i].replace("<", "<");
658 words[i].replace(">", ">");
659 words[i].replace("\"", """);
660 if (style.isEmpty()) {
661 words[i] = "<span>" + words[i] + "</span>";
664 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
667 return words.join("").replace("\n", "<br />");
671 void MultiLineEdit::on_returnPressed()
673 on_returnPressed(convertRichtextToMircCodes());
677 void MultiLineEdit::on_returnPressed(const QString &text)
679 if (!text.isEmpty()) {
680 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
684 emit textEntered(line);
687 _tempHistory.clear();
690 emit noTextEntered();
695 void MultiLineEdit::on_textChanged()
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);