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 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 ui.styleFrame->setVisible(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(new JumpKeyHandler(this));
58 ui.inputEdit->installEventFilter(this);
60 ui.inputEdit->setMinHeight(1);
61 ui.inputEdit->setMaxHeight(5);
62 ui.inputEdit->setMode(MultiLineEdit::MultiLine);
63 ui.inputEdit->setPasteProtectionEnabled(true);
65 ui.boldButton->setIcon(SmallIcon("format-text-bold"));
66 ui.italicButton->setIcon(SmallIcon("format-text-italic"));
67 ui.underlineButton->setIcon(SmallIcon("format-text-underline"));
68 ui.textcolorButton->setIcon(SmallIcon("format-text-color"));
69 ui.highlightcolorButton->setIcon(SmallIcon("format-fill-color"));
71 _colorMenu = new QMenu();
72 _colorFillMenu = new QMenu();
75 names << tr("White") << tr("Black") << tr("Dark blue") << tr("Dark green") << tr("Red") << tr("Dark red") << tr("Dark magenta") << tr("Orange")
76 << tr("Yellow") << tr("Green") << tr("Dark cyan") << tr("Cyan") << tr("Blue") << tr("Magenta") << tr("Dark gray") << tr("Light gray");
79 for (int i = 0; i < inputLine()->mircColorMap().count(); i++) {
80 pix.fill(inputLine()->mircColorMap().values()[i]);
81 _colorMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
82 _colorFillMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
85 pix.fill(Qt::transparent);
86 _colorMenu->addAction(pix, tr("Clear Color"))->setData("");
87 _colorFillMenu->addAction(pix, tr("Clear Color"))->setData("");
89 ui.textcolorButton->setMenu(_colorMenu);
90 connect(_colorMenu, SIGNAL(triggered(QAction*)), this, SLOT(colorChosen(QAction*)));
91 ui.highlightcolorButton->setMenu(_colorFillMenu);
92 connect(_colorFillMenu, SIGNAL(triggered(QAction*)), this, SLOT(colorHighlightChosen(QAction*)));
94 new TabCompleter(ui.inputEdit);
96 UiStyleSettings fs("Fonts");
97 fs.notify("UseCustomInputWidgetFont", this, SLOT(setUseCustomFont(QVariant)));
98 fs.notify("InputWidget", this, SLOT(setCustomFont(QVariant)));
99 if(fs.value("UseCustomInputWidgetFont", false).toBool())
100 setCustomFont(fs.value("InputWidget", QFont()));
102 UiSettings s("InputWidget");
105 s.notify("EnableSpellCheck", this, SLOT(setEnableSpellCheck(QVariant)));
106 setEnableSpellCheck(s.value("EnableSpellCheck", false));
109 s.notify("ShowNickSelector", this, SLOT(setShowNickSelector(QVariant)));
110 setShowNickSelector(s.value("ShowNickSelector", true));
112 s.notify("ShowStyleButtons", this, SLOT(setShowStyleButtons(QVariant)));
113 setShowStyleButtons(s.value("ShowStyleButtons", true));
115 s.notify("EnablePerChatHistory", this, SLOT(setEnablePerChatHistory(QVariant)));
116 setEnablePerChatHistory(s.value("EnablePerChatHistory", false));
118 s.notify("MaxNumLines", this, SLOT(setMaxLines(QVariant)));
119 setMaxLines(s.value("MaxNumLines", 5));
121 s.notify("EnableScrollBars", this, SLOT(setScrollBarsEnabled(QVariant)));
122 setScrollBarsEnabled(s.value("EnableScrollBars", true));
124 s.notify("EnableMultiLine", this, SLOT(setMultiLineEnabled(QVariant)));
125 setMultiLineEnabled(s.value("EnableMultiLine", true));
127 ActionCollection *coll = QtUi::actionCollection();
129 Action *activateInputline = coll->add<Action>("FocusInputLine");
130 connect(activateInputline, SIGNAL(triggered()), SLOT(setFocus()));
131 activateInputline->setText(tr("Focus Input Line"));
132 activateInputline->setShortcut(tr("Ctrl+L"));
134 connect(inputLine(), SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(currentCharFormatChanged(QTextCharFormat)));
137 InputWidget::~InputWidget() {
140 void InputWidget::setUseCustomFont(const QVariant &v) {
142 UiStyleSettings fs("Fonts");
143 setCustomFont(fs.value("InputWidget"));
145 setCustomFont(QFont());
148 void InputWidget::setCustomFont(const QVariant &v) {
149 QFont font = v.value<QFont>();
150 if(font.family().isEmpty())
151 font = QApplication::font();
152 ui.inputEdit->setCustomFont(font);
155 void InputWidget::setEnableSpellCheck(const QVariant &v) {
156 ui.inputEdit->setSpellCheckEnabled(v.toBool());
159 void InputWidget::setShowNickSelector(const QVariant &v) {
160 ui.ownNick->setVisible(v.toBool());
163 void InputWidget::setShowStyleButtons(const QVariant &v) {
164 ui.showStyleButton->setVisible(v.toBool());
167 void InputWidget::setEnablePerChatHistory(const QVariant &v) {
168 _perChatHistory = v.toBool();
171 void InputWidget::setMaxLines(const QVariant &v) {
172 ui.inputEdit->setMaxHeight(v.toInt());
175 void InputWidget::setScrollBarsEnabled(const QVariant &v) {
176 ui.inputEdit->setScrollBarsEnabled(v.toBool());
179 void InputWidget::setMultiLineEnabled(const QVariant &v) {
180 ui.inputEdit->setMode(v.toBool()? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
183 bool InputWidget::eventFilter(QObject *watched, QEvent *event) {
184 if(event->type() != QEvent::KeyPress)
187 QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
189 // keys from BufferView should be sent to (and focus) the input line
190 BufferView *view = qobject_cast<BufferView *>(watched);
192 if(keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier)) ) { // normal key press
193 QChar c = keyEvent->text().at(0);
194 if(c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
196 QCoreApplication::sendEvent(inputLine(), keyEvent);
201 } else if(watched == ui.inputEdit) {
202 if(keyEvent->matches(QKeySequence::Find)) {
203 QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
214 void InputWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous) {
215 BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
216 BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
218 if (_perChatHistory) {
220 historyMap[previousBufferId].history = inputLine()->history();
221 historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
222 historyMap[previousBufferId].idx = inputLine()->idx();
223 historyMap[previousBufferId].inputLine = inputLine()->html();
226 inputLine()->setHistory(historyMap[currentBufferId].history);
227 inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
228 inputLine()->setIdx(historyMap[currentBufferId].idx);
229 inputLine()->setHtml(historyMap[currentBufferId].inputLine);
230 inputLine()->moveCursor(QTextCursor::End,QTextCursor::MoveAnchor);
232 // FIXME this really should be in MultiLineEdit (and the const int on top removed)
233 QTextBlockFormat format = inputLine()->textCursor().blockFormat();
234 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
235 inputLine()->textCursor().setBlockFormat(format);
238 NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
239 if(networkId == _networkId)
242 setNetwork(networkId);
243 updateNickSelector();
244 updateEnabledState();
247 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
248 QItemSelectionRange changedArea(topLeft, bottomRight);
249 if(changedArea.contains(selectionModel()->currentIndex())) {
250 updateEnabledState();
254 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
257 for(int row = start; row <= end; row++) {
258 child = model()->index(row, 0, parent);
259 if(NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
261 networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
262 if(networkId == _networkId) {
264 updateNickSelector();
270 void InputWidget::updateEnabledState() {
271 QModelIndex currentIndex = selectionModel()->currentIndex();
273 const Network *net = Client::networkModel()->networkByIndex(currentIndex);
274 bool enabled = false;
276 // disable inputline if it's a channelbuffer we parted from or...
277 enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
278 // ... if we're not connected to the network at all
279 enabled &= net->isConnected();
281 ui.inputEdit->setEnabled(enabled);
284 const Network *InputWidget::currentNetwork() const {
285 return Client::network(_networkId);
288 BufferInfo InputWidget::currentBufferInfo() const {
289 return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
292 void InputWidget::setNetwork(NetworkId networkId) {
293 if(_networkId == networkId)
296 const Network *previousNet = Client::network(_networkId);
298 disconnect(previousNet, 0, this, 0);
299 if(previousNet->me())
300 disconnect(previousNet->me(), 0, this, 0);
303 _networkId = networkId;
305 const Network *network = Client::network(networkId);
307 connect(network, SIGNAL(identitySet(IdentityId)), this, SLOT(setIdentity(IdentityId)));
309 setIdentity(network->identity());
316 void InputWidget::connectMyIrcUser() {
317 const Network *network = currentNetwork();
319 connect(network->me(), SIGNAL(nickSet(const QString &)), this, SLOT(updateNickSelector()));
320 connect(network->me(), SIGNAL(userModesSet(QString)), this, SLOT(updateNickSelector()));
321 connect(network->me(), SIGNAL(userModesAdded(QString)), this, SLOT(updateNickSelector()));
322 connect(network->me(), SIGNAL(userModesRemoved(QString)), this, SLOT(updateNickSelector()));
323 connect(network->me(), SIGNAL(awaySet(bool)), this, SLOT(updateNickSelector()));
324 disconnect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
325 updateNickSelector();
327 connect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
331 void InputWidget::setIdentity(IdentityId identityId) {
332 if(_identityId == identityId)
335 const Identity *previousIdentity = Client::identity(_identityId);
337 disconnect(previousIdentity, 0, this, 0);
339 _identityId = identityId;
341 const Identity *identity = Client::identity(identityId);
343 connect(identity, SIGNAL(nicksSet(QStringList)), this, SLOT(updateNickSelector()));
347 updateNickSelector();
350 void InputWidget::updateNickSelector() const {
353 const Network *net = currentNetwork();
357 const Identity *identity = Client::identity(net->identity());
359 qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
364 QStringList nicks = identity->nicks();
365 if((nickIdx = nicks.indexOf(net->myNick())) == -1) {
366 nicks.prepend(net->myNick());
373 IrcUser *me = net->me();
375 nicks[nickIdx] = net->myNick();
376 if(!me->userModes().isEmpty())
377 nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
380 ui.ownNick->addItems(nicks);
382 if(me && me->isAway())
383 ui.ownNick->setItemData(nickIdx, SmallIcon("user-away"), Qt::DecorationRole);
385 ui.ownNick->setCurrentIndex(nickIdx);
388 void InputWidget::changeNick(const QString &newNick) const {
389 const Network *net = currentNetwork();
390 if(!net || net->isMyNick(newNick))
393 // we reset the nick selecter as we have no confirmation yet, that this will succeed.
394 // if the action succeeds it will be properly updated anyways.
395 updateNickSelector();
396 Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
399 void InputWidget::on_inputEdit_textEntered(const QString &text) {
400 Client::userInput(currentBufferInfo(), text);
401 ui.boldButton->setChecked(false);
402 ui.underlineButton->setChecked(false);
403 ui.italicButton->setChecked(false);
406 fmt.setFontWeight(QFont::Normal);
407 fmt.setFontUnderline(false);
408 fmt.setFontItalic(false);
409 fmt.clearForeground();
410 fmt.clearBackground();
411 inputLine()->setCurrentCharFormat(fmt);
414 // Set highlighter back to active in case it was deactivated by too many errors.
415 if(ui.inputEdit->highlighter())
416 ui.inputEdit->highlighter()->setActive(true);
420 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format) {
421 QTextCursor cursor = inputLine()->textCursor();
422 cursor.mergeCharFormat(format);
423 inputLine()->mergeCurrentCharFormat(format);
426 void InputWidget::setFormatOnSelection(const QTextCharFormat &format) {
427 QTextCursor cursor = inputLine()->textCursor();
428 cursor.setCharFormat(format);
429 inputLine()->setCurrentCharFormat(format);
432 QTextCharFormat InputWidget::getFormatOfWordOrSelection() {
433 QTextCursor cursor = inputLine()->textCursor();
434 return cursor.charFormat();
437 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format) {
438 fontChanged(format.font());
441 void InputWidget::on_boldButton_clicked(bool checked) {
443 fmt.setFontWeight(checked ? QFont::Bold : QFont::Normal);
444 mergeFormatOnSelection(fmt);
447 void InputWidget::on_underlineButton_clicked(bool checked) {
449 fmt.setFontUnderline(checked);
450 mergeFormatOnSelection(fmt);
453 void InputWidget::on_italicButton_clicked(bool checked) {
455 fmt.setFontItalic(checked);
456 mergeFormatOnSelection(fmt);
459 void InputWidget::fontChanged(const QFont &f)
461 ui.boldButton->setChecked(f.bold());
462 ui.italicButton->setChecked(f.italic());
463 ui.underlineButton->setChecked(f.underline());
466 void InputWidget::colorChosen(QAction *action) {
469 if (qVariantValue<QString>(action->data()) == "") {
470 color = Qt::transparent;
471 fmt = getFormatOfWordOrSelection();
472 fmt.clearForeground();
473 setFormatOnSelection(fmt);
476 color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
477 fmt.setForeground(color);
478 mergeFormatOnSelection(fmt);
480 ui.textcolorButton->setDefaultAction(action);
481 ui.textcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-text-color"), color));
484 void InputWidget::colorHighlightChosen(QAction *action) {
487 if (qVariantValue<QString>(action->data()) == "") {
488 color = Qt::transparent;
489 fmt = getFormatOfWordOrSelection();
490 fmt.clearBackground();
491 setFormatOnSelection(fmt);
494 color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
495 fmt.setBackground(color);
496 mergeFormatOnSelection(fmt);
498 ui.highlightcolorButton->setDefaultAction(action);
499 ui.highlightcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-fill-color"), color));
502 void InputWidget::on_showStyleButton_toggled(bool checked) {
503 ui.styleFrame->setVisible(checked);
505 ui.showStyleButton->setArrowType(Qt::LeftArrow);
508 ui.showStyleButton->setArrowType(Qt::RightArrow);
512 QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color) {
513 QPixmap pixmap(16, 16);
514 pixmap.fill(Qt::transparent);
515 QPainter painter(&pixmap);
516 QPixmap image = icon.pixmap(16,16);
517 QRect target(0, 0, 16, 14);
518 QRect source(0, 0, 16, 14);
519 painter.fillRect(QRect(0, 14, 16, 16), color);
520 painter.drawPixmap(target, image, source);
522 return QIcon(pixmap);
525 // MOUSE WHEEL FILTER
526 MouseWheelFilter::MouseWheelFilter(QObject *parent)
531 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event) {
532 if(event->type() != QEvent::Wheel)
533 return QObject::eventFilter(obj, event);