1 /***************************************************************************
2 * Copyright (C) 2005-2018 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"
26 #include "actioncollection.h"
27 #include "bufferview.h"
30 #include "networkmodel.h"
32 #include "qtuisettings.h"
33 #include "tabcompleter.h"
36 const int leftMargin = 3;
38 InputWidget::InputWidget(QWidget *parent)
39 : AbstractItemView(parent),
43 connect(ui.ownNick, SIGNAL(activated(QString)), this, SLOT(changeNick(QString)));
45 layout()->setAlignment(ui.ownNick, Qt::AlignBottom);
46 layout()->setAlignment(ui.inputEdit, Qt::AlignBottom);
47 layout()->setAlignment(ui.showStyleButton, Qt::AlignBottom);
48 layout()->setAlignment(ui.styleFrame, Qt::AlignBottom);
50 ui.styleFrame->setVisible(false);
52 setFocusProxy(ui.inputEdit);
53 ui.ownNick->setFocusProxy(ui.inputEdit);
55 ui.ownNick->setSizeAdjustPolicy(QComboBox::AdjustToContents);
56 ui.ownNick->installEventFilter(new MouseWheelFilter(this));
57 ui.inputEdit->installEventFilter(this);
59 ui.inputEdit->setMinHeight(1);
60 ui.inputEdit->setMaxHeight(5);
61 ui.inputEdit->setMode(MultiLineEdit::MultiLine);
62 ui.inputEdit->setPasteProtectionEnabled(true);
64 ui.boldButton->setIcon(QIcon::fromTheme("format-text-bold"));
65 ui.italicButton->setIcon(QIcon::fromTheme("format-text-italic"));
66 ui.underlineButton->setIcon(QIcon::fromTheme("format-text-underline"));
67 ui.textcolorButton->setIcon(QIcon::fromTheme("format-text-color"));
68 ui.highlightcolorButton->setIcon(QIcon::fromTheme("format-fill-color"));
69 ui.encryptionIconLabel->hide();
71 _colorMenu = new QMenu();
72 _colorFillMenu = new QMenu();
75 names << tr("White") << tr("Black") << tr("Dark blue") << tr("Dark green") << tr("Red") << tr("Dark red") << tr("Dark magenta") << tr("Orange")
76 << tr("Yellow") << tr("Green") << tr("Dark cyan") << tr("Cyan") << tr("Blue") << tr("Magenta") << tr("Dark gray") << tr("Light gray");
79 for (int i = 0; i < inputLine()->mircColorMap().count(); i++) {
80 pix.fill(inputLine()->mircColorMap().values()[i]);
81 _colorMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
82 _colorFillMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
85 pix.fill(Qt::transparent);
86 _colorMenu->addAction(pix, tr("Clear Color"))->setData("");
87 _colorFillMenu->addAction(pix, tr("Clear Color"))->setData("");
89 ui.textcolorButton->setMenu(_colorMenu);
90 connect(_colorMenu, SIGNAL(triggered(QAction *)), this, SLOT(colorChosen(QAction *)));
91 ui.highlightcolorButton->setMenu(_colorFillMenu);
92 connect(_colorFillMenu, SIGNAL(triggered(QAction *)), this, SLOT(colorHighlightChosen(QAction *)));
94 new TabCompleter(ui.inputEdit);
96 UiStyleSettings fs("Fonts");
97 fs.notify("UseCustomInputWidgetFont", this, SLOT(setUseCustomFont(QVariant)));
98 fs.notify("InputWidget", this, SLOT(setCustomFont(QVariant)));
99 if (fs.value("UseCustomInputWidgetFont", false).toBool())
100 setCustomFont(fs.value("InputWidget", QFont()));
102 UiSettings s("InputWidget");
105 s.notify("EnableSpellCheck", this, SLOT(setEnableSpellCheck(QVariant)));
106 setEnableSpellCheck(s.value("EnableSpellCheck", false));
109 s.notify("EnableEmacsMode", this, SLOT(setEnableEmacsMode(QVariant)));
110 setEnableEmacsMode(s.value("EnableEmacsMode", false));
112 s.notify("ShowNickSelector", this, SLOT(setShowNickSelector(QVariant)));
113 setShowNickSelector(s.value("ShowNickSelector", true));
115 s.notify("ShowStyleButtons", this, SLOT(setShowStyleButtons(QVariant)));
116 setShowStyleButtons(s.value("ShowStyleButtons", true));
118 s.notify("EnablePerChatHistory", this, SLOT(setEnablePerChatHistory(QVariant)));
119 setEnablePerChatHistory(s.value("EnablePerChatHistory", true));
121 s.notify("MaxNumLines", this, SLOT(setMaxLines(QVariant)));
122 setMaxLines(s.value("MaxNumLines", 5));
124 s.notify("EnableScrollBars", this, SLOT(setScrollBarsEnabled(QVariant)));
125 setScrollBarsEnabled(s.value("EnableScrollBars", true));
127 s.notify("EnableLineWrap", this, SLOT(setLineWrapEnabled(QVariant)));
128 setLineWrapEnabled(s.value("EnableLineWrap", true));
130 s.notify("EnableMultiLine", this, SLOT(setMultiLineEnabled(QVariant)));
131 setMultiLineEnabled(s.value("EnableMultiLine", true));
133 ActionCollection *coll = QtUi::actionCollection();
135 Action *activateInputline = coll->add<Action>("FocusInputLine");
136 connect(activateInputline, SIGNAL(triggered()), SLOT(setFocus()));
137 activateInputline->setText(tr("Focus Input Line"));
138 activateInputline->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_L));
140 connect(inputLine(), SIGNAL(textEntered(QString)), SLOT(onTextEntered(QString)), Qt::QueuedConnection); // make sure the line is already reset, bug #984
141 connect(inputLine(), SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(currentCharFormatChanged(QTextCharFormat)));
145 InputWidget::~InputWidget()
150 void InputWidget::setUseCustomFont(const QVariant &v)
153 UiStyleSettings fs("Fonts");
154 setCustomFont(fs.value("InputWidget"));
157 setCustomFont(QFont());
161 void InputWidget::setCustomFont(const QVariant &v)
163 QFont font = v.value<QFont>();
164 if (font.family().isEmpty())
165 font = QApplication::font();
166 // we don't want font styles as this conflics with mirc code richtext editing
168 font.setItalic(false);
169 font.setUnderline(false);
170 font.setStrikeOut(false);
171 ui.inputEdit->setCustomFont(font);
175 void InputWidget::setEnableSpellCheck(const QVariant &v)
177 ui.inputEdit->setSpellCheckEnabled(v.toBool());
181 void InputWidget::setEnableEmacsMode(const QVariant &v)
183 ui.inputEdit->setEmacsMode(v.toBool());
187 void InputWidget::setShowNickSelector(const QVariant &v)
189 ui.ownNick->setVisible(v.toBool());
193 void InputWidget::setShowStyleButtons(const QVariant &v)
195 ui.showStyleButton->setVisible(v.toBool());
199 void InputWidget::setEnablePerChatHistory(const QVariant &v)
201 _perChatHistory = v.toBool();
205 void InputWidget::setMaxLines(const QVariant &v)
207 ui.inputEdit->setMaxHeight(v.toInt());
211 void InputWidget::setScrollBarsEnabled(const QVariant &v)
213 ui.inputEdit->setScrollBarsEnabled(v.toBool());
217 void InputWidget::setLineWrapEnabled(const QVariant &v)
219 ui.inputEdit->setLineWrapEnabled(v.toBool());
223 void InputWidget::setMultiLineEnabled(const QVariant &v)
225 ui.inputEdit->setMode(v.toBool() ? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
229 bool InputWidget::eventFilter(QObject *watched, QEvent *event)
231 if (event->type() != QEvent::KeyPress)
234 QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
236 // keys from BufferView should be sent to (and focus) the input line
237 BufferView *view = qobject_cast<BufferView *>(watched);
239 if (keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier))) { // normal key press
240 QChar c = keyEvent->text().at(0);
241 if (c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
243 QCoreApplication::sendEvent(inputLine(), keyEvent);
249 else if (watched == ui.inputEdit) {
250 if (keyEvent->matches(QKeySequence::Find)) {
251 QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
263 void InputWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
265 BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
266 BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
268 if (_perChatHistory) {
270 historyMap[previousBufferId].history = inputLine()->history();
271 historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
272 historyMap[previousBufferId].idx = inputLine()->idx();
273 historyMap[previousBufferId].inputLine = inputLine()->html();
276 inputLine()->setHistory(historyMap[currentBufferId].history);
277 inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
278 inputLine()->setIdx(historyMap[currentBufferId].idx);
279 inputLine()->setHtml(historyMap[currentBufferId].inputLine);
280 inputLine()->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
282 // FIXME this really should be in MultiLineEdit (and the const int on top removed)
283 QTextBlockFormat format = inputLine()->textCursor().blockFormat();
284 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
285 inputLine()->textCursor().setBlockFormat(format);
288 NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
289 if (networkId == _networkId)
292 setNetwork(networkId);
293 updateNickSelector();
294 updateEnabledState();
298 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
300 QItemSelectionRange changedArea(topLeft, bottomRight);
301 if (changedArea.contains(selectionModel()->currentIndex())) {
302 updateEnabledState();
304 bool encrypted = false;
306 IrcChannel *chan = qobject_cast<IrcChannel *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcChannelRole).value<QObject *>());
308 encrypted = chan->encrypted();
310 IrcUser *user = qobject_cast<IrcUser *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcUserRole).value<QObject *>());
312 encrypted = user->encrypted();
315 ui.encryptionIconLabel->show();
317 ui.encryptionIconLabel->hide();
322 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
326 for (int row = start; row <= end; row++) {
327 child = model()->index(row, 0, parent);
328 if (NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
330 networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
331 if (networkId == _networkId) {
333 updateNickSelector();
340 void InputWidget::updateEnabledState()
342 // FIXME: Find a visualization for this that does not disable the widget!
343 // Disabling kills global action shortcuts, plus users sometimes need/want to enter text
344 // even in inactive channels.
346 QModelIndex currentIndex = selectionModel()->currentIndex();
348 const Network *net = Client::networkModel()->networkByIndex(currentIndex);
349 bool enabled = false;
351 // disable inputline if it's a channelbuffer we parted from or...
352 enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
353 // ... if we're not connected to the network at all
354 enabled &= net->isConnected();
357 ui.inputEdit->setEnabled(enabled);
362 const Network *InputWidget::currentNetwork() const
364 return Client::network(_networkId);
368 BufferInfo InputWidget::currentBufferInfo() const
370 return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
373 void InputWidget::setNetwork(NetworkId networkId)
375 if (_networkId == networkId)
378 const Network *previousNet = Client::network(_networkId);
380 disconnect(previousNet, 0, this, 0);
381 if (previousNet->me())
382 disconnect(previousNet->me(), 0, this, 0);
385 _networkId = networkId;
387 const Network *network = Client::network(networkId);
389 connect(network, SIGNAL(identitySet(IdentityId)), this, SLOT(setIdentity(IdentityId)));
391 setIdentity(network->identity());
400 void InputWidget::connectMyIrcUser()
402 const Network *network = currentNetwork();
404 connect(network->me(), SIGNAL(nickSet(const QString &)), this, SLOT(updateNickSelector()));
405 connect(network->me(), SIGNAL(userModesSet(QString)), this, SLOT(updateNickSelector()));
406 connect(network->me(), SIGNAL(userModesAdded(QString)), this, SLOT(updateNickSelector()));
407 connect(network->me(), SIGNAL(userModesRemoved(QString)), this, SLOT(updateNickSelector()));
408 connect(network->me(), SIGNAL(awaySet(bool)), this, SLOT(updateNickSelector()));
409 disconnect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
410 updateNickSelector();
413 connect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
418 void InputWidget::setIdentity(IdentityId identityId)
420 if (_identityId == identityId)
423 const Identity *previousIdentity = Client::identity(_identityId);
424 if (previousIdentity)
425 disconnect(previousIdentity, 0, this, 0);
427 _identityId = identityId;
429 const Identity *identity = Client::identity(identityId);
431 connect(identity, SIGNAL(nicksSet(QStringList)), this, SLOT(updateNickSelector()));
436 updateNickSelector();
440 void InputWidget::updateNickSelector() const
444 const Network *net = currentNetwork();
448 const Identity *identity = Client::identity(net->identity());
450 qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
455 QStringList nicks = identity->nicks();
456 if ((nickIdx = nicks.indexOf(net->myNick())) == -1) {
457 nicks.prepend(net->myNick());
464 IrcUser *me = net->me();
466 nicks[nickIdx] = net->myNick();
467 if (!me->userModes().isEmpty())
468 nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
471 ui.ownNick->addItems(nicks);
473 if (me && me->isAway())
474 ui.ownNick->setItemData(nickIdx, QIcon::fromTheme("user-away"), Qt::DecorationRole);
476 ui.ownNick->setCurrentIndex(nickIdx);
480 void InputWidget::changeNick(const QString &newNick) const
482 const Network *net = currentNetwork();
483 if (!net || net->isMyNick(newNick))
486 // we reset the nick selecter as we have no confirmation yet, that this will succeed.
487 // if the action succeeds it will be properly updated anyways.
488 updateNickSelector();
489 Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
493 void InputWidget::onTextEntered(const QString &text)
495 Client::userInput(currentBufferInfo(), text);
496 ui.boldButton->setChecked(false);
497 ui.underlineButton->setChecked(false);
498 ui.italicButton->setChecked(false);
501 fmt.setFontWeight(QFont::Normal);
502 fmt.setFontUnderline(false);
503 fmt.setFontItalic(false);
504 fmt.clearForeground();
505 fmt.clearBackground();
506 inputLine()->setCurrentCharFormat(fmt);
510 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format)
512 QTextCursor cursor = inputLine()->textCursor();
513 cursor.mergeCharFormat(format);
514 inputLine()->mergeCurrentCharFormat(format);
518 void InputWidget::setFormatOnSelection(const QTextCharFormat &format)
520 QTextCursor cursor = inputLine()->textCursor();
521 cursor.setCharFormat(format);
522 inputLine()->setCurrentCharFormat(format);
526 QTextCharFormat InputWidget::getFormatOfWordOrSelection()
528 QTextCursor cursor = inputLine()->textCursor();
529 return cursor.charFormat();
533 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format)
535 fontChanged(format.font());
539 void InputWidget::on_boldButton_clicked(bool checked)
542 fmt.setFontWeight(checked ? QFont::Bold : QFont::Normal);
543 mergeFormatOnSelection(fmt);
547 void InputWidget::on_underlineButton_clicked(bool checked)
550 fmt.setFontUnderline(checked);
551 mergeFormatOnSelection(fmt);
555 void InputWidget::on_italicButton_clicked(bool checked)
558 fmt.setFontItalic(checked);
559 mergeFormatOnSelection(fmt);
563 void InputWidget::fontChanged(const QFont &f)
565 ui.boldButton->setChecked(f.bold());
566 ui.italicButton->setChecked(f.italic());
567 ui.underlineButton->setChecked(f.underline());
571 void InputWidget::colorChosen(QAction *action)
575 if (action->data().value<QString>() == "") {
576 color = Qt::transparent;
577 fmt = getFormatOfWordOrSelection();
578 fmt.clearForeground();
579 setFormatOnSelection(fmt);
582 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
583 fmt.setForeground(color);
584 mergeFormatOnSelection(fmt);
586 ui.textcolorButton->setDefaultAction(action);
587 ui.textcolorButton->setIcon(createColorToolButtonIcon(QIcon::fromTheme("format-text-color"), color));
591 void InputWidget::colorHighlightChosen(QAction *action)
595 if (action->data().value<QString>() == "") {
596 color = Qt::transparent;
597 fmt = getFormatOfWordOrSelection();
598 fmt.clearBackground();
599 setFormatOnSelection(fmt);
602 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
603 fmt.setBackground(color);
604 mergeFormatOnSelection(fmt);
606 ui.highlightcolorButton->setDefaultAction(action);
607 ui.highlightcolorButton->setIcon(createColorToolButtonIcon(QIcon::fromTheme("format-fill-color"), color));
611 void InputWidget::on_showStyleButton_toggled(bool checked)
613 ui.styleFrame->setVisible(checked);
615 ui.showStyleButton->setArrowType(Qt::LeftArrow);
618 ui.showStyleButton->setArrowType(Qt::RightArrow);
623 QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color)
625 QPixmap pixmap(16, 16);
626 pixmap.fill(Qt::transparent);
627 QPainter painter(&pixmap);
628 QPixmap image = icon.pixmap(16, 16);
629 QRect target(0, 0, 16, 14);
630 QRect source(0, 0, 16, 14);
631 painter.fillRect(QRect(0, 14, 16, 16), color);
632 painter.drawPixmap(target, image, source);
634 return QIcon(pixmap);
638 // MOUSE WHEEL FILTER
639 MouseWheelFilter::MouseWheelFilter(QObject *parent)
645 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event)
647 if (event->type() != QEvent::Wheel)
648 return QObject::eventFilter(obj, event);