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"
26 #include "actioncollection.h"
27 #include "bufferview.h"
30 #include "networkmodel.h"
32 #include "qtuisettings.h"
33 #include "tabcompleter.h"
36 const int leftMargin = 3;
38 InputWidget::InputWidget(QWidget *parent)
39 : AbstractItemView(parent),
43 connect(ui.ownNick, SIGNAL(activated(QString)), this, SLOT(changeNick(QString)));
45 layout()->setAlignment(ui.ownNick, Qt::AlignBottom);
46 layout()->setAlignment(ui.inputEdit, Qt::AlignBottom);
47 layout()->setAlignment(ui.showStyleButton, Qt::AlignBottom);
48 layout()->setAlignment(ui.styleFrame, Qt::AlignBottom);
50 setStyleOptionsExpanded(false);
52 setFocusProxy(ui.inputEdit);
53 ui.ownNick->setFocusProxy(ui.inputEdit);
55 ui.ownNick->setSizeAdjustPolicy(QComboBox::AdjustToContents);
56 ui.ownNick->installEventFilter(new MouseWheelFilter(this));
57 ui.inputEdit->installEventFilter(this);
59 ui.inputEdit->setMinHeight(1);
60 ui.inputEdit->setMaxHeight(5);
61 ui.inputEdit->setMode(MultiLineEdit::MultiLine);
62 ui.inputEdit->setPasteProtectionEnabled(true);
64 ui.boldButton->setIcon(QIcon::fromTheme("format-text-bold"));
65 ui.italicButton->setIcon(QIcon::fromTheme("format-text-italic"));
66 ui.underlineButton->setIcon(QIcon::fromTheme("format-text-underline"));
67 ui.clearButton->setIcon(QIcon::fromTheme("edit-clear"));
68 ui.encryptionIconLabel->hide();
70 _colorMenu = new QMenu();
71 _colorFillMenu = new QMenu();
74 names << tr("White") << tr("Black") << tr("Dark blue") << tr("Dark green") << tr("Red") << tr("Dark red") << tr("Dark magenta") << tr("Orange")
75 << tr("Yellow") << tr("Green") << tr("Dark cyan") << tr("Cyan") << tr("Blue") << tr("Magenta") << tr("Dark gray") << tr("Light gray");
78 for (int i = 0; i < inputLine()->mircColorMap().count(); i++) {
79 pix.fill(inputLine()->mircColorMap().values()[i]);
80 _colorMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
81 _colorFillMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
84 pix.fill(Qt::transparent);
85 _colorMenu->addAction(pix, tr("Clear Color"))->setData("");
86 _colorFillMenu->addAction(pix, tr("Clear Color"))->setData("");
88 ui.textcolorButton->setMenu(_colorMenu);
89 // Set the default action to clear color (last added action)
90 ui.textcolorButton->setDefaultAction(_colorMenu->actions().last());
91 connect(_colorMenu, SIGNAL(triggered(QAction *)), this, SLOT(colorChosen(QAction *)));
93 ui.highlightcolorButton->setMenu(_colorFillMenu);
94 // Set the default action to clear fill color (last added action)
95 ui.highlightcolorButton->setDefaultAction(_colorFillMenu->actions().last());
96 connect(_colorFillMenu, SIGNAL(triggered(QAction *)), this, SLOT(colorHighlightChosen(QAction *)));
98 // Needs to be done after adding the menu, otherwise the icon mysteriously vanishes until clicked
99 ui.textcolorButton->setIcon(QIcon::fromTheme("format-text-color"));
100 ui.highlightcolorButton->setIcon(QIcon::fromTheme("format-fill-color"));
102 // Show/hide style button
103 connect(ui.showStyleButton, SIGNAL(toggled(bool)), this, SLOT(setStyleOptionsExpanded(bool)));
105 // Clear formatting button
106 connect(ui.clearButton, SIGNAL(clicked()), this, SLOT(clearFormat()));
108 new TabCompleter(ui.inputEdit);
110 UiStyleSettings fs("Fonts");
111 fs.notify("UseCustomInputWidgetFont", this, SLOT(setUseCustomFont(QVariant)));
112 fs.notify("InputWidget", this, SLOT(setCustomFont(QVariant)));
113 if (fs.value("UseCustomInputWidgetFont", false).toBool())
114 setCustomFont(fs.value("InputWidget", QFont()));
116 UiSettings s("InputWidget");
119 s.notify("EnableSpellCheck", this, SLOT(setEnableSpellCheck(QVariant)));
120 setEnableSpellCheck(s.value("EnableSpellCheck", false));
123 s.notify("EnableEmacsMode", this, SLOT(setEnableEmacsMode(QVariant)));
124 setEnableEmacsMode(s.value("EnableEmacsMode", false));
126 s.notify("ShowNickSelector", this, SLOT(setShowNickSelector(QVariant)));
127 setShowNickSelector(s.value("ShowNickSelector", true));
129 s.notify("ShowStyleButtons", this, SLOT(setShowStyleButtons(QVariant)));
130 setShowStyleButtons(s.value("ShowStyleButtons", true));
132 s.notify("EnablePerChatHistory", this, SLOT(setEnablePerChatHistory(QVariant)));
133 setEnablePerChatHistory(s.value("EnablePerChatHistory", true));
135 s.notify("MaxNumLines", this, SLOT(setMaxLines(QVariant)));
136 setMaxLines(s.value("MaxNumLines", 5));
138 s.notify("EnableScrollBars", this, SLOT(setScrollBarsEnabled(QVariant)));
139 setScrollBarsEnabled(s.value("EnableScrollBars", true));
141 s.notify("EnableLineWrap", this, SLOT(setLineWrapEnabled(QVariant)));
142 setLineWrapEnabled(s.value("EnableLineWrap", true));
144 s.notify("EnableMultiLine", this, SLOT(setMultiLineEnabled(QVariant)));
145 setMultiLineEnabled(s.value("EnableMultiLine", true));
147 ActionCollection *coll = QtUi::actionCollection();
149 Action *activateInputline = coll->add<Action>("FocusInputLine");
150 connect(activateInputline, SIGNAL(triggered()), SLOT(setFocus()));
151 activateInputline->setText(tr("Focus Input Line"));
152 activateInputline->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_L));
154 connect(inputLine(), SIGNAL(textEntered(QString)), SLOT(onTextEntered(QString)), Qt::QueuedConnection); // make sure the line is already reset, bug #984
155 connect(inputLine(), SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(currentCharFormatChanged(QTextCharFormat)));
159 InputWidget::~InputWidget()
164 void InputWidget::setUseCustomFont(const QVariant &v)
167 UiStyleSettings fs("Fonts");
168 setCustomFont(fs.value("InputWidget"));
171 setCustomFont(QFont());
175 void InputWidget::setCustomFont(const QVariant &v)
177 QFont font = v.value<QFont>();
178 if (font.family().isEmpty())
179 font = QApplication::font();
180 // we don't want font styles as this conflics with mirc code richtext editing
182 font.setItalic(false);
183 font.setUnderline(false);
184 font.setStrikeOut(false);
185 ui.inputEdit->setCustomFont(font);
189 void InputWidget::setEnableSpellCheck(const QVariant &v)
191 ui.inputEdit->setSpellCheckEnabled(v.toBool());
195 void InputWidget::setEnableEmacsMode(const QVariant &v)
197 ui.inputEdit->setEmacsMode(v.toBool());
201 void InputWidget::setShowNickSelector(const QVariant &v)
203 ui.ownNick->setVisible(v.toBool());
207 void InputWidget::setShowStyleButtons(const QVariant &v)
209 ui.showStyleButton->setVisible(v.toBool());
213 void InputWidget::setEnablePerChatHistory(const QVariant &v)
215 _perChatHistory = v.toBool();
219 void InputWidget::setMaxLines(const QVariant &v)
221 ui.inputEdit->setMaxHeight(v.toInt());
225 void InputWidget::setScrollBarsEnabled(const QVariant &v)
227 ui.inputEdit->setScrollBarsEnabled(v.toBool());
231 void InputWidget::setLineWrapEnabled(const QVariant &v)
233 ui.inputEdit->setLineWrapEnabled(v.toBool());
237 void InputWidget::setMultiLineEnabled(const QVariant &v)
239 ui.inputEdit->setMode(v.toBool() ? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
243 bool InputWidget::eventFilter(QObject *watched, QEvent *event)
245 if (event->type() != QEvent::KeyPress)
248 QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
250 // keys from BufferView should be sent to (and focus) the input line
251 BufferView *view = qobject_cast<BufferView *>(watched);
253 if (keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier))) { // normal key press
254 QChar c = keyEvent->text().at(0);
255 if (c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
257 QCoreApplication::sendEvent(inputLine(), keyEvent);
263 else if (watched == ui.inputEdit) {
264 if (keyEvent->matches(QKeySequence::Find)) {
265 QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
277 void InputWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
279 BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
280 BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
282 if (_perChatHistory) {
284 historyMap[previousBufferId].history = inputLine()->history();
285 historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
286 historyMap[previousBufferId].idx = inputLine()->idx();
287 historyMap[previousBufferId].inputLine = inputLine()->html();
290 inputLine()->setHistory(historyMap[currentBufferId].history);
291 inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
292 inputLine()->setIdx(historyMap[currentBufferId].idx);
293 inputLine()->setHtml(historyMap[currentBufferId].inputLine);
294 inputLine()->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
296 // FIXME this really should be in MultiLineEdit (and the const int on top removed)
297 QTextBlockFormat format = inputLine()->textCursor().blockFormat();
298 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
299 inputLine()->textCursor().setBlockFormat(format);
302 NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
303 if (networkId == _networkId)
306 setNetwork(networkId);
307 updateNickSelector();
308 updateEnabledState();
312 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
314 QItemSelectionRange changedArea(topLeft, bottomRight);
315 if (changedArea.contains(selectionModel()->currentIndex())) {
316 updateEnabledState();
318 bool encrypted = false;
320 IrcChannel *chan = qobject_cast<IrcChannel *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcChannelRole).value<QObject *>());
322 encrypted = chan->encrypted();
324 IrcUser *user = qobject_cast<IrcUser *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcUserRole).value<QObject *>());
326 encrypted = user->encrypted();
329 ui.encryptionIconLabel->show();
331 ui.encryptionIconLabel->hide();
336 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
340 for (int row = start; row <= end; row++) {
341 child = model()->index(row, 0, parent);
342 if (NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
344 networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
345 if (networkId == _networkId) {
347 updateNickSelector();
354 void InputWidget::updateEnabledState()
356 // FIXME: Find a visualization for this that does not disable the widget!
357 // Disabling kills global action shortcuts, plus users sometimes need/want to enter text
358 // even in inactive channels.
360 QModelIndex currentIndex = selectionModel()->currentIndex();
362 const Network *net = Client::networkModel()->networkByIndex(currentIndex);
363 bool enabled = false;
365 // disable inputline if it's a channelbuffer we parted from or...
366 enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
367 // ... if we're not connected to the network at all
368 enabled &= net->isConnected();
371 ui.inputEdit->setEnabled(enabled);
376 const Network *InputWidget::currentNetwork() const
378 return Client::network(_networkId);
382 BufferInfo InputWidget::currentBufferInfo() const
384 return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
388 void InputWidget::applyFormatActiveColor()
390 if (!ui.textcolorButton->defaultAction()) {
393 colorChosen(ui.textcolorButton->defaultAction());
397 void InputWidget::applyFormatActiveColorFill()
399 if (!ui.highlightcolorButton->defaultAction()) {
402 colorHighlightChosen(ui.highlightcolorButton->defaultAction());
406 void InputWidget::toggleFormatBold()
408 setFormatBold(!ui.boldButton->isChecked());
412 void InputWidget::toggleFormatItalic()
414 setFormatItalic(!ui.italicButton->isChecked());
418 void InputWidget::toggleFormatUnderline()
420 setFormatUnderline(!ui.underlineButton->isChecked());
424 void InputWidget::clearFormat()
426 // Clear all formatting for selection (not global)
427 setFormatClear(false);
431 void InputWidget::setNetwork(NetworkId networkId)
433 if (_networkId == networkId)
436 const Network *previousNet = Client::network(_networkId);
438 disconnect(previousNet, 0, this, 0);
439 if (previousNet->me())
440 disconnect(previousNet->me(), 0, this, 0);
443 _networkId = networkId;
445 const Network *network = Client::network(networkId);
447 connect(network, SIGNAL(identitySet(IdentityId)), this, SLOT(setIdentity(IdentityId)));
449 setIdentity(network->identity());
458 void InputWidget::connectMyIrcUser()
460 const Network *network = currentNetwork();
462 connect(network->me(), SIGNAL(nickSet(const QString &)), this, SLOT(updateNickSelector()));
463 connect(network->me(), SIGNAL(userModesSet(QString)), this, SLOT(updateNickSelector()));
464 connect(network->me(), SIGNAL(userModesAdded(QString)), this, SLOT(updateNickSelector()));
465 connect(network->me(), SIGNAL(userModesRemoved(QString)), this, SLOT(updateNickSelector()));
466 connect(network->me(), SIGNAL(awaySet(bool)), this, SLOT(updateNickSelector()));
467 disconnect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
468 updateNickSelector();
471 connect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
476 void InputWidget::setIdentity(IdentityId identityId)
478 if (_identityId == identityId)
481 const Identity *previousIdentity = Client::identity(_identityId);
482 if (previousIdentity)
483 disconnect(previousIdentity, 0, this, 0);
485 _identityId = identityId;
487 const Identity *identity = Client::identity(identityId);
489 connect(identity, SIGNAL(nicksSet(QStringList)), this, SLOT(updateNickSelector()));
494 updateNickSelector();
498 void InputWidget::updateNickSelector() const
502 const Network *net = currentNetwork();
506 const Identity *identity = Client::identity(net->identity());
508 qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
513 QStringList nicks = identity->nicks();
514 if ((nickIdx = nicks.indexOf(net->myNick())) == -1) {
515 nicks.prepend(net->myNick());
522 IrcUser *me = net->me();
524 nicks[nickIdx] = net->myNick();
525 if (!me->userModes().isEmpty())
526 nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
529 ui.ownNick->addItems(nicks);
531 if (me && me->isAway())
532 ui.ownNick->setItemData(nickIdx, QIcon::fromTheme("user-away"), Qt::DecorationRole);
534 ui.ownNick->setCurrentIndex(nickIdx);
538 void InputWidget::changeNick(const QString &newNick) const
540 const Network *net = currentNetwork();
541 if (!net || net->isMyNick(newNick))
544 // we reset the nick selecter as we have no confirmation yet, that this will succeed.
545 // if the action succeeds it will be properly updated anyways.
546 updateNickSelector();
547 Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
551 void InputWidget::onTextEntered(const QString &text)
553 Client::userInput(currentBufferInfo(), text);
554 ui.boldButton->setChecked(false);
555 ui.underlineButton->setChecked(false);
556 ui.italicButton->setChecked(false);
558 setFormatClear(true);
562 void InputWidget::setFormatClear(const bool global)
565 fmt.setFontWeight(QFont::Normal);
566 fmt.setFontUnderline(false);
567 fmt.setFontItalic(false);
568 fmt.clearForeground();
569 fmt.clearBackground();
571 inputLine()->setCurrentCharFormat(fmt);
573 setFormatOnSelection(fmt);
578 void InputWidget::setFormatBold(const bool bold)
581 fmt.setFontWeight(bold ? QFont::Bold : QFont::Normal);
582 mergeFormatOnSelection(fmt);
586 void InputWidget::setFormatItalic(const bool italic)
589 fmt.setFontItalic(italic);
590 mergeFormatOnSelection(fmt);
594 void InputWidget::setFormatUnderline(const bool underline)
597 fmt.setFontUnderline(underline);
598 mergeFormatOnSelection(fmt);
602 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format)
604 QTextCursor cursor = inputLine()->textCursor();
605 cursor.mergeCharFormat(format);
606 inputLine()->mergeCurrentCharFormat(format);
610 void InputWidget::setFormatOnSelection(const QTextCharFormat &format)
612 QTextCursor cursor = inputLine()->textCursor();
613 cursor.setCharFormat(format);
614 inputLine()->setCurrentCharFormat(format);
618 QTextCharFormat InputWidget::getFormatOfWordOrSelection()
620 QTextCursor cursor = inputLine()->textCursor();
621 return cursor.charFormat();
625 void InputWidget::setStyleOptionsExpanded(bool expanded)
627 ui.styleFrame->setVisible(expanded);
629 ui.showStyleButton->setArrowType(Qt::LeftArrow);
630 ui.showStyleButton->setToolTip(tr("Hide formatting options"));
632 ui.showStyleButton->setArrowType(Qt::RightArrow);
633 ui.showStyleButton->setToolTip(tr("Show formatting options"));
638 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format)
640 fontChanged(format.font());
644 void InputWidget::on_boldButton_clicked(bool checked)
646 setFormatBold(checked);
650 void InputWidget::on_underlineButton_clicked(bool checked)
652 setFormatUnderline(checked);
656 void InputWidget::on_italicButton_clicked(bool checked)
658 setFormatItalic(checked);
662 void InputWidget::fontChanged(const QFont &f)
664 ui.boldButton->setChecked(f.bold());
665 ui.italicButton->setChecked(f.italic());
666 ui.underlineButton->setChecked(f.underline());
670 void InputWidget::colorChosen(QAction *action)
674 if (action->data().value<QString>() == "") {
675 color = Qt::transparent;
676 fmt = getFormatOfWordOrSelection();
677 fmt.clearForeground();
678 setFormatOnSelection(fmt);
681 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
682 fmt.setForeground(color);
683 mergeFormatOnSelection(fmt);
685 ui.textcolorButton->setDefaultAction(action);
686 ui.textcolorButton->setIcon(createColorToolButtonIcon(QIcon::fromTheme("format-text-color"), color));
690 void InputWidget::colorHighlightChosen(QAction *action)
694 if (action->data().value<QString>() == "") {
695 color = Qt::transparent;
696 fmt = getFormatOfWordOrSelection();
697 fmt.clearBackground();
698 setFormatOnSelection(fmt);
701 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
702 fmt.setBackground(color);
703 mergeFormatOnSelection(fmt);
705 ui.highlightcolorButton->setDefaultAction(action);
706 ui.highlightcolorButton->setIcon(createColorToolButtonIcon(QIcon::fromTheme("format-fill-color"), color));
710 void InputWidget::on_showStyleButton_toggled(bool checked)
712 setStyleOptionsExpanded(checked);
716 QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color)
718 QPixmap pixmap(16, 16);
719 pixmap.fill(Qt::transparent);
720 QPainter painter(&pixmap);
721 QPixmap image = icon.pixmap(16, 16);
722 QRect target(0, 0, 16, 14);
723 QRect source(0, 0, 16, 14);
724 painter.fillRect(QRect(0, 14, 16, 16), color);
725 painter.drawPixmap(target, image, source);
727 return QIcon(pixmap);
731 // MOUSE WHEEL FILTER
732 MouseWheelFilter::MouseWheelFilter(QObject *parent)
738 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event)
740 if (event->type() != QEvent::Wheel)
741 return QObject::eventFilter(obj, event);