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(QKeySequence(Qt::CTRL + Qt::Key_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 // we don't want font styles as this conflics with mirc code richtext editing
154 font.setItalic(false);
155 font.setUnderline(false);
156 font.setStrikeOut(false);
157 ui.inputEdit->setCustomFont(font);
160 void InputWidget::setEnableSpellCheck(const QVariant &v) {
161 ui.inputEdit->setSpellCheckEnabled(v.toBool());
164 void InputWidget::setShowNickSelector(const QVariant &v) {
165 ui.ownNick->setVisible(v.toBool());
168 void InputWidget::setShowStyleButtons(const QVariant &v) {
169 ui.showStyleButton->setVisible(v.toBool());
172 void InputWidget::setEnablePerChatHistory(const QVariant &v) {
173 _perChatHistory = v.toBool();
176 void InputWidget::setMaxLines(const QVariant &v) {
177 ui.inputEdit->setMaxHeight(v.toInt());
180 void InputWidget::setScrollBarsEnabled(const QVariant &v) {
181 ui.inputEdit->setScrollBarsEnabled(v.toBool());
184 void InputWidget::setMultiLineEnabled(const QVariant &v) {
185 ui.inputEdit->setMode(v.toBool()? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
188 bool InputWidget::eventFilter(QObject *watched, QEvent *event) {
189 if(event->type() != QEvent::KeyPress)
192 QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
194 // keys from BufferView should be sent to (and focus) the input line
195 BufferView *view = qobject_cast<BufferView *>(watched);
197 if(keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier)) ) { // normal key press
198 QChar c = keyEvent->text().at(0);
199 if(c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
201 QCoreApplication::sendEvent(inputLine(), keyEvent);
206 } else if(watched == ui.inputEdit) {
207 if(keyEvent->matches(QKeySequence::Find)) {
208 QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
219 void InputWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous) {
220 BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
221 BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
223 if (_perChatHistory) {
225 historyMap[previousBufferId].history = inputLine()->history();
226 historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
227 historyMap[previousBufferId].idx = inputLine()->idx();
228 historyMap[previousBufferId].inputLine = inputLine()->html();
231 inputLine()->setHistory(historyMap[currentBufferId].history);
232 inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
233 inputLine()->setIdx(historyMap[currentBufferId].idx);
234 inputLine()->setHtml(historyMap[currentBufferId].inputLine);
235 inputLine()->moveCursor(QTextCursor::End,QTextCursor::MoveAnchor);
237 // FIXME this really should be in MultiLineEdit (and the const int on top removed)
238 QTextBlockFormat format = inputLine()->textCursor().blockFormat();
239 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
240 inputLine()->textCursor().setBlockFormat(format);
243 NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
244 if(networkId == _networkId)
247 setNetwork(networkId);
248 updateNickSelector();
249 updateEnabledState();
252 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
253 QItemSelectionRange changedArea(topLeft, bottomRight);
254 if(changedArea.contains(selectionModel()->currentIndex())) {
255 updateEnabledState();
259 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
262 for(int row = start; row <= end; row++) {
263 child = model()->index(row, 0, parent);
264 if(NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
266 networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
267 if(networkId == _networkId) {
269 updateNickSelector();
275 void InputWidget::updateEnabledState() {
276 QModelIndex currentIndex = selectionModel()->currentIndex();
278 const Network *net = Client::networkModel()->networkByIndex(currentIndex);
279 bool enabled = false;
281 // disable inputline if it's a channelbuffer we parted from or...
282 enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
283 // ... if we're not connected to the network at all
284 enabled &= net->isConnected();
286 ui.inputEdit->setEnabled(enabled);
289 const Network *InputWidget::currentNetwork() const {
290 return Client::network(_networkId);
293 BufferInfo InputWidget::currentBufferInfo() const {
294 return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
297 void InputWidget::setNetwork(NetworkId networkId) {
298 if(_networkId == networkId)
301 const Network *previousNet = Client::network(_networkId);
303 disconnect(previousNet, 0, this, 0);
304 if(previousNet->me())
305 disconnect(previousNet->me(), 0, this, 0);
308 _networkId = networkId;
310 const Network *network = Client::network(networkId);
312 connect(network, SIGNAL(identitySet(IdentityId)), this, SLOT(setIdentity(IdentityId)));
314 setIdentity(network->identity());
321 void InputWidget::connectMyIrcUser() {
322 const Network *network = currentNetwork();
324 connect(network->me(), SIGNAL(nickSet(const QString &)), this, SLOT(updateNickSelector()));
325 connect(network->me(), SIGNAL(userModesSet(QString)), this, SLOT(updateNickSelector()));
326 connect(network->me(), SIGNAL(userModesAdded(QString)), this, SLOT(updateNickSelector()));
327 connect(network->me(), SIGNAL(userModesRemoved(QString)), this, SLOT(updateNickSelector()));
328 connect(network->me(), SIGNAL(awaySet(bool)), this, SLOT(updateNickSelector()));
329 disconnect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
330 updateNickSelector();
332 connect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
336 void InputWidget::setIdentity(IdentityId identityId) {
337 if(_identityId == identityId)
340 const Identity *previousIdentity = Client::identity(_identityId);
342 disconnect(previousIdentity, 0, this, 0);
344 _identityId = identityId;
346 const Identity *identity = Client::identity(identityId);
348 connect(identity, SIGNAL(nicksSet(QStringList)), this, SLOT(updateNickSelector()));
352 updateNickSelector();
355 void InputWidget::updateNickSelector() const {
358 const Network *net = currentNetwork();
362 const Identity *identity = Client::identity(net->identity());
364 qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
369 QStringList nicks = identity->nicks();
370 if((nickIdx = nicks.indexOf(net->myNick())) == -1) {
371 nicks.prepend(net->myNick());
378 IrcUser *me = net->me();
380 nicks[nickIdx] = net->myNick();
381 if(!me->userModes().isEmpty())
382 nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
385 ui.ownNick->addItems(nicks);
387 if(me && me->isAway())
388 ui.ownNick->setItemData(nickIdx, SmallIcon("user-away"), Qt::DecorationRole);
390 ui.ownNick->setCurrentIndex(nickIdx);
393 void InputWidget::changeNick(const QString &newNick) const {
394 const Network *net = currentNetwork();
395 if(!net || net->isMyNick(newNick))
398 // we reset the nick selecter as we have no confirmation yet, that this will succeed.
399 // if the action succeeds it will be properly updated anyways.
400 updateNickSelector();
401 Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
404 void InputWidget::on_inputEdit_textEntered(const QString &text) {
405 Client::userInput(currentBufferInfo(), text);
406 ui.boldButton->setChecked(false);
407 ui.underlineButton->setChecked(false);
408 ui.italicButton->setChecked(false);
411 fmt.setFontWeight(QFont::Normal);
412 fmt.setFontUnderline(false);
413 fmt.setFontItalic(false);
414 fmt.clearForeground();
415 fmt.clearBackground();
416 inputLine()->setCurrentCharFormat(fmt);
419 // Set highlighter back to active in case it was deactivated by too many errors.
420 if(ui.inputEdit->highlighter())
421 ui.inputEdit->highlighter()->setActive(true);
425 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format) {
426 QTextCursor cursor = inputLine()->textCursor();
427 cursor.mergeCharFormat(format);
428 inputLine()->mergeCurrentCharFormat(format);
431 void InputWidget::setFormatOnSelection(const QTextCharFormat &format) {
432 QTextCursor cursor = inputLine()->textCursor();
433 cursor.setCharFormat(format);
434 inputLine()->setCurrentCharFormat(format);
437 QTextCharFormat InputWidget::getFormatOfWordOrSelection() {
438 QTextCursor cursor = inputLine()->textCursor();
439 return cursor.charFormat();
442 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format) {
443 fontChanged(format.font());
446 void InputWidget::on_boldButton_clicked(bool checked) {
448 fmt.setFontWeight(checked ? QFont::Bold : QFont::Normal);
449 mergeFormatOnSelection(fmt);
452 void InputWidget::on_underlineButton_clicked(bool checked) {
454 fmt.setFontUnderline(checked);
455 mergeFormatOnSelection(fmt);
458 void InputWidget::on_italicButton_clicked(bool checked) {
460 fmt.setFontItalic(checked);
461 mergeFormatOnSelection(fmt);
464 void InputWidget::fontChanged(const QFont &f)
466 ui.boldButton->setChecked(f.bold());
467 ui.italicButton->setChecked(f.italic());
468 ui.underlineButton->setChecked(f.underline());
471 void InputWidget::colorChosen(QAction *action) {
474 if (qVariantValue<QString>(action->data()) == "") {
475 color = Qt::transparent;
476 fmt = getFormatOfWordOrSelection();
477 fmt.clearForeground();
478 setFormatOnSelection(fmt);
481 color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
482 fmt.setForeground(color);
483 mergeFormatOnSelection(fmt);
485 ui.textcolorButton->setDefaultAction(action);
486 ui.textcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-text-color"), color));
489 void InputWidget::colorHighlightChosen(QAction *action) {
492 if (qVariantValue<QString>(action->data()) == "") {
493 color = Qt::transparent;
494 fmt = getFormatOfWordOrSelection();
495 fmt.clearBackground();
496 setFormatOnSelection(fmt);
499 color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
500 fmt.setBackground(color);
501 mergeFormatOnSelection(fmt);
503 ui.highlightcolorButton->setDefaultAction(action);
504 ui.highlightcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-fill-color"), color));
507 void InputWidget::on_showStyleButton_toggled(bool checked) {
508 ui.styleFrame->setVisible(checked);
510 ui.showStyleButton->setArrowType(Qt::LeftArrow);
513 ui.showStyleButton->setArrowType(Qt::RightArrow);
517 QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color) {
518 QPixmap pixmap(16, 16);
519 pixmap.fill(Qt::transparent);
520 QPainter painter(&pixmap);
521 QPixmap image = icon.pixmap(16,16);
522 QRect target(0, 0, 16, 14);
523 QRect source(0, 0, 16, 14);
524 painter.fillRect(QRect(0, 14, 16, 16), color);
525 painter.drawPixmap(target, image, source);
527 return QIcon(pixmap);
530 // MOUSE WHEEL FILTER
531 MouseWheelFilter::MouseWheelFilter(QObject *parent)
536 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event) {
537 if(event->type() != QEvent::Wheel)
538 return QObject::eventFilter(obj, event);