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"
39 const int leftMargin = 3;
41 InputWidget::InputWidget(QWidget *parent)
42 : AbstractItemView(parent),
46 connect(ui.ownNick, SIGNAL(activated(QString)), this, SLOT(changeNick(QString)));
48 layout()->setAlignment(ui.ownNick, Qt::AlignBottom);
49 layout()->setAlignment(ui.inputEdit, Qt::AlignBottom);
50 layout()->setAlignment(ui.showStyleButton, Qt::AlignBottom);
51 layout()->setAlignment(ui.styleFrame, Qt::AlignBottom);
53 setStyleOptionsExpanded(false);
55 setFocusProxy(ui.inputEdit);
56 ui.ownNick->setFocusProxy(ui.inputEdit);
58 ui.ownNick->setSizeAdjustPolicy(QComboBox::AdjustToContents);
59 ui.ownNick->installEventFilter(new MouseWheelFilter(this));
60 ui.inputEdit->installEventFilter(this);
62 ui.inputEdit->setMinHeight(1);
63 ui.inputEdit->setMaxHeight(5);
64 ui.inputEdit->setMode(MultiLineEdit::MultiLine);
65 ui.inputEdit->setPasteProtectionEnabled(true);
67 ui.boldButton->setIcon(icon::get("format-text-bold"));
68 ui.italicButton->setIcon(icon::get("format-text-italic"));
69 ui.underlineButton->setIcon(icon::get("format-text-underline"));
70 ui.clearButton->setIcon(icon::get("edit-clear"));
71 ui.encryptionIconLabel->hide();
73 _colorMenu = new QMenu();
74 _colorFillMenu = new QMenu();
77 names << tr("White") << tr("Black") << tr("Dark blue") << tr("Dark green") << tr("Red") << tr("Dark red") << tr("Dark magenta") << tr("Orange")
78 << tr("Yellow") << tr("Green") << tr("Dark cyan") << tr("Cyan") << tr("Blue") << tr("Magenta") << tr("Dark gray") << tr("Light gray");
81 for (int i = 0; i < inputLine()->mircColorMap().count(); i++) {
82 pix.fill(inputLine()->mircColorMap().values()[i]);
83 _colorMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
84 _colorFillMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
87 pix.fill(Qt::transparent);
88 _colorMenu->addAction(pix, tr("Clear Color"))->setData("");
89 _colorFillMenu->addAction(pix, tr("Clear Color"))->setData("");
91 ui.textcolorButton->setMenu(_colorMenu);
92 // Set the default action to clear color (last added action)
93 ui.textcolorButton->setDefaultAction(_colorMenu->actions().last());
94 connect(_colorMenu, SIGNAL(triggered(QAction *)), this, SLOT(colorChosen(QAction *)));
96 ui.highlightcolorButton->setMenu(_colorFillMenu);
97 // Set the default action to clear fill color (last added action)
98 ui.highlightcolorButton->setDefaultAction(_colorFillMenu->actions().last());
99 connect(_colorFillMenu, SIGNAL(triggered(QAction *)), this, SLOT(colorHighlightChosen(QAction *)));
101 // Needs to be done after adding the menu, otherwise the icon mysteriously vanishes until clicked
102 ui.textcolorButton->setIcon(icon::get("format-text-color"));
103 ui.highlightcolorButton->setIcon(icon::get("format-fill-color"));
105 // Show/hide style button
106 connect(ui.showStyleButton, SIGNAL(toggled(bool)), this, SLOT(setStyleOptionsExpanded(bool)));
108 // Clear formatting button
109 connect(ui.clearButton, SIGNAL(clicked()), this, SLOT(clearFormat()));
111 new TabCompleter(ui.inputEdit);
113 UiStyleSettings fs("Fonts");
114 fs.notify("UseCustomInputWidgetFont", this, SLOT(setUseCustomFont(QVariant)));
115 fs.notify("InputWidget", this, SLOT(setCustomFont(QVariant)));
116 if (fs.value("UseCustomInputWidgetFont", false).toBool())
117 setCustomFont(fs.value("InputWidget", QFont()));
119 UiSettings s("InputWidget");
122 s.notify("EnableSpellCheck", this, SLOT(setEnableSpellCheck(QVariant)));
123 setEnableSpellCheck(s.value("EnableSpellCheck", false));
126 s.notify("EnableEmacsMode", this, SLOT(setEnableEmacsMode(QVariant)));
127 setEnableEmacsMode(s.value("EnableEmacsMode", false));
129 s.notify("ShowNickSelector", this, SLOT(setShowNickSelector(QVariant)));
130 setShowNickSelector(s.value("ShowNickSelector", true));
132 s.notify("ShowStyleButtons", this, SLOT(setShowStyleButtons(QVariant)));
133 setShowStyleButtons(s.value("ShowStyleButtons", true));
135 s.notify("EnablePerChatHistory", this, SLOT(setEnablePerChatHistory(QVariant)));
136 setEnablePerChatHistory(s.value("EnablePerChatHistory", true));
138 s.notify("MaxNumLines", this, SLOT(setMaxLines(QVariant)));
139 setMaxLines(s.value("MaxNumLines", 5));
141 s.notify("EnableScrollBars", this, SLOT(setScrollBarsEnabled(QVariant)));
142 setScrollBarsEnabled(s.value("EnableScrollBars", true));
144 s.notify("EnableLineWrap", this, SLOT(setLineWrapEnabled(QVariant)));
145 setLineWrapEnabled(s.value("EnableLineWrap", true));
147 s.notify("EnableMultiLine", this, SLOT(setMultiLineEnabled(QVariant)));
148 setMultiLineEnabled(s.value("EnableMultiLine", true));
150 ActionCollection *coll = QtUi::actionCollection();
152 Action *activateInputline = coll->add<Action>("FocusInputLine");
153 connect(activateInputline, SIGNAL(triggered()), SLOT(setFocus()));
154 activateInputline->setText(tr("Focus Input Line"));
155 activateInputline->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_L));
157 connect(inputLine(), SIGNAL(textEntered(QString)), SLOT(onTextEntered(QString)), Qt::QueuedConnection); // make sure the line is already reset, bug #984
158 connect(inputLine(), SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(currentCharFormatChanged(QTextCharFormat)));
162 InputWidget::~InputWidget()
167 void InputWidget::setUseCustomFont(const QVariant &v)
170 UiStyleSettings fs("Fonts");
171 setCustomFont(fs.value("InputWidget"));
174 setCustomFont(QFont());
178 void InputWidget::setCustomFont(const QVariant &v)
180 QFont font = v.value<QFont>();
181 if (font.family().isEmpty())
182 font = QApplication::font();
183 // we don't want font styles as this conflics with mirc code richtext editing
185 font.setItalic(false);
186 font.setUnderline(false);
187 font.setStrikeOut(false);
188 ui.inputEdit->setCustomFont(font);
192 void InputWidget::setEnableSpellCheck(const QVariant &v)
194 ui.inputEdit->setSpellCheckEnabled(v.toBool());
198 void InputWidget::setEnableEmacsMode(const QVariant &v)
200 ui.inputEdit->setEmacsMode(v.toBool());
204 void InputWidget::setShowNickSelector(const QVariant &v)
206 ui.ownNick->setVisible(v.toBool());
210 void InputWidget::setShowStyleButtons(const QVariant &v)
212 ui.showStyleButton->setVisible(v.toBool());
216 void InputWidget::setEnablePerChatHistory(const QVariant &v)
218 _perChatHistory = v.toBool();
222 void InputWidget::setMaxLines(const QVariant &v)
224 ui.inputEdit->setMaxHeight(v.toInt());
228 void InputWidget::setScrollBarsEnabled(const QVariant &v)
230 ui.inputEdit->setScrollBarsEnabled(v.toBool());
234 void InputWidget::setLineWrapEnabled(const QVariant &v)
236 ui.inputEdit->setLineWrapEnabled(v.toBool());
240 void InputWidget::setMultiLineEnabled(const QVariant &v)
242 ui.inputEdit->setMode(v.toBool() ? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
246 bool InputWidget::eventFilter(QObject *watched, QEvent *event)
248 if (event->type() != QEvent::KeyPress)
251 QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
253 // keys from BufferView should be sent to (and focus) the input line
254 BufferView *view = qobject_cast<BufferView *>(watched);
256 if (keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier))) { // normal key press
257 QChar c = keyEvent->text().at(0);
258 if (c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
260 QCoreApplication::sendEvent(inputLine(), keyEvent);
266 else if (watched == ui.inputEdit) {
267 if (keyEvent->matches(QKeySequence::Find)) {
268 QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
280 void InputWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
282 BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
283 BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
285 if (_perChatHistory) {
287 historyMap[previousBufferId].history = inputLine()->history();
288 historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
289 historyMap[previousBufferId].idx = inputLine()->idx();
290 historyMap[previousBufferId].inputLine = inputLine()->html();
293 inputLine()->setHistory(historyMap[currentBufferId].history);
294 inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
295 inputLine()->setIdx(historyMap[currentBufferId].idx);
296 inputLine()->setHtml(historyMap[currentBufferId].inputLine);
297 inputLine()->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
299 // FIXME this really should be in MultiLineEdit (and the const int on top removed)
300 QTextBlockFormat format = inputLine()->textCursor().blockFormat();
301 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
302 inputLine()->textCursor().setBlockFormat(format);
305 NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
306 if (networkId == _networkId)
309 setNetwork(networkId);
310 updateNickSelector();
311 updateEnabledState();
315 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
317 QItemSelectionRange changedArea(topLeft, bottomRight);
318 if (changedArea.contains(selectionModel()->currentIndex())) {
319 updateEnabledState();
321 bool encrypted = false;
323 IrcChannel *chan = qobject_cast<IrcChannel *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcChannelRole).value<QObject *>());
325 encrypted = chan->encrypted();
327 IrcUser *user = qobject_cast<IrcUser *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcUserRole).value<QObject *>());
329 encrypted = user->encrypted();
332 ui.encryptionIconLabel->show();
334 ui.encryptionIconLabel->hide();
339 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
343 for (int row = start; row <= end; row++) {
344 child = model()->index(row, 0, parent);
345 if (NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
347 networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
348 if (networkId == _networkId) {
350 updateNickSelector();
357 void InputWidget::updateEnabledState()
359 // FIXME: Find a visualization for this that does not disable the widget!
360 // Disabling kills global action shortcuts, plus users sometimes need/want to enter text
361 // even in inactive channels.
363 QModelIndex currentIndex = selectionModel()->currentIndex();
365 const Network *net = Client::networkModel()->networkByIndex(currentIndex);
366 bool enabled = false;
368 // disable inputline if it's a channelbuffer we parted from or...
369 enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
370 // ... if we're not connected to the network at all
371 enabled &= net->isConnected();
374 ui.inputEdit->setEnabled(enabled);
379 const Network *InputWidget::currentNetwork() const
381 return Client::network(_networkId);
385 BufferInfo InputWidget::currentBufferInfo() const
387 return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
391 void InputWidget::applyFormatActiveColor()
393 if (!ui.textcolorButton->defaultAction()) {
396 colorChosen(ui.textcolorButton->defaultAction());
400 void InputWidget::applyFormatActiveColorFill()
402 if (!ui.highlightcolorButton->defaultAction()) {
405 colorHighlightChosen(ui.highlightcolorButton->defaultAction());
409 void InputWidget::toggleFormatBold()
411 setFormatBold(!ui.boldButton->isChecked());
415 void InputWidget::toggleFormatItalic()
417 setFormatItalic(!ui.italicButton->isChecked());
421 void InputWidget::toggleFormatUnderline()
423 setFormatUnderline(!ui.underlineButton->isChecked());
427 void InputWidget::clearFormat()
429 // Clear all formatting for selection (not global)
430 setFormatClear(false);
434 void InputWidget::setNetwork(NetworkId networkId)
436 if (_networkId == networkId)
439 const Network *previousNet = Client::network(_networkId);
441 disconnect(previousNet, 0, this, 0);
442 if (previousNet->me())
443 disconnect(previousNet->me(), 0, this, 0);
446 _networkId = networkId;
448 const Network *network = Client::network(networkId);
450 connect(network, SIGNAL(identitySet(IdentityId)), this, SLOT(setIdentity(IdentityId)));
452 setIdentity(network->identity());
461 void InputWidget::connectMyIrcUser()
463 const Network *network = currentNetwork();
465 connect(network->me(), SIGNAL(nickSet(const QString &)), this, SLOT(updateNickSelector()));
466 connect(network->me(), SIGNAL(userModesSet(QString)), this, SLOT(updateNickSelector()));
467 connect(network->me(), SIGNAL(userModesAdded(QString)), this, SLOT(updateNickSelector()));
468 connect(network->me(), SIGNAL(userModesRemoved(QString)), this, SLOT(updateNickSelector()));
469 connect(network->me(), SIGNAL(awaySet(bool)), this, SLOT(updateNickSelector()));
470 disconnect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
471 updateNickSelector();
474 connect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
479 void InputWidget::setIdentity(IdentityId identityId)
481 if (_identityId == identityId)
484 const Identity *previousIdentity = Client::identity(_identityId);
485 if (previousIdentity)
486 disconnect(previousIdentity, 0, this, 0);
488 _identityId = identityId;
490 const Identity *identity = Client::identity(identityId);
492 connect(identity, SIGNAL(nicksSet(QStringList)), this, SLOT(updateNickSelector()));
497 updateNickSelector();
501 void InputWidget::updateNickSelector() const
505 const Network *net = currentNetwork();
509 const Identity *identity = Client::identity(net->identity());
511 qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
516 QStringList nicks = identity->nicks();
517 if ((nickIdx = nicks.indexOf(net->myNick())) == -1) {
518 nicks.prepend(net->myNick());
525 IrcUser *me = net->me();
527 nicks[nickIdx] = net->myNick();
528 if (!me->userModes().isEmpty())
529 nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
532 ui.ownNick->addItems(nicks);
534 if (me && me->isAway())
535 ui.ownNick->setItemData(nickIdx, icon::get({"im-user-away", "user-away"}), Qt::DecorationRole);
537 ui.ownNick->setCurrentIndex(nickIdx);
541 void InputWidget::changeNick(const QString &newNick) const
543 const Network *net = currentNetwork();
544 if (!net || net->isMyNick(newNick))
547 // we reset the nick selecter as we have no confirmation yet, that this will succeed.
548 // if the action succeeds it will be properly updated anyways.
549 updateNickSelector();
550 Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
554 void InputWidget::onTextEntered(const QString &text)
556 Client::userInput(currentBufferInfo(), text);
558 // Remove formatting from entered text
559 // TODO: Offer a way to convert pasted text to mIRC formatting codes
560 setFormatClear(true);
564 void InputWidget::setFormatClear(const bool global)
568 fmt.setFontWeight(QFont::Normal);
569 fmt.setFontUnderline(false);
570 fmt.setFontItalic(false);
571 fmt.clearForeground();
572 fmt.clearBackground();
574 inputLine()->setCurrentCharFormat(fmt);
576 setFormatOnSelection(fmt);
579 // Make sure UI state follows
580 ui.boldButton->setChecked(false);
581 ui.italicButton->setChecked(false);
582 ui.underlineButton->setChecked(false);
586 void InputWidget::setFormatBold(const bool bold)
590 fmt.setFontWeight(bold ? QFont::Bold : QFont::Normal);
591 mergeFormatOnSelection(fmt);
592 // Make sure UI state follows
593 ui.boldButton->setChecked(bold);
597 void InputWidget::setFormatItalic(const bool italic)
601 fmt.setFontItalic(italic);
602 mergeFormatOnSelection(fmt);
603 // Make sure UI state follows
604 ui.italicButton->setChecked(italic);
608 void InputWidget::setFormatUnderline(const bool underline)
612 fmt.setFontUnderline(underline);
613 mergeFormatOnSelection(fmt);
614 // Make sure UI state follows
615 ui.underlineButton->setChecked(underline);
619 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format)
621 QTextCursor cursor = inputLine()->textCursor();
622 cursor.mergeCharFormat(format);
623 inputLine()->mergeCurrentCharFormat(format);
627 void InputWidget::setFormatOnSelection(const QTextCharFormat &format)
629 QTextCursor cursor = inputLine()->textCursor();
630 cursor.setCharFormat(format);
631 inputLine()->setCurrentCharFormat(format);
635 QTextCharFormat InputWidget::getFormatOfWordOrSelection()
637 QTextCursor cursor = inputLine()->textCursor();
638 return cursor.charFormat();
642 void InputWidget::setStyleOptionsExpanded(bool expanded)
644 ui.styleFrame->setVisible(expanded);
646 ui.showStyleButton->setArrowType(Qt::LeftArrow);
647 ui.showStyleButton->setToolTip(tr("Hide formatting options"));
649 ui.showStyleButton->setArrowType(Qt::RightArrow);
650 ui.showStyleButton->setToolTip(tr("Show formatting options"));
655 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format)
657 fontChanged(format.font());
661 void InputWidget::on_boldButton_clicked(bool checked)
663 setFormatBold(checked);
667 void InputWidget::on_underlineButton_clicked(bool checked)
669 setFormatUnderline(checked);
673 void InputWidget::on_italicButton_clicked(bool checked)
675 setFormatItalic(checked);
679 void InputWidget::fontChanged(const QFont &f)
681 ui.boldButton->setChecked(f.bold());
682 ui.italicButton->setChecked(f.italic());
683 ui.underlineButton->setChecked(f.underline());
687 void InputWidget::colorChosen(QAction *action)
691 if (action->data().value<QString>() == "") {
692 color = Qt::transparent;
693 fmt = getFormatOfWordOrSelection();
694 fmt.clearForeground();
695 setFormatOnSelection(fmt);
698 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
699 fmt.setForeground(color);
700 mergeFormatOnSelection(fmt);
702 ui.textcolorButton->setDefaultAction(action);
703 ui.textcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-text-color"), color));
707 void InputWidget::colorHighlightChosen(QAction *action)
711 if (action->data().value<QString>() == "") {
712 color = Qt::transparent;
713 fmt = getFormatOfWordOrSelection();
714 fmt.clearBackground();
715 setFormatOnSelection(fmt);
718 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
719 fmt.setBackground(color);
720 mergeFormatOnSelection(fmt);
722 ui.highlightcolorButton->setDefaultAction(action);
723 ui.highlightcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-fill-color"), color));
727 void InputWidget::on_showStyleButton_toggled(bool checked)
729 setStyleOptionsExpanded(checked);
733 QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color)
735 QPixmap pixmap(16, 16);
736 pixmap.fill(Qt::transparent);
737 QPainter painter(&pixmap);
738 QPixmap image = icon.pixmap(16, 16);
739 QRect target(0, 0, 16, 14);
740 QRect source(0, 0, 16, 14);
741 painter.fillRect(QRect(0, 14, 16, 16), color);
742 painter.drawPixmap(target, image, source);
744 return QIcon(pixmap);
748 // MOUSE WHEEL FILTER
749 MouseWheelFilter::MouseWheelFilter(QObject *parent)
755 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event)
757 if (event->type() != QEvent::Wheel)
758 return QObject::eventFilter(obj, event);