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