since seezer was too slow: fixing double click buffer switches in the chatmonitor
[quassel.git] / src / qtui / inputwidget.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2010 by the Quassel Project                        *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include "inputwidget.h"
22
23 #include "action.h"
24 #include "actioncollection.h"
25 #include "bufferview.h"
26 #include "client.h"
27 #include "iconloader.h"
28 #include "ircuser.h"
29 #include "jumpkeyhandler.h"
30 #include "networkmodel.h"
31 #include "qtui.h"
32 #include "qtuisettings.h"
33 #include "tabcompleter.h"
34 #include <QPainter>
35
36 InputWidget::InputWidget(QWidget *parent)
37   : AbstractItemView(parent),
38     _networkId(0)
39 {
40   ui.setupUi(this);
41   connect(ui.ownNick, SIGNAL(activated(QString)), this, SLOT(changeNick(QString)));
42
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);
47
48   ui.styleFrame->setVisible(false);
49
50   setFocusProxy(ui.inputEdit);
51   ui.ownNick->setFocusProxy(ui.inputEdit);
52
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);
57
58   ui.inputEdit->setMinHeight(1);
59   ui.inputEdit->setMaxHeight(5);
60   ui.inputEdit->setMode(MultiLineEdit::MultiLine);
61   ui.inputEdit->setPasteProtectionEnabled(true);
62
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"));
68
69   _colorMenu = new QMenu();
70   _colorFillMenu = new QMenu();
71
72   QStringList names;
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");
75
76   QPixmap pix(16, 16);
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]);
81   }
82
83   pix.fill(Qt::transparent);
84   _colorMenu->addAction(pix, tr("Clear Color"))->setData("");
85   _colorFillMenu->addAction(pix, tr("Clear Color"))->setData("");
86
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*)));
91
92   new TabCompleter(ui.inputEdit);
93
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()));
99
100   UiSettings s("InputWidget");
101
102 #ifdef HAVE_KDE
103   s.notify("EnableSpellCheck", this, SLOT(setEnableSpellCheck(QVariant)));
104   setEnableSpellCheck(s.value("EnableSpellCheck", false));
105 #endif
106
107   s.notify("ShowNickSelector", this, SLOT(setShowNickSelector(QVariant)));
108   setShowNickSelector(s.value("ShowNickSelector", true));
109
110   s.notify("ShowStyleButtons", this, SLOT(setShowStyleButtons(QVariant)));
111   setShowStyleButtons(s.value("ShowStyleButtons", true));
112
113   s.notify("MaxNumLines", this, SLOT(setMaxLines(QVariant)));
114   setMaxLines(s.value("MaxNumLines", 5));
115
116   s.notify("EnableScrollBars", this, SLOT(setScrollBarsEnabled(QVariant)));
117   setScrollBarsEnabled(s.value("EnableScrollBars", true));
118
119   s.notify("EnableMultiLine", this, SLOT(setMultiLineEnabled(QVariant)));
120   setMultiLineEnabled(s.value("EnableMultiLine", true));
121
122   ActionCollection *coll = QtUi::actionCollection();
123
124   Action *activateInputline = coll->add<Action>("FocusInputLine");
125   connect(activateInputline, SIGNAL(triggered()), SLOT(setFocus()));
126   activateInputline->setText(tr("Focus Input Line"));
127   activateInputline->setShortcut(tr("Ctrl+L"));
128
129   connect(inputLine(), SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(currentCharFormatChanged(QTextCharFormat)));
130 }
131
132 InputWidget::~InputWidget() {
133 }
134
135 void InputWidget::setUseCustomFont(const QVariant &v) {
136   if(v.toBool()) {
137     UiStyleSettings fs("Fonts");
138     setCustomFont(fs.value("InputWidget"));
139   } else
140     setCustomFont(QFont());
141 }
142
143 void InputWidget::setCustomFont(const QVariant &v) {
144   QFont font = v.value<QFont>();
145   if(font.family().isEmpty())
146     font = QApplication::font();
147   ui.inputEdit->setCustomFont(font);
148 }
149
150 void InputWidget::setEnableSpellCheck(const QVariant &v) {
151   ui.inputEdit->setSpellCheckEnabled(v.toBool());
152 }
153
154 void InputWidget::setShowNickSelector(const QVariant &v) {
155   ui.ownNick->setVisible(v.toBool());
156 }
157
158 void InputWidget::setShowStyleButtons(const QVariant &v) {
159   ui.showStyleButton->setVisible(v.toBool());
160 }
161
162 void InputWidget::setMaxLines(const QVariant &v) {
163   ui.inputEdit->setMaxHeight(v.toInt());
164 }
165
166 void InputWidget::setScrollBarsEnabled(const QVariant &v) {
167   ui.inputEdit->setScrollBarsEnabled(v.toBool());
168 }
169
170 void InputWidget::setMultiLineEnabled(const QVariant &v) {
171   ui.inputEdit->setMode(v.toBool()? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
172 }
173
174 bool InputWidget::eventFilter(QObject *watched, QEvent *event) {
175   if(event->type() != QEvent::KeyPress)
176     return false;
177
178   QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
179
180   // keys from BufferView should be sent to (and focus) the input line
181   BufferView *view = qobject_cast<BufferView *>(watched);
182   if(view) {
183     if(keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier)) ) { // normal key press
184       QChar c = keyEvent->text().at(0);
185       if(c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
186         setFocus();
187         QCoreApplication::sendEvent(inputLine(), keyEvent);
188         return true;
189       }
190     }
191     return false;
192   } else if(watched == ui.inputEdit) {
193     if(keyEvent->matches(QKeySequence::Find)) {
194       QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
195       if(act) {
196         act->toggle();
197         return true;
198       }
199     }
200     return false;
201   }
202   return false;
203 }
204
205 void InputWidget::currentChanged(const QModelIndex &current, const QModelIndex &previous) {
206   Q_UNUSED(previous)
207   NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
208   if(networkId == _networkId)
209     return;
210
211   setNetwork(networkId);
212   updateNickSelector();
213   updateEnabledState();
214 }
215
216 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
217   QItemSelectionRange changedArea(topLeft, bottomRight);
218   if(changedArea.contains(selectionModel()->currentIndex())) {
219     updateEnabledState();
220   }
221 };
222
223 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
224   NetworkId networkId;
225   QModelIndex child;
226   for(int row = start; row <= end; row++) {
227     child = model()->index(row, 0, parent);
228     if(NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
229       continue;
230     networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
231     if(networkId == _networkId) {
232       setNetwork(0);
233       updateNickSelector();
234       return;
235     }
236   }
237 }
238
239 void InputWidget::updateEnabledState() {
240   QModelIndex currentIndex = selectionModel()->currentIndex();
241
242   const Network *net = Client::networkModel()->networkByIndex(currentIndex);
243   bool enabled = false;
244   if(net) {
245     // disable inputline if it's a channelbuffer we parted from or...
246     enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
247     // ... if we're not connected to the network at all
248     enabled &= net->isConnected();
249   }
250   ui.inputEdit->setEnabled(enabled);
251 }
252
253 const Network *InputWidget::currentNetwork() const {
254   return Client::network(_networkId);
255 }
256
257 BufferInfo InputWidget::currentBufferInfo() const {
258   return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
259 };
260
261 void InputWidget::setNetwork(NetworkId networkId) {
262   if(_networkId == networkId)
263     return;
264
265   const Network *previousNet = Client::network(_networkId);
266   if(previousNet) {
267     disconnect(previousNet, 0, this, 0);
268     if(previousNet->me())
269       disconnect(previousNet->me(), 0, this, 0);
270   }
271
272   _networkId = networkId;
273
274   const Network *network = Client::network(networkId);
275   if(network) {
276     connect(network, SIGNAL(identitySet(IdentityId)), this, SLOT(setIdentity(IdentityId)));
277     connectMyIrcUser();
278     setIdentity(network->identity());
279   } else {
280     setIdentity(0);
281     _networkId = 0;
282   }
283 }
284
285 void InputWidget::connectMyIrcUser() {
286   const Network *network = currentNetwork();
287   if(network->me()) {
288     connect(network->me(), SIGNAL(nickSet(const QString &)), this, SLOT(updateNickSelector()));
289     connect(network->me(), SIGNAL(userModesSet(QString)), this, SLOT(updateNickSelector()));
290     connect(network->me(), SIGNAL(userModesAdded(QString)), this, SLOT(updateNickSelector()));
291     connect(network->me(), SIGNAL(userModesRemoved(QString)), this, SLOT(updateNickSelector()));
292     connect(network->me(), SIGNAL(awaySet(bool)), this, SLOT(updateNickSelector()));
293     disconnect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
294     updateNickSelector();
295   } else {
296     connect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
297   }
298 }
299
300 void InputWidget::setIdentity(IdentityId identityId) {
301   if(_identityId == identityId)
302     return;
303
304   const Identity *previousIdentity = Client::identity(_identityId);
305   if(previousIdentity)
306     disconnect(previousIdentity, 0, this, 0);
307
308   _identityId = identityId;
309
310   const Identity *identity = Client::identity(identityId);
311   if(identity) {
312     connect(identity, SIGNAL(nicksSet(QStringList)), this, SLOT(updateNickSelector()));
313   } else {
314     _identityId = 0;
315   }
316   updateNickSelector();
317 }
318
319 void InputWidget::updateNickSelector() const {
320   ui.ownNick->clear();
321
322   const Network *net = currentNetwork();
323   if(!net)
324     return;
325
326   const Identity *identity = Client::identity(net->identity());
327   if(!identity) {
328     qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
329     return;
330   }
331
332   int nickIdx;
333   QStringList nicks = identity->nicks();
334   if((nickIdx = nicks.indexOf(net->myNick())) == -1) {
335     nicks.prepend(net->myNick());
336     nickIdx = 0;
337   }
338
339   if(nicks.isEmpty())
340     return;
341
342   IrcUser *me = net->me();
343   if(me) {
344     nicks[nickIdx] = net->myNick();
345     if(!me->userModes().isEmpty())
346       nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
347   }
348
349   ui.ownNick->addItems(nicks);
350
351   if(me && me->isAway())
352     ui.ownNick->setItemData(nickIdx, SmallIcon("user-away"), Qt::DecorationRole);
353
354   ui.ownNick->setCurrentIndex(nickIdx);
355 }
356
357 void InputWidget::changeNick(const QString &newNick) const {
358   const Network *net = currentNetwork();
359   if(!net || net->isMyNick(newNick))
360     return;
361
362   // we reset the nick selecter as we have no confirmation yet, that this will succeed.
363   // if the action succeeds it will be properly updated anyways.
364   updateNickSelector();
365   Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
366 }
367
368 void InputWidget::on_inputEdit_textEntered(const QString &text) {
369   Client::userInput(currentBufferInfo(), text);
370   ui.boldButton->setChecked(false);
371   ui.underlineButton->setChecked(false);
372   ui.italicButton->setChecked(false);
373
374   QTextCharFormat fmt;
375   fmt.setFontWeight(QFont::Normal);
376   fmt.setFontUnderline(false);
377   fmt.setFontItalic(false);
378   fmt.clearForeground();
379   fmt.clearBackground();
380   inputLine()->setCurrentCharFormat(fmt);
381
382 #ifdef HAVE_KDE
383   // Set highlighter back to active in case it was deactivated by too many errors.
384   if(ui.inputEdit->highlighter())
385     ui.inputEdit->highlighter()->setActive(true);
386 #endif
387 }
388
389 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format) {
390   QTextCursor cursor = inputLine()->textCursor();
391   cursor.mergeCharFormat(format);
392   inputLine()->mergeCurrentCharFormat(format);
393 }
394
395 void InputWidget::setFormatOnSelection(const QTextCharFormat &format) {
396   QTextCursor cursor = inputLine()->textCursor();
397   cursor.setCharFormat(format);
398   inputLine()->setCurrentCharFormat(format);
399 }
400
401 QTextCharFormat InputWidget::getFormatOfWordOrSelection() {
402   QTextCursor cursor = inputLine()->textCursor();
403   return cursor.charFormat();
404 }
405
406 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format) {
407   fontChanged(format.font());
408 }
409
410 void InputWidget::on_boldButton_clicked(bool checked) {
411   QTextCharFormat fmt;
412   fmt.setFontWeight(checked ? QFont::Bold : QFont::Normal);
413   mergeFormatOnSelection(fmt);
414 }
415
416 void InputWidget::on_underlineButton_clicked(bool checked) {
417   QTextCharFormat fmt;
418   fmt.setFontUnderline(checked);
419   mergeFormatOnSelection(fmt);
420 }
421
422 void InputWidget::on_italicButton_clicked(bool checked) {
423   QTextCharFormat fmt;
424   fmt.setFontItalic(checked);
425   mergeFormatOnSelection(fmt);
426 }
427
428 void InputWidget::fontChanged(const QFont &f)
429 {
430   ui.boldButton->setChecked(f.bold());
431   ui.italicButton->setChecked(f.italic());
432   ui.underlineButton->setChecked(f.underline());
433 }
434
435 void InputWidget::colorChosen(QAction *action) {
436   QTextCharFormat fmt;
437   QColor color;
438   if (qVariantValue<QString>(action->data()) == "") {
439     color = Qt::transparent;
440     fmt = getFormatOfWordOrSelection();
441     fmt.clearForeground();
442     setFormatOnSelection(fmt);
443   }
444   else {
445     color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
446     fmt.setForeground(color);
447     mergeFormatOnSelection(fmt);
448   }
449   ui.textcolorButton->setDefaultAction(action);
450   ui.textcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-text-color"), color));
451 }
452
453 void InputWidget::colorHighlightChosen(QAction *action) {
454   QTextCharFormat fmt;
455   QColor color;
456   if (qVariantValue<QString>(action->data()) == "") {
457     color = Qt::transparent;
458     fmt = getFormatOfWordOrSelection();
459     fmt.clearBackground();
460     setFormatOnSelection(fmt);
461   }
462   else {
463     color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
464     fmt.setBackground(color);
465     mergeFormatOnSelection(fmt);
466   }
467   ui.highlightcolorButton->setDefaultAction(action);
468   ui.highlightcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-fill-color"), color));
469 }
470
471 void InputWidget::on_showStyleButton_toggled(bool checked) {
472   ui.styleFrame->setVisible(checked);
473   if (checked) {
474     ui.showStyleButton->setArrowType(Qt::LeftArrow);
475   }
476   else {
477     ui.showStyleButton->setArrowType(Qt::RightArrow);
478   }
479 }
480
481 QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color) {
482   QPixmap pixmap(16, 16);
483   pixmap.fill(Qt::transparent);
484   QPainter painter(&pixmap);
485   QPixmap image = icon.pixmap(16,16);
486   QRect target(0, 0, 16, 14);
487   QRect source(0, 0, 16, 14);
488   painter.fillRect(QRect(0, 14, 16, 16), color);
489   painter.drawPixmap(target, image, source);
490
491   return QIcon(pixmap);
492 }
493
494 // MOUSE WHEEL FILTER
495 MouseWheelFilter::MouseWheelFilter(QObject *parent)
496   : QObject(parent)
497 {
498 }
499
500 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event) {
501   if(event->type() != QEvent::Wheel)
502     return QObject::eventFilter(obj, event);
503   else
504     return true;
505 }