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, &InputWidget::setUseCustomFont);
116 fs.notify("InputWidget", this, &InputWidget::setCustomFont);
117 if (fs.value("UseCustomInputWidgetFont", false).toBool())
118 setCustomFont(fs.value("InputWidget", QFont()));
120 UiSettings s("InputWidget");
121 s.initAndNotify("EnableEmacsMode", this, &InputWidget::setEnableEmacsMode, false);
122 s.initAndNotify("ShowNickSelector", this, &InputWidget::setShowNickSelector, true);
123 s.initAndNotify("ShowStyleButtons", this, &InputWidget::setShowStyleButtons, true);
124 s.initAndNotify("EnablePerChatHistory", this, &InputWidget::setEnablePerChatHistory, true);
125 s.initAndNotify("MaxNumLines", this, &InputWidget::setMaxLines, 5);
126 s.initAndNotify("EnableScrollBars", this, &InputWidget::setScrollBarsEnabled, true);
127 s.initAndNotify("EnableLineWrap", this, &InputWidget::setLineWrapEnabled, true);
128 s.initAndNotify("EnableMultiLine", this, &InputWidget::setMultiLineEnabled, true);
130 ActionCollection *coll = QtUi::actionCollection();
131 coll->addAction("FocusInputLine", new Action{tr("Focus Input Line"), coll, this, selectOverload<>(&QWidget::setFocus), QKeySequence(Qt::CTRL + Qt::Key_L)});
133 connect(inputLine(), &MultiLineEdit::textEntered, this, &InputWidget::onTextEntered, Qt::QueuedConnection); // make sure the line is already reset, bug #984
134 connect(inputLine(), &QTextEdit::currentCharFormatChanged, this, &InputWidget::currentCharFormatChanged);
138 void InputWidget::setUseCustomFont(const QVariant &v)
141 UiStyleSettings fs("Fonts");
142 setCustomFont(fs.value("InputWidget"));
145 setCustomFont(QFont());
149 void InputWidget::setCustomFont(const QVariant &v)
151 QFont font = v.value<QFont>();
152 if (font.family().isEmpty())
153 font = QApplication::font();
154 // we don't want font styles as this conflics with mirc code richtext editing
156 font.setItalic(false);
157 font.setUnderline(false);
158 font.setStrikeOut(false);
159 ui.inputEdit->setCustomFont(font);
163 void InputWidget::setEnableEmacsMode(const QVariant &v)
165 ui.inputEdit->setEmacsMode(v.toBool());
169 void InputWidget::setShowNickSelector(const QVariant &v)
171 ui.ownNick->setVisible(v.toBool());
175 void InputWidget::setShowStyleButtons(const QVariant &v)
177 ui.showStyleButton->setVisible(v.toBool());
181 void InputWidget::setEnablePerChatHistory(const QVariant &v)
183 _perChatHistory = v.toBool();
187 void InputWidget::setMaxLines(const QVariant &v)
189 ui.inputEdit->setMaxHeight(v.toInt());
193 void InputWidget::setScrollBarsEnabled(const QVariant &v)
195 ui.inputEdit->setScrollBarsEnabled(v.toBool());
199 void InputWidget::setLineWrapEnabled(const QVariant &v)
201 ui.inputEdit->setLineWrapEnabled(v.toBool());
205 void InputWidget::setMultiLineEnabled(const QVariant &v)
207 ui.inputEdit->setMode(v.toBool() ? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
211 bool InputWidget::eventFilter(QObject *watched, QEvent *event)
213 if (event->type() != QEvent::KeyPress)
216 auto *keyEvent = static_cast<QKeyEvent *>(event);
218 // keys from BufferView should be sent to (and focus) the input line
219 auto *view = qobject_cast<BufferView *>(watched);
221 if (keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier))) { // normal key press
222 QChar c = keyEvent->text().at(0);
223 if (c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
225 QCoreApplication::sendEvent(inputLine(), keyEvent);
231 else if (watched == ui.inputEdit) {
232 if (keyEvent->matches(QKeySequence::Find)) {
233 QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
245 void InputWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
247 BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
248 BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
250 if (_perChatHistory) {
252 historyMap[previousBufferId].history = inputLine()->history();
253 historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
254 historyMap[previousBufferId].idx = inputLine()->idx();
255 historyMap[previousBufferId].inputLine = inputLine()->html();
258 inputLine()->setHistory(historyMap[currentBufferId].history);
259 inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
260 inputLine()->setIdx(historyMap[currentBufferId].idx);
261 inputLine()->setHtml(historyMap[currentBufferId].inputLine);
262 inputLine()->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
264 // FIXME this really should be in MultiLineEdit (and the const int on top removed)
265 QTextBlockFormat format = inputLine()->textCursor().blockFormat();
266 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
267 inputLine()->textCursor().setBlockFormat(format);
270 NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
271 if (networkId == _networkId)
274 setNetwork(networkId);
275 updateNickSelector();
276 updateEnabledState();
280 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
282 QItemSelectionRange changedArea(topLeft, bottomRight);
283 if (changedArea.contains(selectionModel()->currentIndex())) {
284 updateEnabledState();
286 bool encrypted = false;
288 auto *chan = qobject_cast<IrcChannel *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcChannelRole).value<QObject *>());
290 encrypted = chan->encrypted();
292 auto *user = qobject_cast<IrcUser *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcUserRole).value<QObject *>());
294 encrypted = user->encrypted();
297 ui.encryptionIconLabel->show();
299 ui.encryptionIconLabel->hide();
304 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
308 for (int row = start; row <= end; row++) {
309 child = model()->index(row, 0, parent);
310 if (NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
312 networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
313 if (networkId == _networkId) {
315 updateNickSelector();
322 void InputWidget::updateEnabledState()
324 // FIXME: Find a visualization for this that does not disable the widget!
325 // Disabling kills global action shortcuts, plus users sometimes need/want to enter text
326 // even in inactive channels.
328 QModelIndex currentIndex = selectionModel()->currentIndex();
330 const Network *net = Client::networkModel()->networkByIndex(currentIndex);
331 bool enabled = false;
333 // disable inputline if it's a channelbuffer we parted from or...
334 enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
335 // ... if we're not connected to the network at all
336 enabled &= net->isConnected();
339 ui.inputEdit->setEnabled(enabled);
344 const Network *InputWidget::currentNetwork() const
346 return Client::network(_networkId);
350 BufferInfo InputWidget::currentBufferInfo() const
352 return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
356 void InputWidget::applyFormatActiveColor()
358 if (!ui.textcolorButton->defaultAction()) {
361 colorChosen(ui.textcolorButton->defaultAction());
365 void InputWidget::applyFormatActiveColorFill()
367 if (!ui.highlightcolorButton->defaultAction()) {
370 colorHighlightChosen(ui.highlightcolorButton->defaultAction());
374 void InputWidget::toggleFormatBold()
376 setFormatBold(!ui.boldButton->isChecked());
380 void InputWidget::toggleFormatItalic()
382 setFormatItalic(!ui.italicButton->isChecked());
386 void InputWidget::toggleFormatUnderline()
388 setFormatUnderline(!ui.underlineButton->isChecked());
392 void InputWidget::clearFormat()
394 // Clear all formatting for selection (not global)
395 setFormatClear(false);
399 void InputWidget::setNetwork(NetworkId networkId)
401 if (_networkId == networkId)
404 const Network *previousNet = Client::network(_networkId);
406 disconnect(previousNet, nullptr, this, nullptr);
407 if (previousNet->me())
408 disconnect(previousNet->me(), nullptr, this, nullptr);
411 _networkId = networkId;
413 const Network *network = Client::network(networkId);
415 connect(network, &Network::identitySet, this, &InputWidget::setIdentity);
417 setIdentity(network->identity());
426 void InputWidget::connectMyIrcUser()
428 const Network *network = currentNetwork();
430 connect(network->me(), &IrcUser::nickSet, this, &InputWidget::updateNickSelector);
431 connect(network->me(), &IrcUser::userModesSet, this, &InputWidget::updateNickSelector);
432 connect(network->me(), &IrcUser::userModesAdded, this, &InputWidget::updateNickSelector);
433 connect(network->me(), &IrcUser::userModesRemoved, this, &InputWidget::updateNickSelector);
434 connect(network->me(), &IrcUser::awaySet, this, &InputWidget::updateNickSelector);
435 disconnect(network, &Network::myNickSet, this, &InputWidget::connectMyIrcUser);
436 updateNickSelector();
439 connect(network, &Network::myNickSet, this, &InputWidget::connectMyIrcUser);
444 void InputWidget::setIdentity(IdentityId identityId)
446 if (_identityId == identityId)
449 const Identity *previousIdentity = Client::identity(_identityId);
450 if (previousIdentity)
451 disconnect(previousIdentity, nullptr, this, nullptr);
453 _identityId = identityId;
455 const Identity *identity = Client::identity(identityId);
457 connect(identity, &Identity::nicksSet, this, &InputWidget::updateNickSelector);
462 updateNickSelector();
466 void InputWidget::updateNickSelector() const
470 const Network *net = currentNetwork();
474 const Identity *identity = Client::identity(net->identity());
476 qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
481 QStringList nicks = identity->nicks();
482 if ((nickIdx = nicks.indexOf(net->myNick())) == -1) {
483 nicks.prepend(net->myNick());
490 IrcUser *me = net->me();
492 nicks[nickIdx] = net->myNick();
493 if (!me->userModes().isEmpty())
494 nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
497 ui.ownNick->addItems(nicks);
499 if (me && me->isAway())
500 ui.ownNick->setItemData(nickIdx, icon::get({"im-user-away", "user-away"}), Qt::DecorationRole);
502 ui.ownNick->setCurrentIndex(nickIdx);
506 void InputWidget::changeNick(const QString &newNick) const
508 const Network *net = currentNetwork();
509 if (!net || net->isMyNick(newNick))
512 // we reset the nick selecter as we have no confirmation yet, that this will succeed.
513 // if the action succeeds it will be properly updated anyways.
514 updateNickSelector();
515 Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
519 void InputWidget::onTextEntered(const QString &text)
521 Client::userInput(currentBufferInfo(), text);
523 // Remove formatting from entered text
524 // TODO: Offer a way to convert pasted text to mIRC formatting codes
525 setFormatClear(true);
529 void InputWidget::setFormatClear(const bool global)
533 fmt.setFontWeight(QFont::Normal);
534 fmt.setFontUnderline(false);
535 fmt.setFontItalic(false);
536 fmt.clearForeground();
537 fmt.clearBackground();
539 inputLine()->setCurrentCharFormat(fmt);
541 setFormatOnSelection(fmt);
544 // Make sure UI state follows
545 ui.boldButton->setChecked(false);
546 ui.italicButton->setChecked(false);
547 ui.underlineButton->setChecked(false);
551 void InputWidget::setFormatBold(const bool bold)
555 fmt.setFontWeight(bold ? QFont::Bold : QFont::Normal);
556 mergeFormatOnSelection(fmt);
557 // Make sure UI state follows
558 ui.boldButton->setChecked(bold);
562 void InputWidget::setFormatItalic(const bool italic)
566 fmt.setFontItalic(italic);
567 mergeFormatOnSelection(fmt);
568 // Make sure UI state follows
569 ui.italicButton->setChecked(italic);
573 void InputWidget::setFormatUnderline(const bool underline)
577 fmt.setFontUnderline(underline);
578 mergeFormatOnSelection(fmt);
579 // Make sure UI state follows
580 ui.underlineButton->setChecked(underline);
584 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format)
586 QTextCursor cursor = inputLine()->textCursor();
587 cursor.mergeCharFormat(format);
588 inputLine()->mergeCurrentCharFormat(format);
592 void InputWidget::setFormatOnSelection(const QTextCharFormat &format)
594 QTextCursor cursor = inputLine()->textCursor();
595 cursor.setCharFormat(format);
596 inputLine()->setCurrentCharFormat(format);
600 QTextCharFormat InputWidget::getFormatOfWordOrSelection()
602 QTextCursor cursor = inputLine()->textCursor();
603 return cursor.charFormat();
607 void InputWidget::setStyleOptionsExpanded(bool expanded)
609 ui.styleFrame->setVisible(expanded);
611 ui.showStyleButton->setArrowType(Qt::LeftArrow);
612 ui.showStyleButton->setToolTip(tr("Hide formatting options"));
614 ui.showStyleButton->setArrowType(Qt::RightArrow);
615 ui.showStyleButton->setToolTip(tr("Show formatting options"));
620 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format)
622 fontChanged(format.font());
626 void InputWidget::on_boldButton_clicked(bool checked)
628 setFormatBold(checked);
632 void InputWidget::on_underlineButton_clicked(bool checked)
634 setFormatUnderline(checked);
638 void InputWidget::on_italicButton_clicked(bool checked)
640 setFormatItalic(checked);
644 void InputWidget::fontChanged(const QFont &f)
646 ui.boldButton->setChecked(f.bold());
647 ui.italicButton->setChecked(f.italic());
648 ui.underlineButton->setChecked(f.underline());
652 void InputWidget::colorChosen(QAction *action)
656 if (action->data().value<QString>() == "") {
657 color = Qt::transparent;
658 fmt = getFormatOfWordOrSelection();
659 fmt.clearForeground();
660 setFormatOnSelection(fmt);
663 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
664 fmt.setForeground(color);
665 mergeFormatOnSelection(fmt);
667 ui.textcolorButton->setDefaultAction(action);
668 ui.textcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-text-color"), color));
672 void InputWidget::colorHighlightChosen(QAction *action)
676 if (action->data().value<QString>() == "") {
677 color = Qt::transparent;
678 fmt = getFormatOfWordOrSelection();
679 fmt.clearBackground();
680 setFormatOnSelection(fmt);
683 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
684 fmt.setBackground(color);
685 mergeFormatOnSelection(fmt);
687 ui.highlightcolorButton->setDefaultAction(action);
688 ui.highlightcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-fill-color"), color));
692 void InputWidget::on_showStyleButton_toggled(bool checked)
694 setStyleOptionsExpanded(checked);
698 QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color)
700 QPixmap pixmap(16, 16);
701 pixmap.fill(Qt::transparent);
702 QPainter painter(&pixmap);
703 QPixmap image = icon.pixmap(16, 16);
704 QRect target(0, 0, 16, 14);
705 QRect source(0, 0, 16, 14);
706 painter.fillRect(QRect(0, 14, 16, 16), color);
707 painter.drawPixmap(target, image, source);
709 return QIcon(pixmap);
713 // MOUSE WHEEL FILTER
714 MouseWheelFilter::MouseWheelFilter(QObject *parent)
720 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event)
722 if (event->type() != QEvent::Wheel)
723 return QObject::eventFilter(obj, event);