Fix #984 without breaking topic input
[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 "networkmodel.h"
30 #include "qtui.h"
31 #include "qtuisettings.h"
32 #include "tabcompleter.h"
33 #include <QPainter>
34
35 const int leftMargin = 3;
36
37 InputWidget::InputWidget(QWidget *parent)
38   : AbstractItemView(parent),
39     _networkId(0)
40 {
41   ui.setupUi(this);
42   connect(ui.ownNick, SIGNAL(activated(QString)), this, SLOT(changeNick(QString)));
43
44   layout()->setAlignment(ui.ownNick, Qt::AlignBottom);
45   layout()->setAlignment(ui.inputEdit, Qt::AlignBottom);
46   layout()->setAlignment(ui.showStyleButton, Qt::AlignBottom);
47   layout()->setAlignment(ui.styleFrame, Qt::AlignBottom);
48
49   ui.styleFrame->setVisible(false);
50
51   setFocusProxy(ui.inputEdit);
52   ui.ownNick->setFocusProxy(ui.inputEdit);
53
54   ui.ownNick->setSizeAdjustPolicy(QComboBox::AdjustToContents);
55   ui.ownNick->installEventFilter(new MouseWheelFilter(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("EnableEmacsMode", this, SLOT(setEnableEmacsMode(QVariant)));
108   setEnableEmacsMode(s.value("EnableEmacsMode", false));
109
110   s.notify("ShowNickSelector", this, SLOT(setShowNickSelector(QVariant)));
111   setShowNickSelector(s.value("ShowNickSelector", true));
112
113   s.notify("ShowStyleButtons", this, SLOT(setShowStyleButtons(QVariant)));
114   setShowStyleButtons(s.value("ShowStyleButtons", true));
115
116   s.notify("EnablePerChatHistory", this, SLOT(setEnablePerChatHistory(QVariant)));
117   setEnablePerChatHistory(s.value("EnablePerChatHistory", false));
118
119   s.notify("MaxNumLines", this, SLOT(setMaxLines(QVariant)));
120   setMaxLines(s.value("MaxNumLines", 5));
121
122   s.notify("EnableScrollBars", this, SLOT(setScrollBarsEnabled(QVariant)));
123   setScrollBarsEnabled(s.value("EnableScrollBars", true));
124
125   s.notify("EnableMultiLine", this, SLOT(setMultiLineEnabled(QVariant)));
126   setMultiLineEnabled(s.value("EnableMultiLine", true));
127
128   ActionCollection *coll = QtUi::actionCollection();
129
130   Action *activateInputline = coll->add<Action>("FocusInputLine");
131   connect(activateInputline, SIGNAL(triggered()), SLOT(setFocus()));
132   activateInputline->setText(tr("Focus Input Line"));
133   activateInputline->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_L));
134
135   connect(inputLine(), SIGNAL(textEntered(QString)), SLOT(onTextEntered(QString)), Qt::QueuedConnection); // make sure the line is already reset, bug #984
136   connect(inputLine(), SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(currentCharFormatChanged(QTextCharFormat)));
137 }
138
139 InputWidget::~InputWidget() {
140 }
141
142 void InputWidget::setUseCustomFont(const QVariant &v) {
143   if(v.toBool()) {
144     UiStyleSettings fs("Fonts");
145     setCustomFont(fs.value("InputWidget"));
146   } else
147     setCustomFont(QFont());
148 }
149
150 void InputWidget::setCustomFont(const QVariant &v) {
151   QFont font = v.value<QFont>();
152   if(font.family().isEmpty())
153     font = QApplication::font();
154   // we don't want font styles as this conflics with mirc code richtext editing
155   font.setBold(false);
156   font.setItalic(false);
157   font.setUnderline(false);
158   font.setStrikeOut(false);
159   ui.inputEdit->setCustomFont(font);
160 }
161
162 void InputWidget::setEnableSpellCheck(const QVariant &v) {
163   ui.inputEdit->setSpellCheckEnabled(v.toBool());
164 }
165
166 void InputWidget::setEnableEmacsMode(const QVariant &v) {
167   ui.inputEdit->setEmacsMode(v.toBool());
168 }
169
170 void InputWidget::setShowNickSelector(const QVariant &v) {
171   ui.ownNick->setVisible(v.toBool());
172 }
173
174 void InputWidget::setShowStyleButtons(const QVariant &v) {
175   ui.showStyleButton->setVisible(v.toBool());
176 }
177
178 void InputWidget::setEnablePerChatHistory(const QVariant &v) {
179   _perChatHistory = v.toBool();
180 }
181
182 void InputWidget::setMaxLines(const QVariant &v) {
183   ui.inputEdit->setMaxHeight(v.toInt());
184 }
185
186 void InputWidget::setScrollBarsEnabled(const QVariant &v) {
187   ui.inputEdit->setScrollBarsEnabled(v.toBool());
188 }
189
190 void InputWidget::setMultiLineEnabled(const QVariant &v) {
191   ui.inputEdit->setMode(v.toBool()? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
192 }
193
194 bool InputWidget::eventFilter(QObject *watched, QEvent *event) {
195   if(event->type() != QEvent::KeyPress)
196     return false;
197
198   QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
199
200   // keys from BufferView should be sent to (and focus) the input line
201   BufferView *view = qobject_cast<BufferView *>(watched);
202   if(view) {
203     if(keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier)) ) { // normal key press
204       QChar c = keyEvent->text().at(0);
205       if(c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
206         setFocus();
207         QCoreApplication::sendEvent(inputLine(), keyEvent);
208         return true;
209       }
210     }
211     return false;
212   } else if(watched == ui.inputEdit) {
213     if(keyEvent->matches(QKeySequence::Find)) {
214       QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
215       if(act) {
216         act->toggle();
217         return true;
218       }
219     }
220     return false;
221   }
222   return false;
223 }
224
225 void InputWidget::currentChanged(const QModelIndex &current, const QModelIndex &previous) {
226   BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
227   BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
228
229   if (_perChatHistory) {
230     //backup
231     historyMap[previousBufferId].history = inputLine()->history();
232     historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
233     historyMap[previousBufferId].idx = inputLine()->idx();
234     historyMap[previousBufferId].inputLine = inputLine()->html();
235
236     //restore
237     inputLine()->setHistory(historyMap[currentBufferId].history);
238     inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
239     inputLine()->setIdx(historyMap[currentBufferId].idx);
240     inputLine()->setHtml(historyMap[currentBufferId].inputLine);
241     inputLine()->moveCursor(QTextCursor::End,QTextCursor::MoveAnchor);
242
243     // FIXME this really should be in MultiLineEdit (and the const int on top removed)
244     QTextBlockFormat format = inputLine()->textCursor().blockFormat();
245     format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
246     inputLine()->textCursor().setBlockFormat(format);
247   }
248
249   NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
250   if(networkId == _networkId)
251     return;
252
253   setNetwork(networkId);
254   updateNickSelector();
255   updateEnabledState();
256 }
257
258 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
259   QItemSelectionRange changedArea(topLeft, bottomRight);
260   if(changedArea.contains(selectionModel()->currentIndex())) {
261     updateEnabledState();
262   }
263 };
264
265 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
266   NetworkId networkId;
267   QModelIndex child;
268   for(int row = start; row <= end; row++) {
269     child = model()->index(row, 0, parent);
270     if(NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
271       continue;
272     networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
273     if(networkId == _networkId) {
274       setNetwork(0);
275       updateNickSelector();
276       return;
277     }
278   }
279 }
280
281
282 void InputWidget::updateEnabledState() {
283 // FIXME: Find a visualization for this that does not disable the widget!
284 //        Disabling kills global action shortcuts, plus users sometimes need/want to enter text
285 //        even in inactive channels.
286 #if 0
287   QModelIndex currentIndex = selectionModel()->currentIndex();
288
289   const Network *net = Client::networkModel()->networkByIndex(currentIndex);
290   bool enabled = false;
291   if(net) {
292     // disable inputline if it's a channelbuffer we parted from or...
293     enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
294     // ... if we're not connected to the network at all
295     enabled &= net->isConnected();
296   }
297
298   ui.inputEdit->setEnabled(enabled);
299 #endif
300 }
301
302 const Network *InputWidget::currentNetwork() const {
303   return Client::network(_networkId);
304 }
305
306 BufferInfo InputWidget::currentBufferInfo() const {
307   return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
308 };
309
310 void InputWidget::setNetwork(NetworkId networkId) {
311   if(_networkId == networkId)
312     return;
313
314   const Network *previousNet = Client::network(_networkId);
315   if(previousNet) {
316     disconnect(previousNet, 0, this, 0);
317     if(previousNet->me())
318       disconnect(previousNet->me(), 0, this, 0);
319   }
320
321   _networkId = networkId;
322
323   const Network *network = Client::network(networkId);
324   if(network) {
325     connect(network, SIGNAL(identitySet(IdentityId)), this, SLOT(setIdentity(IdentityId)));
326     connectMyIrcUser();
327     setIdentity(network->identity());
328   } else {
329     setIdentity(0);
330     _networkId = 0;
331   }
332 }
333
334 void InputWidget::connectMyIrcUser() {
335   const Network *network = currentNetwork();
336   if(network->me()) {
337     connect(network->me(), SIGNAL(nickSet(const QString &)), this, SLOT(updateNickSelector()));
338     connect(network->me(), SIGNAL(userModesSet(QString)), this, SLOT(updateNickSelector()));
339     connect(network->me(), SIGNAL(userModesAdded(QString)), this, SLOT(updateNickSelector()));
340     connect(network->me(), SIGNAL(userModesRemoved(QString)), this, SLOT(updateNickSelector()));
341     connect(network->me(), SIGNAL(awaySet(bool)), this, SLOT(updateNickSelector()));
342     disconnect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
343     updateNickSelector();
344   } else {
345     connect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
346   }
347 }
348
349 void InputWidget::setIdentity(IdentityId identityId) {
350   if(_identityId == identityId)
351     return;
352
353   const Identity *previousIdentity = Client::identity(_identityId);
354   if(previousIdentity)
355     disconnect(previousIdentity, 0, this, 0);
356
357   _identityId = identityId;
358
359   const Identity *identity = Client::identity(identityId);
360   if(identity) {
361     connect(identity, SIGNAL(nicksSet(QStringList)), this, SLOT(updateNickSelector()));
362   } else {
363     _identityId = 0;
364   }
365   updateNickSelector();
366 }
367
368 void InputWidget::updateNickSelector() const {
369   ui.ownNick->clear();
370
371   const Network *net = currentNetwork();
372   if(!net)
373     return;
374
375   const Identity *identity = Client::identity(net->identity());
376   if(!identity) {
377     qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
378     return;
379   }
380
381   int nickIdx;
382   QStringList nicks = identity->nicks();
383   if((nickIdx = nicks.indexOf(net->myNick())) == -1) {
384     nicks.prepend(net->myNick());
385     nickIdx = 0;
386   }
387
388   if(nicks.isEmpty())
389     return;
390
391   IrcUser *me = net->me();
392   if(me) {
393     nicks[nickIdx] = net->myNick();
394     if(!me->userModes().isEmpty())
395       nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
396   }
397
398   ui.ownNick->addItems(nicks);
399
400   if(me && me->isAway())
401     ui.ownNick->setItemData(nickIdx, SmallIcon("user-away"), Qt::DecorationRole);
402
403   ui.ownNick->setCurrentIndex(nickIdx);
404 }
405
406 void InputWidget::changeNick(const QString &newNick) const {
407   const Network *net = currentNetwork();
408   if(!net || net->isMyNick(newNick))
409     return;
410
411   // we reset the nick selecter as we have no confirmation yet, that this will succeed.
412   // if the action succeeds it will be properly updated anyways.
413   updateNickSelector();
414   Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
415 }
416
417 void InputWidget::onTextEntered(const QString &text) {
418   Client::userInput(currentBufferInfo(), text);
419   ui.boldButton->setChecked(false);
420   ui.underlineButton->setChecked(false);
421   ui.italicButton->setChecked(false);
422
423   QTextCharFormat fmt;
424   fmt.setFontWeight(QFont::Normal);
425   fmt.setFontUnderline(false);
426   fmt.setFontItalic(false);
427   fmt.clearForeground();
428   fmt.clearBackground();
429   inputLine()->setCurrentCharFormat(fmt);
430
431 #ifdef HAVE_KDE
432   // Set highlighter back to active in case it was deactivated by too many errors.
433   if(ui.inputEdit->highlighter())
434     ui.inputEdit->highlighter()->setActive(true);
435 #endif
436 }
437
438 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format) {
439   QTextCursor cursor = inputLine()->textCursor();
440   cursor.mergeCharFormat(format);
441   inputLine()->mergeCurrentCharFormat(format);
442 }
443
444 void InputWidget::setFormatOnSelection(const QTextCharFormat &format) {
445   QTextCursor cursor = inputLine()->textCursor();
446   cursor.setCharFormat(format);
447   inputLine()->setCurrentCharFormat(format);
448 }
449
450 QTextCharFormat InputWidget::getFormatOfWordOrSelection() {
451   QTextCursor cursor = inputLine()->textCursor();
452   return cursor.charFormat();
453 }
454
455 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format) {
456   fontChanged(format.font());
457 }
458
459 void InputWidget::on_boldButton_clicked(bool checked) {
460   QTextCharFormat fmt;
461   fmt.setFontWeight(checked ? QFont::Bold : QFont::Normal);
462   mergeFormatOnSelection(fmt);
463 }
464
465 void InputWidget::on_underlineButton_clicked(bool checked) {
466   QTextCharFormat fmt;
467   fmt.setFontUnderline(checked);
468   mergeFormatOnSelection(fmt);
469 }
470
471 void InputWidget::on_italicButton_clicked(bool checked) {
472   QTextCharFormat fmt;
473   fmt.setFontItalic(checked);
474   mergeFormatOnSelection(fmt);
475 }
476
477 void InputWidget::fontChanged(const QFont &f)
478 {
479   ui.boldButton->setChecked(f.bold());
480   ui.italicButton->setChecked(f.italic());
481   ui.underlineButton->setChecked(f.underline());
482 }
483
484 void InputWidget::colorChosen(QAction *action) {
485   QTextCharFormat fmt;
486   QColor color;
487   if (qVariantValue<QString>(action->data()) == "") {
488     color = Qt::transparent;
489     fmt = getFormatOfWordOrSelection();
490     fmt.clearForeground();
491     setFormatOnSelection(fmt);
492   }
493   else {
494     color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
495     fmt.setForeground(color);
496     mergeFormatOnSelection(fmt);
497   }
498   ui.textcolorButton->setDefaultAction(action);
499   ui.textcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-text-color"), color));
500 }
501
502 void InputWidget::colorHighlightChosen(QAction *action) {
503   QTextCharFormat fmt;
504   QColor color;
505   if (qVariantValue<QString>(action->data()) == "") {
506     color = Qt::transparent;
507     fmt = getFormatOfWordOrSelection();
508     fmt.clearBackground();
509     setFormatOnSelection(fmt);
510   }
511   else {
512     color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
513     fmt.setBackground(color);
514     mergeFormatOnSelection(fmt);
515   }
516   ui.highlightcolorButton->setDefaultAction(action);
517   ui.highlightcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-fill-color"), color));
518 }
519
520 void InputWidget::on_showStyleButton_toggled(bool checked) {
521   ui.styleFrame->setVisible(checked);
522   if (checked) {
523     ui.showStyleButton->setArrowType(Qt::LeftArrow);
524   }
525   else {
526     ui.showStyleButton->setArrowType(Qt::RightArrow);
527   }
528 }
529
530 QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color) {
531   QPixmap pixmap(16, 16);
532   pixmap.fill(Qt::transparent);
533   QPainter painter(&pixmap);
534   QPixmap image = icon.pixmap(16,16);
535   QRect target(0, 0, 16, 14);
536   QRect source(0, 0, 16, 14);
537   painter.fillRect(QRect(0, 14, 16, 16), color);
538   painter.drawPixmap(target, image, source);
539
540   return QIcon(pixmap);
541 }
542
543 // MOUSE WHEEL FILTER
544 MouseWheelFilter::MouseWheelFilter(QObject *parent)
545   : QObject(parent)
546 {
547 }
548
549 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event) {
550   if(event->type() != QEvent::Wheel)
551     return QObject::eventFilter(obj, event);
552   else
553     return true;
554 }