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");
121 s.notify("EnableEmacsMode", this, SLOT(setEnableEmacsMode(QVariant)));
122 setEnableEmacsMode(s.value("EnableEmacsMode", false));
124 s.notify("ShowNickSelector", this, SLOT(setShowNickSelector(QVariant)));
125 setShowNickSelector(s.value("ShowNickSelector", true));
127 s.notify("ShowStyleButtons", this, SLOT(setShowStyleButtons(QVariant)));
128 setShowStyleButtons(s.value("ShowStyleButtons", true));
130 s.notify("EnablePerChatHistory", this, SLOT(setEnablePerChatHistory(QVariant)));
131 setEnablePerChatHistory(s.value("EnablePerChatHistory", true));
133 s.notify("MaxNumLines", this, SLOT(setMaxLines(QVariant)));
134 setMaxLines(s.value("MaxNumLines", 5));
136 s.notify("EnableScrollBars", this, SLOT(setScrollBarsEnabled(QVariant)));
137 setScrollBarsEnabled(s.value("EnableScrollBars", true));
139 s.notify("EnableLineWrap", this, SLOT(setLineWrapEnabled(QVariant)));
140 setLineWrapEnabled(s.value("EnableLineWrap", true));
142 s.notify("EnableMultiLine", this, SLOT(setMultiLineEnabled(QVariant)));
143 setMultiLineEnabled(s.value("EnableMultiLine", true));
145 ActionCollection *coll = QtUi::actionCollection();
147 Action *activateInputline = coll->add<Action>("FocusInputLine");
148 connect(activateInputline, SIGNAL(triggered()), SLOT(setFocus()));
149 activateInputline->setText(tr("Focus Input Line"));
150 activateInputline->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_L));
152 connect(inputLine(), SIGNAL(textEntered(QString)), SLOT(onTextEntered(QString)), Qt::QueuedConnection); // make sure the line is already reset, bug #984
153 connect(inputLine(), SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(currentCharFormatChanged(QTextCharFormat)));
157 InputWidget::~InputWidget()
162 void InputWidget::setUseCustomFont(const QVariant &v)
165 UiStyleSettings fs("Fonts");
166 setCustomFont(fs.value("InputWidget"));
169 setCustomFont(QFont());
173 void InputWidget::setCustomFont(const QVariant &v)
175 QFont font = v.value<QFont>();
176 if (font.family().isEmpty())
177 font = QApplication::font();
178 // we don't want font styles as this conflics with mirc code richtext editing
180 font.setItalic(false);
181 font.setUnderline(false);
182 font.setStrikeOut(false);
183 ui.inputEdit->setCustomFont(font);
187 void InputWidget::setEnableEmacsMode(const QVariant &v)
189 ui.inputEdit->setEmacsMode(v.toBool());
193 void InputWidget::setShowNickSelector(const QVariant &v)
195 ui.ownNick->setVisible(v.toBool());
199 void InputWidget::setShowStyleButtons(const QVariant &v)
201 ui.showStyleButton->setVisible(v.toBool());
205 void InputWidget::setEnablePerChatHistory(const QVariant &v)
207 _perChatHistory = v.toBool();
211 void InputWidget::setMaxLines(const QVariant &v)
213 ui.inputEdit->setMaxHeight(v.toInt());
217 void InputWidget::setScrollBarsEnabled(const QVariant &v)
219 ui.inputEdit->setScrollBarsEnabled(v.toBool());
223 void InputWidget::setLineWrapEnabled(const QVariant &v)
225 ui.inputEdit->setLineWrapEnabled(v.toBool());
229 void InputWidget::setMultiLineEnabled(const QVariant &v)
231 ui.inputEdit->setMode(v.toBool() ? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
235 bool InputWidget::eventFilter(QObject *watched, QEvent *event)
237 if (event->type() != QEvent::KeyPress)
240 QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
242 // keys from BufferView should be sent to (and focus) the input line
243 BufferView *view = qobject_cast<BufferView *>(watched);
245 if (keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier))) { // normal key press
246 QChar c = keyEvent->text().at(0);
247 if (c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
249 QCoreApplication::sendEvent(inputLine(), keyEvent);
255 else if (watched == ui.inputEdit) {
256 if (keyEvent->matches(QKeySequence::Find)) {
257 QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
269 void InputWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
271 BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
272 BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
274 if (_perChatHistory) {
276 historyMap[previousBufferId].history = inputLine()->history();
277 historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
278 historyMap[previousBufferId].idx = inputLine()->idx();
279 historyMap[previousBufferId].inputLine = inputLine()->html();
282 inputLine()->setHistory(historyMap[currentBufferId].history);
283 inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
284 inputLine()->setIdx(historyMap[currentBufferId].idx);
285 inputLine()->setHtml(historyMap[currentBufferId].inputLine);
286 inputLine()->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
288 // FIXME this really should be in MultiLineEdit (and the const int on top removed)
289 QTextBlockFormat format = inputLine()->textCursor().blockFormat();
290 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
291 inputLine()->textCursor().setBlockFormat(format);
294 NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
295 if (networkId == _networkId)
298 setNetwork(networkId);
299 updateNickSelector();
300 updateEnabledState();
304 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
306 QItemSelectionRange changedArea(topLeft, bottomRight);
307 if (changedArea.contains(selectionModel()->currentIndex())) {
308 updateEnabledState();
310 bool encrypted = false;
312 IrcChannel *chan = qobject_cast<IrcChannel *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcChannelRole).value<QObject *>());
314 encrypted = chan->encrypted();
316 IrcUser *user = qobject_cast<IrcUser *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcUserRole).value<QObject *>());
318 encrypted = user->encrypted();
321 ui.encryptionIconLabel->show();
323 ui.encryptionIconLabel->hide();
328 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
332 for (int row = start; row <= end; row++) {
333 child = model()->index(row, 0, parent);
334 if (NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
336 networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
337 if (networkId == _networkId) {
339 updateNickSelector();
346 void InputWidget::updateEnabledState()
348 // FIXME: Find a visualization for this that does not disable the widget!
349 // Disabling kills global action shortcuts, plus users sometimes need/want to enter text
350 // even in inactive channels.
352 QModelIndex currentIndex = selectionModel()->currentIndex();
354 const Network *net = Client::networkModel()->networkByIndex(currentIndex);
355 bool enabled = false;
357 // disable inputline if it's a channelbuffer we parted from or...
358 enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
359 // ... if we're not connected to the network at all
360 enabled &= net->isConnected();
363 ui.inputEdit->setEnabled(enabled);
368 const Network *InputWidget::currentNetwork() const
370 return Client::network(_networkId);
374 BufferInfo InputWidget::currentBufferInfo() const
376 return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
380 void InputWidget::applyFormatActiveColor()
382 if (!ui.textcolorButton->defaultAction()) {
385 colorChosen(ui.textcolorButton->defaultAction());
389 void InputWidget::applyFormatActiveColorFill()
391 if (!ui.highlightcolorButton->defaultAction()) {
394 colorHighlightChosen(ui.highlightcolorButton->defaultAction());
398 void InputWidget::toggleFormatBold()
400 setFormatBold(!ui.boldButton->isChecked());
404 void InputWidget::toggleFormatItalic()
406 setFormatItalic(!ui.italicButton->isChecked());
410 void InputWidget::toggleFormatUnderline()
412 setFormatUnderline(!ui.underlineButton->isChecked());
416 void InputWidget::clearFormat()
418 // Clear all formatting for selection (not global)
419 setFormatClear(false);
423 void InputWidget::setNetwork(NetworkId networkId)
425 if (_networkId == networkId)
428 const Network *previousNet = Client::network(_networkId);
430 disconnect(previousNet, 0, this, 0);
431 if (previousNet->me())
432 disconnect(previousNet->me(), 0, this, 0);
435 _networkId = networkId;
437 const Network *network = Client::network(networkId);
439 connect(network, SIGNAL(identitySet(IdentityId)), this, SLOT(setIdentity(IdentityId)));
441 setIdentity(network->identity());
450 void InputWidget::connectMyIrcUser()
452 const Network *network = currentNetwork();
454 connect(network->me(), SIGNAL(nickSet(const QString &)), this, SLOT(updateNickSelector()));
455 connect(network->me(), SIGNAL(userModesSet(QString)), this, SLOT(updateNickSelector()));
456 connect(network->me(), SIGNAL(userModesAdded(QString)), this, SLOT(updateNickSelector()));
457 connect(network->me(), SIGNAL(userModesRemoved(QString)), this, SLOT(updateNickSelector()));
458 connect(network->me(), SIGNAL(awaySet(bool)), this, SLOT(updateNickSelector()));
459 disconnect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
460 updateNickSelector();
463 connect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
468 void InputWidget::setIdentity(IdentityId identityId)
470 if (_identityId == identityId)
473 const Identity *previousIdentity = Client::identity(_identityId);
474 if (previousIdentity)
475 disconnect(previousIdentity, 0, this, 0);
477 _identityId = identityId;
479 const Identity *identity = Client::identity(identityId);
481 connect(identity, SIGNAL(nicksSet(QStringList)), this, SLOT(updateNickSelector()));
486 updateNickSelector();
490 void InputWidget::updateNickSelector() const
494 const Network *net = currentNetwork();
498 const Identity *identity = Client::identity(net->identity());
500 qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
505 QStringList nicks = identity->nicks();
506 if ((nickIdx = nicks.indexOf(net->myNick())) == -1) {
507 nicks.prepend(net->myNick());
514 IrcUser *me = net->me();
516 nicks[nickIdx] = net->myNick();
517 if (!me->userModes().isEmpty())
518 nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
521 ui.ownNick->addItems(nicks);
523 if (me && me->isAway())
524 ui.ownNick->setItemData(nickIdx, icon::get({"im-user-away", "user-away"}), Qt::DecorationRole);
526 ui.ownNick->setCurrentIndex(nickIdx);
530 void InputWidget::changeNick(const QString &newNick) const
532 const Network *net = currentNetwork();
533 if (!net || net->isMyNick(newNick))
536 // we reset the nick selecter as we have no confirmation yet, that this will succeed.
537 // if the action succeeds it will be properly updated anyways.
538 updateNickSelector();
539 Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
543 void InputWidget::onTextEntered(const QString &text)
545 Client::userInput(currentBufferInfo(), text);
547 // Remove formatting from entered text
548 // TODO: Offer a way to convert pasted text to mIRC formatting codes
549 setFormatClear(true);
553 void InputWidget::setFormatClear(const bool global)
557 fmt.setFontWeight(QFont::Normal);
558 fmt.setFontUnderline(false);
559 fmt.setFontItalic(false);
560 fmt.clearForeground();
561 fmt.clearBackground();
563 inputLine()->setCurrentCharFormat(fmt);
565 setFormatOnSelection(fmt);
568 // Make sure UI state follows
569 ui.boldButton->setChecked(false);
570 ui.italicButton->setChecked(false);
571 ui.underlineButton->setChecked(false);
575 void InputWidget::setFormatBold(const bool bold)
579 fmt.setFontWeight(bold ? QFont::Bold : QFont::Normal);
580 mergeFormatOnSelection(fmt);
581 // Make sure UI state follows
582 ui.boldButton->setChecked(bold);
586 void InputWidget::setFormatItalic(const bool italic)
590 fmt.setFontItalic(italic);
591 mergeFormatOnSelection(fmt);
592 // Make sure UI state follows
593 ui.italicButton->setChecked(italic);
597 void InputWidget::setFormatUnderline(const bool underline)
601 fmt.setFontUnderline(underline);
602 mergeFormatOnSelection(fmt);
603 // Make sure UI state follows
604 ui.underlineButton->setChecked(underline);
608 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format)
610 QTextCursor cursor = inputLine()->textCursor();
611 cursor.mergeCharFormat(format);
612 inputLine()->mergeCurrentCharFormat(format);
616 void InputWidget::setFormatOnSelection(const QTextCharFormat &format)
618 QTextCursor cursor = inputLine()->textCursor();
619 cursor.setCharFormat(format);
620 inputLine()->setCurrentCharFormat(format);
624 QTextCharFormat InputWidget::getFormatOfWordOrSelection()
626 QTextCursor cursor = inputLine()->textCursor();
627 return cursor.charFormat();
631 void InputWidget::setStyleOptionsExpanded(bool expanded)
633 ui.styleFrame->setVisible(expanded);
635 ui.showStyleButton->setArrowType(Qt::LeftArrow);
636 ui.showStyleButton->setToolTip(tr("Hide formatting options"));
638 ui.showStyleButton->setArrowType(Qt::RightArrow);
639 ui.showStyleButton->setToolTip(tr("Show formatting options"));
644 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format)
646 fontChanged(format.font());
650 void InputWidget::on_boldButton_clicked(bool checked)
652 setFormatBold(checked);
656 void InputWidget::on_underlineButton_clicked(bool checked)
658 setFormatUnderline(checked);
662 void InputWidget::on_italicButton_clicked(bool checked)
664 setFormatItalic(checked);
668 void InputWidget::fontChanged(const QFont &f)
670 ui.boldButton->setChecked(f.bold());
671 ui.italicButton->setChecked(f.italic());
672 ui.underlineButton->setChecked(f.underline());
676 void InputWidget::colorChosen(QAction *action)
680 if (action->data().value<QString>() == "") {
681 color = Qt::transparent;
682 fmt = getFormatOfWordOrSelection();
683 fmt.clearForeground();
684 setFormatOnSelection(fmt);
687 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
688 fmt.setForeground(color);
689 mergeFormatOnSelection(fmt);
691 ui.textcolorButton->setDefaultAction(action);
692 ui.textcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-text-color"), color));
696 void InputWidget::colorHighlightChosen(QAction *action)
700 if (action->data().value<QString>() == "") {
701 color = Qt::transparent;
702 fmt = getFormatOfWordOrSelection();
703 fmt.clearBackground();
704 setFormatOnSelection(fmt);
707 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
708 fmt.setBackground(color);
709 mergeFormatOnSelection(fmt);
711 ui.highlightcolorButton->setDefaultAction(action);
712 ui.highlightcolorButton->setIcon(createColorToolButtonIcon(icon::get("format-fill-color"), color));
716 void InputWidget::on_showStyleButton_toggled(bool checked)
718 setStyleOptionsExpanded(checked);
722 QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color)
724 QPixmap pixmap(16, 16);
725 pixmap.fill(Qt::transparent);
726 QPainter painter(&pixmap);
727 QPixmap image = icon.pixmap(16, 16);
728 QRect target(0, 0, 16, 14);
729 QRect source(0, 0, 16, 14);
730 painter.fillRect(QRect(0, 14, 16, 16), color);
731 painter.drawPixmap(target, image, source);
733 return QIcon(pixmap);
737 // MOUSE WHEEL FILTER
738 MouseWheelFilter::MouseWheelFilter(QObject *parent)
744 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event)
746 if (event->type() != QEvent::Wheel)
747 return QObject::eventFilter(obj, event);