1 /***************************************************************************
2 * Copyright (C) 2005-2020 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"
40 const int leftMargin = 3;
42 InputWidget::InputWidget(QWidget* parent)
43 : AbstractItemView(parent)
47 connect(ui.ownNick, selectOverload<const QString&>(&QComboBox::activated), this, &InputWidget::changeNick);
49 layout()->setAlignment(ui.ownNick, Qt::AlignBottom);
50 layout()->setAlignment(ui.inputEdit, Qt::AlignBottom);
51 layout()->setAlignment(ui.showStyleButton, Qt::AlignBottom);
52 layout()->setAlignment(ui.styleFrame, Qt::AlignBottom);
54 setStyleOptionsExpanded(false);
56 setFocusProxy(ui.inputEdit);
57 ui.ownNick->setFocusProxy(ui.inputEdit);
59 ui.ownNick->setSizeAdjustPolicy(QComboBox::AdjustToContents);
60 ui.ownNick->installEventFilter(new MouseWheelFilter(this));
61 ui.inputEdit->installEventFilter(this);
63 ui.inputEdit->setMinHeight(1);
64 ui.inputEdit->setMaxHeight(5);
65 ui.inputEdit->setMode(MultiLineEdit::MultiLine);
66 ui.inputEdit->setPasteProtectionEnabled(true);
68 ui.boldButton->setIcon(icon::get("format-text-bold"));
69 ui.italicButton->setIcon(icon::get("format-text-italic"));
70 ui.underlineButton->setIcon(icon::get("format-text-underline"));
71 ui.strikethroughButton->setIcon(icon::get("format-text-strikethrough"));
72 ui.clearButton->setIcon(icon::get("edit-clear"));
73 ui.encryptionIconLabel->hide();
75 _colorMenu = new QMenu();
76 _colorFillMenu = new QMenu();
79 names << tr("White") << tr("Black") << tr("Dark blue") << tr("Dark green") << tr("Red") << tr("Dark red") << tr("Dark magenta")
80 << tr("Orange") << tr("Yellow") << tr("Green") << tr("Dark cyan") << tr("Cyan") << tr("Blue") << tr("Magenta") << tr("Dark gray")
84 for (int i = 0; i < inputLine()->mircColorMap().count(); i++) {
85 pix.fill(inputLine()->mircColorMap().values()[i]);
86 _colorMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
87 _colorFillMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
90 pix.fill(Qt::transparent);
91 _colorMenu->addAction(pix, tr("Clear Color"))->setData("");
92 _colorFillMenu->addAction(pix, tr("Clear Color"))->setData("");
94 ui.textcolorButton->setMenu(_colorMenu);
95 // Set the default action to clear color (last added action)
96 ui.textcolorButton->setDefaultAction(_colorMenu->actions().last());
97 connect(_colorMenu, &QMenu::triggered, this, &InputWidget::colorChosen);
99 ui.highlightcolorButton->setMenu(_colorFillMenu);
100 // Set the default action to clear fill color (last added action)
101 ui.highlightcolorButton->setDefaultAction(_colorFillMenu->actions().last());
102 connect(_colorFillMenu, &QMenu::triggered, this, &InputWidget::colorHighlightChosen);
104 // Needs to be done after adding the menu, otherwise the icon mysteriously vanishes until clicked
105 ui.textcolorButton->setIcon(icon::get("format-text-color"));
106 ui.highlightcolorButton->setIcon(icon::get("format-fill-color"));
108 // Show/hide style button
109 connect(ui.showStyleButton, &QAbstractButton::toggled, this, &InputWidget::setStyleOptionsExpanded);
111 // Clear formatting button
112 connect(ui.clearButton, &QAbstractButton::clicked, this, &InputWidget::clearFormat);
114 new TabCompleter(ui.inputEdit);
116 UiStyleSettings fs("Fonts");
117 fs.notify("UseCustomInputWidgetFont", this, &InputWidget::setUseCustomFont);
118 fs.notify("InputWidget", this, &InputWidget::setCustomFont);
119 if (fs.value("UseCustomInputWidgetFont", false).toBool())
120 setCustomFont(fs.value("InputWidget", QFont()));
122 UiSettings s("InputWidget");
123 s.initAndNotify("EnableEmacsMode", this, &InputWidget::setEnableEmacsMode, false);
124 s.initAndNotify("ShowNickSelector", this, &InputWidget::setShowNickSelector, true);
125 s.initAndNotify("ShowStyleButtons", this, &InputWidget::setShowStyleButtons, true);
126 s.initAndNotify("EnablePerChatHistory", this, &InputWidget::setEnablePerChatHistory, true);
127 s.initAndNotify("MaxNumLines", this, &InputWidget::setMaxLines, 5);
128 s.initAndNotify("EnableScrollBars", this, &InputWidget::setScrollBarsEnabled, true);
129 s.initAndNotify("EnableLineWrap", this, &InputWidget::setLineWrapEnabled, true);
130 s.initAndNotify("EnableMultiLine", this, &InputWidget::setMultiLineEnabled, true);
132 ActionCollection* coll = QtUi::actionCollection();
133 coll->addAction("FocusInputLine",
134 new Action{tr("Focus Input Line"), coll, this, selectOverload<>(&QWidget::setFocus), QKeySequence(Qt::CTRL + Qt::Key_L)});
137 &MultiLineEdit::textEntered,
139 &InputWidget::onTextEntered,
140 Qt::QueuedConnection); // make sure the line is already reset, bug #984
141 connect(inputLine(), &QTextEdit::currentCharFormatChanged, this, &InputWidget::currentCharFormatChanged);
144 void InputWidget::setUseCustomFont(const QVariant& v)
147 UiStyleSettings fs("Fonts");
148 setCustomFont(fs.value("InputWidget"));
151 setCustomFont(QFont());
154 void InputWidget::setCustomFont(const QVariant& v)
156 QFont font = v.value<QFont>();
157 if (font.family().isEmpty())
158 font = QApplication::font();
159 // we don't want font styles as this conflics with mirc code richtext editing
161 font.setItalic(false);
162 font.setUnderline(false);
163 font.setStrikeOut(false);
164 ui.inputEdit->setCustomFont(font);
167 void InputWidget::setEnableEmacsMode(const QVariant& v)
169 ui.inputEdit->setEmacsMode(v.toBool());
172 void InputWidget::setShowNickSelector(const QVariant& v)
174 ui.ownNick->setVisible(v.toBool());
177 void InputWidget::setShowStyleButtons(const QVariant& v)
179 ui.showStyleButton->setVisible(v.toBool());
182 void InputWidget::setEnablePerChatHistory(const QVariant& v)
184 _perChatHistory = v.toBool();
187 void InputWidget::setMaxLines(const QVariant& v)
189 ui.inputEdit->setMaxHeight(v.toInt());
192 void InputWidget::setScrollBarsEnabled(const QVariant& v)
194 ui.inputEdit->setScrollBarsEnabled(v.toBool());
197 void InputWidget::setLineWrapEnabled(const QVariant& v)
199 ui.inputEdit->setLineWrapEnabled(v.toBool());
202 void InputWidget::setMultiLineEnabled(const QVariant& v)
204 ui.inputEdit->setMode(v.toBool() ? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
207 bool InputWidget::eventFilter(QObject* watched, QEvent* event)
209 if (event->type() != QEvent::KeyPress)
212 auto* keyEvent = static_cast<QKeyEvent*>(event);
214 // keys from BufferView should be sent to (and focus) the input line
215 auto* view = qobject_cast<BufferView*>(watched);
217 if (keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier))) { // normal key press
218 QChar c = keyEvent->text().at(0);
219 if (c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
221 QCoreApplication::sendEvent(inputLine(), keyEvent);
227 else if (watched == ui.inputEdit) {
228 if (keyEvent->matches(QKeySequence::Find)) {
229 QAction* act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
240 void InputWidget::currentChanged(const QModelIndex& current, const QModelIndex& previous)
242 BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
243 BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
245 if (_perChatHistory) {
247 historyMap[previousBufferId].history = inputLine()->history();
248 historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
249 historyMap[previousBufferId].idx = inputLine()->idx();
250 historyMap[previousBufferId].inputLine = inputLine()->html();
253 inputLine()->setHistory(historyMap[currentBufferId].history);
254 inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
255 inputLine()->setIdx(historyMap[currentBufferId].idx);
256 inputLine()->setHtml(historyMap[currentBufferId].inputLine);
257 inputLine()->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
259 // FIXME this really should be in MultiLineEdit (and the const int on top removed)
260 QTextBlockFormat format = inputLine()->textCursor().blockFormat();
261 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
262 inputLine()->textCursor().setBlockFormat(format);
265 NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
266 if (networkId == _networkId)
269 setNetwork(networkId);
270 updateNickSelector();
271 updateEnabledState();
274 void InputWidget::dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
276 QItemSelectionRange changedArea(topLeft, bottomRight);
277 if (changedArea.contains(selectionModel()->currentIndex())) {
278 updateEnabledState();
280 bool encrypted = false;
282 auto* chan = qobject_cast<IrcChannel*>(
283 Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcChannelRole).value<QObject*>());
285 encrypted = chan->encrypted();
287 auto* user = qobject_cast<IrcUser*>(
288 Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcUserRole).value<QObject*>());
290 encrypted = user->encrypted();
293 ui.encryptionIconLabel->show();
295 ui.encryptionIconLabel->hide();
299 void InputWidget::rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end)
303 for (int row = start; row <= end; row++) {
304 child = model()->index(row, 0, parent);
305 if (NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
307 networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
308 if (networkId == _networkId) {
310 updateNickSelector();
316 void InputWidget::updateEnabledState()
318 // FIXME: Find a visualization for this that does not disable the widget!
319 // Disabling kills global action shortcuts, plus users sometimes need/want to enter text
320 // even in inactive channels.
322 QModelIndex currentIndex = selectionModel()->currentIndex();
324 const Network *net = Client::networkModel()->networkByIndex(currentIndex);
325 bool enabled = false;
327 // disable inputline if it's a channelbuffer we parted from or...
328 enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
329 // ... if we're not connected to the network at all
330 enabled &= net->isConnected();
333 ui.inputEdit->setEnabled(enabled);
337 const Network* InputWidget::currentNetwork() const
339 return Client::network(_networkId);
342 BufferInfo InputWidget::currentBufferInfo() const
344 return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
347 void InputWidget::applyFormatActiveColor()
349 if (!ui.textcolorButton->defaultAction()) {
352 colorChosen(ui.textcolorButton->defaultAction());
355 void InputWidget::applyFormatActiveColorFill()
357 if (!ui.highlightcolorButton->defaultAction()) {
360 colorHighlightChosen(ui.highlightcolorButton->defaultAction());
363 void InputWidget::toggleFormatBold()
365 setFormatBold(!ui.boldButton->isChecked());
368 void InputWidget::toggleFormatItalic()
370 setFormatItalic(!ui.italicButton->isChecked());
373 void InputWidget::toggleFormatUnderline()
375 setFormatUnderline(!ui.underlineButton->isChecked());
378 void InputWidget::toggleFormatStrikethrough()
380 setFormatStrikethrough(!ui.strikethroughButton->isChecked());
383 void InputWidget::clearFormat()
385 // Clear all formatting for selection (not global)
386 setFormatClear(false);
389 void InputWidget::setNetwork(NetworkId networkId)
391 if (_networkId == networkId)
394 const Network* previousNet = Client::network(_networkId);
396 disconnect(previousNet, nullptr, this, nullptr);
397 if (previousNet->me())
398 disconnect(previousNet->me(), nullptr, this, nullptr);
401 _networkId = networkId;
403 const Network* network = Client::network(networkId);
405 connect(network, &Network::identitySet, this, &InputWidget::setIdentity);
407 setIdentity(network->identity());
415 void InputWidget::connectMyIrcUser()
417 const Network* network = currentNetwork();
419 connect(network->me(), &IrcUser::nickSet, this, &InputWidget::updateNickSelector);
420 connect(network->me(), &IrcUser::userModesSet, this, &InputWidget::updateNickSelector);
421 connect(network->me(), &IrcUser::userModesAdded, this, &InputWidget::updateNickSelector);
422 connect(network->me(), &IrcUser::userModesRemoved, this, &InputWidget::updateNickSelector);
423 connect(network->me(), &IrcUser::awaySet, this, &InputWidget::updateNickSelector);
424 disconnect(network, &Network::myNickSet, this, &InputWidget::connectMyIrcUser);
425 updateNickSelector();
428 connect(network, &Network::myNickSet, this, &InputWidget::connectMyIrcUser);
432 void InputWidget::setIdentity(IdentityId identityId)
434 if (_identityId == identityId)
437 const Identity* previousIdentity = Client::identity(_identityId);
438 if (previousIdentity)
439 disconnect(previousIdentity, nullptr, this, nullptr);
441 _identityId = identityId;
443 const Identity* identity = Client::identity(identityId);
445 connect(identity, &Identity::nicksSet, this, &InputWidget::updateNickSelector);
450 updateNickSelector();
453 void InputWidget::updateNickSelector() const
457 const Network* net = currentNetwork();
461 const Identity* identity = Client::identity(net->identity());
463 qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId()
464 << "IdentityId:" << net->identity();
469 QStringList nicks = identity->nicks();
470 if ((nickIdx = nicks.indexOf(net->myNick())) == -1) {
471 nicks.prepend(net->myNick());
478 IrcUser* me = net->me();
480 nicks[nickIdx] = net->myNick();
481 if (!me->userModes().isEmpty())
482 nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
485 ui.ownNick->addItems(nicks);
487 if (me && me->isAway())
488 ui.ownNick->setItemData(nickIdx, icon::get({"im-user-away", "user-away"}), Qt::DecorationRole);
490 ui.ownNick->setCurrentIndex(nickIdx);
493 void InputWidget::changeNick(const QString& newNick) const
495 const Network* net = currentNetwork();
496 if (!net || net->isMyNick(newNick))
499 // we reset the nick selecter as we have no confirmation yet, that this will succeed.
500 // if the action succeeds it will be properly updated anyways.
501 updateNickSelector();
502 Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
505 void InputWidget::onTextEntered(const QString& text)
507 Client::userInput(currentBufferInfo(), text);
509 // Remove formatting from entered text
510 // TODO: Offer a way to convert pasted text to mIRC formatting codes
511 setFormatClear(true);
514 void InputWidget::setFormatClear(const bool global)
518 fmt.setFontWeight(QFont::Normal);
519 fmt.setFontUnderline(false);
520 fmt.setFontStrikeOut(false);
521 fmt.setFontItalic(false);
522 fmt.clearForeground();
523 fmt.clearBackground();
525 inputLine()->setCurrentCharFormat(fmt);
528 setFormatOnSelection(fmt);
531 // Make sure UI state follows
532 ui.boldButton->setChecked(false);
533 ui.italicButton->setChecked(false);
534 ui.underlineButton->setChecked(false);
535 ui.strikethroughButton->setChecked(false);
538 void InputWidget::setFormatBold(const bool bold)
542 fmt.setFontWeight(bold ? QFont::Bold : QFont::Normal);
543 mergeFormatOnSelection(fmt);
544 // Make sure UI state follows
545 ui.boldButton->setChecked(bold);
548 void InputWidget::setFormatItalic(const bool italic)
552 fmt.setFontItalic(italic);
553 mergeFormatOnSelection(fmt);
554 // Make sure UI state follows
555 ui.italicButton->setChecked(italic);
558 void InputWidget::setFormatUnderline(const bool underline)
562 fmt.setFontUnderline(underline);
563 mergeFormatOnSelection(fmt);
564 // Make sure UI state follows
565 ui.underlineButton->setChecked(underline);
568 void InputWidget::setFormatStrikethrough(const bool strike)
572 fmt.setFontStrikeOut(strike);
573 mergeFormatOnSelection(fmt);
574 // Make sure UI state follows
575 ui.strikethroughButton->setChecked(strike);
578 void InputWidget::mergeFormatOnSelection(const QTextCharFormat& format)
580 QTextCursor cursor = inputLine()->textCursor();
581 cursor.mergeCharFormat(format);
582 inputLine()->mergeCurrentCharFormat(format);
585 void InputWidget::setFormatOnSelection(const QTextCharFormat& format)
587 QTextCursor cursor = inputLine()->textCursor();
588 cursor.setCharFormat(format);
589 inputLine()->setCurrentCharFormat(format);
592 QTextCharFormat InputWidget::getFormatOfWordOrSelection()
594 QTextCursor cursor = inputLine()->textCursor();
595 return cursor.charFormat();
598 void InputWidget::setStyleOptionsExpanded(bool expanded)
600 ui.styleFrame->setVisible(expanded);
602 ui.showStyleButton->setArrowType(Qt::LeftArrow);
603 ui.showStyleButton->setToolTip(tr("Hide formatting options"));
606 ui.showStyleButton->setArrowType(Qt::RightArrow);
607 ui.showStyleButton->setToolTip(tr("Show formatting options"));
611 void InputWidget::currentCharFormatChanged(const QTextCharFormat& format)
613 fontChanged(format.font());
616 void InputWidget::on_boldButton_clicked(bool checked)
618 setFormatBold(checked);
621 void InputWidget::on_underlineButton_clicked(bool checked)
623 setFormatUnderline(checked);
626 void InputWidget::on_strikethroughButton_clicked(bool checked)
628 setFormatStrikethrough(checked);
631 void InputWidget::on_italicButton_clicked(bool checked)
633 setFormatItalic(checked);
636 void InputWidget::fontChanged(const QFont& f)
638 ui.boldButton->setChecked(f.bold());
639 ui.italicButton->setChecked(f.italic());
640 ui.underlineButton->setChecked(f.underline());
641 ui.strikethroughButton->setChecked(f.strikeOut());
644 void InputWidget::colorChosen(QAction* action)
648 if (action->data().value<QString>() == "") {
649 color = Qt::transparent;
650 fmt = getFormatOfWordOrSelection();
651 fmt.clearForeground();
652 setFormatOnSelection(fmt);
655 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
656 fmt.setForeground(color);
657 mergeFormatOnSelection(fmt);
659 ui.textcolorButton->setDefaultAction(action);
660 ui.textcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-text-color"), color));
663 void InputWidget::colorHighlightChosen(QAction* action)
667 if (action->data().value<QString>() == "") {
668 color = Qt::transparent;
669 fmt = getFormatOfWordOrSelection();
670 fmt.clearBackground();
671 setFormatOnSelection(fmt);
674 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
675 fmt.setBackground(color);
676 mergeFormatOnSelection(fmt);
678 ui.highlightcolorButton->setDefaultAction(action);
679 ui.highlightcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-fill-color"), color));
682 void InputWidget::on_showStyleButton_toggled(bool checked)
684 setStyleOptionsExpanded(checked);
687 QIcon InputWidget::createColorToolButtonIcon(const QIcon& icon, const QColor& color)
689 QPixmap pixmap(16, 16);
690 pixmap.fill(Qt::transparent);
691 QPainter painter(&pixmap);
692 QPixmap image = icon.pixmap(16, 16);
693 QRect target(0, 0, 16, 14);
694 QRect source(0, 0, 16, 14);
695 painter.fillRect(QRect(0, 14, 16, 16), color);
696 painter.drawPixmap(target, image, source);
698 return QIcon(pixmap);
701 // MOUSE WHEEL FILTER
702 MouseWheelFilter::MouseWheelFilter(QObject* parent)
706 bool MouseWheelFilter::eventFilter(QObject* obj, QEvent* event)
708 if (event->type() != QEvent::Wheel)
709 return QObject::eventFilter(obj, event);