Happy New Year!
[quassel.git] / src / qtui / inputwidget.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2014 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  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, 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     ui.encryptionIconLabel->hide();
69
70     _colorMenu = new QMenu();
71     _colorFillMenu = new QMenu();
72
73     QStringList names;
74     names << tr("White") << tr("Black") << tr("Dark blue") << tr("Dark green") << tr("Red") << tr("Dark red") << tr("Dark magenta")  << tr("Orange")
75           << tr("Yellow") << tr("Green") << tr("Dark cyan") << tr("Cyan") << tr("Blue") << tr("Magenta") << tr("Dark gray") << tr("Light gray");
76
77     QPixmap pix(16, 16);
78     for (int i = 0; i < inputLine()->mircColorMap().count(); i++) {
79         pix.fill(inputLine()->mircColorMap().values()[i]);
80         _colorMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
81         _colorFillMenu->addAction(pix, names[i])->setData(inputLine()->mircColorMap().keys()[i]);
82     }
83
84     pix.fill(Qt::transparent);
85     _colorMenu->addAction(pix, tr("Clear Color"))->setData("");
86     _colorFillMenu->addAction(pix, tr("Clear Color"))->setData("");
87
88     ui.textcolorButton->setMenu(_colorMenu);
89     connect(_colorMenu, SIGNAL(triggered(QAction *)), this, SLOT(colorChosen(QAction *)));
90     ui.highlightcolorButton->setMenu(_colorFillMenu);
91     connect(_colorFillMenu, SIGNAL(triggered(QAction *)), this, SLOT(colorHighlightChosen(QAction *)));
92
93     new TabCompleter(ui.inputEdit);
94
95     UiStyleSettings fs("Fonts");
96     fs.notify("UseCustomInputWidgetFont", this, SLOT(setUseCustomFont(QVariant)));
97     fs.notify("InputWidget", this, SLOT(setCustomFont(QVariant)));
98     if (fs.value("UseCustomInputWidgetFont", false).toBool())
99         setCustomFont(fs.value("InputWidget", QFont()));
100
101     UiSettings s("InputWidget");
102
103 #ifdef HAVE_KDE
104     s.notify("EnableSpellCheck", this, SLOT(setEnableSpellCheck(QVariant)));
105     setEnableSpellCheck(s.value("EnableSpellCheck", false));
106 #endif
107
108     s.notify("EnableEmacsMode", this, SLOT(setEnableEmacsMode(QVariant)));
109     setEnableEmacsMode(s.value("EnableEmacsMode", false));
110
111     s.notify("ShowNickSelector", this, SLOT(setShowNickSelector(QVariant)));
112     setShowNickSelector(s.value("ShowNickSelector", true));
113
114     s.notify("ShowStyleButtons", this, SLOT(setShowStyleButtons(QVariant)));
115     setShowStyleButtons(s.value("ShowStyleButtons", true));
116
117     s.notify("EnablePerChatHistory", this, SLOT(setEnablePerChatHistory(QVariant)));
118     setEnablePerChatHistory(s.value("EnablePerChatHistory", false));
119
120     s.notify("MaxNumLines", this, SLOT(setMaxLines(QVariant)));
121     setMaxLines(s.value("MaxNumLines", 5));
122
123     s.notify("EnableScrollBars", this, SLOT(setScrollBarsEnabled(QVariant)));
124     setScrollBarsEnabled(s.value("EnableScrollBars", true));
125
126     s.notify("EnableMultiLine", this, SLOT(setMultiLineEnabled(QVariant)));
127     setMultiLineEnabled(s.value("EnableMultiLine", true));
128
129     ActionCollection *coll = QtUi::actionCollection();
130
131     Action *activateInputline = coll->add<Action>("FocusInputLine");
132     connect(activateInputline, SIGNAL(triggered()), SLOT(setFocus()));
133     activateInputline->setText(tr("Focus Input Line"));
134     activateInputline->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_L));
135
136     connect(inputLine(), SIGNAL(textEntered(QString)), SLOT(onTextEntered(QString)), Qt::QueuedConnection); // make sure the line is already reset, bug #984
137     connect(inputLine(), SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(currentCharFormatChanged(QTextCharFormat)));
138 }
139
140
141 InputWidget::~InputWidget()
142 {
143 }
144
145
146 void InputWidget::setUseCustomFont(const QVariant &v)
147 {
148     if (v.toBool()) {
149         UiStyleSettings fs("Fonts");
150         setCustomFont(fs.value("InputWidget"));
151     }
152     else
153         setCustomFont(QFont());
154 }
155
156
157 void InputWidget::setCustomFont(const QVariant &v)
158 {
159     QFont font = v.value<QFont>();
160     if (font.family().isEmpty())
161         font = QApplication::font();
162     // we don't want font styles as this conflics with mirc code richtext editing
163     font.setBold(false);
164     font.setItalic(false);
165     font.setUnderline(false);
166     font.setStrikeOut(false);
167     ui.inputEdit->setCustomFont(font);
168 }
169
170
171 void InputWidget::setEnableSpellCheck(const QVariant &v)
172 {
173     ui.inputEdit->setSpellCheckEnabled(v.toBool());
174 }
175
176
177 void InputWidget::setEnableEmacsMode(const QVariant &v)
178 {
179     ui.inputEdit->setEmacsMode(v.toBool());
180 }
181
182
183 void InputWidget::setShowNickSelector(const QVariant &v)
184 {
185     ui.ownNick->setVisible(v.toBool());
186 }
187
188
189 void InputWidget::setShowStyleButtons(const QVariant &v)
190 {
191     ui.showStyleButton->setVisible(v.toBool());
192 }
193
194
195 void InputWidget::setEnablePerChatHistory(const QVariant &v)
196 {
197     _perChatHistory = v.toBool();
198 }
199
200
201 void InputWidget::setMaxLines(const QVariant &v)
202 {
203     ui.inputEdit->setMaxHeight(v.toInt());
204 }
205
206
207 void InputWidget::setScrollBarsEnabled(const QVariant &v)
208 {
209     ui.inputEdit->setScrollBarsEnabled(v.toBool());
210 }
211
212
213 void InputWidget::setMultiLineEnabled(const QVariant &v)
214 {
215     ui.inputEdit->setMode(v.toBool() ? MultiLineEdit::MultiLine : MultiLineEdit::SingleLine);
216 }
217
218
219 bool InputWidget::eventFilter(QObject *watched, QEvent *event)
220 {
221     if (event->type() != QEvent::KeyPress)
222         return false;
223
224     QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
225
226     // keys from BufferView should be sent to (and focus) the input line
227     BufferView *view = qobject_cast<BufferView *>(watched);
228     if (view) {
229         if (keyEvent->text().length() == 1 && !(keyEvent->modifiers() & (Qt::ControlModifier ^ Qt::AltModifier))) { // normal key press
230             QChar c = keyEvent->text().at(0);
231             if (c.isLetterOrNumber() || c.isSpace() || c.isPunct() || c.isSymbol()) {
232                 setFocus();
233                 QCoreApplication::sendEvent(inputLine(), keyEvent);
234                 return true;
235             }
236         }
237         return false;
238     }
239     else if (watched == ui.inputEdit) {
240         if (keyEvent->matches(QKeySequence::Find)) {
241             QAction *act = GraphicalUi::actionCollection()->action("ToggleSearchBar");
242             if (act) {
243                 act->toggle();
244                 return true;
245             }
246         }
247         return false;
248     }
249     return false;
250 }
251
252
253 void InputWidget::currentChanged(const QModelIndex &current, const QModelIndex &previous)
254 {
255     BufferId currentBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
256     BufferId previousBufferId = previous.data(NetworkModel::BufferIdRole).value<BufferId>();
257
258     if (_perChatHistory) {
259         //backup
260         historyMap[previousBufferId].history = inputLine()->history();
261         historyMap[previousBufferId].tempHistory = inputLine()->tempHistory();
262         historyMap[previousBufferId].idx = inputLine()->idx();
263         historyMap[previousBufferId].inputLine = inputLine()->html();
264
265         //restore
266         inputLine()->setHistory(historyMap[currentBufferId].history);
267         inputLine()->setTempHistory(historyMap[currentBufferId].tempHistory);
268         inputLine()->setIdx(historyMap[currentBufferId].idx);
269         inputLine()->setHtml(historyMap[currentBufferId].inputLine);
270         inputLine()->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
271
272         // FIXME this really should be in MultiLineEdit (and the const int on top removed)
273         QTextBlockFormat format = inputLine()->textCursor().blockFormat();
274         format.setLeftMargin(leftMargin); // we want a little space between the frame and the contents
275         inputLine()->textCursor().setBlockFormat(format);
276     }
277
278     NetworkId networkId = current.data(NetworkModel::NetworkIdRole).value<NetworkId>();
279     if (networkId == _networkId)
280         return;
281
282     setNetwork(networkId);
283     updateNickSelector();
284     updateEnabledState();
285 }
286
287
288 void InputWidget::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
289 {
290     QItemSelectionRange changedArea(topLeft, bottomRight);
291     if (changedArea.contains(selectionModel()->currentIndex())) {
292         updateEnabledState();
293
294         bool encrypted = false;
295
296         IrcChannel *chan = qobject_cast<IrcChannel *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcChannelRole).value<QObject *>());
297         if (chan)
298             encrypted = chan->encrypted();
299
300         IrcUser *user = qobject_cast<IrcUser *>(Client::bufferModel()->data(selectionModel()->currentIndex(), NetworkModel::IrcUserRole).value<QObject *>());
301         if (user)
302             encrypted = user->encrypted();
303
304         if (encrypted)
305             ui.encryptionIconLabel->show();
306         else
307             ui.encryptionIconLabel->hide();
308     }
309 }
310
311
312 void InputWidget::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
313 {
314     NetworkId networkId;
315     QModelIndex child;
316     for (int row = start; row <= end; row++) {
317         child = model()->index(row, 0, parent);
318         if (NetworkModel::NetworkItemType != child.data(NetworkModel::ItemTypeRole).toInt())
319             continue;
320         networkId = child.data(NetworkModel::NetworkIdRole).value<NetworkId>();
321         if (networkId == _networkId) {
322             setNetwork(0);
323             updateNickSelector();
324             return;
325         }
326     }
327 }
328
329
330 void InputWidget::updateEnabledState()
331 {
332 // FIXME: Find a visualization for this that does not disable the widget!
333 //        Disabling kills global action shortcuts, plus users sometimes need/want to enter text
334 //        even in inactive channels.
335 #if 0
336     QModelIndex currentIndex = selectionModel()->currentIndex();
337
338     const Network *net = Client::networkModel()->networkByIndex(currentIndex);
339     bool enabled = false;
340     if (net) {
341         // disable inputline if it's a channelbuffer we parted from or...
342         enabled = (currentIndex.data(NetworkModel::ItemActiveRole).value<bool>() || (currentIndex.data(NetworkModel::BufferTypeRole).toInt() != BufferInfo::ChannelBuffer));
343         // ... if we're not connected to the network at all
344         enabled &= net->isConnected();
345     }
346
347     ui.inputEdit->setEnabled(enabled);
348 #endif
349 }
350
351
352 const Network *InputWidget::currentNetwork() const
353 {
354     return Client::network(_networkId);
355 }
356
357
358 BufferInfo InputWidget::currentBufferInfo() const
359 {
360     return selectionModel()->currentIndex().data(NetworkModel::BufferInfoRole).value<BufferInfo>();
361 };
362
363 void InputWidget::setNetwork(NetworkId networkId)
364 {
365     if (_networkId == networkId)
366         return;
367
368     const Network *previousNet = Client::network(_networkId);
369     if (previousNet) {
370         disconnect(previousNet, 0, this, 0);
371         if (previousNet->me())
372             disconnect(previousNet->me(), 0, this, 0);
373     }
374
375     _networkId = networkId;
376
377     const Network *network = Client::network(networkId);
378     if (network) {
379         connect(network, SIGNAL(identitySet(IdentityId)), this, SLOT(setIdentity(IdentityId)));
380         connectMyIrcUser();
381         setIdentity(network->identity());
382     }
383     else {
384         setIdentity(0);
385         _networkId = 0;
386     }
387 }
388
389
390 void InputWidget::connectMyIrcUser()
391 {
392     const Network *network = currentNetwork();
393     if (network->me()) {
394         connect(network->me(), SIGNAL(nickSet(const QString &)), this, SLOT(updateNickSelector()));
395         connect(network->me(), SIGNAL(userModesSet(QString)), this, SLOT(updateNickSelector()));
396         connect(network->me(), SIGNAL(userModesAdded(QString)), this, SLOT(updateNickSelector()));
397         connect(network->me(), SIGNAL(userModesRemoved(QString)), this, SLOT(updateNickSelector()));
398         connect(network->me(), SIGNAL(awaySet(bool)), this, SLOT(updateNickSelector()));
399         disconnect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
400         updateNickSelector();
401     }
402     else {
403         connect(network, SIGNAL(myNickSet(const QString &)), this, SLOT(connectMyIrcUser()));
404     }
405 }
406
407
408 void InputWidget::setIdentity(IdentityId identityId)
409 {
410     if (_identityId == identityId)
411         return;
412
413     const Identity *previousIdentity = Client::identity(_identityId);
414     if (previousIdentity)
415         disconnect(previousIdentity, 0, this, 0);
416
417     _identityId = identityId;
418
419     const Identity *identity = Client::identity(identityId);
420     if (identity) {
421         connect(identity, SIGNAL(nicksSet(QStringList)), this, SLOT(updateNickSelector()));
422     }
423     else {
424         _identityId = 0;
425     }
426     updateNickSelector();
427 }
428
429
430 void InputWidget::updateNickSelector() const
431 {
432     ui.ownNick->clear();
433
434     const Network *net = currentNetwork();
435     if (!net)
436         return;
437
438     const Identity *identity = Client::identity(net->identity());
439     if (!identity) {
440         qWarning() << "InputWidget::updateNickSelector(): can't find Identity for Network" << net->networkId() << "IdentityId:" << net->identity();
441         return;
442     }
443
444     int nickIdx;
445     QStringList nicks = identity->nicks();
446     if ((nickIdx = nicks.indexOf(net->myNick())) == -1) {
447         nicks.prepend(net->myNick());
448         nickIdx = 0;
449     }
450
451     if (nicks.isEmpty())
452         return;
453
454     IrcUser *me = net->me();
455     if (me) {
456         nicks[nickIdx] = net->myNick();
457         if (!me->userModes().isEmpty())
458             nicks[nickIdx] += QString(" (+%1)").arg(me->userModes());
459     }
460
461     ui.ownNick->addItems(nicks);
462
463     if (me && me->isAway())
464         ui.ownNick->setItemData(nickIdx, SmallIcon("user-away"), Qt::DecorationRole);
465
466     ui.ownNick->setCurrentIndex(nickIdx);
467 }
468
469
470 void InputWidget::changeNick(const QString &newNick) const
471 {
472     const Network *net = currentNetwork();
473     if (!net || net->isMyNick(newNick))
474         return;
475
476     // we reset the nick selecter as we have no confirmation yet, that this will succeed.
477     // if the action succeeds it will be properly updated anyways.
478     updateNickSelector();
479     Client::userInput(BufferInfo::fakeStatusBuffer(net->networkId()), QString("/NICK %1").arg(newNick));
480 }
481
482
483 void InputWidget::onTextEntered(const QString &text)
484 {
485     Client::userInput(currentBufferInfo(), text);
486     ui.boldButton->setChecked(false);
487     ui.underlineButton->setChecked(false);
488     ui.italicButton->setChecked(false);
489
490     QTextCharFormat fmt;
491     fmt.setFontWeight(QFont::Normal);
492     fmt.setFontUnderline(false);
493     fmt.setFontItalic(false);
494     fmt.clearForeground();
495     fmt.clearBackground();
496     inputLine()->setCurrentCharFormat(fmt);
497
498 #ifdef HAVE_KDE
499     // Set highlighter back to active in case it was deactivated by too many errors.
500     if (ui.inputEdit->highlighter())
501         ui.inputEdit->highlighter()->setActive(true);
502 #endif
503 }
504
505
506 void InputWidget::mergeFormatOnSelection(const QTextCharFormat &format)
507 {
508     QTextCursor cursor = inputLine()->textCursor();
509     cursor.mergeCharFormat(format);
510     inputLine()->mergeCurrentCharFormat(format);
511 }
512
513
514 void InputWidget::setFormatOnSelection(const QTextCharFormat &format)
515 {
516     QTextCursor cursor = inputLine()->textCursor();
517     cursor.setCharFormat(format);
518     inputLine()->setCurrentCharFormat(format);
519 }
520
521
522 QTextCharFormat InputWidget::getFormatOfWordOrSelection()
523 {
524     QTextCursor cursor = inputLine()->textCursor();
525     return cursor.charFormat();
526 }
527
528
529 void InputWidget::currentCharFormatChanged(const QTextCharFormat &format)
530 {
531     fontChanged(format.font());
532 }
533
534
535 void InputWidget::on_boldButton_clicked(bool checked)
536 {
537     QTextCharFormat fmt;
538     fmt.setFontWeight(checked ? QFont::Bold : QFont::Normal);
539     mergeFormatOnSelection(fmt);
540 }
541
542
543 void InputWidget::on_underlineButton_clicked(bool checked)
544 {
545     QTextCharFormat fmt;
546     fmt.setFontUnderline(checked);
547     mergeFormatOnSelection(fmt);
548 }
549
550
551 void InputWidget::on_italicButton_clicked(bool checked)
552 {
553     QTextCharFormat fmt;
554     fmt.setFontItalic(checked);
555     mergeFormatOnSelection(fmt);
556 }
557
558
559 void InputWidget::fontChanged(const QFont &f)
560 {
561     ui.boldButton->setChecked(f.bold());
562     ui.italicButton->setChecked(f.italic());
563     ui.underlineButton->setChecked(f.underline());
564 }
565
566
567 void InputWidget::colorChosen(QAction *action)
568 {
569     QTextCharFormat fmt;
570     QColor color;
571     if (qVariantValue<QString>(action->data()) == "") {
572         color = Qt::transparent;
573         fmt = getFormatOfWordOrSelection();
574         fmt.clearForeground();
575         setFormatOnSelection(fmt);
576     }
577     else {
578         color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
579         fmt.setForeground(color);
580         mergeFormatOnSelection(fmt);
581     }
582     ui.textcolorButton->setDefaultAction(action);
583     ui.textcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-text-color"), color));
584 }
585
586
587 void InputWidget::colorHighlightChosen(QAction *action)
588 {
589     QTextCharFormat fmt;
590     QColor color;
591     if (qVariantValue<QString>(action->data()) == "") {
592         color = Qt::transparent;
593         fmt = getFormatOfWordOrSelection();
594         fmt.clearBackground();
595         setFormatOnSelection(fmt);
596     }
597     else {
598         color = QColor(inputLine()->rgbColorFromMirc(qVariantValue<QString>(action->data())));
599         fmt.setBackground(color);
600         mergeFormatOnSelection(fmt);
601     }
602     ui.highlightcolorButton->setDefaultAction(action);
603     ui.highlightcolorButton->setIcon(createColorToolButtonIcon(SmallIcon("format-fill-color"), color));
604 }
605
606
607 void InputWidget::on_showStyleButton_toggled(bool checked)
608 {
609     ui.styleFrame->setVisible(checked);
610     if (checked) {
611         ui.showStyleButton->setArrowType(Qt::LeftArrow);
612     }
613     else {
614         ui.showStyleButton->setArrowType(Qt::RightArrow);
615     }
616 }
617
618
619 QIcon InputWidget::createColorToolButtonIcon(const QIcon &icon, const QColor &color)
620 {
621     QPixmap pixmap(16, 16);
622     pixmap.fill(Qt::transparent);
623     QPainter painter(&pixmap);
624     QPixmap image = icon.pixmap(16, 16);
625     QRect target(0, 0, 16, 14);
626     QRect source(0, 0, 16, 14);
627     painter.fillRect(QRect(0, 14, 16, 16), color);
628     painter.drawPixmap(target, image, source);
629
630     return QIcon(pixmap);
631 }
632
633
634 // MOUSE WHEEL FILTER
635 MouseWheelFilter::MouseWheelFilter(QObject *parent)
636     : QObject(parent)
637 {
638 }
639
640
641 bool MouseWheelFilter::eventFilter(QObject *obj, QEvent *event)
642 {
643     if (event->type() != QEvent::Wheel)
644         return QObject::eventFilter(obj, event);
645     else
646         return true;
647 }