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"
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") << tr("Orange")
79 << tr("Yellow") << tr("Green") << tr("Dark cyan") << tr("Cyan") << tr("Blue") << tr("Magenta") << tr("Dark gray") << tr("Light gray");
82 for (int i = 0; i < inputLine()->mircColorMap().count(); i++) {
83 pix.fill(inputLine()->mircColorMap().values()[i]);
84 _colorMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
85 _colorFillMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
88 pix.fill(Qt::transparent);
89 _colorMenu->addAction(pix, tr("Clear Color"))->setData("");
90 _colorFillMenu->addAction(pix, tr("Clear Color"))->setData("");
92 ui.textcolorButton->setMenu(_colorMenu);
93 // Set the default action to clear color (last added action)
94 ui.textcolorButton->setDefaultAction(_colorMenu->actions().last());
95 connect(_colorMenu, &QMenu::triggered, this, &InputWidget::colorChosen);
97 ui.highlightcolorButton->setMenu(_colorFillMenu);
98 // Set the default action to clear fill color (last added action)
99 ui.highlightcolorButton->setDefaultAction(_colorFillMenu->actions().last());
100 connect(_colorFillMenu, &QMenu::triggered, this, &InputWidget::colorHighlightChosen);
102 // Needs to be done after adding the menu, otherwise the icon mysteriously vanishes until clicked
103 ui.textcolorButton->setIcon(icon::get("format-text-color"));
104 ui.highlightcolorButton->setIcon(icon::get("format-fill-color"));
106 // Show/hide style button
107 connect(ui.showStyleButton, &QAbstractButton::toggled, this, &InputWidget::setStyleOptionsExpanded);
109 // Clear formatting button
110 connect(ui.clearButton, &QAbstractButton::clicked, this, &InputWidget::clearFormat);
112 new TabCompleter(ui.inputEdit);
114 UiStyleSettings fs("Fonts");
115 fs.notify("UseCustomInputWidgetFont", this, SLOT(setUseCustomFont(QVariant)));
116 fs.notify("InputWidget", this, SLOT(setCustomFont(QVariant)));
117 if (fs.value("UseCustomInputWidgetFont", false).toBool())
118 setCustomFont(fs.value("InputWidget", QFont()));
120 UiSettings s("InputWidget");
122 s.notify("EnableEmacsMode", this, SLOT(setEnableEmacsMode(QVariant)));
123 setEnableEmacsMode(s.value("EnableEmacsMode", false));
125 s.notify("ShowNickSelector", this, SLOT(setShowNickSelector(QVariant)));
126 setShowNickSelector(s.value("ShowNickSelector", true));
128 s.notify("ShowStyleButtons", this, SLOT(setShowStyleButtons(QVariant)));
129 setShowStyleButtons(s.value("ShowStyleButtons", true));
131 s.notify("EnablePerChatHistory", this, SLOT(setEnablePerChatHistory(QVariant)));
132 setEnablePerChatHistory(s.value("EnablePerChatHistory", true));
134 s.notify("MaxNumLines", this, SLOT(setMaxLines(QVariant)));
135 setMaxLines(s.value("MaxNumLines", 5));
137 s.notify("EnableScrollBars", this, SLOT(setScrollBarsEnabled(QVariant)));
138 setScrollBarsEnabled(s.value("EnableScrollBars", true));
140 s.notify("EnableLineWrap", this, SLOT(setLineWrapEnabled(QVariant)));
141 setLineWrapEnabled(s.value("EnableLineWrap", true));
143 s.notify("EnableMultiLine", this, SLOT(setMultiLineEnabled(QVariant)));
144 setMultiLineEnabled(s.value("EnableMultiLine", true));
146 ActionCollection *coll = QtUi::actionCollection();
147 coll->addAction("FocusInputLine", new Action{tr("Focus Input Line"), coll, this, selectOverload<>(&QWidget::setFocus), QKeySequence(Qt::CTRL + Qt::Key_L)});
149 connect(inputLine(), &MultiLineEdit::textEntered, this, &InputWidget::onTextEntered, Qt::QueuedConnection); // make sure the line is already reset, bug #984
150 connect(inputLine(), &QTextEdit::currentCharFormatChanged, this, &InputWidget::currentCharFormatChanged);
154 void InputWidget::setUseCustomFont(const QVariant &v)
157 UiStyleSettings fs("Fonts");
158 setCustomFont(fs.value("InputWidget"));
161 setCustomFont(QFont());
165 void InputWidget::setCustomFont(const QVariant &v)
167 QFont font = v.value<QFont>();
168 if (font.family().isEmpty())
169 font = QApplication::font();
170 // we don't want font styles as this conflics with mirc code richtext editing
172 font.setItalic(false);
173 font.setUnderline(false);
174 font.setStrikeOut(false);
175 ui.inputEdit->setCustomFont(font);
179 void InputWidget::setEnableEmacsMode(const QVariant &v)
181 ui.inputEdit->setEmacsMode(v.toBool());
185 void InputWidget::setShowNickSelector(const QVariant &v)
187 ui.ownNick->setVisible(v.toBool());
191 void InputWidget::setShowStyleButtons(const QVariant &v)
193 ui.showStyleButton->setVisible(v.toBool());
197 void InputWidget::setEnablePerChatHistory(const QVariant &v)
199 _perChatHistory = v.toBool();
203 void InputWidget::setMaxLines(const QVariant &v)
205 ui.inputEdit->setMaxHeight(v.toInt());
209 void InputWidget::setScrollBarsEnabled(const QVariant &v)
211 ui.inputEdit->setScrollBarsEnabled(v.toBool());
215 void InputWidget::setLineWrapEnabled(const QVariant &v)
217 ui.inputEdit->setLineWrapEnabled(v.toBool());
221 void InputWidget::setMultiLineEnabled(const QVariant &v)
223 ui.inputEdit->setMode(v.toBool() ? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
227 bool InputWidget::eventFilter(QObject *watched, QEvent *event)
229 if (event->type() != QEvent::KeyPress)
232 auto *keyEvent = static_cast<QKeyEvent *>(event);
234 // keys from BufferView should be sent to (and focus) the input line
235 auto *view = qobject_cast<BufferView *>(watched);
237 if (keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier))) { // normal key press
238 QChar c = keyEvent->text().at(0);
239 if (c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
241 QCoreApplication::sendEvent(inputLine(), keyEvent);
247 else if (watched == ui.inputEdit) {
248 if (keyEvent->matches(QKeySequence::Find)) {
249 QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
261 void InputWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
263 BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
264 BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
266 if (_perChatHistory) {
268 historyMap[previousBufferId].history = inputLine()->history();
269 historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
270 historyMap[previousBufferId].idx = inputLine()->idx();
271 historyMap[previousBufferId].inputLine = inputLine()->html();
274 inputLine()->setHistory(historyMap[currentBufferId].history);
275 inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
276 inputLine()->setIdx(historyMap[currentBufferId].idx);
277 inputLine()->setHtml(historyMap[currentBufferId].inputLine);
278 inputLine()->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
280 // FIXME this really should be in MultiLineEdit (and the const int on top removed)
281 QTextBlockFormat format = inputLine()->textCursor().blockFormat();
282 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
283 inputLine()->textCursor().setBlockFormat(format);
286 NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
287 if (networkId == _networkId)
290 setNetwork(networkId);
291 updateNickSelector();
292 updateEnabledState();
296 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
298 QItemSelectionRange changedArea(topLeft, bottomRight);
299 if (changedArea.contains(selectionModel()->currentIndex())) {
300 updateEnabledState();
302 bool encrypted = false;
304 auto *chan = qobject_cast<IrcChannel *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcChannelRole).value<QObject *>());
306 encrypted = chan->encrypted();
308 auto *user = qobject_cast<IrcUser *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcUserRole).value<QObject *>());
310 encrypted = user->encrypted();
313 ui.encryptionIconLabel->show();
315 ui.encryptionIconLabel->hide();
320 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
324 for (int row = start; row <= end; row++) {
325 child = model()->index(row, 0, parent);
326 if (NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
328 networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
329 if (networkId == _networkId) {
331 updateNickSelector();
338 void InputWidget::updateEnabledState()
340 // FIXME: Find a visualization for this that does not disable the widget!
341 // Disabling kills global action shortcuts, plus users sometimes need/want to enter text
342 // even in inactive channels.
344 QModelIndex currentIndex = selectionModel()->currentIndex();
346 const Network *net = Client::networkModel()->networkByIndex(currentIndex);
347 bool enabled = false;
349 // disable inputline if it's a channelbuffer we parted from or...
350 enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
351 // ... if we're not connected to the network at all
352 enabled &= net->isConnected();
355 ui.inputEdit->setEnabled(enabled);
360 const Network *InputWidget::currentNetwork() const
362 return Client::network(_networkId);
366 BufferInfo InputWidget::currentBufferInfo() const
368 return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
372 void InputWidget::applyFormatActiveColor()
374 if (!ui.textcolorButton->defaultAction()) {
377 colorChosen(ui.textcolorButton->defaultAction());
381 void InputWidget::applyFormatActiveColorFill()
383 if (!ui.highlightcolorButton->defaultAction()) {
386 colorHighlightChosen(ui.highlightcolorButton->defaultAction());
390 void InputWidget::toggleFormatBold()
392 setFormatBold(!ui.boldButton->isChecked());
396 void InputWidget::toggleFormatItalic()
398 setFormatItalic(!ui.italicButton->isChecked());
402 void InputWidget::toggleFormatUnderline()
404 setFormatUnderline(!ui.underlineButton->isChecked());
408 void InputWidget::clearFormat()
410 // Clear all formatting for selection (not global)
411 setFormatClear(false);
415 void InputWidget::setNetwork(NetworkId networkId)
417 if (_networkId == networkId)
420 const Network *previousNet = Client::network(_networkId);
422 disconnect(previousNet, nullptr, this, nullptr);
423 if (previousNet->me())
424 disconnect(previousNet->me(), nullptr, this, nullptr);
427 _networkId = networkId;
429 const Network *network = Client::network(networkId);
431 connect(network, &Network::identitySet, this, &InputWidget::setIdentity);
433 setIdentity(network->identity());
442 void InputWidget::connectMyIrcUser()
444 const Network *network = currentNetwork();
446 connect(network->me(), &IrcUser::nickSet, this, &InputWidget::updateNickSelector);
447 connect(network->me(), &IrcUser::userModesSet, this, &InputWidget::updateNickSelector);
448 connect(network->me(), &IrcUser::userModesAdded, this, &InputWidget::updateNickSelector);
449 connect(network->me(), &IrcUser::userModesRemoved, this, &InputWidget::updateNickSelector);
450 connect(network->me(), &IrcUser::awaySet, this, &InputWidget::updateNickSelector);
451 disconnect(network, &Network::myNickSet, this, &InputWidget::connectMyIrcUser);
452 updateNickSelector();
455 connect(network, &Network::myNickSet, this, &InputWidget::connectMyIrcUser);
460 void InputWidget::setIdentity(IdentityId identityId)
462 if (_identityId == identityId)
465 const Identity *previousIdentity = Client::identity(_identityId);
466 if (previousIdentity)
467 disconnect(previousIdentity, nullptr, this, nullptr);
469 _identityId = identityId;
471 const Identity *identity = Client::identity(identityId);
473 connect(identity, &Identity::nicksSet, this, &InputWidget::updateNickSelector);
478 updateNickSelector();
482 void InputWidget::updateNickSelector() const
486 const Network *net = currentNetwork();
490 const Identity *identity = Client::identity(net->identity());
492 qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
497 QStringList nicks = identity->nicks();
498 if ((nickIdx = nicks.indexOf(net->myNick())) == -1) {
499 nicks.prepend(net->myNick());
506 IrcUser *me = net->me();
508 nicks[nickIdx] = net->myNick();
509 if (!me->userModes().isEmpty())
510 nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
513 ui.ownNick->addItems(nicks);
515 if (me && me->isAway())
516 ui.ownNick->setItemData(nickIdx, icon::get({"im-user-away", "user-away"}), Qt::DecorationRole);
518 ui.ownNick->setCurrentIndex(nickIdx);
522 void InputWidget::changeNick(const QString &newNick) const
524 const Network *net = currentNetwork();
525 if (!net || net->isMyNick(newNick))
528 // we reset the nick selecter as we have no confirmation yet, that this will succeed.
529 // if the action succeeds it will be properly updated anyways.
530 updateNickSelector();
531 Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
535 void InputWidget::onTextEntered(const QString &text)
537 Client::userInput(currentBufferInfo(), text);
539 // Remove formatting from entered text
540 // TODO: Offer a way to convert pasted text to mIRC formatting codes
541 setFormatClear(true);
545 void InputWidget::setFormatClear(const bool global)
549 fmt.setFontWeight(QFont::Normal);
550 fmt.setFontUnderline(false);
551 fmt.setFontItalic(false);
552 fmt.clearForeground();
553 fmt.clearBackground();
555 inputLine()->setCurrentCharFormat(fmt);
557 setFormatOnSelection(fmt);
560 // Make sure UI state follows
561 ui.boldButton->setChecked(false);
562 ui.italicButton->setChecked(false);
563 ui.underlineButton->setChecked(false);
567 void InputWidget::setFormatBold(const bool bold)
571 fmt.setFontWeight(bold ? QFont::Bold : QFont::Normal);
572 mergeFormatOnSelection(fmt);
573 // Make sure UI state follows
574 ui.boldButton->setChecked(bold);
578 void InputWidget::setFormatItalic(const bool italic)
582 fmt.setFontItalic(italic);
583 mergeFormatOnSelection(fmt);
584 // Make sure UI state follows
585 ui.italicButton->setChecked(italic);
589 void InputWidget::setFormatUnderline(const bool underline)
593 fmt.setFontUnderline(underline);
594 mergeFormatOnSelection(fmt);
595 // Make sure UI state follows
596 ui.underlineButton->setChecked(underline);
600 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format)
602 QTextCursor cursor = inputLine()->textCursor();
603 cursor.mergeCharFormat(format);
604 inputLine()->mergeCurrentCharFormat(format);
608 void InputWidget::setFormatOnSelection(const QTextCharFormat &format)
610 QTextCursor cursor = inputLine()->textCursor();
611 cursor.setCharFormat(format);
612 inputLine()->setCurrentCharFormat(format);
616 QTextCharFormat InputWidget::getFormatOfWordOrSelection()
618 QTextCursor cursor = inputLine()->textCursor();
619 return cursor.charFormat();
623 void InputWidget::setStyleOptionsExpanded(bool expanded)
625 ui.styleFrame->setVisible(expanded);
627 ui.showStyleButton->setArrowType(Qt::LeftArrow);
628 ui.showStyleButton->setToolTip(tr("Hide formatting options"));
630 ui.showStyleButton->setArrowType(Qt::RightArrow);
631 ui.showStyleButton->setToolTip(tr("Show formatting options"));
636 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format)
638 fontChanged(format.font());
642 void InputWidget::on_boldButton_clicked(bool checked)
644 setFormatBold(checked);
648 void InputWidget::on_underlineButton_clicked(bool checked)
650 setFormatUnderline(checked);
654 void InputWidget::on_italicButton_clicked(bool checked)
656 setFormatItalic(checked);
660 void InputWidget::fontChanged(const QFont &f)
662 ui.boldButton->setChecked(f.bold());
663 ui.italicButton->setChecked(f.italic());
664 ui.underlineButton->setChecked(f.underline());
668 void InputWidget::colorChosen(QAction *action)
672 if (action->data().value<QString>() == "") {
673 color = Qt::transparent;
674 fmt = getFormatOfWordOrSelection();
675 fmt.clearForeground();
676 setFormatOnSelection(fmt);
679 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
680 fmt.setForeground(color);
681 mergeFormatOnSelection(fmt);
683 ui.textcolorButton->setDefaultAction(action);
684 ui.textcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-text-color"), color));
688 void InputWidget::colorHighlightChosen(QAction *action)
692 if (action->data().value<QString>() == "") {
693 color = Qt::transparent;
694 fmt = getFormatOfWordOrSelection();
695 fmt.clearBackground();
696 setFormatOnSelection(fmt);
699 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
700 fmt.setBackground(color);
701 mergeFormatOnSelection(fmt);
703 ui.highlightcolorButton->setDefaultAction(action);
704 ui.highlightcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-fill-color"), color));
708 void InputWidget::on_showStyleButton_toggled(bool checked)
710 setStyleOptionsExpanded(checked);
714 QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color)
716 QPixmap pixmap(16, 16);
717 pixmap.fill(Qt::transparent);
718 QPainter painter(&pixmap);
719 QPixmap image = icon.pixmap(16, 16);
720 QRect target(0, 0, 16, 14);
721 QRect source(0, 0, 16, 14);
722 painter.fillRect(QRect(0, 14, 16, 16), color);
723 painter.drawPixmap(target, image, source);
725 return QIcon(pixmap);
729 // MOUSE WHEEL FILTER
730 MouseWheelFilter::MouseWheelFilter(QObject *parent)
736 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event)
738 if (event->type() != QEvent::Wheel)
739 return QObject::eventFilter(obj, event);