added basic support for Emacs style key bindings
[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("EnableEmacsMode", this, SLOT(setEnableEmacsMode(QVariant)));
110   setEnableEmacsMode(s.value("EnableEmacsMode", false));
111
112   s.notify("ShowNickSelector", this, SLOT(setShowNickSelector(QVariant)));
113   setShowNickSelector(s.value("ShowNickSelector", true));
114
115   s.notify("ShowStyleButtons", this, SLOT(setShowStyleButtons(QVariant)));
116   setShowStyleButtons(s.value("ShowStyleButtons", true));
117
118   s.notify("EnablePerChatHistory", this, SLOT(setEnablePerChatHistory(QVariant)));
119   setEnablePerChatHistory(s.value("EnablePerChatHistory", false));
120
121   s.notify("MaxNumLines", this, SLOT(setMaxLines(QVariant)));
122   setMaxLines(s.value("MaxNumLines", 5));
123
124   s.notify("EnableScrollBars", this, SLOT(setScrollBarsEnabled(QVariant)));
125   setScrollBarsEnabled(s.value("EnableScrollBars", true));
126
127   s.notify("EnableMultiLine", this, SLOT(setMultiLineEnabled(QVariant)));
128   setMultiLineEnabled(s.value("EnableMultiLine", true));
129
130   ActionCollection *coll = QtUi::actionCollection();
131
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));
136
137   connect(inputLine(), SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(currentCharFormatChanged(QTextCharFormat)));
138 }
139
140 InputWidget::~InputWidget() {
141 }
142
143 void InputWidget::setUseCustomFont(const QVariant &v) {
144   if(v.toBool()) {
145     UiStyleSettings fs("Fonts");
146     setCustomFont(fs.value("InputWidget"));
147   } else
148     setCustomFont(QFont());
149 }
150
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
156   font.setBold(false);
157   font.setItalic(false);
158   font.setUnderline(false);
159   font.setStrikeOut(false);
160   ui.inputEdit->setCustomFont(font);
161 }
162
163 void InputWidget::setEnableSpellCheck(const QVariant &v) {
164   ui.inputEdit->setSpellCheckEnabled(v.toBool());
165 }
166
167 void InputWidget::setEnableEmacsMode(const QVariant &v) {
168   ui.inputEdit->setEmacsMode(v.toBool());
169 }
170
171 void InputWidget::setShowNickSelector(const QVariant &v) {
172   ui.ownNick->setVisible(v.toBool());
173 }
174
175 void InputWidget::setShowStyleButtons(const QVariant &v) {
176   ui.showStyleButton->setVisible(v.toBool());
177 }
178
179 void InputWidget::setEnablePerChatHistory(const QVariant &v) {
180   _perChatHistory = v.toBool();
181 }
182
183 void InputWidget::setMaxLines(const QVariant &v) {
184   ui.inputEdit->setMaxHeight(v.toInt());
185 }
186
187 void InputWidget::setScrollBarsEnabled(const QVariant &v) {
188   ui.inputEdit->setScrollBarsEnabled(v.toBool());
189 }
190
191 void InputWidget::setMultiLineEnabled(const QVariant &v) {
192   ui.inputEdit->setMode(v.toBool()? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
193 }
194
195 bool InputWidget::eventFilter(QObject *watched, QEvent *event) {
196   if(event->type() != QEvent::KeyPress)
197     return false;
198
199   QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
200
201   // keys from BufferView should be sent to (and focus) the input line
202   BufferView *view = qobject_cast<BufferView *>(watched);
203   if(view) {
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()) {
207         setFocus();
208         QCoreApplication::sendEvent(inputLine(), keyEvent);
209         return true;
210       }
211     }
212     return false;
213   } else if(watched == ui.inputEdit) {
214     if(keyEvent->matches(QKeySequence::Find)) {
215       QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
216       if(act) {
217         act->toggle();
218         return true;
219       }
220     }
221     return false;
222   }
223   return false;
224 }
225
226 void InputWidget::currentChanged(const QModelIndex &current, const QModelIndex &previous) {
227   BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
228   BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
229
230   if (_perChatHistory) {
231     //backup
232     historyMap[previousBufferId].history = inputLine()->history();
233     historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
234     historyMap[previousBufferId].idx = inputLine()->idx();
235     historyMap[previousBufferId].inputLine = inputLine()->html();
236
237     //restore
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);
243
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);
248   }
249
250   NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
251   if(networkId == _networkId)
252     return;
253
254   setNetwork(networkId);
255   updateNickSelector();
256   updateEnabledState();
257 }
258
259 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
260   QItemSelectionRange changedArea(topLeft, bottomRight);
261   if(changedArea.contains(selectionModel()->currentIndex())) {
262     updateEnabledState();
263   }
264 };
265
266 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) {
267   NetworkId networkId;
268   QModelIndex child;
269   for(int row = start; row <= end; row++) {
270     child = model()->index(row, 0, parent);
271     if(NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
272       continue;
273     networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
274     if(networkId == _networkId) {
275       setNetwork(0);
276       updateNickSelector();
277       return;
278     }
279   }
280 }
281
282 void InputWidget::updateEnabledState() {
283   QModelIndex currentIndex = selectionModel()->currentIndex();
284
285   const Network *net = Client::networkModel()->networkByIndex(currentIndex);
286   bool enabled = false;
287   if(net) {
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();
292   }
293   ui.inputEdit->setEnabled(enabled);
294 }
295
296 const Network *InputWidget::currentNetwork() const {
297   return Client::network(_networkId);
298 }
299
300 BufferInfo InputWidget::currentBufferInfo() const {
301   return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
302 };
303
304 void InputWidget::setNetwork(NetworkId networkId) {
305   if(_networkId == networkId)
306     return;
307
308   const Network *previousNet = Client::network(_networkId);
309   if(previousNet) {
310     disconnect(previousNet, 0, this, 0);
311     if(previousNet->me())
312       disconnect(previousNet->me(), 0, this, 0);
313   }
314
315   _networkId = networkId;
316
317   const Network *network = Client::network(networkId);
318   if(network) {
319     connect(network, SIGNAL(identitySet(IdentityId)), this, SLOT(setIdentity(IdentityId)));
320     connectMyIrcUser();
321     setIdentity(network->identity());
322   } else {
323     setIdentity(0);
324     _networkId = 0;
325   }
326 }
327
328 void InputWidget::connectMyIrcUser() {
329   const Network *network = currentNetwork();
330   if(network->me()) {
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();
338   } else {
339     connect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
340   }
341 }
342
343 void InputWidget::setIdentity(IdentityId identityId) {
344   if(_identityId == identityId)
345     return;
346
347   const Identity *previousIdentity = Client::identity(_identityId);
348   if(previousIdentity)
349     disconnect(previousIdentity, 0, this, 0);
350
351   _identityId = identityId;
352
353   const Identity *identity = Client::identity(identityId);
354   if(identity) {
355     connect(identity, SIGNAL(nicksSet(QStringList)), this, SLOT(updateNickSelector()));
356   } else {
357     _identityId = 0;
358   }
359   updateNickSelector();
360 }
361
362 void InputWidget::updateNickSelector() const {
363   ui.ownNick->clear();
364
365   const Network *net = currentNetwork();
366   if(!net)
367     return;
368
369   const Identity *identity = Client::identity(net->identity());
370   if(!identity) {
371     qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
372     return;
373   }
374
375   int nickIdx;
376   QStringList nicks = identity->nicks();
377   if((nickIdx = nicks.indexOf(net->myNick())) == -1) {
378     nicks.prepend(net->myNick());
379     nickIdx = 0;
380   }
381
382   if(nicks.isEmpty())
383     return;
384
385   IrcUser *me = net->me();
386   if(me) {
387     nicks[nickIdx] = net->myNick();
388     if(!me->userModes().isEmpty())
389       nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
390   }
391
392   ui.ownNick->addItems(nicks);
393
394   if(me && me->isAway())
395     ui.ownNick->setItemData(nickIdx, SmallIcon("user-away"), Qt::DecorationRole);
396
397   ui.ownNick->setCurrentIndex(nickIdx);
398 }
399
400 void InputWidget::changeNick(const QString &newNick) const {
401   const Network *net = currentNetwork();
402   if(!net || net->isMyNick(newNick))
403     return;
404
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));
409 }
410
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);
416
417   QTextCharFormat fmt;
418   fmt.setFontWeight(QFont::Normal);
419   fmt.setFontUnderline(false);
420   fmt.setFontItalic(false);
421   fmt.clearForeground();
422   fmt.clearBackground();
423   inputLine()->setCurrentCharFormat(fmt);
424
425 #ifdef HAVE_KDE
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);
429 #endif
430 }
431
432 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format) {
433   QTextCursor cursor = inputLine()->textCursor();
434   cursor.mergeCharFormat(format);
435   inputLine()->mergeCurrentCharFormat(format);
436 }
437
438 void InputWidget::setFormatOnSelection(const QTextCharFormat &format) {
439   QTextCursor cursor = inputLine()->textCursor();
440   cursor.setCharFormat(format);
441   inputLine()->setCurrentCharFormat(format);
442 }
443
444 QTextCharFormat InputWidget::getFormatOfWordOrSelection() {
445   QTextCursor cursor = inputLine()->textCursor();
446   return cursor.charFormat();
447 }
448
449 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format) {
450   fontChanged(format.font());
451 }
452
453 void InputWidget::on_boldButton_clicked(bool checked) {
454   QTextCharFormat fmt;
455   fmt.setFontWeight(checked ? QFont::Bold : QFont::Normal);
456   mergeFormatOnSelection(fmt);
457 }
458
459 void InputWidget::on_underlineButton_clicked(bool checked) {
460   QTextCharFormat fmt;
461   fmt.setFontUnderline(checked);
462   mergeFormatOnSelection(fmt);
463 }
464
465 void InputWidget::on_italicButton_clicked(bool checked) {
466   QTextCharFormat fmt;
467   fmt.setFontItalic(checked);
468   mergeFormatOnSelection(fmt);
469 }
470
471 void InputWidget::fontChanged(const QFont &f)
472 {
473   ui.boldButton->setChecked(f.bold());
474   ui.italicButton->setChecked(f.italic());
475   ui.underlineButton->setChecked(f.underline());
476 }
477
478 void InputWidget::colorChosen(QAction *action) {
479   QTextCharFormat fmt;
480   QColor color;
481   if (qVariantValue<QString>(action->data()) == "") {
482     color = Qt::transparent;
483     fmt = getFormatOfWordOrSelection();
484     fmt.clearForeground();
485     setFormatOnSelection(fmt);
486   }
487   else {
488     color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
489     fmt.setForeground(color);
490     mergeFormatOnSelection(fmt);
491   }
492   ui.textcolorButton->setDefaultAction(action);
493   ui.textcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-text-color"), color));
494 }
495
496 void InputWidget::colorHighlightChosen(QAction *action) {
497   QTextCharFormat fmt;
498   QColor color;
499   if (qVariantValue<QString>(action->data()) == "") {
500     color = Qt::transparent;
501     fmt = getFormatOfWordOrSelection();
502     fmt.clearBackground();
503     setFormatOnSelection(fmt);
504   }
505   else {
506     color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
507     fmt.setBackground(color);
508     mergeFormatOnSelection(fmt);
509   }
510   ui.highlightcolorButton->setDefaultAction(action);
511   ui.highlightcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-fill-color"), color));
512 }
513
514 void InputWidget::on_showStyleButton_toggled(bool checked) {
515   ui.styleFrame->setVisible(checked);
516   if (checked) {
517     ui.showStyleButton->setArrowType(Qt::LeftArrow);
518   }
519   else {
520     ui.showStyleButton->setArrowType(Qt::RightArrow);
521   }
522 }
523
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);
533
534   return QIcon(pixmap);
535 }
536
537 // MOUSE WHEEL FILTER
538 MouseWheelFilter::MouseWheelFilter(QObject *parent)
539   : QObject(parent)
540 {
541 }
542
543 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event) {
544   if(event->type() != QEvent::Wheel)
545     return QObject::eventFilter(obj, event);
546   else
547     return true;
548 }