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