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 "bufferview.h"
27 #include "graphicalui.h"
28 #include "multilineedit.h"
29 #include "tabcompleter.h"
31 const int leftMargin = 3;
33 MultiLineEdit::MultiLineEdit(QWidget *parent)
45 _scrollBarsEnabled(true),
46 _pasteProtectionEnabled(true),
47 _lastDocumentHeight(-1)
49 #if QT_VERSION >= 0x040500
50 document()->setDocumentMargin(0); // new in Qt 4.5 and we really don't want it here
53 setAcceptRichText(false);
55 enableFindReplace(false);
59 setWordWrapEnabled(false);
62 connect(this, SIGNAL(textChanged()), this, SLOT(on_textChanged()));
64 _mircColorMap["00"] = "#ffffff";
65 _mircColorMap["01"] = "#000000";
66 _mircColorMap["02"] = "#000080";
67 _mircColorMap["03"] = "#008000";
68 _mircColorMap["04"] = "#ff0000";
69 _mircColorMap["05"] = "#800000";
70 _mircColorMap["06"] = "#800080";
71 _mircColorMap["07"] = "#ffa500";
72 _mircColorMap["08"] = "#ffff00";
73 _mircColorMap["09"] = "#00ff00";
74 _mircColorMap["10"] = "#008080";
75 _mircColorMap["11"] = "#00ffff";
76 _mircColorMap["12"] = "#4169e1";
77 _mircColorMap["13"] = "#ff00ff";
78 _mircColorMap["14"] = "#808080";
79 _mircColorMap["15"] = "#c0c0c0";
83 MultiLineEdit::~MultiLineEdit() {
86 void MultiLineEdit::setCustomFont(const QFont &font) {
91 void MultiLineEdit::setMode(Mode mode) {
98 void MultiLineEdit::setMinHeight(int lines) {
99 if(lines == _minHeight)
106 void MultiLineEdit::setMaxHeight(int lines) {
107 if(lines == _maxHeight)
114 void MultiLineEdit::setScrollBarsEnabled(bool enable) {
115 if(_scrollBarsEnabled == enable)
118 _scrollBarsEnabled = enable;
122 void MultiLineEdit::updateScrollBars() {
123 QFontMetrics fm(font());
124 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
125 if(_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
126 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
128 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
130 if(!_scrollBarsEnabled || isSingleLine())
131 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
133 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
136 void MultiLineEdit::resizeEvent(QResizeEvent *event) {
137 QTextEdit::resizeEvent(event);
142 void MultiLineEdit::updateSizeHint() {
143 QFontMetrics fm(font());
144 int minPixelHeight = fm.lineSpacing() * _minHeight;
145 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
146 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
148 // use the style to determine a decent size
149 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
150 QStyleOptionFrameV2 opt;
152 opt.rect = QRect(0, 0, 100, h);
153 opt.lineWidth = lineWidth();
154 opt.midLineWidth = midLineWidth();
155 opt.state |= QStyle::State_Sunken;
156 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), this);
163 QSize MultiLineEdit::sizeHint() const {
164 if(!_sizeHint.isValid()) {
165 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
166 that->updateSizeHint();
171 QSize MultiLineEdit::minimumSizeHint() const {
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 void MultiLineEdit::keyPressEvent(QKeyEvent *event) {
241 // Workaround the fact that Qt < 4.5 doesn't know InsertLineSeparator yet
242 #if QT_VERSION >= 0x040500
243 if(event == QKeySequence::InsertLineSeparator) {
247 if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::META) {
249 if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::SHIFT) {
253 if(_mode == SingleLine) {
259 KTextEdit::keyPressEvent(event);
261 QTextEdit::keyPressEvent(event);
266 switch(event->key()) {
268 if(event->modifiers() & Qt::ShiftModifier)
272 if(!(event->modifiers() & Qt::ControlModifier)) {
273 int pos = textCursor().position();
274 moveCursor(QTextCursor::Up);
275 if(pos == textCursor().position()) // already on top line -> history
283 if(event->modifiers() & Qt::ShiftModifier)
287 if(!(event->modifiers() & Qt::ControlModifier)) {
288 int pos = textCursor().position();
289 moveCursor(QTextCursor::Down);
290 if(pos == textCursor().position()) // already on bottom line -> history
291 historyMoveForward();
293 historyMoveForward();
304 // We don't want to have the tab key react even if no completer is installed
315 KTextEdit::keyPressEvent(event);
317 QTextEdit::keyPressEvent(event);
321 QString MultiLineEdit::convertRichtextToMircCodes() {
322 bool underline, bold, italic, color;
323 QString mircText, mircFgColor, mircBgColor;
324 QTextCursor cursor = textCursor();
325 QTextCursor peekcursor = textCursor();
326 cursor.movePosition(QTextCursor::Start);
328 underline = bold = italic = color = false;
330 while (cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor)) {
332 if (cursor.selectedText() == QString(QChar(QChar::LineSeparator))
333 || cursor.selectedText() == QString(QChar(QChar::ParagraphSeparator))) {
336 mircText.append('\x03');
340 mircText.append('\x1f');
344 mircText.append('\x1d');
348 mircText.append('\x02');
350 mircText.append('\n');
353 if (!bold && cursor.charFormat().font().bold()) {
355 mircText.append('\x02');
357 if (!italic && cursor.charFormat().fontItalic()) {
359 mircText.append('\x1d');
361 if (!underline && cursor.charFormat().fontUnderline()) {
363 mircText.append('\x1f');
365 if (!color && (cursor.charFormat().foreground().isOpaque() || cursor.charFormat().background().isOpaque())) {
367 mircText.append('\x03');
368 mircFgColor = _mircColorMap.key(cursor.charFormat().foreground().color().name());
369 mircBgColor = _mircColorMap.key(cursor.charFormat().background().color().name());
371 if (mircFgColor.isEmpty()) {
372 mircFgColor = "01"; //use black if the current foreground color can't be converted
375 mircText.append(mircFgColor);
376 if (cursor.charFormat().background().isOpaque())
377 mircText.append("," + mircBgColor);
380 mircText.append(cursor.selectedText());
382 peekcursor.setPosition(cursor.position());
383 peekcursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
385 if (mircCodesChanged(cursor, peekcursor)) {
388 mircText.append('\x03');
392 mircText.append('\x1f');
396 mircText.append('\x1d');
400 mircText.append('\x02');
405 cursor.clearSelection();
409 mircText.append('\x03');
413 mircText.append('\x1f');
417 mircText.append('\x1d');
421 mircText.append('\x02');
427 bool MultiLineEdit::mircCodesChanged(QTextCursor &cursor, QTextCursor &peekcursor) {
428 bool changed = false;
429 if (cursor.charFormat().font().bold() != peekcursor.charFormat().font().bold())
431 if (cursor.charFormat().fontItalic() != peekcursor.charFormat().fontItalic())
433 if (cursor.charFormat().fontUnderline() != peekcursor.charFormat().fontUnderline())
435 if (cursor.charFormat().foreground().color() != peekcursor.charFormat().foreground().color())
437 if (cursor.charFormat().background().color() != peekcursor.charFormat().background().color())
442 QString MultiLineEdit::convertMircCodesToHtml(const QString &text) {
444 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
450 posRight = mircCode.indexIn(text, posLeft);
453 words << text.mid(posLeft);
454 break; // no more mirc color codes
457 if (posLeft < posRight) {
458 words << text.mid(posLeft, posRight - posLeft);
462 posRight = text.indexOf(mircCode.cap(), posRight + 1);
463 words << text.mid(posLeft, posRight + 1 - posLeft);
464 posLeft = posRight + 1;
467 for (int i = 0; i < words.count(); i++) {
469 if (words[i].contains('\x02')) {
470 style.append(" font-weight:600;");
471 words[i].replace('\x02',"");
473 if (words[i].contains('\x1d')) {
474 style.append(" font-style:italic;");
475 words[i].replace('\x1d',"");
477 if (words[i].contains('\x1f')) {
478 style.append(" text-decoration: underline;");
479 words[i].replace('\x1f',"");
481 if (words[i].contains('\x03')) {
482 int pos = words[i].indexOf('\x03');
484 QString fg = words[i].mid(pos + 1,2);
486 if (words[i][pos+3] == ',')
487 bg = words[i].mid(pos+4,2);
489 style.append(" color:");
490 style.append(_mircColorMap[fg]);
494 style.append(" background-color:");
495 style.append(_mircColorMap[bg]);
499 words[i].replace(pos, len, "");
500 words[i].replace('\x03',"");
502 words[i].replace("&","&");
503 words[i].replace("<", "<");
504 words[i].replace(">", ">");
505 words[i].replace("\"", """);
506 if (style.isEmpty()) {
507 words[i] = "<span>" + words[i] + "</span>";
510 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
513 return words.join("").replace("\n","<br />");
516 void MultiLineEdit::on_returnPressed() {
517 on_returnPressed(convertRichtextToMircCodes());
520 void MultiLineEdit::on_returnPressed(const QString & text) {
521 if(!text.isEmpty()) {
522 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
526 emit textEntered(line);
529 _tempHistory.clear();
531 emit noTextEntered();
535 void MultiLineEdit::on_textChanged() {
536 QString newText = text();
537 newText.replace("\r\n", "\n");
538 newText.replace('\r', '\n');
539 if(_mode == SingleLine) {
540 if(!pasteProtectionEnabled())
541 newText.replace('\n', ' ');
542 else if(newText.contains('\n')) {
543 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
546 if(lines.count() >= 4) {
547 QString msg = tr("Do you really want to paste %n lines?", "", lines.count());
549 for(int i = 0; i < 4; i++) {
550 msg += Qt::escape(lines[i].left(40));
551 if(lines[i].count() > 40)
556 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
557 question.setDefaultButton(QMessageBox::No);
559 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
561 if(question.exec() != QMessageBox::Yes)
565 foreach(QString line, lines) {
573 _singleLine = (newText.indexOf('\n') < 0);
575 if(document()->size().height() != _lastDocumentHeight) {
576 _lastDocumentHeight = document()->size().height();
577 on_documentHeightChanged(_lastDocumentHeight);
580 ensureCursorVisible();
583 void MultiLineEdit::on_documentHeightChanged(qreal) {
587 void MultiLineEdit::reset() {
588 // every time the MultiLineEdit is cleared we also reset history index
589 _idx = _history.count();
591 QTextBlockFormat format = textCursor().blockFormat();
592 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
593 textCursor().setBlockFormat(format);
597 void MultiLineEdit::showHistoryEntry() {
598 // if the user changed the history, display the changed line
599 setHtml(convertMircCodesToHtml(_tempHistory.contains(_idx) ? _tempHistory[_idx] : _history[_idx]));
600 QTextCursor cursor = textCursor();
601 QTextBlockFormat format = cursor.blockFormat();
602 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
603 cursor.setBlockFormat(format);
604 cursor.movePosition(QTextCursor::End);
605 setTextCursor(cursor);