Fix genversion error in unclean build directories
[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 const int leftMargin = 3;
37
38 InputWidget::InputWidget(QWidget *parent)
39   : AbstractItemView(parent),
40     _networkId(0)
41 {
42   ui.setupUi(this);
43   connect(ui.ownNick, SIGNAL(activated(QString)), this, SLOT(changeNick(QString)));
44
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);
49
50   ui.styleFrame->setVisible(false);
51
52   setFocusProxy(ui.inputEdit);
53   ui.ownNick->setFocusProxy(ui.inputEdit);
54
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);
59
60   ui.inputEdit->setMinHeight(1);
61   ui.inputEdit->setMaxHeight(5);
62   ui.inputEdit->setMode(MultiLineEdit::MultiLine);
63   ui.inputEdit->setPasteProtectionEnabled(true);
64
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"));
70
71   _colorMenu = new QMenu();
72   _colorFillMenu = new QMenu();
73
74   QStringList names;
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");
77
78   QPixmap pix(16, 16);
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]);
83   }
84
85   pix.fill(Qt::transparent);
86   _colorMenu->addAction(pix, tr("Clear Color"))->setData("");
87   _colorFillMenu->addAction(pix, tr("Clear Color"))->setData("");
88
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*)));
93
94   new TabCompleter(ui.inputEdit);
95
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()));
101
102   UiSettings s("InputWidget");
103
104 #ifdef HAVE_KDE
105   s.notify("EnableSpellCheck", this, SLOT(setEnableSpellCheck(QVariant)));
106   setEnableSpellCheck(s.value("EnableSpellCheck", false));
107 #endif
108
109   s.notify("ShowNickSelector", this, SLOT(setShowNickSelector(QVariant)));
110   setShowNickSelector(s.value("ShowNickSelector", true));
111
112   s.notify("ShowStyleButtons", this, SLOT(setShowStyleButtons(QVariant)));
113   setShowStyleButtons(s.value("ShowStyleButtons", true));
114
115   s.notify("EnablePerChatHistory", this, SLOT(setEnablePerChatHistory(QVariant)));
116   setEnablePerChatHistory(s.value("EnablePerChatHistory", false));
117
118   s.notify("MaxNumLines", this, SLOT(setMaxLines(QVariant)));
119   setMaxLines(s.value("MaxNumLines", 5));
120
121   s.notify("EnableScrollBars", this, SLOT(setScrollBarsEnabled(QVariant)));
122   setScrollBarsEnabled(s.value("EnableScrollBars", true));
123
124   s.notify("EnableMultiLine", this, SLOT(setMultiLineEnabled(QVariant)));
125   setMultiLineEnabled(s.value("EnableMultiLine", true));
126
127   ActionCollection *coll = QtUi::actionCollection();
128
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"));
133
134   connect(inputLine(), SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(currentCharFormatChanged(QTextCharFormat)));
135 }
136
137 InputWidget::~InputWidget() {
138 }
139
140 void InputWidget::setUseCustomFont(const QVariant &v) {
141   if(v.toBool()) {
142     UiStyleSettings fs("Fonts");
143     setCustomFont(fs.value("InputWidget"));
144   } else
145     setCustomFont(QFont());
146 }
147
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);
153 }
154
155 void InputWidget::setEnableSpellCheck(const QVariant &v) {
156   ui.inputEdit->setSpellCheckEnabled(v.toBool());
157 }
158
159 void InputWidget::setShowNickSelector(const QVariant &v) {
160   ui.ownNick->setVisible(v.toBool());
161 }
162
163 void InputWidget::setShowStyleButtons(const QVariant &v) {
164   ui.showStyleButton->setVisible(v.toBool());
165 }
166
167 void InputWidget::setEnablePerChatHistory(const QVariant &v) {
168   _perChatHistory = v.toBool();
169 }
170
171 void InputWidget::setMaxLines(const QVariant &v) {
172   ui.inputEdit->setMaxHeight(v.toInt());
173 }
174
175 void InputWidget::setScrollBarsEnabled(const QVariant &v) {
176   ui.inputEdit->setScrollBarsEnabled(v.toBool());
177 }
178
179 void InputWidget::setMultiLineEnabled(const QVariant &v) {
180   ui.inputEdit->setMode(v.toBool()? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
181 }
182
183 bool InputWidget::eventFilter(QObject *watched, QEvent *event) {
184   if(event->type() != QEvent::KeyPress)
185     return false;
186
187   QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
188
189   // keys from BufferView should be sent to (and focus) the input line
190   BufferView *view = qobject_cast<BufferView *>(watched);
191   if(view) {
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()) {
195         setFocus();
196         QCoreApplication::sendEvent(inputLine(), keyEvent);
197         return true;
198       }
199     }
200     return false;
201   } else if(watched == ui.inputEdit) {
202     if(keyEvent->matches(QKeySequence::Find)) {
203       QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
204       if(act) {
205         act->toggle();
206         return true;
207       }
208     }
209     return false;
210   }
211   return false;
212 }
213
214 void InputWidget::currentChanged(const QModelIndex &current, const QModelIndex &previous) {
215   BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
216   BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
217
218   if (_perChatHistory) {
219     //backup
220     historyMap[previousBufferId].history = inputLine()->history();
221     historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
222     historyMap[previousBufferId].idx = inputLine()->idx();
223     historyMap[previousBufferId].inputLine = inputLine()->html();
224
225     //restore
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);
231
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);
236   }
237
238   NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
239   if(networkId == _networkId)
240     return;
241
242   setNetwork(networkId);
243   updateNickSelector();
244   updateEnabledState();
245 }
246
247 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
248   QItemSelectionRange changedArea(topLeft, bottomRight);
249   if(changedArea.contains(selectionModel()->currentIndex())) {
250     updateEnabledState();
251   }
252 };
253
254 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
255   NetworkId networkId;
256   QModelIndex child;
257   for(int row = start; row <= end; row++) {
258     child = model()->index(row, 0, parent);
259     if(NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
260       continue;
261     networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
262     if(networkId == _networkId) {
263       setNetwork(0);
264       updateNickSelector();
265       return;
266     }
267   }
268 }
269
270 void InputWidget::updateEnabledState() {
271   QModelIndex currentIndex = selectionModel()->currentIndex();
272
273   const Network *net = Client::networkModel()->networkByIndex(currentIndex);
274   bool enabled = false;
275   if(net) {
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();
280   }
281   ui.inputEdit->setEnabled(enabled);
282 }
283
284 const Network *InputWidget::currentNetwork() const {
285   return Client::network(_networkId);
286 }
287
288 BufferInfo InputWidget::currentBufferInfo() const {
289   return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
290 };
291
292 void InputWidget::setNetwork(NetworkId networkId) {
293   if(_networkId == networkId)
294     return;
295
296   const Network *previousNet = Client::network(_networkId);
297   if(previousNet) {
298     disconnect(previousNet, 0, this, 0);
299     if(previousNet->me())
300       disconnect(previousNet->me(), 0, this, 0);
301   }
302
303   _networkId = networkId;
304
305   const Network *network = Client::network(networkId);
306   if(network) {
307     connect(network, SIGNAL(identitySet(IdentityId)), this, SLOT(setIdentity(IdentityId)));
308     connectMyIrcUser();
309     setIdentity(network->identity());
310   } else {
311     setIdentity(0);
312     _networkId = 0;
313   }
314 }
315
316 void InputWidget::connectMyIrcUser() {
317   const Network *network = currentNetwork();
318   if(network->me()) {
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();
326   } else {
327     connect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
328   }
329 }
330
331 void InputWidget::setIdentity(IdentityId identityId) {
332   if(_identityId == identityId)
333     return;
334
335   const Identity *previousIdentity = Client::identity(_identityId);
336   if(previousIdentity)
337     disconnect(previousIdentity, 0, this, 0);
338
339   _identityId = identityId;
340
341   const Identity *identity = Client::identity(identityId);
342   if(identity) {
343     connect(identity, SIGNAL(nicksSet(QStringList)), this, SLOT(updateNickSelector()));
344   } else {
345     _identityId = 0;
346   }
347   updateNickSelector();
348 }
349
350 void InputWidget::updateNickSelector() const {
351   ui.ownNick->clear();
352
353   const Network *net = currentNetwork();
354   if(!net)
355     return;
356
357   const Identity *identity = Client::identity(net->identity());
358   if(!identity) {
359     qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
360     return;
361   }
362
363   int nickIdx;
364   QStringList nicks = identity->nicks();
365   if((nickIdx = nicks.indexOf(net->myNick())) == -1) {
366     nicks.prepend(net->myNick());
367     nickIdx = 0;
368   }
369
370   if(nicks.isEmpty())
371     return;
372
373   IrcUser *me = net->me();
374   if(me) {
375     nicks[nickIdx] = net->myNick();
376     if(!me->userModes().isEmpty())
377       nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
378   }
379
380   ui.ownNick->addItems(nicks);
381
382   if(me && me->isAway())
383     ui.ownNick->setItemData(nickIdx, SmallIcon("user-away"), Qt::DecorationRole);
384
385   ui.ownNick->setCurrentIndex(nickIdx);
386 }
387
388 void InputWidget::changeNick(const QString &newNick) const {
389   const Network *net = currentNetwork();
390   if(!net || net->isMyNick(newNick))
391     return;
392
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));
397 }
398
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);
404
405   QTextCharFormat fmt;
406   fmt.setFontWeight(QFont::Normal);
407   fmt.setFontUnderline(false);
408   fmt.setFontItalic(false);
409   fmt.clearForeground();
410   fmt.clearBackground();
411   inputLine()->setCurrentCharFormat(fmt);
412
413 #ifdef HAVE_KDE
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);
417 #endif
418 }
419
420 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format) {
421   QTextCursor cursor = inputLine()->textCursor();
422   cursor.mergeCharFormat(format);
423   inputLine()->mergeCurrentCharFormat(format);
424 }
425
426 void InputWidget::setFormatOnSelection(const QTextCharFormat &format) {
427   QTextCursor cursor = inputLine()->textCursor();
428   cursor.setCharFormat(format);
429   inputLine()->setCurrentCharFormat(format);
430 }
431
432 QTextCharFormat InputWidget::getFormatOfWordOrSelection() {
433   QTextCursor cursor = inputLine()->textCursor();
434   return cursor.charFormat();
435 }
436
437 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format) {
438   fontChanged(format.font());
439 }
440
441 void InputWidget::on_boldButton_clicked(bool checked) {
442   QTextCharFormat fmt;
443   fmt.setFontWeight(checked ? QFont::Bold : QFont::Normal);
444   mergeFormatOnSelection(fmt);
445 }
446
447 void InputWidget::on_underlineButton_clicked(bool checked) {
448   QTextCharFormat fmt;
449   fmt.setFontUnderline(checked);
450   mergeFormatOnSelection(fmt);
451 }
452
453 void InputWidget::on_italicButton_clicked(bool checked) {
454   QTextCharFormat fmt;
455   fmt.setFontItalic(checked);
456   mergeFormatOnSelection(fmt);
457 }
458
459 void InputWidget::fontChanged(const QFont &f)
460 {
461   ui.boldButton->setChecked(f.bold());
462   ui.italicButton->setChecked(f.italic());
463   ui.underlineButton->setChecked(f.underline());
464 }
465
466 void InputWidget::colorChosen(QAction *action) {
467   QTextCharFormat fmt;
468   QColor color;
469   if (qVariantValue<QString>(action->data()) == "") {
470     color = Qt::transparent;
471     fmt = getFormatOfWordOrSelection();
472     fmt.clearForeground();
473     setFormatOnSelection(fmt);
474   }
475   else {
476     color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
477     fmt.setForeground(color);
478     mergeFormatOnSelection(fmt);
479   }
480   ui.textcolorButton->setDefaultAction(action);
481   ui.textcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-text-color"), color));
482 }
483
484 void InputWidget::colorHighlightChosen(QAction *action) {
485   QTextCharFormat fmt;
486   QColor color;
487   if (qVariantValue<QString>(action->data()) == "") {
488     color = Qt::transparent;
489     fmt = getFormatOfWordOrSelection();
490     fmt.clearBackground();
491     setFormatOnSelection(fmt);
492   }
493   else {
494     color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
495     fmt.setBackground(color);
496     mergeFormatOnSelection(fmt);
497   }
498   ui.highlightcolorButton->setDefaultAction(action);
499   ui.highlightcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-fill-color"), color));
500 }
501
502 void InputWidget::on_showStyleButton_toggled(bool checked) {
503   ui.styleFrame->setVisible(checked);
504   if (checked) {
505     ui.showStyleButton->setArrowType(Qt::LeftArrow);
506   }
507   else {
508     ui.showStyleButton->setArrowType(Qt::RightArrow);
509   }
510 }
511
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);
521
522   return QIcon(pixmap);
523 }
524
525 // MOUSE WHEEL FILTER
526 MouseWheelFilter::MouseWheelFilter(QObject *parent)
527   : QObject(parent)
528 {
529 }
530
531 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event) {
532   if(event->type() != QEvent::Wheel)
533     return QObject::eventFilter(obj, event);
534   else
535     return true;
536 }