1 /***************************************************************************
2 * Copyright (C) 2005-2010 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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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),
43 _lastDocumentHeight(-1)
45 #if QT_VERSION >= 0x040500
46 document()->setDocumentMargin(0); // new in Qt 4.5 and we really don't want it here
49 setAcceptRichText(false);
51 enableFindReplace(false);
55 setWordWrapEnabled(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() {
82 void MultiLineEdit::setCustomFont(const QFont &font) {
87 void MultiLineEdit::setMode(Mode mode) {
94 void MultiLineEdit::setMinHeight(int lines) {
95 if(lines == _minHeight)
102 void MultiLineEdit::setMaxHeight(int lines) {
103 if(lines == _maxHeight)
110 void MultiLineEdit::setScrollBarsEnabled(bool enable) {
111 if(_scrollBarsEnabled == enable)
114 _scrollBarsEnabled = enable;
118 void MultiLineEdit::updateScrollBars() {
119 QFontMetrics fm(font());
120 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
121 if(_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
122 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
124 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
126 if(!_scrollBarsEnabled || isSingleLine())
127 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
129 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
132 void MultiLineEdit::resizeEvent(QResizeEvent *event) {
133 QTextEdit::resizeEvent(event);
138 void MultiLineEdit::updateSizeHint() {
139 QFontMetrics fm(font());
140 int minPixelHeight = fm.lineSpacing() * _minHeight;
141 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
142 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
144 // use the style to determine a decent size
145 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
146 QStyleOptionFrameV2 opt;
148 opt.rect = QRect(0, 0, 100, h);
149 opt.lineWidth = lineWidth();
150 opt.midLineWidth = midLineWidth();
151 opt.state |= QStyle::State_Sunken;
152 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), this);
159 QSize MultiLineEdit::sizeHint() const {
160 if(!_sizeHint.isValid()) {
161 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
162 that->updateSizeHint();
167 QSize MultiLineEdit::minimumSizeHint() const {
171 void MultiLineEdit::setEmacsMode(bool enable) {
175 void MultiLineEdit::setSpellCheckEnabled(bool enable) {
177 setCheckSpellingEnabled(enable);
183 void MultiLineEdit::setWordWrapEnabled(bool enable) {
184 setLineWrapMode(enable? WidgetWidth : NoWrap);
188 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *) {
189 _pasteProtectionEnabled = enable;
192 void MultiLineEdit::historyMoveBack() {
193 addToHistory(convertRichtextToMircCodes(), true);
201 void MultiLineEdit::historyMoveForward() {
202 addToHistory(convertRichtextToMircCodes(), true);
204 if(_idx < _history.count()) {
206 if(_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
209 reset(); // equals clear() in this case
211 addToHistory(convertRichtextToMircCodes());
216 bool MultiLineEdit::addToHistory(const QString &text, bool temporary) {
220 Q_ASSERT(0 <= _idx && _idx <= _history.count());
223 // if an entry of the history is changed, we remember it and show it again at this
224 // position until a line was actually sent
225 // sent lines get appended to the history
226 if(_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
227 _tempHistory[_idx] = text;
231 if(_history.isEmpty() || text != _history.last()) {
233 _tempHistory.clear();
240 bool MultiLineEdit::event(QEvent *e) {
241 // We need to make sure that global shortcuts aren't eaten
242 if(e->type() == QEvent::ShortcutOverride) {
243 QKeyEvent* event = static_cast<QKeyEvent *>(e);
244 QKeySequence key = QKeySequence(event->key() | event->modifiers());
245 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
246 if(action->shortcuts().contains(key)) {
253 return MultiLineEditParent::event(e);
256 void MultiLineEdit::keyPressEvent(QKeyEvent *event) {
257 // Workaround the fact that Qt < 4.5 doesn't know InsertLineSeparator yet
258 #if QT_VERSION >= 0x040500
259 if(event == QKeySequence::InsertLineSeparator) {
263 if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::META) {
265 if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::SHIFT) {
269 if(_mode == SingleLine) {
274 MultiLineEditParent::keyPressEvent(event);
278 switch(event->key()) {
280 if(event->modifiers() & Qt::ShiftModifier)
284 if(!(event->modifiers() & Qt::ControlModifier)) {
285 int pos = textCursor().position();
286 moveCursor(QTextCursor::Up);
287 if(pos == textCursor().position()) // already on top line -> history
295 if(event->modifiers() & Qt::ShiftModifier)
299 if(!(event->modifiers() & Qt::ControlModifier)) {
300 int pos = textCursor().position();
301 moveCursor(QTextCursor::Down);
302 if(pos == textCursor().position()) // already on bottom line -> history
303 historyMoveForward();
305 historyMoveForward();
316 // We don't want to have the tab key react even if no completer is installed
326 if(event->modifiers() & Qt::ControlModifier) {
327 switch(event->key()) {
330 moveCursor(QTextCursor::StartOfLine);
333 moveCursor(QTextCursor::EndOfLine);
336 moveCursor(QTextCursor::Right);
339 moveCursor(QTextCursor::Left);
347 moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
352 else if(event->modifiers() & Qt::MetaModifier ||
353 event->modifiers() & Qt::AltModifier)
355 switch(event->key()) {
357 moveCursor(QTextCursor::WordRight);
360 moveCursor(QTextCursor::WordLeft);
363 moveCursor(QTextCursor::WordRight);
366 moveCursor(QTextCursor::WordLeft);
369 moveCursor(QTextCursor::Start);
371 case Qt::Key_Greater:
372 moveCursor(QTextCursor::End);
377 moveCursor(QTextCursor::WordRight, QTextCursor::KeepAnchor);
385 KTextEdit::keyPressEvent(event);
387 QTextEdit::keyPressEvent(event);
391 QString MultiLineEdit::convertRichtextToMircCodes() {
392 bool underline, bold, italic, color;
393 QString mircText, mircFgColor, mircBgColor;
394 QTextCursor cursor = textCursor();
395 QTextCursor peekcursor = textCursor();
396 cursor.movePosition(QTextCursor::Start);
398 underline = bold = italic = color = false;
400 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
402 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
403 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
406 mircText.append('\x03');
410 mircText.append('\x1f');
414 mircText.append('\x1d');
418 mircText.append('\x02');
420 mircText.append('\n');
423 if (!bold && cursor.charFormat().font().bold()) {
425 mircText.append('\x02');
427 if (!italic && cursor.charFormat().fontItalic()) {
429 mircText.append('\x1d');
431 if (!underline && cursor.charFormat().fontUnderline()) {
433 mircText.append('\x1f');
435 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
437 mircText.append('\x03');
438 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
439 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
441 if (mircFgColor.isEmpty()) {
442 mircFgColor = "01"; //use black if the current foreground color can't be converted
445 mircText.append(mircFgColor);
446 if (cursor.charFormat().background().isOpaque())
447 mircText.append("," + mircBgColor);
450 mircText.append(cursor.selectedText());
452 peekcursor.setPosition(cursor.position());
453 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
455 if (mircCodesChanged(cursor, peekcursor)) {
458 mircText.append('\x03');
462 mircText.append('\x1f');
466 mircText.append('\x1d');
470 mircText.append('\x02');
475 cursor.clearSelection();
479 mircText.append('\x03');
483 mircText.append('\x1f');
487 mircText.append('\x1d');
491 mircText.append('\x02');
497 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor) {
498 bool changed = false;
499 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
501 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
503 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
505 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
507 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
512 QString MultiLineEdit::convertMircCodesToHtml(const QString &text) {
514 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
520 posRight = mircCode.indexIn(text, posLeft);
523 words << text.mid(posLeft);
524 break; // no more mirc color codes
527 if (posLeft < posRight) {
528 words << text.mid(posLeft, posRight - posLeft);
532 posRight = text.indexOf(mircCode.cap(), posRight + 1);
533 words << text.mid(posLeft, posRight + 1 - posLeft);
534 posLeft = posRight + 1;
537 for (int i = 0; i < words.count(); i++) {
539 if (words[i].contains('\x02')) {
540 style.append(" font-weight:600;");
541 words[i].replace('\x02',"");
543 if (words[i].contains('\x1d')) {
544 style.append(" font-style:italic;");
545 words[i].replace('\x1d',"");
547 if (words[i].contains('\x1f')) {
548 style.append(" text-decoration: underline;");
549 words[i].replace('\x1f',"");
551 if (words[i].contains('\x03')) {
552 int pos = words[i].indexOf('\x03');
554 QString fg = words[i].mid(pos + 1,2);
556 if (words[i][pos+3] == ',')
557 bg = words[i].mid(pos+4,2);
559 style.append(" color:");
560 style.append(_mircColorMap[fg]);
564 style.append(" background-color:");
565 style.append(_mircColorMap[bg]);
569 words[i].replace(pos, len, "");
570 words[i].replace('\x03',"");
572 words[i].replace("&","&");
573 words[i].replace("<", "<");
574 words[i].replace(">", ">");
575 words[i].replace("\"", """);
576 if (style.isEmpty()) {
577 words[i] = "<span>" + words[i] + "</span>";
580 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
583 return words.join("").replace("\n","<br />");
586 void MultiLineEdit::on_returnPressed() {
587 on_returnPressed(convertRichtextToMircCodes());
590 void MultiLineEdit::on_returnPressed(const QString & text) {
591 if(!text.isEmpty()) {
592 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
596 emit textEntered(line);
599 _tempHistory.clear();
601 emit noTextEntered();
605 void MultiLineEdit::on_textChanged() {
606 QString newText = text();
607 newText.replace("\r\n", "\n");
608 newText.replace('\r', '\n');
609 if(_mode == SingleLine) {
610 if(!pasteProtectionEnabled())
611 newText.replace('\n', ' ');
612 else if(newText.contains('\n')) {
613 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
616 if(lines.count() >= 4) {
617 QString msg = tr("Do you really want to paste %n lines?", "", lines.count());
619 for(int i = 0; i < 4; i++) {
620 msg += Qt::escape(lines[i].left(40));
621 if(lines[i].count() > 40)
626 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
627 question.setDefaultButton(QMessageBox::No);
629 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
631 if(question.exec() != QMessageBox::Yes)
635 foreach(QString line, lines) {
643 _singleLine = (newText.indexOf('\n') < 0);
645 if(document()->size().height() != _lastDocumentHeight) {
646 _lastDocumentHeight = document()->size().height();
647 on_documentHeightChanged(_lastDocumentHeight);
650 ensureCursorVisible();
653 void MultiLineEdit::on_documentHeightChanged(qreal) {
657 void MultiLineEdit::reset() {
658 // every time the MultiLineEdit is cleared we also reset history index
659 _idx = _history.count();
661 QTextBlockFormat format = textCursor().blockFormat();
662 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
663 textCursor().setBlockFormat(format);
667 void MultiLineEdit::showHistoryEntry() {
668 // if the user changed the history, display the changed line
669 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
670 QTextCursor cursor = textCursor();
671 QTextBlockFormat format = cursor.blockFormat();
672 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
673 cursor.setBlockFormat(format);
674 cursor.movePosition(QTextCursor::End);
675 setTextCursor(cursor);