1 /***************************************************************************
2 * Copyright (C) 2005-2019 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.clearButton->setIcon(icon::get("edit-clear"));
72 ui.encryptionIconLabel->hide();
74 _colorMenu = new QMenu();
75 _colorFillMenu = new QMenu();
78 names << tr("White") << tr("Black") << tr("Dark blue") << tr("Dark green") << tr("Red") << tr("Dark red") << tr("Dark magenta")
79 << tr("Orange") << tr("Yellow") << tr("Green") << tr("Dark cyan") << tr("Cyan") << tr("Blue") << tr("Magenta") << tr("Dark gray")
83 for (int i = 0; i < inputLine()->mircColorMap().count(); i++) {
84 pix.fill(inputLine()->mircColorMap().values()[i]);
85 _colorMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
86 _colorFillMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
89 pix.fill(Qt::transparent);
90 _colorMenu->addAction(pix, tr("Clear Color"))->setData("");
91 _colorFillMenu->addAction(pix, tr("Clear Color"))->setData("");
93 ui.textcolorButton->setMenu(_colorMenu);
94 // Set the default action to clear color (last added action)
95 ui.textcolorButton->setDefaultAction(_colorMenu->actions().last());
96 connect(_colorMenu, &QMenu::triggered, this, &InputWidget::colorChosen);
98 ui.highlightcolorButton->setMenu(_colorFillMenu);
99 // Set the default action to clear fill color (last added action)
100 ui.highlightcolorButton->setDefaultAction(_colorFillMenu->actions().last());
101 connect(_colorFillMenu, &QMenu::triggered, this, &InputWidget::colorHighlightChosen);
103 // Needs to be done after adding the menu, otherwise the icon mysteriously vanishes until clicked
104 ui.textcolorButton->setIcon(icon::get("format-text-color"));
105 ui.highlightcolorButton->setIcon(icon::get("format-fill-color"));
107 // Show/hide style button
108 connect(ui.showStyleButton, &QAbstractButton::toggled, this, &InputWidget::setStyleOptionsExpanded);
110 // Clear formatting button
111 connect(ui.clearButton, &QAbstractButton::clicked, this, &InputWidget::clearFormat);
113 new TabCompleter(ui.inputEdit);
115 UiStyleSettings fs("Fonts");
116 fs.notify("UseCustomInputWidgetFont", this, &InputWidget::setUseCustomFont);
117 fs.notify("InputWidget", this, &InputWidget::setCustomFont);
118 if (fs.value("UseCustomInputWidgetFont", false).toBool())
119 setCustomFont(fs.value("InputWidget", QFont()));
121 UiSettings s("InputWidget");
122 s.initAndNotify("EnableEmacsMode", this, &InputWidget::setEnableEmacsMode, false);
123 s.initAndNotify("ShowNickSelector", this, &InputWidget::setShowNickSelector, true);
124 s.initAndNotify("ShowStyleButtons", this, &InputWidget::setShowStyleButtons, true);
125 s.initAndNotify("EnablePerChatHistory", this, &InputWidget::setEnablePerChatHistory, true);
126 s.initAndNotify("MaxNumLines", this, &InputWidget::setMaxLines, 5);
127 s.initAndNotify("EnableScrollBars", this, &InputWidget::setScrollBarsEnabled, true);
128 s.initAndNotify("EnableLineWrap", this, &InputWidget::setLineWrapEnabled, true);
129 s.initAndNotify("EnableMultiLine", this, &InputWidget::setMultiLineEnabled, true);
131 ActionCollection* coll = QtUi::actionCollection();
132 coll->addAction("FocusInputLine",
133 new Action{tr("Focus Input Line"), coll, this, selectOverload<>(&QWidget::setFocus), QKeySequence(Qt::CTRL + Qt::Key_L)});
136 &MultiLineEdit::textEntered,
138 &InputWidget::onTextEntered,
139 Qt::QueuedConnection); // make sure the line is already reset, bug #984
140 connect(inputLine(), &QTextEdit::currentCharFormatChanged, this, &InputWidget::currentCharFormatChanged);
143 void InputWidget::setUseCustomFont(const QVariant& v)
146 UiStyleSettings fs("Fonts");
147 setCustomFont(fs.value("InputWidget"));
150 setCustomFont(QFont());
153 void InputWidget::setCustomFont(const QVariant& v)
155 QFont font = v.value<QFont>();
156 if (font.family().isEmpty())
157 font = QApplication::font();
158 // we don't want font styles as this conflics with mirc code richtext editing
160 font.setItalic(false);
161 font.setUnderline(false);
162 font.setStrikeOut(false);
163 ui.inputEdit->setCustomFont(font);
166 void InputWidget::setEnableEmacsMode(const QVariant& v)
168 ui.inputEdit->setEmacsMode(v.toBool());
171 void InputWidget::setShowNickSelector(const QVariant& v)
173 ui.ownNick->setVisible(v.toBool());
176 void InputWidget::setShowStyleButtons(const QVariant& v)
178 ui.showStyleButton->setVisible(v.toBool());
181 void InputWidget::setEnablePerChatHistory(const QVariant& v)
183 _perChatHistory = v.toBool();
186 void InputWidget::setMaxLines(const QVariant& v)
188 ui.inputEdit->setMaxHeight(v.toInt());
191 void InputWidget::setScrollBarsEnabled(const QVariant& v)
193 ui.inputEdit->setScrollBarsEnabled(v.toBool());
196 void InputWidget::setLineWrapEnabled(const QVariant& v)
198 ui.inputEdit->setLineWrapEnabled(v.toBool());
201 void InputWidget::setMultiLineEnabled(const QVariant& v)
203 ui.inputEdit->setMode(v.toBool() ? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
206 bool InputWidget::eventFilter(QObject* watched, QEvent* event)
208 if (event->type() != QEvent::KeyPress)
211 auto* keyEvent = static_cast<QKeyEvent*>(event);
213 // keys from BufferView should be sent to (and focus) the input line
214 auto* view = qobject_cast<BufferView*>(watched);
216 if (keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier))) { // normal key press
217 QChar c = keyEvent->text().at(0);
218 if (c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
220 QCoreApplication::sendEvent(inputLine(), keyEvent);
226 else if (watched == ui.inputEdit) {
227 if (keyEvent->matches(QKeySequence::Find)) {
228 QAction* act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
239 void InputWidget::currentChanged(const QModelIndex& current, const QModelIndex& previous)
241 BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
242 BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
244 if (_perChatHistory) {
246 historyMap[previousBufferId].history = inputLine()->history();
247 historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
248 historyMap[previousBufferId].idx = inputLine()->idx();
249 historyMap[previousBufferId].inputLine = inputLine()->html();
252 inputLine()->setHistory(historyMap[currentBufferId].history);
253 inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
254 inputLine()->setIdx(historyMap[currentBufferId].idx);
255 inputLine()->setHtml(historyMap[currentBufferId].inputLine);
256 inputLine()->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
258 // FIXME this really should be in MultiLineEdit (and the const int on top removed)
259 QTextBlockFormat format = inputLine()->textCursor().blockFormat();
260 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
261 inputLine()->textCursor().setBlockFormat(format);
264 NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
265 if (networkId == _networkId)
268 setNetwork(networkId);
269 updateNickSelector();
270 updateEnabledState();
273 void InputWidget::dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight)
275 QItemSelectionRange changedArea(topLeft, bottomRight);
276 if (changedArea.contains(selectionModel()->currentIndex())) {
277 updateEnabledState();
279 bool encrypted = false;
281 auto* chan = qobject_cast<IrcChannel*>(
282 Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcChannelRole).value<QObject*>());
284 encrypted = chan->encrypted();
286 auto* user = qobject_cast<IrcUser*>(
287 Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcUserRole).value<QObject*>());
289 encrypted = user->encrypted();
292 ui.encryptionIconLabel->show();
294 ui.encryptionIconLabel->hide();
298 void InputWidget::rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end)
302 for (int row = start; row <= end; row++) {
303 child = model()->index(row, 0, parent);
304 if (NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
306 networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
307 if (networkId == _networkId) {
309 updateNickSelector();
315 void InputWidget::updateEnabledState()
317 // FIXME: Find a visualization for this that does not disable the widget!
318 // Disabling kills global action shortcuts, plus users sometimes need/want to enter text
319 // even in inactive channels.
321 QModelIndex currentIndex = selectionModel()->currentIndex();
323 const Network *net = Client::networkModel()->networkByIndex(currentIndex);
324 bool enabled = false;
326 // disable inputline if it's a channelbuffer we parted from or...
327 enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
328 // ... if we're not connected to the network at all
329 enabled &= net->isConnected();
332 ui.inputEdit->setEnabled(enabled);
336 const Network* InputWidget::currentNetwork() const
338 return Client::network(_networkId);
341 BufferInfo InputWidget::currentBufferInfo() const
343 return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
346 void InputWidget::applyFormatActiveColor()
348 if (!ui.textcolorButton->defaultAction()) {
351 colorChosen(ui.textcolorButton->defaultAction());
354 void InputWidget::applyFormatActiveColorFill()
356 if (!ui.highlightcolorButton->defaultAction()) {
359 colorHighlightChosen(ui.highlightcolorButton->defaultAction());
362 void InputWidget::toggleFormatBold()
364 setFormatBold(!ui.boldButton->isChecked());
367 void InputWidget::toggleFormatItalic()
369 setFormatItalic(!ui.italicButton->isChecked());
372 void InputWidget::toggleFormatUnderline()
374 setFormatUnderline(!ui.underlineButton->isChecked());
377 void InputWidget::clearFormat()
379 // Clear all formatting for selection (not global)
380 setFormatClear(false);
383 void InputWidget::setNetwork(NetworkId networkId)
385 if (_networkId == networkId)
388 const Network* previousNet = Client::network(_networkId);
390 disconnect(previousNet, nullptr, this, nullptr);
391 if (previousNet->me())
392 disconnect(previousNet->me(), nullptr, this, nullptr);
395 _networkId = networkId;
397 const Network* network = Client::network(networkId);
399 connect(network, &Network::identitySet, this, &InputWidget::setIdentity);
401 setIdentity(network->identity());
409 void InputWidget::connectMyIrcUser()
411 const Network* network = currentNetwork();
413 connect(network->me(), &IrcUser::nickSet, this, &InputWidget::updateNickSelector);
414 connect(network->me(), &IrcUser::userModesSet, this, &InputWidget::updateNickSelector);
415 connect(network->me(), &IrcUser::userModesAdded, this, &InputWidget::updateNickSelector);
416 connect(network->me(), &IrcUser::userModesRemoved, this, &InputWidget::updateNickSelector);
417 connect(network->me(), &IrcUser::awaySet, this, &InputWidget::updateNickSelector);
418 disconnect(network, &Network::myNickSet, this, &InputWidget::connectMyIrcUser);
419 updateNickSelector();
422 connect(network, &Network::myNickSet, this, &InputWidget::connectMyIrcUser);
426 void InputWidget::setIdentity(IdentityId identityId)
428 if (_identityId == identityId)
431 const Identity* previousIdentity = Client::identity(_identityId);
432 if (previousIdentity)
433 disconnect(previousIdentity, nullptr, this, nullptr);
435 _identityId = identityId;
437 const Identity* identity = Client::identity(identityId);
439 connect(identity, &Identity::nicksSet, this, &InputWidget::updateNickSelector);
444 updateNickSelector();
447 void InputWidget::updateNickSelector() const
451 const Network* net = currentNetwork();
455 const Identity* identity = Client::identity(net->identity());
457 qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId()
458 << "IdentityId:" << net->identity();
463 QStringList nicks = identity->nicks();
464 if ((nickIdx = nicks.indexOf(net->myNick())) == -1) {
465 nicks.prepend(net->myNick());
472 IrcUser* me = net->me();
474 nicks[nickIdx] = net->myNick();
475 if (!me->userModes().isEmpty())
476 nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
479 ui.ownNick->addItems(nicks);
481 if (me && me->isAway())
482 ui.ownNick->setItemData(nickIdx, icon::get({"im-user-away", "user-away"}), Qt::DecorationRole);
484 ui.ownNick->setCurrentIndex(nickIdx);
487 void InputWidget::changeNick(const QString& newNick) const
489 const Network* net = currentNetwork();
490 if (!net || net->isMyNick(newNick))
493 // we reset the nick selecter as we have no confirmation yet, that this will succeed.
494 // if the action succeeds it will be properly updated anyways.
495 updateNickSelector();
496 Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
499 void InputWidget::onTextEntered(const QString& text)
501 Client::userInput(currentBufferInfo(), text);
503 // Remove formatting from entered text
504 // TODO: Offer a way to convert pasted text to mIRC formatting codes
505 setFormatClear(true);
508 void InputWidget::setFormatClear(const bool global)
512 fmt.setFontWeight(QFont::Normal);
513 fmt.setFontUnderline(false);
514 fmt.setFontItalic(false);
515 fmt.clearForeground();
516 fmt.clearBackground();
518 inputLine()->setCurrentCharFormat(fmt);
521 setFormatOnSelection(fmt);
524 // Make sure UI state follows
525 ui.boldButton->setChecked(false);
526 ui.italicButton->setChecked(false);
527 ui.underlineButton->setChecked(false);
530 void InputWidget::setFormatBold(const bool bold)
534 fmt.setFontWeight(bold ? QFont::Bold : QFont::Normal);
535 mergeFormatOnSelection(fmt);
536 // Make sure UI state follows
537 ui.boldButton->setChecked(bold);
540 void InputWidget::setFormatItalic(const bool italic)
544 fmt.setFontItalic(italic);
545 mergeFormatOnSelection(fmt);
546 // Make sure UI state follows
547 ui.italicButton->setChecked(italic);
550 void InputWidget::setFormatUnderline(const bool underline)
554 fmt.setFontUnderline(underline);
555 mergeFormatOnSelection(fmt);
556 // Make sure UI state follows
557 ui.underlineButton->setChecked(underline);
560 void InputWidget::mergeFormatOnSelection(const QTextCharFormat& format)
562 QTextCursor cursor = inputLine()->textCursor();
563 cursor.mergeCharFormat(format);
564 inputLine()->mergeCurrentCharFormat(format);
567 void InputWidget::setFormatOnSelection(const QTextCharFormat& format)
569 QTextCursor cursor = inputLine()->textCursor();
570 cursor.setCharFormat(format);
571 inputLine()->setCurrentCharFormat(format);
574 QTextCharFormat InputWidget::getFormatOfWordOrSelection()
576 QTextCursor cursor = inputLine()->textCursor();
577 return cursor.charFormat();
580 void InputWidget::setStyleOptionsExpanded(bool expanded)
582 ui.styleFrame->setVisible(expanded);
584 ui.showStyleButton->setArrowType(Qt::LeftArrow);
585 ui.showStyleButton->setToolTip(tr("Hide formatting options"));
588 ui.showStyleButton->setArrowType(Qt::RightArrow);
589 ui.showStyleButton->setToolTip(tr("Show formatting options"));
593 void InputWidget::currentCharFormatChanged(const QTextCharFormat& format)
595 fontChanged(format.font());
598 void InputWidget::on_boldButton_clicked(bool checked)
600 setFormatBold(checked);
603 void InputWidget::on_underlineButton_clicked(bool checked)
605 setFormatUnderline(checked);
608 void InputWidget::on_italicButton_clicked(bool checked)
610 setFormatItalic(checked);
613 void InputWidget::fontChanged(const QFont& f)
615 ui.boldButton->setChecked(f.bold());
616 ui.italicButton->setChecked(f.italic());
617 ui.underlineButton->setChecked(f.underline());
620 void InputWidget::colorChosen(QAction* action)
624 if (action->data().value<QString>() == "") {
625 color = Qt::transparent;
626 fmt = getFormatOfWordOrSelection();
627 fmt.clearForeground();
628 setFormatOnSelection(fmt);
631 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
632 fmt.setForeground(color);
633 mergeFormatOnSelection(fmt);
635 ui.textcolorButton->setDefaultAction(action);
636 ui.textcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-text-color"), color));
639 void InputWidget::colorHighlightChosen(QAction* action)
643 if (action->data().value<QString>() == "") {
644 color = Qt::transparent;
645 fmt = getFormatOfWordOrSelection();
646 fmt.clearBackground();
647 setFormatOnSelection(fmt);
650 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
651 fmt.setBackground(color);
652 mergeFormatOnSelection(fmt);
654 ui.highlightcolorButton->setDefaultAction(action);
655 ui.highlightcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-fill-color"), color));
658 void InputWidget::on_showStyleButton_toggled(bool checked)
660 setStyleOptionsExpanded(checked);
663 QIcon InputWidget::createColorToolButtonIcon(const QIcon& icon, const QColor& color)
665 QPixmap pixmap(16, 16);
666 pixmap.fill(Qt::transparent);
667 QPainter painter(&pixmap);
668 QPixmap image = icon.pixmap(16, 16);
669 QRect target(0, 0, 16, 14);
670 QRect source(0, 0, 16, 14);
671 painter.fillRect(QRect(0, 14, 16, 16), color);
672 painter.drawPixmap(target, image, source);
674 return QIcon(pixmap);
677 // MOUSE WHEEL FILTER
678 MouseWheelFilter::MouseWheelFilter(QObject* parent)
682 bool MouseWheelFilter::eventFilter(QObject* obj, QEvent* event)
684 if (event->type() != QEvent::Wheel)
685 return QObject::eventFilter(obj, event);