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();
148 auto *activateInputline = coll->add<Action>("FocusInputLine");
149 connect(activateInputline, &QAction::triggered, this, selectOverload<>(&QWidget::setFocus));
150 activateInputline->setText(tr("Focus Input Line"));
151 activateInputline->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_L));
153 connect(inputLine(), &MultiLineEdit::textEntered, this, &InputWidget::onTextEntered, Qt::QueuedConnection); // make sure the line is already reset, bug #984
154 connect(inputLine(), &QTextEdit::currentCharFormatChanged, this, &InputWidget::currentCharFormatChanged);
158 void InputWidget::setUseCustomFont(const QVariant &v)
161 UiStyleSettings fs("Fonts");
162 setCustomFont(fs.value("InputWidget"));
165 setCustomFont(QFont());
169 void InputWidget::setCustomFont(const QVariant &v)
171 QFont font = v.value<QFont>();
172 if (font.family().isEmpty())
173 font = QApplication::font();
174 // we don't want font styles as this conflics with mirc code richtext editing
176 font.setItalic(false);
177 font.setUnderline(false);
178 font.setStrikeOut(false);
179 ui.inputEdit->setCustomFont(font);
183 void InputWidget::setEnableEmacsMode(const QVariant &v)
185 ui.inputEdit->setEmacsMode(v.toBool());
189 void InputWidget::setShowNickSelector(const QVariant &v)
191 ui.ownNick->setVisible(v.toBool());
195 void InputWidget::setShowStyleButtons(const QVariant &v)
197 ui.showStyleButton->setVisible(v.toBool());
201 void InputWidget::setEnablePerChatHistory(const QVariant &v)
203 _perChatHistory = v.toBool();
207 void InputWidget::setMaxLines(const QVariant &v)
209 ui.inputEdit->setMaxHeight(v.toInt());
213 void InputWidget::setScrollBarsEnabled(const QVariant &v)
215 ui.inputEdit->setScrollBarsEnabled(v.toBool());
219 void InputWidget::setLineWrapEnabled(const QVariant &v)
221 ui.inputEdit->setLineWrapEnabled(v.toBool());
225 void InputWidget::setMultiLineEnabled(const QVariant &v)
227 ui.inputEdit->setMode(v.toBool() ? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
231 bool InputWidget::eventFilter(QObject *watched, QEvent *event)
233 if (event->type() != QEvent::KeyPress)
236 auto *keyEvent = static_cast<QKeyEvent *>(event);
238 // keys from BufferView should be sent to (and focus) the input line
239 auto *view = qobject_cast<BufferView *>(watched);
241 if (keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier))) { // normal key press
242 QChar c = keyEvent->text().at(0);
243 if (c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
245 QCoreApplication::sendEvent(inputLine(), keyEvent);
251 else if (watched == ui.inputEdit) {
252 if (keyEvent->matches(QKeySequence::Find)) {
253 QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
265 void InputWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
267 BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
268 BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
270 if (_perChatHistory) {
272 historyMap[previousBufferId].history = inputLine()->history();
273 historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
274 historyMap[previousBufferId].idx = inputLine()->idx();
275 historyMap[previousBufferId].inputLine = inputLine()->html();
278 inputLine()->setHistory(historyMap[currentBufferId].history);
279 inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
280 inputLine()->setIdx(historyMap[currentBufferId].idx);
281 inputLine()->setHtml(historyMap[currentBufferId].inputLine);
282 inputLine()->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
284 // FIXME this really should be in MultiLineEdit (and the const int on top removed)
285 QTextBlockFormat format = inputLine()->textCursor().blockFormat();
286 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
287 inputLine()->textCursor().setBlockFormat(format);
290 NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
291 if (networkId == _networkId)
294 setNetwork(networkId);
295 updateNickSelector();
296 updateEnabledState();
300 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
302 QItemSelectionRange changedArea(topLeft, bottomRight);
303 if (changedArea.contains(selectionModel()->currentIndex())) {
304 updateEnabledState();
306 bool encrypted = false;
308 auto *chan = qobject_cast<IrcChannel *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcChannelRole).value<QObject *>());
310 encrypted = chan->encrypted();
312 auto *user = qobject_cast<IrcUser *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcUserRole).value<QObject *>());
314 encrypted = user->encrypted();
317 ui.encryptionIconLabel->show();
319 ui.encryptionIconLabel->hide();
324 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
328 for (int row = start; row <= end; row++) {
329 child = model()->index(row, 0, parent);
330 if (NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
332 networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
333 if (networkId == _networkId) {
335 updateNickSelector();
342 void InputWidget::updateEnabledState()
344 // FIXME: Find a visualization for this that does not disable the widget!
345 // Disabling kills global action shortcuts, plus users sometimes need/want to enter text
346 // even in inactive channels.
348 QModelIndex currentIndex = selectionModel()->currentIndex();
350 const Network *net = Client::networkModel()->networkByIndex(currentIndex);
351 bool enabled = false;
353 // disable inputline if it's a channelbuffer we parted from or...
354 enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
355 // ... if we're not connected to the network at all
356 enabled &= net->isConnected();
359 ui.inputEdit->setEnabled(enabled);
364 const Network *InputWidget::currentNetwork() const
366 return Client::network(_networkId);
370 BufferInfo InputWidget::currentBufferInfo() const
372 return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
376 void InputWidget::applyFormatActiveColor()
378 if (!ui.textcolorButton->defaultAction()) {
381 colorChosen(ui.textcolorButton->defaultAction());
385 void InputWidget::applyFormatActiveColorFill()
387 if (!ui.highlightcolorButton->defaultAction()) {
390 colorHighlightChosen(ui.highlightcolorButton->defaultAction());
394 void InputWidget::toggleFormatBold()
396 setFormatBold(!ui.boldButton->isChecked());
400 void InputWidget::toggleFormatItalic()
402 setFormatItalic(!ui.italicButton->isChecked());
406 void InputWidget::toggleFormatUnderline()
408 setFormatUnderline(!ui.underlineButton->isChecked());
412 void InputWidget::clearFormat()
414 // Clear all formatting for selection (not global)
415 setFormatClear(false);
419 void InputWidget::setNetwork(NetworkId networkId)
421 if (_networkId == networkId)
424 const Network *previousNet = Client::network(_networkId);
426 disconnect(previousNet, nullptr, this, nullptr);
427 if (previousNet->me())
428 disconnect(previousNet->me(), nullptr, this, nullptr);
431 _networkId = networkId;
433 const Network *network = Client::network(networkId);
435 connect(network, &Network::identitySet, this, &InputWidget::setIdentity);
437 setIdentity(network->identity());
446 void InputWidget::connectMyIrcUser()
448 const Network *network = currentNetwork();
450 connect(network->me(), &IrcUser::nickSet, this, &InputWidget::updateNickSelector);
451 connect(network->me(), &IrcUser::userModesSet, this, &InputWidget::updateNickSelector);
452 connect(network->me(), &IrcUser::userModesAdded, this, &InputWidget::updateNickSelector);
453 connect(network->me(), &IrcUser::userModesRemoved, this, &InputWidget::updateNickSelector);
454 connect(network->me(), &IrcUser::awaySet, this, &InputWidget::updateNickSelector);
455 disconnect(network, &Network::myNickSet, this, &InputWidget::connectMyIrcUser);
456 updateNickSelector();
459 connect(network, &Network::myNickSet, this, &InputWidget::connectMyIrcUser);
464 void InputWidget::setIdentity(IdentityId identityId)
466 if (_identityId == identityId)
469 const Identity *previousIdentity = Client::identity(_identityId);
470 if (previousIdentity)
471 disconnect(previousIdentity, nullptr, this, nullptr);
473 _identityId = identityId;
475 const Identity *identity = Client::identity(identityId);
477 connect(identity, &Identity::nicksSet, this, &InputWidget::updateNickSelector);
482 updateNickSelector();
486 void InputWidget::updateNickSelector() const
490 const Network *net = currentNetwork();
494 const Identity *identity = Client::identity(net->identity());
496 qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
501 QStringList nicks = identity->nicks();
502 if ((nickIdx = nicks.indexOf(net->myNick())) == -1) {
503 nicks.prepend(net->myNick());
510 IrcUser *me = net->me();
512 nicks[nickIdx] = net->myNick();
513 if (!me->userModes().isEmpty())
514 nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
517 ui.ownNick->addItems(nicks);
519 if (me && me->isAway())
520 ui.ownNick->setItemData(nickIdx, icon::get({"im-user-away", "user-away"}), Qt::DecorationRole);
522 ui.ownNick->setCurrentIndex(nickIdx);
526 void InputWidget::changeNick(const QString &newNick) const
528 const Network *net = currentNetwork();
529 if (!net || net->isMyNick(newNick))
532 // we reset the nick selecter as we have no confirmation yet, that this will succeed.
533 // if the action succeeds it will be properly updated anyways.
534 updateNickSelector();
535 Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
539 void InputWidget::onTextEntered(const QString &text)
541 Client::userInput(currentBufferInfo(), text);
543 // Remove formatting from entered text
544 // TODO: Offer a way to convert pasted text to mIRC formatting codes
545 setFormatClear(true);
549 void InputWidget::setFormatClear(const bool global)
553 fmt.setFontWeight(QFont::Normal);
554 fmt.setFontUnderline(false);
555 fmt.setFontItalic(false);
556 fmt.clearForeground();
557 fmt.clearBackground();
559 inputLine()->setCurrentCharFormat(fmt);
561 setFormatOnSelection(fmt);
564 // Make sure UI state follows
565 ui.boldButton->setChecked(false);
566 ui.italicButton->setChecked(false);
567 ui.underlineButton->setChecked(false);
571 void InputWidget::setFormatBold(const bool bold)
575 fmt.setFontWeight(bold ? QFont::Bold : QFont::Normal);
576 mergeFormatOnSelection(fmt);
577 // Make sure UI state follows
578 ui.boldButton->setChecked(bold);
582 void InputWidget::setFormatItalic(const bool italic)
586 fmt.setFontItalic(italic);
587 mergeFormatOnSelection(fmt);
588 // Make sure UI state follows
589 ui.italicButton->setChecked(italic);
593 void InputWidget::setFormatUnderline(const bool underline)
597 fmt.setFontUnderline(underline);
598 mergeFormatOnSelection(fmt);
599 // Make sure UI state follows
600 ui.underlineButton->setChecked(underline);
604 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format)
606 QTextCursor cursor = inputLine()->textCursor();
607 cursor.mergeCharFormat(format);
608 inputLine()->mergeCurrentCharFormat(format);
612 void InputWidget::setFormatOnSelection(const QTextCharFormat &format)
614 QTextCursor cursor = inputLine()->textCursor();
615 cursor.setCharFormat(format);
616 inputLine()->setCurrentCharFormat(format);
620 QTextCharFormat InputWidget::getFormatOfWordOrSelection()
622 QTextCursor cursor = inputLine()->textCursor();
623 return cursor.charFormat();
627 void InputWidget::setStyleOptionsExpanded(bool expanded)
629 ui.styleFrame->setVisible(expanded);
631 ui.showStyleButton->setArrowType(Qt::LeftArrow);
632 ui.showStyleButton->setToolTip(tr("Hide formatting options"));
634 ui.showStyleButton->setArrowType(Qt::RightArrow);
635 ui.showStyleButton->setToolTip(tr("Show formatting options"));
640 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format)
642 fontChanged(format.font());
646 void InputWidget::on_boldButton_clicked(bool checked)
648 setFormatBold(checked);
652 void InputWidget::on_underlineButton_clicked(bool checked)
654 setFormatUnderline(checked);
658 void InputWidget::on_italicButton_clicked(bool checked)
660 setFormatItalic(checked);
664 void InputWidget::fontChanged(const QFont &f)
666 ui.boldButton->setChecked(f.bold());
667 ui.italicButton->setChecked(f.italic());
668 ui.underlineButton->setChecked(f.underline());
672 void InputWidget::colorChosen(QAction *action)
676 if (action->data().value<QString>() == "") {
677 color = Qt::transparent;
678 fmt = getFormatOfWordOrSelection();
679 fmt.clearForeground();
680 setFormatOnSelection(fmt);
683 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
684 fmt.setForeground(color);
685 mergeFormatOnSelection(fmt);
687 ui.textcolorButton->setDefaultAction(action);
688 ui.textcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-text-color"), color));
692 void InputWidget::colorHighlightChosen(QAction *action)
696 if (action->data().value<QString>() == "") {
697 color = Qt::transparent;
698 fmt = getFormatOfWordOrSelection();
699 fmt.clearBackground();
700 setFormatOnSelection(fmt);
703 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
704 fmt.setBackground(color);
705 mergeFormatOnSelection(fmt);
707 ui.highlightcolorButton->setDefaultAction(action);
708 ui.highlightcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-fill-color"), color));
712 void InputWidget::on_showStyleButton_toggled(bool checked)
714 setStyleOptionsExpanded(checked);
718 QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color)
720 QPixmap pixmap(16, 16);
721 pixmap.fill(Qt::transparent);
722 QPainter painter(&pixmap);
723 QPixmap image = icon.pixmap(16, 16);
724 QRect target(0, 0, 16, 14);
725 QRect source(0, 0, 16, 14);
726 painter.fillRect(QRect(0, 14, 16, 16), color);
727 painter.drawPixmap(target, image, source);
729 return QIcon(pixmap);
733 // MOUSE WHEEL FILTER
734 MouseWheelFilter::MouseWheelFilter(QObject *parent)
740 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event)
742 if (event->type() != QEvent::Wheel)
743 return QObject::eventFilter(obj, event);