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("EnableEmacsMode", this, SLOT(setEnableEmacsMode(QVariant)));
110 setEnableEmacsMode(s.value("EnableEmacsMode", false));
112 s.notify("ShowNickSelector", this, SLOT(setShowNickSelector(QVariant)));
113 setShowNickSelector(s.value("ShowNickSelector", true));
115 s.notify("ShowStyleButtons", this, SLOT(setShowStyleButtons(QVariant)));
116 setShowStyleButtons(s.value("ShowStyleButtons", true));
118 s.notify("EnablePerChatHistory", this, SLOT(setEnablePerChatHistory(QVariant)));
119 setEnablePerChatHistory(s.value("EnablePerChatHistory", false));
121 s.notify("MaxNumLines", this, SLOT(setMaxLines(QVariant)));
122 setMaxLines(s.value("MaxNumLines", 5));
124 s.notify("EnableScrollBars", this, SLOT(setScrollBarsEnabled(QVariant)));
125 setScrollBarsEnabled(s.value("EnableScrollBars", true));
127 s.notify("EnableMultiLine", this, SLOT(setMultiLineEnabled(QVariant)));
128 setMultiLineEnabled(s.value("EnableMultiLine", true));
130 ActionCollection *coll = QtUi::actionCollection();
132 Action *activateInputline = coll->add<Action>("FocusInputLine");
133 connect(activateInputline, SIGNAL(triggered()), SLOT(setFocus()));
134 activateInputline->setText(tr("Focus Input Line"));
135 activateInputline->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_L));
137 connect(inputLine(), SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(currentCharFormatChanged(QTextCharFormat)));
140 InputWidget::~InputWidget() {
143 void InputWidget::setUseCustomFont(const QVariant &v) {
145 UiStyleSettings fs("Fonts");
146 setCustomFont(fs.value("InputWidget"));
148 setCustomFont(QFont());
151 void InputWidget::setCustomFont(const QVariant &v) {
152 QFont font = v.value<QFont>();
153 if(font.family().isEmpty())
154 font = QApplication::font();
155 // we don't want font styles as this conflics with mirc code richtext editing
157 font.setItalic(false);
158 font.setUnderline(false);
159 font.setStrikeOut(false);
160 ui.inputEdit->setCustomFont(font);
163 void InputWidget::setEnableSpellCheck(const QVariant &v) {
164 ui.inputEdit->setSpellCheckEnabled(v.toBool());
167 void InputWidget::setEnableEmacsMode(const QVariant &v) {
168 ui.inputEdit->setEmacsMode(v.toBool());
171 void InputWidget::setShowNickSelector(const QVariant &v) {
172 ui.ownNick->setVisible(v.toBool());
175 void InputWidget::setShowStyleButtons(const QVariant &v) {
176 ui.showStyleButton->setVisible(v.toBool());
179 void InputWidget::setEnablePerChatHistory(const QVariant &v) {
180 _perChatHistory = v.toBool();
183 void InputWidget::setMaxLines(const QVariant &v) {
184 ui.inputEdit->setMaxHeight(v.toInt());
187 void InputWidget::setScrollBarsEnabled(const QVariant &v) {
188 ui.inputEdit->setScrollBarsEnabled(v.toBool());
191 void InputWidget::setMultiLineEnabled(const QVariant &v) {
192 ui.inputEdit->setMode(v.toBool()? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
195 bool InputWidget::eventFilter(QObject *watched, QEvent *event) {
196 if(event->type() != QEvent::KeyPress)
199 QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
201 // keys from BufferView should be sent to (and focus) the input line
202 BufferView *view = qobject_cast<BufferView *>(watched);
204 if(keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier)) ) { // normal key press
205 QChar c = keyEvent->text().at(0);
206 if(c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
208 QCoreApplication::sendEvent(inputLine(), keyEvent);
213 } else if(watched == ui.inputEdit) {
214 if(keyEvent->matches(QKeySequence::Find)) {
215 QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
226 void InputWidget::currentChanged(const QModelIndex ¤t, const QModelIndex &previous) {
227 BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
228 BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
230 if (_perChatHistory) {
232 historyMap[previousBufferId].history = inputLine()->history();
233 historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
234 historyMap[previousBufferId].idx = inputLine()->idx();
235 historyMap[previousBufferId].inputLine = inputLine()->html();
238 inputLine()->setHistory(historyMap[currentBufferId].history);
239 inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
240 inputLine()->setIdx(historyMap[currentBufferId].idx);
241 inputLine()->setHtml(historyMap[currentBufferId].inputLine);
242 inputLine()->moveCursor(QTextCursor::End,QTextCursor::MoveAnchor);
244 // FIXME this really should be in MultiLineEdit (and the const int on top removed)
245 QTextBlockFormat format = inputLine()->textCursor().blockFormat();
246 format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
247 inputLine()->textCursor().setBlockFormat(format);
250 NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
251 if(networkId == _networkId)
254 setNetwork(networkId);
255 updateNickSelector();
256 updateEnabledState();
259 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
260 QItemSelectionRange changedArea(topLeft, bottomRight);
261 if(changedArea.contains(selectionModel()->currentIndex())) {
262 updateEnabledState();
266 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
269 for(int row = start; row <= end; row++) {
270 child = model()->index(row, 0, parent);
271 if(NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
273 networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
274 if(networkId == _networkId) {
276 updateNickSelector();
282 void InputWidget::updateEnabledState() {
283 QModelIndex currentIndex = selectionModel()->currentIndex();
285 const Network *net = Client::networkModel()->networkByIndex(currentIndex);
286 bool enabled = false;
288 // disable inputline if it's a channelbuffer we parted from or...
289 enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
290 // ... if we're not connected to the network at all
291 enabled &= net->isConnected();
293 ui.inputEdit->setEnabled(enabled);
296 const Network *InputWidget::currentNetwork() const {
297 return Client::network(_networkId);
300 BufferInfo InputWidget::currentBufferInfo() const {
301 return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
304 void InputWidget::setNetwork(NetworkId networkId) {
305 if(_networkId == networkId)
308 const Network *previousNet = Client::network(_networkId);
310 disconnect(previousNet, 0, this, 0);
311 if(previousNet->me())
312 disconnect(previousNet->me(), 0, this, 0);
315 _networkId = networkId;
317 const Network *network = Client::network(networkId);
319 connect(network, SIGNAL(identitySet(IdentityId)), this, SLOT(setIdentity(IdentityId)));
321 setIdentity(network->identity());
328 void InputWidget::connectMyIrcUser() {
329 const Network *network = currentNetwork();
331 connect(network->me(), SIGNAL(nickSet(const QString &)), this, SLOT(updateNickSelector()));
332 connect(network->me(), SIGNAL(userModesSet(QString)), this, SLOT(updateNickSelector()));
333 connect(network->me(), SIGNAL(userModesAdded(QString)), this, SLOT(updateNickSelector()));
334 connect(network->me(), SIGNAL(userModesRemoved(QString)), this, SLOT(updateNickSelector()));
335 connect(network->me(), SIGNAL(awaySet(bool)), this, SLOT(updateNickSelector()));
336 disconnect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
337 updateNickSelector();
339 connect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
343 void InputWidget::setIdentity(IdentityId identityId) {
344 if(_identityId == identityId)
347 const Identity *previousIdentity = Client::identity(_identityId);
349 disconnect(previousIdentity, 0, this, 0);
351 _identityId = identityId;
353 const Identity *identity = Client::identity(identityId);
355 connect(identity, SIGNAL(nicksSet(QStringList)), this, SLOT(updateNickSelector()));
359 updateNickSelector();
362 void InputWidget::updateNickSelector() const {
365 const Network *net = currentNetwork();
369 const Identity *identity = Client::identity(net->identity());
371 qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
376 QStringList nicks = identity->nicks();
377 if((nickIdx = nicks.indexOf(net->myNick())) == -1) {
378 nicks.prepend(net->myNick());
385 IrcUser *me = net->me();
387 nicks[nickIdx] = net->myNick();
388 if(!me->userModes().isEmpty())
389 nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
392 ui.ownNick->addItems(nicks);
394 if(me && me->isAway())
395 ui.ownNick->setItemData(nickIdx, SmallIcon("user-away"), Qt::DecorationRole);
397 ui.ownNick->setCurrentIndex(nickIdx);
400 void InputWidget::changeNick(const QString &newNick) const {
401 const Network *net = currentNetwork();
402 if(!net || net->isMyNick(newNick))
405 // we reset the nick selecter as we have no confirmation yet, that this will succeed.
406 // if the action succeeds it will be properly updated anyways.
407 updateNickSelector();
408 Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
411 void InputWidget::on_inputEdit_textEntered(const QString &text) {
412 Client::userInput(currentBufferInfo(), text);
413 ui.boldButton->setChecked(false);
414 ui.underlineButton->setChecked(false);
415 ui.italicButton->setChecked(false);
418 fmt.setFontWeight(QFont::Normal);
419 fmt.setFontUnderline(false);
420 fmt.setFontItalic(false);
421 fmt.clearForeground();
422 fmt.clearBackground();
423 inputLine()->setCurrentCharFormat(fmt);
426 // Set highlighter back to active in case it was deactivated by too many errors.
427 if(ui.inputEdit->highlighter())
428 ui.inputEdit->highlighter()->setActive(true);
432 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format) {
433 QTextCursor cursor = inputLine()->textCursor();
434 cursor.mergeCharFormat(format);
435 inputLine()->mergeCurrentCharFormat(format);
438 void InputWidget::setFormatOnSelection(const QTextCharFormat &format) {
439 QTextCursor cursor = inputLine()->textCursor();
440 cursor.setCharFormat(format);
441 inputLine()->setCurrentCharFormat(format);
444 QTextCharFormat InputWidget::getFormatOfWordOrSelection() {
445 QTextCursor cursor = inputLine()->textCursor();
446 return cursor.charFormat();
449 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format) {
450 fontChanged(format.font());
453 void InputWidget::on_boldButton_clicked(bool checked) {
455 fmt.setFontWeight(checked ? QFont::Bold : QFont::Normal);
456 mergeFormatOnSelection(fmt);
459 void InputWidget::on_underlineButton_clicked(bool checked) {
461 fmt.setFontUnderline(checked);
462 mergeFormatOnSelection(fmt);
465 void InputWidget::on_italicButton_clicked(bool checked) {
467 fmt.setFontItalic(checked);
468 mergeFormatOnSelection(fmt);
471 void InputWidget::fontChanged(const QFont &f)
473 ui.boldButton->setChecked(f.bold());
474 ui.italicButton->setChecked(f.italic());
475 ui.underlineButton->setChecked(f.underline());
478 void InputWidget::colorChosen(QAction *action) {
481 if (qVariantValue<QString>(action->data()) == "") {
482 color = Qt::transparent;
483 fmt = getFormatOfWordOrSelection();
484 fmt.clearForeground();
485 setFormatOnSelection(fmt);
488 color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
489 fmt.setForeground(color);
490 mergeFormatOnSelection(fmt);
492 ui.textcolorButton->setDefaultAction(action);
493 ui.textcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-text-color"), color));
496 void InputWidget::colorHighlightChosen(QAction *action) {
499 if (qVariantValue<QString>(action->data()) == "") {
500 color = Qt::transparent;
501 fmt = getFormatOfWordOrSelection();
502 fmt.clearBackground();
503 setFormatOnSelection(fmt);
506 color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
507 fmt.setBackground(color);
508 mergeFormatOnSelection(fmt);
510 ui.highlightcolorButton->setDefaultAction(action);
511 ui.highlightcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-fill-color"), color));
514 void InputWidget::on_showStyleButton_toggled(bool checked) {
515 ui.styleFrame->setVisible(checked);
517 ui.showStyleButton->setArrowType(Qt::LeftArrow);
520 ui.showStyleButton->setArrowType(Qt::RightArrow);
524 QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color) {
525 QPixmap pixmap(16, 16);
526 pixmap.fill(Qt::transparent);
527 QPainter painter(&pixmap);
528 QPixmap image = icon.pixmap(16,16);
529 QRect target(0, 0, 16, 14);
530 QRect source(0, 0, 16, 14);
531 painter.fillRect(QRect(0, 14, 16, 16), color);
532 painter.drawPixmap(target, image, source);
534 return QIcon(pixmap);
537 // MOUSE WHEEL FILTER
538 MouseWheelFilter::MouseWheelFilter(QObject *parent)
543 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event) {
544 if(event->type() != QEvent::Wheel)
545 return QObject::eventFilter(obj, event);