1 /***************************************************************************
2 * Copyright (C) 2005/06 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 _lastDocumentHeight(-1)
48 #if QT_VERSION >= 0x040500
49 document()->setDocumentMargin(0); // new in Qt 4.5 and we really don't want it here
52 setAcceptRichText(false);
54 enableFindReplace(false);
58 setWordWrapEnabled(false);
61 connect(this, SIGNAL(textChanged()), this, SLOT(on_textChanged()));
63 _mircColorMap["00"] = "#ffffff";
64 _mircColorMap["01"] = "#000000";
65 _mircColorMap["02"] = "#000080";
66 _mircColorMap["03"] = "#008000";
67 _mircColorMap["04"] = "#ff0000";
68 _mircColorMap["05"] = "#800000";
69 _mircColorMap["06"] = "#800080";
70 _mircColorMap["07"] = "#ffa500";
71 _mircColorMap["08"] = "#ffff00";
72 _mircColorMap["09"] = "#00ff00";
73 _mircColorMap["10"] = "#008080";
74 _mircColorMap["11"] = "#00ffff";
75 _mircColorMap["12"] = "#4169e1";
76 _mircColorMap["13"] = "#ff00ff";
77 _mircColorMap["14"] = "#808080";
78 _mircColorMap["15"] = "#c0c0c0";
82 MultiLineEdit::~MultiLineEdit() {
85 void MultiLineEdit::setCustomFont(const QFont &font) {
90 void MultiLineEdit::setMode(Mode mode) {
97 void MultiLineEdit::setMinHeight(int lines) {
98 if(lines == _minHeight)
105 void MultiLineEdit::setMaxHeight(int lines) {
106 if(lines == _maxHeight)
113 void MultiLineEdit::setScrollBarsEnabled(bool enable) {
114 if(_scrollBarsEnabled == enable)
117 _scrollBarsEnabled = enable;
121 void MultiLineEdit::updateScrollBars() {
122 QFontMetrics fm(font());
123 int _maxPixelHeight = fm.lineSpacing() * _maxHeight;
124 if(_scrollBarsEnabled && document()->size().height() > _maxPixelHeight)
125 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
127 setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
129 if(!_scrollBarsEnabled || isSingleLine())
130 setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
132 setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
135 void MultiLineEdit::resizeEvent(QResizeEvent *event) {
136 QTextEdit::resizeEvent(event);
141 void MultiLineEdit::updateSizeHint() {
142 QFontMetrics fm(font());
143 int minPixelHeight = fm.lineSpacing() * _minHeight;
144 int maxPixelHeight = fm.lineSpacing() * _maxHeight;
145 int scrollBarHeight = horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0;
147 // use the style to determine a decent size
148 int h = qMin(qMax((int)document()->size().height() + scrollBarHeight, minPixelHeight), maxPixelHeight) + 2 * frameWidth();
149 QStyleOptionFrameV2 opt;
151 opt.rect = QRect(0, 0, 100, h);
152 opt.lineWidth = lineWidth();
153 opt.midLineWidth = midLineWidth();
154 opt.state |= QStyle::State_Sunken;
155 QSize s = style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(100, h).expandedTo(QApplication::globalStrut()), this);
162 QSize MultiLineEdit::sizeHint() const {
163 if(!_sizeHint.isValid()) {
164 MultiLineEdit *that = const_cast<MultiLineEdit *>(this);
165 that->updateSizeHint();
170 QSize MultiLineEdit::minimumSizeHint() const {
174 void MultiLineEdit::setSpellCheckEnabled(bool enable) {
176 setCheckSpellingEnabled(enable);
182 void MultiLineEdit::setWordWrapEnabled(bool enable) {
183 setLineWrapMode(enable? WidgetWidth : NoWrap);
187 void MultiLineEdit::setPasteProtectionEnabled(bool enable, QWidget *) {
188 _pasteProtectionEnabled = enable;
191 void MultiLineEdit::historyMoveBack() {
192 addToHistory(convertHtmlToMircCodes(html()), true);
200 void MultiLineEdit::historyMoveForward() {
201 addToHistory(convertHtmlToMircCodes(html()), true);
203 if(idx < history.count()) {
205 if(idx < history.count() || tempHistory.contains(idx)) // tempHistory might have an entry for idx == history.count() + 1
208 reset(); // equals clear() in this case
210 addToHistory(convertHtmlToMircCodes(html()));
215 bool MultiLineEdit::addToHistory(const QString &text, bool temporary) {
219 Q_ASSERT(0 <= idx && idx <= history.count());
222 // if an entry of the history is changed, we remember it and show it again at this
223 // position until a line was actually sent
224 // sent lines get appended to the history
225 if(history.isEmpty() || text != history[idx - (int)(idx == history.count())]) {
226 tempHistory[idx] = text;
230 if(history.isEmpty() || text != history.last()) {
239 void MultiLineEdit::keyPressEvent(QKeyEvent *event) {
240 // Workaround the fact that Qt < 4.5 doesn't know InsertLineSeparator yet
241 #if QT_VERSION >= 0x040500
242 if(event == QKeySequence::InsertLineSeparator) {
246 if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::META) {
248 if((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() & Qt::SHIFT) {
252 if(_mode == SingleLine) {
258 KTextEdit::keyPressEvent(event);
260 QTextEdit::keyPressEvent(event);
265 switch(event->key()) {
267 if(event->modifiers() & Qt::ShiftModifier)
271 if(!(event->modifiers() & Qt::ControlModifier)) {
272 int pos = textCursor().position();
273 moveCursor(QTextCursor::Up);
274 if(pos == textCursor().position()) // already on top line -> history
282 if(event->modifiers() & Qt::ShiftModifier)
286 if(!(event->modifiers() & Qt::ControlModifier)) {
287 int pos = textCursor().position();
288 moveCursor(QTextCursor::Down);
289 if(pos == textCursor().position()) // already on bottom line -> history
290 historyMoveForward();
292 historyMoveForward();
303 // We don't want to have the tab key react even if no completer is installed
314 KTextEdit::keyPressEvent(event);
316 QTextEdit::keyPressEvent(event);
320 QString MultiLineEdit::convertHtmlToMircCodes(const QString &text) {
323 QRegExp regexHtmlContent = QRegExp("<p.*>(.*)</p>", Qt::CaseInsensitive);
324 regexHtmlContent.setMinimal(true);
326 QRegExp regexLines = QRegExp("(.*)(?:<br />)?", Qt::CaseInsensitive);
327 regexLines.setMinimal(true);
329 QRegExp regexStyles = QRegExp("(?:((<span.*>)(.*)</span>))", Qt::CaseInsensitive);
330 regexStyles.setMinimal(true);
332 QRegExp regexColors = QRegExp("((?:background-)?color):(#[0-9a-f]{6})", Qt::CaseInsensitive);
333 regexStyles.setMinimal(true);
336 QString htmlContent, line, line2, styleText, style, content;
338 if (regexHtmlContent.indexIn((text)) > -1) {
339 htmlContent = regexHtmlContent.cap(1);
340 qWarning() << htmlContent;
341 QStringList lines = htmlContent.split("<br />");
342 for (int i=0; i < lines.count(); i++) {
343 line = line2 = lines[i];
345 while ((posStyles = regexStyles.indexIn(line2, posStyles)) != -1) {
346 styleText = regexStyles.cap(1);
347 style = regexStyles.cap(2);
348 content = regexStyles.cap(3);
350 if (style.contains("font-weight:600;")) {
351 content.prepend('\x02');
352 content.append('\x02');
354 if (style.contains("font-style:italic;")) {
355 content.prepend('\x1d');
356 content.append('\x1d');
358 if (style.contains("text-decoration: underline;")) {
359 content.prepend('\x1f');
360 content.append('\x1f');
362 if (style.contains("color:#")) { // we have either foreground or background color or both
364 QString mircFgColor, mircBgColor;
365 while ((posColors = regexColors.indexIn(style, posColors)) != -1) {
366 QString colorType = regexColors.cap(1);
367 QString color = regexColors.cap(2);
369 if (colorType == "color")
370 mircFgColor = _mircColorMap.key(color);
372 if (colorType == "background-color")
373 mircBgColor = _mircColorMap.key(color);
375 posColors += regexColors.matchedLength();
377 if (!mircBgColor.isEmpty())
378 content.prepend("," + mircBgColor);
380 // we need a fg color to be able to use a bg color
381 if (mircFgColor.isEmpty()) {
382 //FIXME try to use the current forecolor
383 mircFgColor = _mircColorMap.key(textColor().name());
384 if (mircFgColor.isEmpty())
385 mircFgColor = "01"; //use black if the current foreground color can't be converted
388 content.prepend(mircFgColor);
389 content.prepend('\x03');
390 content.append('\x03');
393 line.replace(styleText, content);
394 posStyles += regexStyles.matchedLength();
397 // get rid of all remaining html tags
398 QRegExp regexTags = QRegExp("<.*>",Qt::CaseInsensitive);
399 regexTags.setMinimal(true);
400 line.replace(regexTags, "");
402 line.replace("&","&");
403 line.replace("<","<");
404 line.replace(">",">");
405 line.replace(""","\"");
412 return result.join("\n");
415 QString MultiLineEdit::convertMircCodesToHtml(const QString &text) {
417 QRegExp mircCode = QRegExp("(
\ 2|
\1d|
\1f|
\ 3)", Qt::CaseSensitive);
423 posRight = mircCode.indexIn(text, posLeft);
426 words << text.mid(posLeft);
427 break; // no more mirc color codes
430 if (posLeft < posRight) {
431 words << text.mid(posLeft, posRight - posLeft);
435 posRight = text.indexOf(mircCode.cap(), posRight + 1);
436 words << text.mid(posLeft, posRight + 1 - posLeft);
437 posLeft = posRight + 1;
440 for (int i = 0; i < words.count(); i++) {
442 if (words[i].contains('\x02')) {
443 style.append(" font-weight:600;");
444 words[i].replace('\x02',"");
446 if (words[i].contains('\x1d')) {
447 style.append(" font-style:italic;");
448 words[i].replace('\x1d',"");
450 if (words[i].contains('\x1f')) {
451 style.append(" text-decoration: underline;");
452 words[i].replace('\x1f',"");
454 if (words[i].contains('\x03')) {
455 int pos = words[i].indexOf('\x03');
457 QString fg = words[i].mid(pos + 1,2);
459 if (words[i][pos+3] == ',')
460 bg = words[i].mid(pos+4,2);
462 style.append(" color:");
463 style.append(_mircColorMap[fg]);
467 style.append(" background-color:");
468 style.append(_mircColorMap[bg]);
472 words[i].replace(pos, len, "");
473 words[i].replace('\x03',"");
475 words[i].replace("&","&");
476 words[i].replace("<", "<");
477 words[i].replace(">", ">");
478 words[i].replace("\"", """);
479 if (style.isEmpty()) {
480 words[i] = "<span>" + words[i] + "</span>";
483 words[i] = "<span style=\"" + style + "\">" + words[i] + "</span>";
486 return words.join("");
489 void MultiLineEdit::on_returnPressed() {
490 on_returnPressed(convertHtmlToMircCodes(html()));
493 void MultiLineEdit::on_returnPressed(const QString & text) {
494 if(!text.isEmpty()) {
495 foreach(const QString &line, text.split('\n', QString::SkipEmptyParts)) {
499 emit textEntered(line);
504 emit noTextEntered();
508 void MultiLineEdit::on_textChanged() {
509 QString newText = text();
510 newText.replace("\r\n", "\n");
511 newText.replace('\r', '\n');
512 if(_mode == SingleLine) {
513 if(!pasteProtectionEnabled())
514 newText.replace('\n', ' ');
515 else if(newText.contains('\n')) {
516 QStringList lines = newText.split('\n', QString::SkipEmptyParts);
519 if(lines.count() >= 4) {
520 QString msg = tr("Do you really want to paste %n lines?", "", lines.count());
522 for(int i = 0; i < 4; i++) {
523 msg += Qt::escape(lines[i].left(40));
524 if(lines[i].count() > 40)
529 QMessageBox question(QMessageBox::NoIcon, tr("Paste Protection"), msg, QMessageBox::Yes|QMessageBox::No);
530 question.setDefaultButton(QMessageBox::No);
532 question.setWindowFlags(question.windowFlags() | Qt::Sheet);
534 if(question.exec() != QMessageBox::Yes)
538 foreach(QString line, lines) {
546 _singleLine = (newText.indexOf('\n') < 0);
548 if(document()->size().height() != _lastDocumentHeight) {
549 _lastDocumentHeight = document()->size().height();
550 on_documentHeightChanged(_lastDocumentHeight);
553 ensureCursorVisible();
556 void MultiLineEdit::on_documentHeightChanged(qreal) {
560 void MultiLineEdit::reset() {
561 // every time the MultiLineEdit is cleared we also reset history index
562 idx = history.count();
564 QTextBlockFormat format = textCursor().blockFormat();
565 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
566 textCursor().setBlockFormat(format);
570 void MultiLineEdit::showHistoryEntry() {
571 // if the user changed the history, display the changed line
572 setHtml(convertMircCodesToHtml(tempHistory.contains(idx) ? tempHistory[idx] : history[idx]));
573 //setPlainText(tempHistory.contains(idx) ? tempHistory[idx] : history[idx]);
574 QTextCursor cursor = textCursor();
575 QTextBlockFormat format = cursor.blockFormat();
576 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
577 cursor.setBlockFormat(format);
578 cursor.movePosition(QTextCursor::End);
579 setTextCursor(cursor);