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.textcolorButton->setIcon(QIcon::fromTheme("format-text-color"));
68 ui.highlightcolorButton->setIcon(QIcon::fromTheme("format-fill-color"));
69 ui.clearButton->setIcon(QIcon::fromTheme("edit-clear"));
70 ui.encryptionIconLabel->hide();
72 _colorMenu = new QMenu();
73 _colorFillMenu = new QMenu();
76 names << tr("White") << tr("Black") << tr("Dark blue") << tr("Dark green") << tr("Red") << tr("Dark red") << tr("Dark magenta") << tr("Orange")
77 << tr("Yellow") << tr("Green") << tr("Dark cyan") << tr("Cyan") << tr("Blue") << tr("Magenta") << tr("Dark gray") << tr("Light gray");
80 for (int i = 0; i < inputLine()->mircColorMap().count(); i++) {
81 pix.fill(inputLine()->mircColorMap().values()[i]);
82 _colorMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
83 _colorFillMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
86 pix.fill(Qt::transparent);
87 _colorMenu->addAction(pix, tr("Clear Color"))->setData("");
88 _colorFillMenu->addAction(pix, tr("Clear Color"))->setData("");
90 ui.textcolorButton->setMenu(_colorMenu);
91 // Set the default action to clear color (last added action)
92 ui.textcolorButton->setDefaultAction(_colorMenu->actions().last());
93 connect(_colorMenu, SIGNAL(triggered(QAction *)), this, SLOT(colorChosen(QAction *)));
95 ui.highlightcolorButton->setMenu(_colorFillMenu);
96 // Set the default action to clear fill color (last added action)
97 ui.highlightcolorButton->setDefaultAction(_colorFillMenu->actions().last());
98 connect(_colorFillMenu, SIGNAL(triggered(QAction *)), this, SLOT(colorHighlightChosen(QAction *)));
100 // Show/hide style button
101 connect(ui.showStyleButton, SIGNAL(toggled(bool)), this, SLOT(setStyleOptionsExpanded(bool)));
103 // Clear formatting button
104 connect(ui.clearButton, SIGNAL(clicked()), this, SLOT(clearFormat()));
106 new TabCompleter(ui.inputEdit);
108 UiStyleSettings fs("Fonts");
109 fs.notify("UseCustomInputWidgetFont", this, SLOT(setUseCustomFont(QVariant)));
110 fs.notify("InputWidget", this, SLOT(setCustomFont(QVariant)));
111 if (fs.value("UseCustomInputWidgetFont", false).toBool())
112 setCustomFont(fs.value("InputWidget", QFont()));
114 UiSettings s("InputWidget");
117 s.notify("EnableSpellCheck", this, SLOT(setEnableSpellCheck(QVariant)));
118 setEnableSpellCheck(s.value("EnableSpellCheck", false));
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::setEnableSpellCheck(const QVariant &v)
189 ui.inputEdit->setSpellCheckEnabled(v.toBool());
193 void InputWidget::setEnableEmacsMode(const QVariant &v)
195 ui.inputEdit->setEmacsMode(v.toBool());
199 void InputWidget::setShowNickSelector(const QVariant &v)
201 ui.ownNick->setVisible(v.toBool());
205 void InputWidget::setShowStyleButtons(const QVariant &v)
207 ui.showStyleButton->setVisible(v.toBool());
211 void InputWidget::setEnablePerChatHistory(const QVariant &v)
213 _perChatHistory = v.toBool();
217 void InputWidget::setMaxLines(const QVariant &v)
219 ui.inputEdit->setMaxHeight(v.toInt());
223 void InputWidget::setScrollBarsEnabled(const QVariant &v)
225 ui.inputEdit->setScrollBarsEnabled(v.toBool());
229 void InputWidget::setLineWrapEnabled(const QVariant &v)
231 ui.inputEdit->setLineWrapEnabled(v.toBool());
235 void InputWidget::setMultiLineEnabled(const QVariant &v)
237 ui.inputEdit->setMode(v.toBool() ? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
241 bool InputWidget::eventFilter(QObject *watched, QEvent *event)
243 if (event->type() != QEvent::KeyPress)
246 QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
248 // keys from BufferView should be sent to (and focus) the input line
249 BufferView *view = qobject_cast<BufferView *>(watched);
251 if (keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier))) { // normal key press
252 QChar c = keyEvent->text().at(0);
253 if (c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
255 QCoreApplication::sendEvent(inputLine(), keyEvent);
261 else if (watched == ui.inputEdit) {
262 if (keyEvent->matches(QKeySequence::Find)) {
263 QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
275 void InputWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous)
277 BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
278 BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
280 if (_perChatHistory) {
282 historyMap[previousBufferId].history = inputLine()->history();
283 historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
284 historyMap[previousBufferId].idx = inputLine()->idx();
285 historyMap[previousBufferId].inputLine = inputLine()->html();
288 inputLine()->setHistory(historyMap[currentBufferId].history);
289 inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
290 inputLine()->setIdx(historyMap[currentBufferId].idx);
291 inputLine()->setHtml(historyMap[currentBufferId].inputLine);
292 inputLine()->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
294 // FIXME this really should be in MultiLineEdit (and the const int on top removed)
295 QTextBlockFormat format = inputLine()->textCursor().blockFormat();
296 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
297 inputLine()->textCursor().setBlockFormat(format);
300 NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
301 if (networkId == _networkId)
304 setNetwork(networkId);
305 updateNickSelector();
306 updateEnabledState();
310 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
312 QItemSelectionRange changedArea(topLeft, bottomRight);
313 if (changedArea.contains(selectionModel()->currentIndex())) {
314 updateEnabledState();
316 bool encrypted = false;
318 IrcChannel *chan = qobject_cast<IrcChannel *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcChannelRole).value<QObject *>());
320 encrypted = chan->encrypted();
322 IrcUser *user = qobject_cast<IrcUser *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcUserRole).value<QObject *>());
324 encrypted = user->encrypted();
327 ui.encryptionIconLabel->show();
329 ui.encryptionIconLabel->hide();
334 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
338 for (int row = start; row <= end; row++) {
339 child = model()->index(row, 0, parent);
340 if (NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
342 networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
343 if (networkId == _networkId) {
345 updateNickSelector();
352 void InputWidget::updateEnabledState()
354 // FIXME: Find a visualization for this that does not disable the widget!
355 // Disabling kills global action shortcuts, plus users sometimes need/want to enter text
356 // even in inactive channels.
358 QModelIndex currentIndex = selectionModel()->currentIndex();
360 const Network *net = Client::networkModel()->networkByIndex(currentIndex);
361 bool enabled = false;
363 // disable inputline if it's a channelbuffer we parted from or...
364 enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
365 // ... if we're not connected to the network at all
366 enabled &= net->isConnected();
369 ui.inputEdit->setEnabled(enabled);
374 const Network *InputWidget::currentNetwork() const
376 return Client::network(_networkId);
380 BufferInfo InputWidget::currentBufferInfo() const
382 return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
386 void InputWidget::applyFormatActiveColor()
388 if (!ui.textcolorButton->defaultAction()) {
391 colorChosen(ui.textcolorButton->defaultAction());
395 void InputWidget::applyFormatActiveColorFill()
397 if (!ui.highlightcolorButton->defaultAction()) {
400 colorHighlightChosen(ui.highlightcolorButton->defaultAction());
404 void InputWidget::toggleFormatBold()
406 setFormatBold(!ui.boldButton->isChecked());
410 void InputWidget::toggleFormatItalic()
412 setFormatItalic(!ui.italicButton->isChecked());
416 void InputWidget::toggleFormatUnderline()
418 setFormatUnderline(!ui.underlineButton->isChecked());
422 void InputWidget::clearFormat()
424 // Clear all formatting for selection (not global)
425 setFormatClear(false);
429 void InputWidget::setNetwork(NetworkId networkId)
431 if (_networkId == networkId)
434 const Network *previousNet = Client::network(_networkId);
436 disconnect(previousNet, 0, this, 0);
437 if (previousNet->me())
438 disconnect(previousNet->me(), 0, this, 0);
441 _networkId = networkId;
443 const Network *network = Client::network(networkId);
445 connect(network, SIGNAL(identitySet(IdentityId)), this, SLOT(setIdentity(IdentityId)));
447 setIdentity(network->identity());
456 void InputWidget::connectMyIrcUser()
458 const Network *network = currentNetwork();
460 connect(network->me(), SIGNAL(nickSet(const QString &)), this, SLOT(updateNickSelector()));
461 connect(network->me(), SIGNAL(userModesSet(QString)), this, SLOT(updateNickSelector()));
462 connect(network->me(), SIGNAL(userModesAdded(QString)), this, SLOT(updateNickSelector()));
463 connect(network->me(), SIGNAL(userModesRemoved(QString)), this, SLOT(updateNickSelector()));
464 connect(network->me(), SIGNAL(awaySet(bool)), this, SLOT(updateNickSelector()));
465 disconnect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
466 updateNickSelector();
469 connect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
474 void InputWidget::setIdentity(IdentityId identityId)
476 if (_identityId == identityId)
479 const Identity *previousIdentity = Client::identity(_identityId);
480 if (previousIdentity)
481 disconnect(previousIdentity, 0, this, 0);
483 _identityId = identityId;
485 const Identity *identity = Client::identity(identityId);
487 connect(identity, SIGNAL(nicksSet(QStringList)), this, SLOT(updateNickSelector()));
492 updateNickSelector();
496 void InputWidget::updateNickSelector() const
500 const Network *net = currentNetwork();
504 const Identity *identity = Client::identity(net->identity());
506 qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
511 QStringList nicks = identity->nicks();
512 if ((nickIdx = nicks.indexOf(net->myNick())) == -1) {
513 nicks.prepend(net->myNick());
520 IrcUser *me = net->me();
522 nicks[nickIdx] = net->myNick();
523 if (!me->userModes().isEmpty())
524 nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
527 ui.ownNick->addItems(nicks);
529 if (me && me->isAway())
530 ui.ownNick->setItemData(nickIdx, QIcon::fromTheme("user-away"), Qt::DecorationRole);
532 ui.ownNick->setCurrentIndex(nickIdx);
536 void InputWidget::changeNick(const QString &newNick) const
538 const Network *net = currentNetwork();
539 if (!net || net->isMyNick(newNick))
542 // we reset the nick selecter as we have no confirmation yet, that this will succeed.
543 // if the action succeeds it will be properly updated anyways.
544 updateNickSelector();
545 Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
549 void InputWidget::onTextEntered(const QString &text)
551 Client::userInput(currentBufferInfo(), text);
552 ui.boldButton->setChecked(false);
553 ui.underlineButton->setChecked(false);
554 ui.italicButton->setChecked(false);
556 setFormatClear(true);
560 void InputWidget::setFormatClear(const bool global)
563 fmt.setFontWeight(QFont::Normal);
564 fmt.setFontUnderline(false);
565 fmt.setFontItalic(false);
566 fmt.clearForeground();
567 fmt.clearBackground();
569 inputLine()->setCurrentCharFormat(fmt);
571 setFormatOnSelection(fmt);
576 void InputWidget::setFormatBold(const bool bold)
579 fmt.setFontWeight(bold ? QFont::Bold : QFont::Normal);
580 mergeFormatOnSelection(fmt);
584 void InputWidget::setFormatItalic(const bool italic)
587 fmt.setFontItalic(italic);
588 mergeFormatOnSelection(fmt);
592 void InputWidget::setFormatUnderline(const bool underline)
595 fmt.setFontUnderline(underline);
596 mergeFormatOnSelection(fmt);
600 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format)
602 QTextCursor cursor = inputLine()->textCursor();
603 cursor.mergeCharFormat(format);
604 inputLine()->mergeCurrentCharFormat(format);
608 void InputWidget::setFormatOnSelection(const QTextCharFormat &format)
610 QTextCursor cursor = inputLine()->textCursor();
611 cursor.setCharFormat(format);
612 inputLine()->setCurrentCharFormat(format);
616 QTextCharFormat InputWidget::getFormatOfWordOrSelection()
618 QTextCursor cursor = inputLine()->textCursor();
619 return cursor.charFormat();
623 void InputWidget::setStyleOptionsExpanded(bool expanded)
625 ui.styleFrame->setVisible(expanded);
627 ui.showStyleButton->setArrowType(Qt::LeftArrow);
628 ui.showStyleButton->setToolTip(tr("Hide formatting options"));
630 ui.showStyleButton->setArrowType(Qt::RightArrow);
631 ui.showStyleButton->setToolTip(tr("Show formatting options"));
636 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format)
638 fontChanged(format.font());
642 void InputWidget::on_boldButton_clicked(bool checked)
644 setFormatBold(checked);
648 void InputWidget::on_underlineButton_clicked(bool checked)
650 setFormatUnderline(checked);
654 void InputWidget::on_italicButton_clicked(bool checked)
656 setFormatItalic(checked);
660 void InputWidget::fontChanged(const QFont &f)
662 ui.boldButton->setChecked(f.bold());
663 ui.italicButton->setChecked(f.italic());
664 ui.underlineButton->setChecked(f.underline());
668 void InputWidget::colorChosen(QAction *action)
672 if (action->data().value<QString>() == "") {
673 color = Qt::transparent;
674 fmt = getFormatOfWordOrSelection();
675 fmt.clearForeground();
676 setFormatOnSelection(fmt);
679 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
680 fmt.setForeground(color);
681 mergeFormatOnSelection(fmt);
683 ui.textcolorButton->setDefaultAction(action);
684 ui.textcolorButton->setIcon(createColorToolButtonIcon(QIcon::fromTheme("format-text-color"), color));
688 void InputWidget::colorHighlightChosen(QAction *action)
692 if (action->data().value<QString>() == "") {
693 color = Qt::transparent;
694 fmt = getFormatOfWordOrSelection();
695 fmt.clearBackground();
696 setFormatOnSelection(fmt);
699 color = QColor(inputLine()->rgbColorFromMirc(action->data().value<QString>()));
700 fmt.setBackground(color);
701 mergeFormatOnSelection(fmt);
703 ui.highlightcolorButton->setDefaultAction(action);
704 ui.highlightcolorButton->setIcon(createColorToolButtonIcon(QIcon::fromTheme("format-fill-color"), color));
708 void InputWidget::on_showStyleButton_toggled(bool checked)
710 setStyleOptionsExpanded(checked);
714 QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color)
716 QPixmap pixmap(16, 16);
717 pixmap.fill(Qt::transparent);
718 QPainter painter(&pixmap);
719 QPixmap image = icon.pixmap(16, 16);
720 QRect target(0, 0, 16, 14);
721 QRect source(0, 0, 16, 14);
722 painter.fillRect(QRect(0, 14, 16, 16), color);
723 painter.drawPixmap(target, image, source);
725 return QIcon(pixmap);
729 // MOUSE WHEEL FILTER
730 MouseWheelFilter::MouseWheelFilter(QObject *parent)
736 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event)
738 if (event->type() != QEvent::Wheel)
739 return QObject::eventFilter(obj, event);