1 /***************************************************************************
2 * Copyright (C) 2005-2010 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 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
21 #include "inputwidget.h"
24 #include "actioncollection.h"
25 #include "bufferview.h"
27 #include "iconloader.h"
29 #include "jumpkeyhandler.h"
30 #include "networkmodel.h"
32 #include "qtuisettings.h"
33 #include "tabcompleter.h"
36 InputWidget::InputWidget(QWidget *parent)
37 : AbstractItemView(parent),
41 connect(ui.ownNick, SIGNAL(activated(QString)), this, SLOT(changeNick(QString)));
43 layout()->setAlignment(ui.ownNick, Qt::AlignBottom);
44 layout()->setAlignment(ui.inputEdit, Qt::AlignBottom);
45 layout()->setAlignment(ui.showStyleButton, Qt::AlignBottom);
46 layout()->setAlignment(ui.styleFrame, Qt::AlignBottom);
48 ui.styleFrame->setVisible(false);
50 setFocusProxy(ui.inputEdit);
51 ui.ownNick->setFocusProxy(ui.inputEdit);
53 ui.ownNick->setSizeAdjustPolicy(QComboBox::AdjustToContents);
54 ui.ownNick->installEventFilter(new MouseWheelFilter(this));
55 ui.inputEdit->installEventFilter(new JumpKeyHandler(this));
56 ui.inputEdit->installEventFilter(this);
58 ui.inputEdit->setMinHeight(1);
59 ui.inputEdit->setMaxHeight(5);
60 ui.inputEdit->setMode(MultiLineEdit::MultiLine);
61 ui.inputEdit->setPasteProtectionEnabled(true);
63 ui.boldButton->setIcon(SmallIcon("format-text-bold"));
64 ui.italicButton->setIcon(SmallIcon("format-text-italic"));
65 ui.underlineButton->setIcon(SmallIcon("format-text-underline"));
66 ui.textcolorButton->setIcon(SmallIcon("format-text-color"));
67 ui.highlightcolorButton->setIcon(SmallIcon("format-fill-color"));
69 _colorMenu = new QMenu();
70 _colorFillMenu = new QMenu();
73 names << tr("White") << tr("Black") << tr("Dark blue") << tr("Dark green") << tr("Red") << tr("Dark red") << tr("Dark magenta") << tr("Orange")
74 << tr("Yellow") << tr("Green") << tr("Dark cyan") << tr("Cyan") << tr("Blue") << tr("Magenta") << tr("Dark gray") << tr("Light gray");
77 for (int i = 0; i < inputLine()->mircColorMap().count(); i++) {
78 pix.fill(inputLine()->mircColorMap().values()[i]);
79 _colorMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
80 _colorFillMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
83 pix.fill(Qt::transparent);
84 _colorMenu->addAction(pix, tr("Clear Color"))->setData("");
85 _colorFillMenu->addAction(pix, tr("Clear Color"))->setData("");
87 ui.textcolorButton->setMenu(_colorMenu);
88 connect(_colorMenu, SIGNAL(triggered(QAction*)), this, SLOT(colorChosen(QAction*)));
89 ui.highlightcolorButton->setMenu(_colorFillMenu);
90 connect(_colorFillMenu, SIGNAL(triggered(QAction*)), this, SLOT(colorHighlightChosen(QAction*)));
92 new TabCompleter(ui.inputEdit);
94 UiStyleSettings fs("Fonts");
95 fs.notify("UseCustomInputWidgetFont", this, SLOT(setUseCustomFont(QVariant)));
96 fs.notify("InputWidget", this, SLOT(setCustomFont(QVariant)));
97 if(fs.value("UseCustomInputWidgetFont", false).toBool())
98 setCustomFont(fs.value("InputWidget", QFont()));
100 UiSettings s("InputWidget");
103 s.notify("EnableSpellCheck", this, SLOT(setEnableSpellCheck(QVariant)));
104 setEnableSpellCheck(s.value("EnableSpellCheck", false));
107 s.notify("ShowNickSelector", this, SLOT(setShowNickSelector(QVariant)));
108 setShowNickSelector(s.value("ShowNickSelector", true));
110 s.notify("ShowStyleButtons", this, SLOT(setShowStyleButtons(QVariant)));
111 setShowStyleButtons(s.value("ShowStyleButtons", true));
113 s.notify("EnablePerChatHistory", this, SLOT(setEnablePerChatHistory(QVariant)));
114 setEnablePerChatHistory(s.value("EnablePerChatHistory", true));
116 s.notify("MaxNumLines", this, SLOT(setMaxLines(QVariant)));
117 setMaxLines(s.value("MaxNumLines", 5));
119 s.notify("EnableScrollBars", this, SLOT(setScrollBarsEnabled(QVariant)));
120 setScrollBarsEnabled(s.value("EnableScrollBars", true));
122 s.notify("EnableMultiLine", this, SLOT(setMultiLineEnabled(QVariant)));
123 setMultiLineEnabled(s.value("EnableMultiLine", true));
125 ActionCollection *coll = QtUi::actionCollection();
127 Action *activateInputline = coll->add<Action>("FocusInputLine");
128 connect(activateInputline, SIGNAL(triggered()), SLOT(setFocus()));
129 activateInputline->setText(tr("Focus Input Line"));
130 activateInputline->setShortcut(tr("Ctrl+L"));
132 connect(inputLine(), SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(currentCharFormatChanged(QTextCharFormat)));
135 InputWidget::~InputWidget() {
138 void InputWidget::setUseCustomFont(const QVariant &v) {
140 UiStyleSettings fs("Fonts");
141 setCustomFont(fs.value("InputWidget"));
143 setCustomFont(QFont());
146 void InputWidget::setCustomFont(const QVariant &v) {
147 QFont font = v.value<QFont>();
148 if(font.family().isEmpty())
149 font = QApplication::font();
150 ui.inputEdit->setCustomFont(font);
153 void InputWidget::setEnableSpellCheck(const QVariant &v) {
154 ui.inputEdit->setSpellCheckEnabled(v.toBool());
157 void InputWidget::setShowNickSelector(const QVariant &v) {
158 ui.ownNick->setVisible(v.toBool());
161 void InputWidget::setShowStyleButtons(const QVariant &v) {
162 ui.showStyleButton->setVisible(v.toBool());
165 void InputWidget::setEnablePerChatHistory(const QVariant &v) {
166 _perChatHistory = v.toBool();
169 void InputWidget::setMaxLines(const QVariant &v) {
170 ui.inputEdit->setMaxHeight(v.toInt());
173 void InputWidget::setScrollBarsEnabled(const QVariant &v) {
174 ui.inputEdit->setScrollBarsEnabled(v.toBool());
177 void InputWidget::setMultiLineEnabled(const QVariant &v) {
178 ui.inputEdit->setMode(v.toBool()? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
181 bool InputWidget::eventFilter(QObject *watched, QEvent *event) {
182 if(event->type() != QEvent::KeyPress)
185 QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
187 // keys from BufferView should be sent to (and focus) the input line
188 BufferView *view = qobject_cast<BufferView *>(watched);
190 if(keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier)) ) { // normal key press
191 QChar c = keyEvent->text().at(0);
192 if(c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
194 QCoreApplication::sendEvent(inputLine(), keyEvent);
199 } else if(watched == ui.inputEdit) {
200 if(keyEvent->matches(QKeySequence::Find)) {
201 QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
212 void InputWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous) {
213 BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
214 BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
216 if (_perChatHistory) {
218 historyMap[previousBufferId].history = inputLine()->history();
219 historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
220 historyMap[previousBufferId].idx = inputLine()->idx();
221 historyMap[previousBufferId].inputLine = inputLine()->html();
224 inputLine()->setHistory(historyMap[currentBufferId].history);
225 inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
226 inputLine()->setIdx(historyMap[currentBufferId].idx);
227 inputLine()->setHtml(historyMap[currentBufferId].inputLine);
228 inputLine()->moveCursor(QTextCursor::End,QTextCursor::MoveAnchor);
231 NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
232 if(networkId == _networkId)
235 setNetwork(networkId);
236 updateNickSelector();
237 updateEnabledState();
240 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
241 QItemSelectionRange changedArea(topLeft, bottomRight);
242 if(changedArea.contains(selectionModel()->currentIndex())) {
243 updateEnabledState();
247 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
250 for(int row = start; row <= end; row++) {
251 child = model()->index(row, 0, parent);
252 if(NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
254 networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
255 if(networkId == _networkId) {
257 updateNickSelector();
263 void InputWidget::updateEnabledState() {
264 QModelIndex currentIndex = selectionModel()->currentIndex();
266 const Network *net = Client::networkModel()->networkByIndex(currentIndex);
267 bool enabled = false;
269 // disable inputline if it's a channelbuffer we parted from or...
270 enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
271 // ... if we're not connected to the network at all
272 enabled &= net->isConnected();
274 ui.inputEdit->setEnabled(enabled);
277 const Network *InputWidget::currentNetwork() const {
278 return Client::network(_networkId);
281 BufferInfo InputWidget::currentBufferInfo() const {
282 return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
285 void InputWidget::setNetwork(NetworkId networkId) {
286 if(_networkId == networkId)
289 const Network *previousNet = Client::network(_networkId);
291 disconnect(previousNet, 0, this, 0);
292 if(previousNet->me())
293 disconnect(previousNet->me(), 0, this, 0);
296 _networkId = networkId;
298 const Network *network = Client::network(networkId);
300 connect(network, SIGNAL(identitySet(IdentityId)), this, SLOT(setIdentity(IdentityId)));
302 setIdentity(network->identity());
309 void InputWidget::connectMyIrcUser() {
310 const Network *network = currentNetwork();
312 connect(network->me(), SIGNAL(nickSet(const QString &)), this, SLOT(updateNickSelector()));
313 connect(network->me(), SIGNAL(userModesSet(QString)), this, SLOT(updateNickSelector()));
314 connect(network->me(), SIGNAL(userModesAdded(QString)), this, SLOT(updateNickSelector()));
315 connect(network->me(), SIGNAL(userModesRemoved(QString)), this, SLOT(updateNickSelector()));
316 connect(network->me(), SIGNAL(awaySet(bool)), this, SLOT(updateNickSelector()));
317 disconnect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
318 updateNickSelector();
320 connect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
324 void InputWidget::setIdentity(IdentityId identityId) {
325 if(_identityId == identityId)
328 const Identity *previousIdentity = Client::identity(_identityId);
330 disconnect(previousIdentity, 0, this, 0);
332 _identityId = identityId;
334 const Identity *identity = Client::identity(identityId);
336 connect(identity, SIGNAL(nicksSet(QStringList)), this, SLOT(updateNickSelector()));
340 updateNickSelector();
343 void InputWidget::updateNickSelector() const {
346 const Network *net = currentNetwork();
350 const Identity *identity = Client::identity(net->identity());
352 qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
357 QStringList nicks = identity->nicks();
358 if((nickIdx = nicks.indexOf(net->myNick())) == -1) {
359 nicks.prepend(net->myNick());
366 IrcUser *me = net->me();
368 nicks[nickIdx] = net->myNick();
369 if(!me->userModes().isEmpty())
370 nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
373 ui.ownNick->addItems(nicks);
375 if(me && me->isAway())
376 ui.ownNick->setItemData(nickIdx, SmallIcon("user-away"), Qt::DecorationRole);
378 ui.ownNick->setCurrentIndex(nickIdx);
381 void InputWidget::changeNick(const QString &newNick) const {
382 const Network *net = currentNetwork();
383 if(!net || net->isMyNick(newNick))
386 // we reset the nick selecter as we have no confirmation yet, that this will succeed.
387 // if the action succeeds it will be properly updated anyways.
388 updateNickSelector();
389 Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
392 void InputWidget::on_inputEdit_textEntered(const QString &text) {
393 Client::userInput(currentBufferInfo(), text);
394 ui.boldButton->setChecked(false);
395 ui.underlineButton->setChecked(false);
396 ui.italicButton->setChecked(false);
399 fmt.setFontWeight(QFont::Normal);
400 fmt.setFontUnderline(false);
401 fmt.setFontItalic(false);
402 fmt.clearForeground();
403 fmt.clearBackground();
404 inputLine()->setCurrentCharFormat(fmt);
407 // Set highlighter back to active in case it was deactivated by too many errors.
408 if(ui.inputEdit->highlighter())
409 ui.inputEdit->highlighter()->setActive(true);
413 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format) {
414 QTextCursor cursor = inputLine()->textCursor();
415 cursor.mergeCharFormat(format);
416 inputLine()->mergeCurrentCharFormat(format);
419 void InputWidget::setFormatOnSelection(const QTextCharFormat &format) {
420 QTextCursor cursor = inputLine()->textCursor();
421 cursor.setCharFormat(format);
422 inputLine()->setCurrentCharFormat(format);
425 QTextCharFormat InputWidget::getFormatOfWordOrSelection() {
426 QTextCursor cursor = inputLine()->textCursor();
427 return cursor.charFormat();
430 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format) {
431 fontChanged(format.font());
434 void InputWidget::on_boldButton_clicked(bool checked) {
436 fmt.setFontWeight(checked ? QFont::Bold : QFont::Normal);
437 mergeFormatOnSelection(fmt);
440 void InputWidget::on_underlineButton_clicked(bool checked) {
442 fmt.setFontUnderline(checked);
443 mergeFormatOnSelection(fmt);
446 void InputWidget::on_italicButton_clicked(bool checked) {
448 fmt.setFontItalic(checked);
449 mergeFormatOnSelection(fmt);
452 void InputWidget::fontChanged(const QFont &f)
454 ui.boldButton->setChecked(f.bold());
455 ui.italicButton->setChecked(f.italic());
456 ui.underlineButton->setChecked(f.underline());
459 void InputWidget::colorChosen(QAction *action) {
462 if (qVariantValue<QString>(action->data()) == "") {
463 color = Qt::transparent;
464 fmt = getFormatOfWordOrSelection();
465 fmt.clearForeground();
466 setFormatOnSelection(fmt);
469 color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
470 fmt.setForeground(color);
471 mergeFormatOnSelection(fmt);
473 ui.textcolorButton->setDefaultAction(action);
474 ui.textcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-text-color"), color));
477 void InputWidget::colorHighlightChosen(QAction *action) {
480 if (qVariantValue<QString>(action->data()) == "") {
481 color = Qt::transparent;
482 fmt = getFormatOfWordOrSelection();
483 fmt.clearBackground();
484 setFormatOnSelection(fmt);
487 color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
488 fmt.setBackground(color);
489 mergeFormatOnSelection(fmt);
491 ui.highlightcolorButton->setDefaultAction(action);
492 ui.highlightcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-fill-color"), color));
495 void InputWidget::on_showStyleButton_toggled(bool checked) {
496 ui.styleFrame->setVisible(checked);
498 ui.showStyleButton->setArrowType(Qt::LeftArrow);
501 ui.showStyleButton->setArrowType(Qt::RightArrow);
505 QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color) {
506 QPixmap pixmap(16, 16);
507 pixmap.fill(Qt::transparent);
508 QPainter painter(&pixmap);
509 QPixmap image = icon.pixmap(16,16);
510 QRect target(0, 0, 16, 14);
511 QRect source(0, 0, 16, 14);
512 painter.fillRect(QRect(0, 14, 16, 16), color);
513 painter.drawPixmap(target, image, source);
515 return QIcon(pixmap);
518 // MOUSE WHEEL FILTER
519 MouseWheelFilter::MouseWheelFilter(QObject *parent)
524 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event) {
525 if(event->type() != QEvent::Wheel)
526 return QObject::eventFilter(obj, event);