1 /***************************************************************************
2 * Copyright (C) 2005-2014 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 "inputwidget.h"
24 #include "actioncollection.h"
25 #include "bufferview.h"
27 #include "iconloader.h"
29 #include "networkmodel.h"
31 #include "qtuisettings.h"
32 #include "tabcompleter.h"
35 const int leftMargin = 3;
37 InputWidget::InputWidget(QWidget *parent)
38 : AbstractItemView(parent),
42 connect(ui.ownNick, SIGNAL(activated(QString)), this, SLOT(changeNick(QString)));
44 layout()->setAlignment(ui.ownNick, Qt::AlignBottom);
45 layout()->setAlignment(ui.inputEdit, Qt::AlignBottom);
46 layout()->setAlignment(ui.showStyleButton, Qt::AlignBottom);
47 layout()->setAlignment(ui.styleFrame, Qt::AlignBottom);
49 ui.styleFrame->setVisible(false);
51 setFocusProxy(ui.inputEdit);
52 ui.ownNick->setFocusProxy(ui.inputEdit);
54 ui.ownNick->setSizeAdjustPolicy(QComboBox::AdjustToContents);
55 ui.ownNick->installEventFilter(new MouseWheelFilter(this));
56 ui.inputEdit->installEventFilter(this);
58 ui.inputEdit->setMinHeight(1);
59 ui.inputEdit->setMaxHeight(5);
60 ui.inputEdit->setMode(MultiLineEdit::MultiLine);
61 ui.inputEdit->setPasteProtectionEnabled(true);
63 ui.boldButton->setIcon(SmallIcon("format-text-bold"));
64 ui.italicButton->setIcon(SmallIcon("format-text-italic"));
65 ui.underlineButton->setIcon(SmallIcon("format-text-underline"));
66 ui.textcolorButton->setIcon(SmallIcon("format-text-color"));
67 ui.highlightcolorButton->setIcon(SmallIcon("format-fill-color"));
68 ui.encryptionIconLabel->hide();
70 _colorMenu = new QMenu();
71 _colorFillMenu = new QMenu();
74 names << tr("White") << tr("Black") << tr("Dark blue") << tr("Dark green") << tr("Red") << tr("Dark red") << tr("Dark magenta") << tr("Orange")
75 << tr("Yellow") << tr("Green") << tr("Dark cyan") << tr("Cyan") << tr("Blue") << tr("Magenta") << tr("Dark gray") << tr("Light gray");
78 for (int i = 0; i < inputLine()->mircColorMap().count(); i++) {
79 pix.fill(inputLine()->mircColorMap().values()[i]);
80 _colorMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
81 _colorFillMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
84 pix.fill(Qt::transparent);
85 _colorMenu->addAction(pix, tr("Clear Color"))->setData("");
86 _colorFillMenu->addAction(pix, tr("Clear Color"))->setData("");
88 ui.textcolorButton->setMenu(_colorMenu);
89 connect(_colorMenu, SIGNAL(triggered(QAction *)), this, SLOT(colorChosen(QAction *)));
90 ui.highlightcolorButton->setMenu(_colorFillMenu);
91 connect(_colorFillMenu, SIGNAL(triggered(QAction *)), this, SLOT(colorHighlightChosen(QAction *)));
93 new TabCompleter(ui.inputEdit);
95 UiStyleSettings fs("Fonts");
96 fs.notify("UseCustomInputWidgetFont", this, SLOT(setUseCustomFont(QVariant)));
97 fs.notify("InputWidget", this, SLOT(setCustomFont(QVariant)));
98 if (fs.value("UseCustomInputWidgetFont", false).toBool())
99 setCustomFont(fs.value("InputWidget", QFont()));
101 UiSettings s("InputWidget");
104 s.notify("EnableSpellCheck", this, SLOT(setEnableSpellCheck(QVariant)));
105 setEnableSpellCheck(s.value("EnableSpellCheck", false));
108 s.notify("EnableEmacsMode", this, SLOT(setEnableEmacsMode(QVariant)));
109 setEnableEmacsMode(s.value("EnableEmacsMode", false));
111 s.notify("ShowNickSelector", this, SLOT(setShowNickSelector(QVariant)));
112 setShowNickSelector(s.value("ShowNickSelector", true));
114 s.notify("ShowStyleButtons", this, SLOT(setShowStyleButtons(QVariant)));
115 setShowStyleButtons(s.value("ShowStyleButtons", true));
117 s.notify("EnablePerChatHistory", this, SLOT(setEnablePerChatHistory(QVariant)));
118 setEnablePerChatHistory(s.value("EnablePerChatHistory", false));
120 s.notify("MaxNumLines", this, SLOT(setMaxLines(QVariant)));
121 setMaxLines(s.value("MaxNumLines", 5));
123 s.notify("EnableScrollBars", this, SLOT(setScrollBarsEnabled(QVariant)));
124 setScrollBarsEnabled(s.value("EnableScrollBars", true));
126 s.notify("EnableMultiLine", this, SLOT(setMultiLineEnabled(QVariant)));
127 setMultiLineEnabled(s.value("EnableMultiLine", true));
129 ActionCollection *coll = QtUi::actionCollection();
131 Action *activateInputline = coll->add<Action>("FocusInputLine");
132 connect(activateInputline, SIGNAL(triggered()), SLOT(setFocus()));
133 activateInputline->setText(tr("Focus Input Line"));
134 activateInputline->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_L));
136 connect(inputLine(), SIGNAL(textEntered(QString)), SLOT(onTextEntered(QString)), Qt::QueuedConnection); // make sure the line is already reset, bug #984
137 connect(inputLine(), SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(currentCharFormatChanged(QTextCharFormat)));
141 InputWidget::~InputWidget()
146 void InputWidget::setUseCustomFont(const QVariant &v)
149 UiStyleSettings fs("Fonts");
150 setCustomFont(fs.value("InputWidget"));
153 setCustomFont(QFont());
157 void InputWidget::setCustomFont(const QVariant &v)
159 QFont font = v.value<QFont>();
160 if (font.family().isEmpty())
161 font = QApplication::font();
162 // we don't want font styles as this conflics with mirc code richtext editing
164 font.setItalic(false);
165 font.setUnderline(false);
166 font.setStrikeOut(false);
167 ui.inputEdit->setCustomFont(font);
171 void InputWidget::setEnableSpellCheck(const QVariant &v)
173 ui.inputEdit->setSpellCheckEnabled(v.toBool());
177 void InputWidget::setEnableEmacsMode(const QVariant &v)
179 ui.inputEdit->setEmacsMode(v.toBool());
183 void InputWidget::setShowNickSelector(const QVariant &v)
185 ui.ownNick->setVisible(v.toBool());
189 void InputWidget::setShowStyleButtons(const QVariant &v)
191 ui.showStyleButton->setVisible(v.toBool());
195 void InputWidget::setEnablePerChatHistory(const QVariant &v)
197 _perChatHistory = v.toBool();
201 void InputWidget::setMaxLines(const QVariant &v)
203 ui.inputEdit->setMaxHeight(v.toInt());
207 void InputWidget::setScrollBarsEnabled(const QVariant &v)
209 ui.inputEdit->setScrollBarsEnabled(v.toBool());
213 void InputWidget::setMultiLineEnabled(const QVariant &v)
215 ui.inputEdit->setMode(v.toBool() ? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
219 bool InputWidget::eventFilter(QObject *watched, QEvent *event)
221 if (event->type() != QEvent::KeyPress)
224 QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
226 // keys from BufferView should be sent to (and focus) the input line
227 BufferView *view = qobject_cast<BufferView *>(watched);
229 if (keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier))) { // normal key press
230 QChar c = keyEvent->text().at(0);
231 if (c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
233 QCoreApplication::sendEvent(inputLine(), keyEvent);
239 else if (watched == ui.inputEdit) {
240 if (keyEvent->matches(QKeySequence::Find)) {
241 QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
253 void InputWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
255 BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
256 BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
258 if (_perChatHistory) {
260 historyMap[previousBufferId].history = inputLine()->history();
261 historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
262 historyMap[previousBufferId].idx = inputLine()->idx();
263 historyMap[previousBufferId].inputLine = inputLine()->html();
266 inputLine()->setHistory(historyMap[currentBufferId].history);
267 inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
268 inputLine()->setIdx(historyMap[currentBufferId].idx);
269 inputLine()->setHtml(historyMap[currentBufferId].inputLine);
270 inputLine()->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
272 // FIXME this really should be in MultiLineEdit (and the const int on top removed)
273 QTextBlockFormat format = inputLine()->textCursor().blockFormat();
274 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
275 inputLine()->textCursor().setBlockFormat(format);
278 NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
279 if (networkId == _networkId)
282 setNetwork(networkId);
283 updateNickSelector();
284 updateEnabledState();
288 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
290 QItemSelectionRange changedArea(topLeft, bottomRight);
291 if (changedArea.contains(selectionModel()->currentIndex())) {
292 updateEnabledState();
294 bool encrypted = false;
296 IrcChannel *chan = qobject_cast<IrcChannel *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcChannelRole).value<QObject *>());
298 encrypted = chan->encrypted();
300 IrcUser *user = qobject_cast<IrcUser *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcUserRole).value<QObject *>());
302 encrypted = user->encrypted();
305 ui.encryptionIconLabel->show();
307 ui.encryptionIconLabel->hide();
312 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
316 for (int row = start; row <= end; row++) {
317 child = model()->index(row, 0, parent);
318 if (NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
320 networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
321 if (networkId == _networkId) {
323 updateNickSelector();
330 void InputWidget::updateEnabledState()
332 // FIXME: Find a visualization for this that does not disable the widget!
333 // Disabling kills global action shortcuts, plus users sometimes need/want to enter text
334 // even in inactive channels.
336 QModelIndex currentIndex = selectionModel()->currentIndex();
338 const Network *net = Client::networkModel()->networkByIndex(currentIndex);
339 bool enabled = false;
341 // disable inputline if it's a channelbuffer we parted from or...
342 enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
343 // ... if we're not connected to the network at all
344 enabled &= net->isConnected();
347 ui.inputEdit->setEnabled(enabled);
352 const Network *InputWidget::currentNetwork() const
354 return Client::network(_networkId);
358 BufferInfo InputWidget::currentBufferInfo() const
360 return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
363 void InputWidget::setNetwork(NetworkId networkId)
365 if (_networkId == networkId)
368 const Network *previousNet = Client::network(_networkId);
370 disconnect(previousNet, 0, this, 0);
371 if (previousNet->me())
372 disconnect(previousNet->me(), 0, this, 0);
375 _networkId = networkId;
377 const Network *network = Client::network(networkId);
379 connect(network, SIGNAL(identitySet(IdentityId)), this, SLOT(setIdentity(IdentityId)));
381 setIdentity(network->identity());
390 void InputWidget::connectMyIrcUser()
392 const Network *network = currentNetwork();
394 connect(network->me(), SIGNAL(nickSet(const QString &)), this, SLOT(updateNickSelector()));
395 connect(network->me(), SIGNAL(userModesSet(QString)), this, SLOT(updateNickSelector()));
396 connect(network->me(), SIGNAL(userModesAdded(QString)), this, SLOT(updateNickSelector()));
397 connect(network->me(), SIGNAL(userModesRemoved(QString)), this, SLOT(updateNickSelector()));
398 connect(network->me(), SIGNAL(awaySet(bool)), this, SLOT(updateNickSelector()));
399 disconnect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
400 updateNickSelector();
403 connect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
408 void InputWidget::setIdentity(IdentityId identityId)
410 if (_identityId == identityId)
413 const Identity *previousIdentity = Client::identity(_identityId);
414 if (previousIdentity)
415 disconnect(previousIdentity, 0, this, 0);
417 _identityId = identityId;
419 const Identity *identity = Client::identity(identityId);
421 connect(identity, SIGNAL(nicksSet(QStringList)), this, SLOT(updateNickSelector()));
426 updateNickSelector();
430 void InputWidget::updateNickSelector() const
434 const Network *net = currentNetwork();
438 const Identity *identity = Client::identity(net->identity());
440 qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
445 QStringList nicks = identity->nicks();
446 if ((nickIdx = nicks.indexOf(net->myNick())) == -1) {
447 nicks.prepend(net->myNick());
454 IrcUser *me = net->me();
456 nicks[nickIdx] = net->myNick();
457 if (!me->userModes().isEmpty())
458 nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
461 ui.ownNick->addItems(nicks);
463 if (me && me->isAway())
464 ui.ownNick->setItemData(nickIdx, SmallIcon("user-away"), Qt::DecorationRole);
466 ui.ownNick->setCurrentIndex(nickIdx);
470 void InputWidget::changeNick(const QString &newNick) const
472 const Network *net = currentNetwork();
473 if (!net || net->isMyNick(newNick))
476 // we reset the nick selecter as we have no confirmation yet, that this will succeed.
477 // if the action succeeds it will be properly updated anyways.
478 updateNickSelector();
479 Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
483 void InputWidget::onTextEntered(const QString &text)
485 Client::userInput(currentBufferInfo(), text);
486 ui.boldButton->setChecked(false);
487 ui.underlineButton->setChecked(false);
488 ui.italicButton->setChecked(false);
491 fmt.setFontWeight(QFont::Normal);
492 fmt.setFontUnderline(false);
493 fmt.setFontItalic(false);
494 fmt.clearForeground();
495 fmt.clearBackground();
496 inputLine()->setCurrentCharFormat(fmt);
499 // Set highlighter back to active in case it was deactivated by too many errors.
500 if (ui.inputEdit->highlighter())
501 ui.inputEdit->highlighter()->setActive(true);
506 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format)
508 QTextCursor cursor = inputLine()->textCursor();
509 cursor.mergeCharFormat(format);
510 inputLine()->mergeCurrentCharFormat(format);
514 void InputWidget::setFormatOnSelection(const QTextCharFormat &format)
516 QTextCursor cursor = inputLine()->textCursor();
517 cursor.setCharFormat(format);
518 inputLine()->setCurrentCharFormat(format);
522 QTextCharFormat InputWidget::getFormatOfWordOrSelection()
524 QTextCursor cursor = inputLine()->textCursor();
525 return cursor.charFormat();
529 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format)
531 fontChanged(format.font());
535 void InputWidget::on_boldButton_clicked(bool checked)
538 fmt.setFontWeight(checked ? QFont::Bold : QFont::Normal);
539 mergeFormatOnSelection(fmt);
543 void InputWidget::on_underlineButton_clicked(bool checked)
546 fmt.setFontUnderline(checked);
547 mergeFormatOnSelection(fmt);
551 void InputWidget::on_italicButton_clicked(bool checked)
554 fmt.setFontItalic(checked);
555 mergeFormatOnSelection(fmt);
559 void InputWidget::fontChanged(const QFont &f)
561 ui.boldButton->setChecked(f.bold());
562 ui.italicButton->setChecked(f.italic());
563 ui.underlineButton->setChecked(f.underline());
567 void InputWidget::colorChosen(QAction *action)
571 if (qVariantValue<QString>(action->data()) == "") {
572 color = Qt::transparent;
573 fmt = getFormatOfWordOrSelection();
574 fmt.clearForeground();
575 setFormatOnSelection(fmt);
578 color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
579 fmt.setForeground(color);
580 mergeFormatOnSelection(fmt);
582 ui.textcolorButton->setDefaultAction(action);
583 ui.textcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-text-color"), color));
587 void InputWidget::colorHighlightChosen(QAction *action)
591 if (qVariantValue<QString>(action->data()) == "") {
592 color = Qt::transparent;
593 fmt = getFormatOfWordOrSelection();
594 fmt.clearBackground();
595 setFormatOnSelection(fmt);
598 color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
599 fmt.setBackground(color);
600 mergeFormatOnSelection(fmt);
602 ui.highlightcolorButton->setDefaultAction(action);
603 ui.highlightcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-fill-color"), color));
607 void InputWidget::on_showStyleButton_toggled(bool checked)
609 ui.styleFrame->setVisible(checked);
611 ui.showStyleButton->setArrowType(Qt::LeftArrow);
614 ui.showStyleButton->setArrowType(Qt::RightArrow);
619 QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color)
621 QPixmap pixmap(16, 16);
622 pixmap.fill(Qt::transparent);
623 QPainter painter(&pixmap);
624 QPixmap image = icon.pixmap(16, 16);
625 QRect target(0, 0, 16, 14);
626 QRect source(0, 0, 16, 14);
627 painter.fillRect(QRect(0, 14, 16, 16), color);
628 painter.drawPixmap(target, image, source);
630 return QIcon(pixmap);
634 // MOUSE WHEEL FILTER
635 MouseWheelFilter::MouseWheelFilter(QObject *parent)
641 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event)
643 if (event->type() != QEvent::Wheel)
644 return QObject::eventFilter(obj, event);