1 /***************************************************************************
2 * Copyright (C) 2005-2013 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 #if QT_VERSION >= 0x040500
47 document()->setDocumentMargin(0); // new in Qt 4.5 and we really don't want it here
50 setAcceptRichText(false);
52 enableFindReplace(false);
56 setWordWrapEnabled(false);
59 connect(this, SIGNAL(textChanged()), this, SLOT(on_textChanged()));
61 _mircColorMap["00"] = "#ffffff";
62 _mircColorMap["01"] = "#000000";
63 _mircColorMap["02"] = "#000080";
64 _mircColorMap["03"] = "#008000";
65 _mircColorMap["04"] = "#ff0000";
66 _mircColorMap["05"] = "#800000";
67 _mircColorMap["06"] = "#800080";
68 _mircColorMap["07"] = "#ffa500";
69 _mircColorMap["08"] = "#ffff00";
70 _mircColorMap["09"] = "#00ff00";
71 _mircColorMap["10"] = "#008080";
72 _mircColorMap["11"] = "#00ffff";
73 _mircColorMap["12"] = "#4169e1";
74 _mircColorMap["13"] = "#ff00ff";
75 _mircColorMap["14"] = "#808080";
76 _mircColorMap["15"] = "#c0c0c0";
80 MultiLineEdit::~MultiLineEdit()
85 void MultiLineEdit::setCustomFont(const QFont &font)
92 void MultiLineEdit::setMode(Mode mode)
101 void MultiLineEdit::setMinHeight(int lines)
103 if (lines == _minHeight)
111 void MultiLineEdit::setMaxHeight(int lines)
113 if (lines == _maxHeight)
121 void MultiLineEdit::setScrollBarsEnabled(bool enable)
123 if (_scrollBarsEnabled == enable)
126 _scrollBarsEnabled = enable;
131 void MultiLineEdit::updateScrollBars()
133 QFontMetrics fm(font());
134 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
135 if (_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
136 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
138 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
140 if (!_scrollBarsEnabled || isSingleLine())
141 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
143 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
147 void MultiLineEdit::resizeEvent(QResizeEvent *event)
149 QTextEdit::resizeEvent(event);
155 void MultiLineEdit::updateSizeHint()
157 QFontMetrics fm(font());
158 int minPixelHeight = fm.lineSpacing() * _minHeight;
159 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
160 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
162 // use the style to determine a decent size
163 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
164 QStyleOptionFrameV2 opt;
166 opt.rect = QRect(0, 0, 100, h);
167 opt.lineWidth = lineWidth();
168 opt.midLineWidth = midLineWidth();
169 opt.state |= QStyle::State_Sunken;
170 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), this);
171 if (s != _sizeHint) {
178 QSize MultiLineEdit::sizeHint() const
180 if (!_sizeHint.isValid()) {
181 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
182 that->updateSizeHint();
188 QSize MultiLineEdit::minimumSizeHint() const
194 void MultiLineEdit::setEmacsMode(bool enable)
200 void MultiLineEdit::setSpellCheckEnabled(bool enable)
203 setCheckSpellingEnabled(enable);
210 void MultiLineEdit::setWordWrapEnabled(bool enable)
212 setLineWrapMode(enable ? WidgetWidth : NoWrap);
217 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *)
219 _pasteProtectionEnabled = enable;
223 void MultiLineEdit::historyMoveBack()
225 addToHistory(convertRichtextToMircCodes(), true);
234 void MultiLineEdit::historyMoveForward()
236 addToHistory(convertRichtextToMircCodes(), true);
238 if (_idx < _history.count()) {
240 if (_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
243 reset(); // equals clear() in this case
246 addToHistory(convertRichtextToMircCodes());
252 bool MultiLineEdit::addToHistory(const QString &text, bool temporary)
257 Q_ASSERT(0 <= _idx && _idx <= _history.count());
260 // if an entry of the history is changed, we remember it and show it again at this
261 // position until a line was actually sent
262 // sent lines get appended to the history
263 if (_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
264 _tempHistory[_idx] = text;
269 if (_history.isEmpty() || text != _history.last()) {
271 _tempHistory.clear();
279 bool MultiLineEdit::event(QEvent *e)
281 // We need to make sure that global shortcuts aren't eaten
282 if (e->type() == QEvent::ShortcutOverride) {
283 QKeyEvent *event = static_cast<QKeyEvent *>(e);
284 QKeySequence key = QKeySequence(event->key() | event->modifiers());
285 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
286 if (action->shortcuts().contains(key)) {
293 return MultiLineEditParent::event(e);
297 void MultiLineEdit::keyPressEvent(QKeyEvent *event)
299 // Workaround the fact that Qt < 4.5 doesn't know InsertLineSeparator yet
300 #if QT_VERSION >= 0x040500
301 if (event == QKeySequence::InsertLineSeparator) {
305 if ((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::META) {
307 if ((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::SHIFT) {
311 if (_mode == SingleLine) {
316 MultiLineEditParent::keyPressEvent(event);
320 switch (event->key()) {
322 if (event->modifiers() & Qt::ShiftModifier)
326 if (!(event->modifiers() & Qt::ControlModifier)) {
327 int pos = textCursor().position();
328 moveCursor(QTextCursor::Up);
329 if (pos == textCursor().position()) // already on top line -> history
338 if (event->modifiers() & Qt::ShiftModifier)
342 if (!(event->modifiers() & Qt::ControlModifier)) {
343 int pos = textCursor().position();
344 moveCursor(QTextCursor::Down);
345 if (pos == textCursor().position()) // already on bottom line -> history
346 historyMoveForward();
349 historyMoveForward();
360 // We don't want to have the tab key react even if no completer is installed
370 if (event->modifiers() & Qt::ControlModifier) {
371 switch (event->key()) {
374 moveCursor(QTextCursor::StartOfLine);
377 moveCursor(QTextCursor::EndOfLine);
380 moveCursor(QTextCursor::Right);
383 moveCursor(QTextCursor::Left);
391 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
399 else if (event->modifiers() & Qt::MetaModifier ||
400 event->modifiers() & Qt::AltModifier)
402 switch (event->key()) {
404 moveCursor(QTextCursor::WordRight);
407 moveCursor(QTextCursor::WordLeft);
410 moveCursor(QTextCursor::WordRight);
413 moveCursor(QTextCursor::WordLeft);
416 moveCursor(QTextCursor::Start);
418 case Qt::Key_Greater:
419 moveCursor(QTextCursor::End);
424 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
428 case Qt::Key_U: // uppercase word
429 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
430 textCursor().insertText(textCursor().selectedText().toUpper());
433 case Qt::Key_L: // lowercase word
434 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
435 textCursor().insertText(textCursor().selectedText().toLower());
440 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
441 QString const text = textCursor().selectedText();
442 textCursor().insertText(text.left(1).toUpper() + text.mid(1).toLower());
448 moveCursor(QTextCursor::StartOfWord);
449 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
450 QString const word1 = textCursor().selectedText();
451 textCursor().clearSelection();
452 moveCursor(QTextCursor::WordRight);
453 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
454 QString const word2 = textCursor().selectedText();
455 if (!word2.isEmpty() && !word1.isEmpty()) {
456 textCursor().insertText(word1);
457 moveCursor(QTextCursor::WordLeft);
458 moveCursor(QTextCursor::WordLeft);
459 moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor);
460 textCursor().insertText(word2);
461 moveCursor(QTextCursor::WordRight);
462 moveCursor(QTextCursor::EndOfWord);
474 KTextEdit::keyPressEvent(event);
476 QTextEdit::keyPressEvent(event);
481 QString MultiLineEdit::convertRichtextToMircCodes()
483 bool underline, bold, italic, color;
484 QString mircText, mircFgColor, mircBgColor;
485 QTextCursor cursor = textCursor();
486 QTextCursor peekcursor = textCursor();
487 cursor.movePosition(QTextCursor::Start);
489 underline = bold = italic = color = false;
491 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
492 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
493 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
496 mircText.append('\x03');
500 mircText.append('\x1f');
504 mircText.append('\x1d');
508 mircText.append('\x02');
510 mircText.append('\n');
513 if (!bold && cursor.charFormat().font().bold()) {
515 mircText.append('\x02');
517 if (!italic && cursor.charFormat().fontItalic()) {
519 mircText.append('\x1d');
521 if (!underline && cursor.charFormat().fontUnderline()) {
523 mircText.append('\x1f');
525 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
527 mircText.append('\x03');
528 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
529 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
531 if (mircFgColor.isEmpty()) {
532 mircFgColor = "01"; //use black if the current foreground color can't be converted
535 mircText.append(mircFgColor);
536 if (cursor.charFormat().background().isOpaque())
537 mircText.append("," + mircBgColor);
540 mircText.append(cursor.selectedText());
542 peekcursor.setPosition(cursor.position());
543 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
545 if (mircCodesChanged(cursor, peekcursor)) {
548 mircText.append('\x03');
552 mircText.append('\x1f');
556 mircText.append('\x1d');
560 mircText.append('\x02');
565 cursor.clearSelection();
569 mircText.append('\x03');
573 mircText.append('\x1f');
577 mircText.append('\x1d');
581 mircText.append('\x02');
588 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor)
590 bool changed = false;
591 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
593 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
595 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
597 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
599 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
605 QString MultiLineEdit::convertMircCodesToHtml(const QString &text)
608 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
614 posRight = mircCode.indexIn(text, posLeft);
617 words << text.mid(posLeft);
618 break; // no more mirc color codes
621 if (posLeft < posRight) {
622 words << text.mid(posLeft, posRight - posLeft);
626 posRight = text.indexOf(mircCode.cap(), posRight + 1);
627 words << text.mid(posLeft, posRight + 1 - posLeft);
628 posLeft = posRight + 1;
631 for (int i = 0; i < words.count(); i++) {
633 if (words[i].contains('\x02')) {
634 style.append(" font-weight:600;");
635 words[i].replace('\x02', "");
637 if (words[i].contains('\x1d')) {
638 style.append(" font-style:italic;");
639 words[i].replace('\x1d', "");
641 if (words[i].contains('\x1f')) {
642 style.append(" text-decoration: underline;");
643 words[i].replace('\x1f', "");
645 if (words[i].contains('\x03')) {
646 int pos = words[i].indexOf('\x03');
648 QString fg = words[i].mid(pos + 1, 2);
650 if (words[i][pos+3] == ',')
651 bg = words[i].mid(pos+4, 2);
653 style.append(" color:");
654 style.append(_mircColorMap[fg]);
658 style.append(" background-color:");
659 style.append(_mircColorMap[bg]);
663 words[i].replace(pos, len, "");
664 words[i].replace('\x03', "");
666 words[i].replace("&", "&");
667 words[i].replace("<", "<");
668 words[i].replace(">", ">");
669 words[i].replace("\"", """);
670 if (style.isEmpty()) {
671 words[i] = "<span>" + words[i] + "</span>";
674 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
677 return words.join("").replace("\n", "<br />");
681 void MultiLineEdit::on_returnPressed()
683 on_returnPressed(convertRichtextToMircCodes());
687 void MultiLineEdit::on_returnPressed(const QString &text)
689 if (!text.isEmpty()) {
690 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
694 emit textEntered(line);
697 _tempHistory.clear();
700 emit noTextEntered();
705 void MultiLineEdit::on_textChanged()
707 QString newText = text();
708 newText.replace("\r\n", "\n");
709 newText.replace('\r', '\n');
710 if (_mode == SingleLine) {
711 if (!pasteProtectionEnabled())
712 newText.replace('\n', ' ');
713 else if (newText.contains('\n')) {
714 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
717 if (lines.count() >= 4) {
718 QString msg = tr("Do you really want to paste %n line(s)?", "", lines.count());
720 for (int i = 0; i < 4; i++) {
721 msg += Qt::escape(lines[i].left(40));
722 if (lines[i].count() > 40)
727 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
728 question.setDefaultButton(QMessageBox::No);
730 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
732 if (question.exec() != QMessageBox::Yes)
736 foreach(QString line, lines) {
744 _singleLine = (newText.indexOf('\n') < 0);
746 if (document()->size().height() != _lastDocumentHeight) {
747 _lastDocumentHeight = document()->size().height();
748 on_documentHeightChanged(_lastDocumentHeight);
751 ensureCursorVisible();
755 void MultiLineEdit::on_documentHeightChanged(qreal)
761 void MultiLineEdit::reset()
763 // every time the MultiLineEdit is cleared we also reset history index
764 _idx = _history.count();
766 QTextBlockFormat format = textCursor().blockFormat();
767 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
768 textCursor().setBlockFormat(format);
773 void MultiLineEdit::showHistoryEntry()
775 // if the user changed the history, display the changed line
776 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
777 QTextCursor cursor = textCursor();
778 QTextBlockFormat format = cursor.blockFormat();
779 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
780 cursor.setBlockFormat(format);
781 cursor.movePosition(QTextCursor::End);
782 setTextCursor(cursor);