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::setSpellCheckEnabled(bool enable) {
173 setCheckSpellingEnabled(enable);
179 void MultiLineEdit::setWordWrapEnabled(bool enable) {
180 setLineWrapMode(enable? WidgetWidth : NoWrap);
184 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *) {
185 _pasteProtectionEnabled = enable;
188 void MultiLineEdit::historyMoveBack() {
189 addToHistory(convertRichtextToMircCodes(), true);
197 void MultiLineEdit::historyMoveForward() {
198 addToHistory(convertRichtextToMircCodes(), true);
200 if(_idx < _history.count()) {
202 if(_idx < _history.count() || _tempHistory.contains(_idx)) // tempHistory might have an entry for idx == history.count() + 1
205 reset(); // equals clear() in this case
207 addToHistory(convertRichtextToMircCodes());
212 bool MultiLineEdit::addToHistory(const QString &text, bool temporary) {
216 Q_ASSERT(0 <= _idx && _idx <= _history.count());
219 // if an entry of the history is changed, we remember it and show it again at this
220 // position until a line was actually sent
221 // sent lines get appended to the history
222 if(_history.isEmpty() || text != _history[_idx - (int)(_idx == _history.count())]) {
223 _tempHistory[_idx] = text;
227 if(_history.isEmpty() || text != _history.last()) {
229 _tempHistory.clear();
236 bool MultiLineEdit::event(QEvent *e) {
237 // We need to make sure that global shortcuts aren't eaten
238 if(e->type() == QEvent::ShortcutOverride) {
239 QKeyEvent* event = static_cast<QKeyEvent *>(e);
240 QKeySequence key = QKeySequence(event->key() | event->modifiers());
241 foreach(QAction *action, GraphicalUi::actionCollection()->actions()) {
242 if(action->shortcuts().contains(key)) {
249 return MultiLineEditParent::event(e);
252 void MultiLineEdit::keyPressEvent(QKeyEvent *event) {
253 // Workaround the fact that Qt < 4.5 doesn't know InsertLineSeparator yet
254 #if QT_VERSION >= 0x040500
255 if(event == QKeySequence::InsertLineSeparator) {
259 if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::META) {
261 if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::SHIFT) {
265 if(_mode == SingleLine) {
270 MultiLineEditParent::keyPressEvent(event);
274 switch(event->key()) {
276 if(event->modifiers() & Qt::ShiftModifier)
280 if(!(event->modifiers() & Qt::ControlModifier)) {
281 int pos = textCursor().position();
282 moveCursor(QTextCursor::Up);
283 if(pos == textCursor().position()) // already on top line -> history
291 if(event->modifiers() & Qt::ShiftModifier)
295 if(!(event->modifiers() & Qt::ControlModifier)) {
296 int pos = textCursor().position();
297 moveCursor(QTextCursor::Down);
298 if(pos == textCursor().position()) // already on bottom line -> history
299 historyMoveForward();
301 historyMoveForward();
312 // We don't want to have the tab key react even if no completer is installed
323 KTextEdit::keyPressEvent(event);
325 QTextEdit::keyPressEvent(event);
329 QString MultiLineEdit::convertRichtextToMircCodes() {
330 bool underline, bold, italic, color;
331 QString mircText, mircFgColor, mircBgColor;
332 QTextCursor cursor = textCursor();
333 QTextCursor peekcursor = textCursor();
334 cursor.movePosition(QTextCursor::Start);
336 underline = bold = italic = color = false;
338 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
340 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
341 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
344 mircText.append('\x03');
348 mircText.append('\x1f');
352 mircText.append('\x1d');
356 mircText.append('\x02');
358 mircText.append('\n');
361 if (!bold && cursor.charFormat().font().bold()) {
363 mircText.append('\x02');
365 if (!italic && cursor.charFormat().fontItalic()) {
367 mircText.append('\x1d');
369 if (!underline && cursor.charFormat().fontUnderline()) {
371 mircText.append('\x1f');
373 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
375 mircText.append('\x03');
376 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
377 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
379 if (mircFgColor.isEmpty()) {
380 mircFgColor = "01"; //use black if the current foreground color can't be converted
383 mircText.append(mircFgColor);
384 if (cursor.charFormat().background().isOpaque())
385 mircText.append("," + mircBgColor);
388 mircText.append(cursor.selectedText());
390 peekcursor.setPosition(cursor.position());
391 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
393 if (mircCodesChanged(cursor, peekcursor)) {
396 mircText.append('\x03');
400 mircText.append('\x1f');
404 mircText.append('\x1d');
408 mircText.append('\x02');
413 cursor.clearSelection();
417 mircText.append('\x03');
421 mircText.append('\x1f');
425 mircText.append('\x1d');
429 mircText.append('\x02');
435 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor) {
436 bool changed = false;
437 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
439 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
441 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
443 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
445 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
450 QString MultiLineEdit::convertMircCodesToHtml(const QString &text) {
452 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
458 posRight = mircCode.indexIn(text, posLeft);
461 words << text.mid(posLeft);
462 break; // no more mirc color codes
465 if (posLeft < posRight) {
466 words << text.mid(posLeft, posRight - posLeft);
470 posRight = text.indexOf(mircCode.cap(), posRight + 1);
471 words << text.mid(posLeft, posRight + 1 - posLeft);
472 posLeft = posRight + 1;
475 for (int i = 0; i < words.count(); i++) {
477 if (words[i].contains('\x02')) {
478 style.append(" font-weight:600;");
479 words[i].replace('\x02',"");
481 if (words[i].contains('\x1d')) {
482 style.append(" font-style:italic;");
483 words[i].replace('\x1d',"");
485 if (words[i].contains('\x1f')) {
486 style.append(" text-decoration: underline;");
487 words[i].replace('\x1f',"");
489 if (words[i].contains('\x03')) {
490 int pos = words[i].indexOf('\x03');
492 QString fg = words[i].mid(pos + 1,2);
494 if (words[i][pos+3] == ',')
495 bg = words[i].mid(pos+4,2);
497 style.append(" color:");
498 style.append(_mircColorMap[fg]);
502 style.append(" background-color:");
503 style.append(_mircColorMap[bg]);
507 words[i].replace(pos, len, "");
508 words[i].replace('\x03',"");
510 words[i].replace("&","&");
511 words[i].replace("<", "<");
512 words[i].replace(">", ">");
513 words[i].replace("\"", """);
514 if (style.isEmpty()) {
515 words[i] = "<span>" + words[i] + "</span>";
518 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
521 return words.join("").replace("\n","<br />");
524 void MultiLineEdit::on_returnPressed() {
525 on_returnPressed(convertRichtextToMircCodes());
528 void MultiLineEdit::on_returnPressed(const QString & text) {
529 if(!text.isEmpty()) {
530 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
534 emit textEntered(line);
537 _tempHistory.clear();
539 emit noTextEntered();
543 void MultiLineEdit::on_textChanged() {
544 QString newText = text();
545 newText.replace("\r\n", "\n");
546 newText.replace('\r', '\n');
547 if(_mode == SingleLine) {
548 if(!pasteProtectionEnabled())
549 newText.replace('\n', ' ');
550 else if(newText.contains('\n')) {
551 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
554 if(lines.count() >= 4) {
555 QString msg = tr("Do you really want to paste %n lines?", "", lines.count());
557 for(int i = 0; i < 4; i++) {
558 msg += Qt::escape(lines[i].left(40));
559 if(lines[i].count() > 40)
564 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
565 question.setDefaultButton(QMessageBox::No);
567 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
569 if(question.exec() != QMessageBox::Yes)
573 foreach(QString line, lines) {
581 _singleLine = (newText.indexOf('\n') < 0);
583 if(document()->size().height() != _lastDocumentHeight) {
584 _lastDocumentHeight = document()->size().height();
585 on_documentHeightChanged(_lastDocumentHeight);
588 ensureCursorVisible();
591 void MultiLineEdit::on_documentHeightChanged(qreal) {
595 void MultiLineEdit::reset() {
596 // every time the MultiLineEdit is cleared we also reset history index
597 _idx = _history.count();
599 QTextBlockFormat format = textCursor().blockFormat();
600 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
601 textCursor().setBlockFormat(format);
605 void MultiLineEdit::showHistoryEntry() {
606 // if the user changed the history, display the changed line
607 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
608 QTextCursor cursor = textCursor();
609 QTextBlockFormat format = cursor.blockFormat();
610 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
611 cursor.setBlockFormat(format);
612 cursor.movePosition(QTextCursor::End);
613 setTextCursor(cursor);