Fix tray icon behavior for non-KDE StatusNotifier
[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(QKeySequence(Qt::CTRL + Qt::Key_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   // we don't want font styles as this conflics with mirc code richtext editing
153   font.setBold(false);
154   font.setItalic(false);
155   font.setUnderline(false);
156   font.setStrikeOut(false);
157   ui.inputEdit->setCustomFont(font);
158 }
159
160 void InputWidget::setEnableSpellCheck(const QVariant &v) {
161   ui.inputEdit->setSpellCheckEnabled(v.toBool());
162 }
163
164 void InputWidget::setShowNickSelector(const QVariant &v) {
165   ui.ownNick->setVisible(v.toBool());
166 }
167
168 void InputWidget::setShowStyleButtons(const QVariant &v) {
169   ui.showStyleButton->setVisible(v.toBool());
170 }
171
172 void InputWidget::setEnablePerChatHistory(const QVariant &v) {
173   _perChatHistory = v.toBool();
174 }
175
176 void InputWidget::setMaxLines(const QVariant &v) {
177   ui.inputEdit->setMaxHeight(v.toInt());
178 }
179
180 void InputWidget::setScrollBarsEnabled(const QVariant &v) {
181   ui.inputEdit->setScrollBarsEnabled(v.toBool());
182 }
183
184 void InputWidget::setMultiLineEnabled(const QVariant &v) {
185   ui.inputEdit->setMode(v.toBool()? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
186 }
187
188 bool InputWidget::eventFilter(QObject *watched, QEvent *event) {
189   if(event->type() != QEvent::KeyPress)
190     return false;
191
192   QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
193
194   // keys from BufferView should be sent to (and focus) the input line
195   BufferView *view = qobject_cast<BufferView *>(watched);
196   if(view) {
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()) {
200         setFocus();
201         QCoreApplication::sendEvent(inputLine(), keyEvent);
202         return true;
203       }
204     }
205     return false;
206   } else if(watched == ui.inputEdit) {
207     if(keyEvent->matches(QKeySequence::Find)) {
208       QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
209       if(act) {
210         act->toggle();
211         return true;
212       }
213     }
214     return false;
215   }
216   return false;
217 }
218
219 void InputWidget::currentChanged(const QModelIndex &current, const QModelIndex &previous) {
220   BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
221   BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
222
223   if (_perChatHistory) {
224     //backup
225     historyMap[previousBufferId].history = inputLine()->history();
226     historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
227     historyMap[previousBufferId].idx = inputLine()->idx();
228     historyMap[previousBufferId].inputLine = inputLine()->html();
229
230     //restore
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);
236
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);
241   }
242
243   NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
244   if(networkId == _networkId)
245     return;
246
247   setNetwork(networkId);
248   updateNickSelector();
249   updateEnabledState();
250 }
251
252 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
253   QItemSelectionRange changedArea(topLeft, bottomRight);
254   if(changedArea.contains(selectionModel()->currentIndex())) {
255     updateEnabledState();
256   }
257 };
258
259 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
260   NetworkId networkId;
261   QModelIndex child;
262   for(int row = start; row <= end; row++) {
263     child = model()->index(row, 0, parent);
264     if(NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
265       continue;
266     networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
267     if(networkId == _networkId) {
268       setNetwork(0);
269       updateNickSelector();
270       return;
271     }
272   }
273 }
274
275 void InputWidget::updateEnabledState() {
276   QModelIndex currentIndex = selectionModel()->currentIndex();
277
278   const Network *net = Client::networkModel()->networkByIndex(currentIndex);
279   bool enabled = false;
280   if(net) {
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();
285   }
286   ui.inputEdit->setEnabled(enabled);
287 }
288
289 const Network *InputWidget::currentNetwork() const {
290   return Client::network(_networkId);
291 }
292
293 BufferInfo InputWidget::currentBufferInfo() const {
294   return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
295 };
296
297 void InputWidget::setNetwork(NetworkId networkId) {
298   if(_networkId == networkId)
299     return;
300
301   const Network *previousNet = Client::network(_networkId);
302   if(previousNet) {
303     disconnect(previousNet, 0, this, 0);
304     if(previousNet->me())
305       disconnect(previousNet->me(), 0, this, 0);
306   }
307
308   _networkId = networkId;
309
310   const Network *network = Client::network(networkId);
311   if(network) {
312     connect(network, SIGNAL(identitySet(IdentityId)), this, SLOT(setIdentity(IdentityId)));
313     connectMyIrcUser();
314     setIdentity(network->identity());
315   } else {
316     setIdentity(0);
317     _networkId = 0;
318   }
319 }
320
321 void InputWidget::connectMyIrcUser() {
322   const Network *network = currentNetwork();
323   if(network->me()) {
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();
331   } else {
332     connect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
333   }
334 }
335
336 void InputWidget::setIdentity(IdentityId identityId) {
337   if(_identityId == identityId)
338     return;
339
340   const Identity *previousIdentity = Client::identity(_identityId);
341   if(previousIdentity)
342     disconnect(previousIdentity, 0, this, 0);
343
344   _identityId = identityId;
345
346   const Identity *identity = Client::identity(identityId);
347   if(identity) {
348     connect(identity, SIGNAL(nicksSet(QStringList)), this, SLOT(updateNickSelector()));
349   } else {
350     _identityId = 0;
351   }
352   updateNickSelector();
353 }
354
355 void InputWidget::updateNickSelector() const {
356   ui.ownNick->clear();
357
358   const Network *net = currentNetwork();
359   if(!net)
360     return;
361
362   const Identity *identity = Client::identity(net->identity());
363   if(!identity) {
364     qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
365     return;
366   }
367
368   int nickIdx;
369   QStringList nicks = identity->nicks();
370   if((nickIdx = nicks.indexOf(net->myNick())) == -1) {
371     nicks.prepend(net->myNick());
372     nickIdx = 0;
373   }
374
375   if(nicks.isEmpty())
376     return;
377
378   IrcUser *me = net->me();
379   if(me) {
380     nicks[nickIdx] = net->myNick();
381     if(!me->userModes().isEmpty())
382       nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
383   }
384
385   ui.ownNick->addItems(nicks);
386
387   if(me && me->isAway())
388     ui.ownNick->setItemData(nickIdx, SmallIcon("user-away"), Qt::DecorationRole);
389
390   ui.ownNick->setCurrentIndex(nickIdx);
391 }
392
393 void InputWidget::changeNick(const QString &newNick) const {
394   const Network *net = currentNetwork();
395   if(!net || net->isMyNick(newNick))
396     return;
397
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));
402 }
403
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);
409
410   QTextCharFormat fmt;
411   fmt.setFontWeight(QFont::Normal);
412   fmt.setFontUnderline(false);
413   fmt.setFontItalic(false);
414   fmt.clearForeground();
415   fmt.clearBackground();
416   inputLine()->setCurrentCharFormat(fmt);
417
418 #ifdef HAVE_KDE
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);
422 #endif
423 }
424
425 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format) {
426   QTextCursor cursor = inputLine()->textCursor();
427   cursor.mergeCharFormat(format);
428   inputLine()->mergeCurrentCharFormat(format);
429 }
430
431 void InputWidget::setFormatOnSelection(const QTextCharFormat &format) {
432   QTextCursor cursor = inputLine()->textCursor();
433   cursor.setCharFormat(format);
434   inputLine()->setCurrentCharFormat(format);
435 }
436
437 QTextCharFormat InputWidget::getFormatOfWordOrSelection() {
438   QTextCursor cursor = inputLine()->textCursor();
439   return cursor.charFormat();
440 }
441
442 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format) {
443   fontChanged(format.font());
444 }
445
446 void InputWidget::on_boldButton_clicked(bool checked) {
447   QTextCharFormat fmt;
448   fmt.setFontWeight(checked ? QFont::Bold : QFont::Normal);
449   mergeFormatOnSelection(fmt);
450 }
451
452 void InputWidget::on_underlineButton_clicked(bool checked) {
453   QTextCharFormat fmt;
454   fmt.setFontUnderline(checked);
455   mergeFormatOnSelection(fmt);
456 }
457
458 void InputWidget::on_italicButton_clicked(bool checked) {
459   QTextCharFormat fmt;
460   fmt.setFontItalic(checked);
461   mergeFormatOnSelection(fmt);
462 }
463
464 void InputWidget::fontChanged(const QFont &f)
465 {
466   ui.boldButton->setChecked(f.bold());
467   ui.italicButton->setChecked(f.italic());
468   ui.underlineButton->setChecked(f.underline());
469 }
470
471 void InputWidget::colorChosen(QAction *action) {
472   QTextCharFormat fmt;
473   QColor color;
474   if (qVariantValue<QString>(action->data()) == "") {
475     color = Qt::transparent;
476     fmt = getFormatOfWordOrSelection();
477     fmt.clearForeground();
478     setFormatOnSelection(fmt);
479   }
480   else {
481     color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
482     fmt.setForeground(color);
483     mergeFormatOnSelection(fmt);
484   }
485   ui.textcolorButton->setDefaultAction(action);
486   ui.textcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-text-color"), color));
487 }
488
489 void InputWidget::colorHighlightChosen(QAction *action) {
490   QTextCharFormat fmt;
491   QColor color;
492   if (qVariantValue<QString>(action->data()) == "") {
493     color = Qt::transparent;
494     fmt = getFormatOfWordOrSelection();
495     fmt.clearBackground();
496     setFormatOnSelection(fmt);
497   }
498   else {
499     color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
500     fmt.setBackground(color);
501     mergeFormatOnSelection(fmt);
502   }
503   ui.highlightcolorButton->setDefaultAction(action);
504   ui.highlightcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-fill-color"), color));
505 }
506
507 void InputWidget::on_showStyleButton_toggled(bool checked) {
508   ui.styleFrame->setVisible(checked);
509   if (checked) {
510     ui.showStyleButton->setArrowType(Qt::LeftArrow);
511   }
512   else {
513     ui.showStyleButton->setArrowType(Qt::RightArrow);
514   }
515 }
516
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);
526
527   return QIcon(pixmap);
528 }
529
530 // MOUSE WHEEL FILTER
531 MouseWheelFilter::MouseWheelFilter(QObject *parent)
532   : QObject(parent)
533 {
534 }
535
536 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event) {
537   if(event->type() != QEvent::Wheel)
538     return QObject::eventFilter(obj, event);
539   else
540     return true;
541 }