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"
29 #include "actioncollection.h"
30 #include "bufferview.h"
34 #include "networkmodel.h"
36 #include "qtuisettings.h"
37 #include "tabcompleter.h"
39 const int leftMargin = 3;
41 InputWidget::InputWidget(QWidget *parent)
42 : AbstractItemView(parent),
46 connect(ui.ownNick, SIGNAL(activated(QString)), this, SLOT(changeNick(QString)));
48 layout()->setAlignment(ui.ownNick, Qt::AlignBottom);
49 layout()->setAlignment(ui.inputEdit, Qt::AlignBottom);
50 layout()->setAlignment(ui.showStyleButton, Qt::AlignBottom);
51 layout()->setAlignment(ui.styleFrame, Qt::AlignBottom);
53 setStyleOptionsExpanded(false);
55 setFocusProxy(ui.inputEdit);
56 ui.ownNick->setFocusProxy(ui.inputEdit);
58 ui.ownNick->setSizeAdjustPolicy(QComboBox::AdjustToContents);
59 ui.ownNick->installEventFilter(new MouseWheelFilter(this));
60 ui.inputEdit->installEventFilter(this);
62 ui.inputEdit->setMinHeight(1);
63 ui.inputEdit->setMaxHeight(5);
64 ui.inputEdit->setMode(MultiLineEdit::MultiLine);
65 ui.inputEdit->setPasteProtectionEnabled(true);
67 ui.boldButton->setIcon(icon::get("format-text-bold"));
68 ui.italicButton->setIcon(icon::get("format-text-italic"));
69 ui.underlineButton->setIcon(icon::get("format-text-underline"));
70 ui.clearButton->setIcon(icon::get("edit-clear"));
71 ui.encryptionIconLabel->hide();
73 _colorMenu = new QMenu();
74 _colorFillMenu = new QMenu();
77 names << tr("White") << tr("Black") << tr("Dark blue") << tr("Dark green") << tr("Red") << tr("Dark red") << tr("Dark magenta") << tr("Orange")
78 << tr("Yellow") << tr("Green") << tr("Dark cyan") << tr("Cyan") << tr("Blue") << tr("Magenta") << tr("Dark gray") << tr("Light gray");
81 for (int i = 0; i < inputLine()->mircColorMap().count(); i++) {
82 pix.fill(inputLine()->mircColorMap().values()[i]);
83 _colorMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
84 _colorFillMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
87 pix.fill(Qt::transparent);
88 _colorMenu->addAction(pix, tr("Clear Color"))->setData("");
89 _colorFillMenu->addAction(pix, tr("Clear Color"))->setData("");
91 ui.textcolorButton->setMenu(_colorMenu);
92 // Set the default action to clear color (last added action)
93 ui.textcolorButton->setDefaultAction(_colorMenu->actions().last());
94 connect(_colorMenu, SIGNAL(triggered(QAction *)), this, SLOT(colorChosen(QAction *)));
96 ui.highlightcolorButton->setMenu(_colorFillMenu);
97 // Set the default action to clear fill color (last added action)
98 ui.highlightcolorButton->setDefaultAction(_colorFillMenu->actions().last());
99 connect(_colorFillMenu, SIGNAL(triggered(QAction *)), this, SLOT(colorHighlightChosen(QAction *)));
101 // Needs to be done after adding the menu, otherwise the icon mysteriously vanishes until clicked
102 ui.textcolorButton->setIcon(icon::get("format-text-color"));
103 ui.highlightcolorButton->setIcon(icon::get("format-fill-color"));
105 // Show/hide style button
106 connect(ui.showStyleButton, SIGNAL(toggled(bool)), this, SLOT(setStyleOptionsExpanded(bool)));
108 // Clear formatting button
109 connect(ui.clearButton, SIGNAL(clicked()), this, SLOT(clearFormat()));
111 new TabCompleter(ui.inputEdit);
113 UiStyleSettings fs("Fonts");
114 fs.notify("UseCustomInputWidgetFont", this, SLOT(setUseCustomFont(QVariant)));
115 fs.notify("InputWidget", this, SLOT(setCustomFont(QVariant)));
116 if (fs.value("UseCustomInputWidgetFont", false).toBool())
117 setCustomFont(fs.value("InputWidget", QFont()));
119 UiSettings s("InputWidget");
121 s.notify("EnableEmacsMode", this, SLOT(setEnableEmacsMode(QVariant)));
122 setEnableEmacsMode(s.value("EnableEmacsMode", false));
124 s.notify("ShowNickSelector", this, SLOT(setShowNickSelector(QVariant)));
125 setShowNickSelector(s.value("ShowNickSelector", true));
127 s.notify("ShowStyleButtons", this, SLOT(setShowStyleButtons(QVariant)));
128 setShowStyleButtons(s.value("ShowStyleButtons", true));
130 s.notify("EnablePerChatHistory", this, SLOT(setEnablePerChatHistory(QVariant)));
131 setEnablePerChatHistory(s.value("EnablePerChatHistory", true));
133 s.notify("MaxNumLines", this, SLOT(setMaxLines(QVariant)));
134 setMaxLines(s.value("MaxNumLines", 5));
136 s.notify("EnableScrollBars", this, SLOT(setScrollBarsEnabled(QVariant)));
137 setScrollBarsEnabled(s.value("EnableScrollBars", true));
139 s.notify("EnableLineWrap", this, SLOT(setLineWrapEnabled(QVariant)));
140 setLineWrapEnabled(s.value("EnableLineWrap", true));
142 s.notify("EnableMultiLine", this, SLOT(setMultiLineEnabled(QVariant)));
143 setMultiLineEnabled(s.value("EnableMultiLine", true));
145 ActionCollection *coll = QtUi::actionCollection();
147 auto *activateInputline = coll->add<Action>("FocusInputLine");
148 connect(activateInputline, SIGNAL(triggered()), SLOT(setFocus()));
149 activateInputline->setText(tr("Focus Input Line"));
150 activateInputline->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_L));
152 connect(inputLine(), SIGNAL(textEntered(QString)), SLOT(onTextEntered(QString)), Qt::QueuedConnection); // make sure the line is already reset, bug #984
153 connect(inputLine(), SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(currentCharFormatChanged(QTextCharFormat)));
157 void InputWidget::setUseCustomFont(const QVariant &v)
160 UiStyleSettings fs("Fonts");
161 setCustomFont(fs.value("InputWidget"));
164 setCustomFont(QFont());
168 void InputWidget::setCustomFont(const QVariant &v)
170 QFont font = v.value<QFont>();
171 if (font.family().isEmpty())
172 font = QApplication::font();
173 // we don't want font styles as this conflics with mirc code richtext editing
175 font.setItalic(false);
176 font.setUnderline(false);
177 font.setStrikeOut(false);
178 ui.inputEdit->setCustomFont(font);
182 void InputWidget::setEnableEmacsMode(const QVariant &v)
184 ui.inputEdit->setEmacsMode(v.toBool());
188 void InputWidget::setShowNickSelector(const QVariant &v)
190 ui.ownNick->setVisible(v.toBool());
194 void InputWidget::setShowStyleButtons(const QVariant &v)
196 ui.showStyleButton->setVisible(v.toBool());
200 void InputWidget::setEnablePerChatHistory(const QVariant &v)
202 _perChatHistory = v.toBool();
206 void InputWidget::setMaxLines(const QVariant &v)
208 ui.inputEdit->setMaxHeight(v.toInt());
212 void InputWidget::setScrollBarsEnabled(const QVariant &v)
214 ui.inputEdit->setScrollBarsEnabled(v.toBool());
218 void InputWidget::setLineWrapEnabled(const QVariant &v)
220 ui.inputEdit->setLineWrapEnabled(v.toBool());
224 void InputWidget::setMultiLineEnabled(const QVariant &v)
226 ui.inputEdit->setMode(v.toBool() ? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
230 bool InputWidget::eventFilter(QObject *watched, QEvent *event)
232 if (event->type() != QEvent::KeyPress)
235 auto *keyEvent = static_cast<QKeyEvent *>(event);
237 // keys from BufferView should be sent to (and focus) the input line
238 auto *view = qobject_cast<BufferView *>(watched);
240 if (keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier))) { // normal key press
241 QChar c = keyEvent->text().at(0);
242 if (c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
244 QCoreApplication::sendEvent(inputLine(), keyEvent);
250 else if (watched == ui.inputEdit) {
251 if (keyEvent->matches(QKeySequence::Find)) {
252 QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
264 void InputWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
266 BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
267 BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
269 if (_perChatHistory) {
271 historyMap[previousBufferId].history = inputLine()->history();
272 historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
273 historyMap[previousBufferId].idx = inputLine()->idx();
274 historyMap[previousBufferId].inputLine = inputLine()->html();
277 inputLine()->setHistory(historyMap[currentBufferId].history);
278 inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
279 inputLine()->setIdx(historyMap[currentBufferId].idx);
280 inputLine()->setHtml(historyMap[currentBufferId].inputLine);
281 inputLine()->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
283 // FIXME this really should be in MultiLineEdit (and the const int on top removed)
284 QTextBlockFormat format = inputLine()->textCursor().blockFormat();
285 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
286 inputLine()->textCursor().setBlockFormat(format);
289 NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
290 if (networkId == _networkId)
293 setNetwork(networkId);
294 updateNickSelector();
295 updateEnabledState();
299 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
301 QItemSelectionRange changedArea(topLeft, bottomRight);
302 if (changedArea.contains(selectionModel()->currentIndex())) {
303 updateEnabledState();
305 bool encrypted = false;
307 auto *chan = qobject_cast<IrcChannel *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcChannelRole).value<QObject *>());
309 encrypted = chan->encrypted();
311 auto *user = qobject_cast<IrcUser *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcUserRole).value<QObject *>());
313 encrypted = user->encrypted();
316 ui.encryptionIconLabel->show();
318 ui.encryptionIconLabel->hide();
323 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
327 for (int row = start; row <= end; row++) {
328 child = model()->index(row, 0, parent);
329 if (NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
331 networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
332 if (networkId == _networkId) {
334 updateNickSelector();
341 void InputWidget::updateEnabledState()
343 // FIXME: Find a visualization for this that does not disable the widget!
344 // Disabling kills global action shortcuts, plus users sometimes need/want to enter text
345 // even in inactive channels.
347 QModelIndex currentIndex = selectionModel()->currentIndex();
349 const Network *net = Client::networkModel()->networkByIndex(currentIndex);
350 bool enabled = false;
352 // disable inputline if it's a channelbuffer we parted from or...
353 enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
354 // ... if we're not connected to the network at all
355 enabled &= net->isConnected();
358 ui.inputEdit->setEnabled(enabled);
363 const Network *InputWidget::currentNetwork() const
365 return Client::network(_networkId);
369 BufferInfo InputWidget::currentBufferInfo() const
371 return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
375 void InputWidget::applyFormatActiveColor()
377 if (!ui.textcolorButton->defaultAction()) {
380 colorChosen(ui.textcolorButton->defaultAction());
384 void InputWidget::applyFormatActiveColorFill()
386 if (!ui.highlightcolorButton->defaultAction()) {
389 colorHighlightChosen(ui.highlightcolorButton->defaultAction());
393 void InputWidget::toggleFormatBold()
395 setFormatBold(!ui.boldButton->isChecked());
399 void InputWidget::toggleFormatItalic()
401 setFormatItalic(!ui.italicButton->isChecked());
405 void InputWidget::toggleFormatUnderline()
407 setFormatUnderline(!ui.underlineButton->isChecked());
411 void InputWidget::clearFormat()
413 // Clear all formatting for selection (not global)
414 setFormatClear(false);
418 void InputWidget::setNetwork(NetworkId networkId)
420 if (_networkId == networkId)
423 const Network *previousNet = Client::network(_networkId);
425 disconnect(previousNet, nullptr, this, nullptr);
426 if (previousNet->me())
427 disconnect(previousNet->me(), nullptr, this, nullptr);
430 _networkId = networkId;
432 const Network *network = Client::network(networkId);
434 connect(network, SIGNAL(identitySet(IdentityId)), this, SLOT(setIdentity(IdentityId)));
436 setIdentity(network->identity());
445 void InputWidget::connectMyIrcUser()
447 const Network *network = currentNetwork();
449 connect(network->me(), SIGNAL(nickSet(const QString &)), this, SLOT(updateNickSelector()));
450 connect(network->me(), SIGNAL(userModesSet(QString)), this, SLOT(updateNickSelector()));
451 connect(network->me(), SIGNAL(userModesAdded(QString)), this, SLOT(updateNickSelector()));
452 connect(network->me(), SIGNAL(userModesRemoved(QString)), this, SLOT(updateNickSelector()));
453 connect(network->me(), SIGNAL(awaySet(bool)), this, SLOT(updateNickSelector()));
454 disconnect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
455 updateNickSelector();
458 connect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
463 void InputWidget::setIdentity(IdentityId identityId)
465 if (_identityId == identityId)
468 const Identity *previousIdentity = Client::identity(_identityId);
469 if (previousIdentity)
470 disconnect(previousIdentity, nullptr, this, nullptr);
472 _identityId = identityId;
474 const Identity *identity = Client::identity(identityId);
476 connect(identity, SIGNAL(nicksSet(QStringList)), this, SLOT(updateNickSelector()));
481 updateNickSelector();
485 void InputWidget::updateNickSelector() const
489 const Network *net = currentNetwork();
493 const Identity *identity = Client::identity(net->identity());
495 qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
500 QStringList nicks = identity->nicks();
501 if ((nickIdx = nicks.indexOf(net->myNick())) == -1) {
502 nicks.prepend(net->myNick());
509 IrcUser *me = net->me();
511 nicks[nickIdx] = net->myNick();
512 if (!me->userModes().isEmpty())
513 nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
516 ui.ownNick->addItems(nicks);
518 if (me && me->isAway())
519 ui.ownNick->setItemData(nickIdx, icon::get({"im-user-away", "user-away"}), Qt::DecorationRole);
521 ui.ownNick->setCurrentIndex(nickIdx);
525 void InputWidget::changeNick(const QString &newNick) const
527 const Network *net = currentNetwork();
528 if (!net || net->isMyNick(newNick))
531 // we reset the nick selecter as we have no confirmation yet, that this will succeed.
532 // if the action succeeds it will be properly updated anyways.
533 updateNickSelector();
534 Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
538 void InputWidget::onTextEntered(const QString &text)
540 Client::userInput(currentBufferInfo(), text);
542 // Remove formatting from entered text
543 // TODO: Offer a way to convert pasted text to mIRC formatting codes
544 setFormatClear(true);
548 void InputWidget::setFormatClear(const bool global)
552 fmt.setFontWeight(QFont::Normal);
553 fmt.setFontUnderline(false);
554 fmt.setFontItalic(false);
555 fmt.clearForeground();
556 fmt.clearBackground();
558 inputLine()->setCurrentCharFormat(fmt);
560 setFormatOnSelection(fmt);
563 // Make sure UI state follows
564 ui.boldButton->setChecked(false);
565 ui.italicButton->setChecked(false);
566 ui.underlineButton->setChecked(false);
570 void InputWidget::setFormatBold(const bool bold)
574 fmt.setFontWeight(bold ? QFont::Bold : QFont::Normal);
575 mergeFormatOnSelection(fmt);
576 // Make sure UI state follows
577 ui.boldButton->setChecked(bold);
581 void InputWidget::setFormatItalic(const bool italic)
585 fmt.setFontItalic(italic);
586 mergeFormatOnSelection(fmt);
587 // Make sure UI state follows
588 ui.italicButton->setChecked(italic);
592 void InputWidget::setFormatUnderline(const bool underline)
596 fmt.setFontUnderline(underline);
597 mergeFormatOnSelection(fmt);
598 // Make sure UI state follows
599 ui.underlineButton->setChecked(underline);
603 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format)
605 QTextCursor cursor = inputLine()->textCursor();
606 cursor.mergeCharFormat(format);
607 inputLine()->mergeCurrentCharFormat(format);
611 void InputWidget::setFormatOnSelection(const QTextCharFormat &format)
613 QTextCursor cursor = inputLine()->textCursor();
614 cursor.setCharFormat(format);
615 inputLine()->setCurrentCharFormat(format);
619 QTextCharFormat InputWidget::getFormatOfWordOrSelection()
621 QTextCursor cursor = inputLine()->textCursor();
622 return cursor.charFormat();
626 void InputWidget::setStyleOptionsExpanded(bool expanded)
628 ui.styleFrame->setVisible(expanded);
630 ui.showStyleButton->setArrowType(Qt::LeftArrow);
631 ui.showStyleButton->setToolTip(tr("Hide formatting options"));
633 ui.showStyleButton->setArrowType(Qt::RightArrow);
634 ui.showStyleButton->setToolTip(tr("Show formatting options"));
639 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format)
641 fontChanged(format.font());
645 void InputWidget::on_boldButton_clicked(bool checked)
647 setFormatBold(checked);
651 void InputWidget::on_underlineButton_clicked(bool checked)
653 setFormatUnderline(checked);
657 void InputWidget::on_italicButton_clicked(bool checked)
659 setFormatItalic(checked);
663 void InputWidget::fontChanged(const QFont &f)
665 ui.boldButton->setChecked(f.bold());
666 ui.italicButton->setChecked(f.italic());
667 ui.underlineButton->setChecked(f.underline());
671 void InputWidget::colorChosen(QAction *action)
675 if (action->data().value<QString>() == "") {
676 color = Qt::transparent;
677 fmt = getFormatOfWordOrSelection();
678 fmt.clearForeground();
679 setFormatOnSelection(fmt);
682 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
683 fmt.setForeground(color);
684 mergeFormatOnSelection(fmt);
686 ui.textcolorButton->setDefaultAction(action);
687 ui.textcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-text-color"), color));
691 void InputWidget::colorHighlightChosen(QAction *action)
695 if (action->data().value<QString>() == "") {
696 color = Qt::transparent;
697 fmt = getFormatOfWordOrSelection();
698 fmt.clearBackground();
699 setFormatOnSelection(fmt);
702 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
703 fmt.setBackground(color);
704 mergeFormatOnSelection(fmt);
706 ui.highlightcolorButton->setDefaultAction(action);
707 ui.highlightcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-fill-color"), color));
711 void InputWidget::on_showStyleButton_toggled(bool checked)
713 setStyleOptionsExpanded(checked);
717 QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color)
719 QPixmap pixmap(16, 16);
720 pixmap.fill(Qt::transparent);
721 QPainter painter(&pixmap);
722 QPixmap image = icon.pixmap(16, 16);
723 QRect target(0, 0, 16, 14);
724 QRect source(0, 0, 16, 14);
725 painter.fillRect(QRect(0, 14, 16, 16), color);
726 painter.drawPixmap(target, image, source);
728 return QIcon(pixmap);
732 // MOUSE WHEEL FILTER
733 MouseWheelFilter::MouseWheelFilter(QObject *parent)
739 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event)
741 if (event->type() != QEvent::Wheel)
742 return QObject::eventFilter(obj, event);