modernize: Remove old-style slot usage in NetworkModelController
[quassel.git] / src / uisupport / contextmenuactionprovider.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2018 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 "contextmenuactionprovider.h"
22
23 #include <QInputDialog>
24 #include <QMenu>
25 #include <QMessageBox>
26 #include <QMap>
27
28 #include "buffermodel.h"
29 #include "buffersettings.h"
30 #include "client.h"
31 #include "clientignorelistmanager.h"
32 #include "icon.h"
33 #include "network.h"
34 #include "util.h"
35
36 ContextMenuActionProvider::ContextMenuActionProvider(QObject *parent) : NetworkModelController(parent)
37 {
38     registerAction(NetworkConnect, icon::get("network-connect"), tr("Connect"));
39     registerAction(NetworkDisconnect, icon::get("network-disconnect"), tr("Disconnect"));
40
41     registerAction(BufferJoin, icon::get("irc-join-channel"), tr("Join"));
42     registerAction(BufferPart, icon::get("irc-close-channel"), tr("Part"));
43     registerAction(BufferRemove, tr("Delete Chat(s)..."));
44     registerAction(BufferSwitchTo, tr("Go to Chat"));
45
46     registerAction(HideJoinPartQuit, tr("Joins/Parts/Quits"));
47     registerAction(HideJoin, tr("Joins"), true);
48     registerAction(HidePart, tr("Parts"), true);
49     registerAction(HideQuit, tr("Quits"), true);
50     registerAction(HideNick, tr("Nick Changes"), true);
51     registerAction(HideMode, tr("Mode Changes"), true);
52     registerAction(HideDayChange, tr("Day Changes"), true);
53     registerAction(HideTopic, tr("Topic Changes"), true);
54     registerAction(HideApplyToAll, tr("Set as Default..."));
55     registerAction(HideUseDefaults, tr("Use Defaults..."));
56
57     registerAction(JoinChannel, icon::get("irc-join-channel"), tr("Join Channel..."));
58
59     registerAction(NickQuery, tr("Start Query"));
60     registerAction(NickSwitchTo, tr("Show Query"));
61     registerAction(NickWhois, tr("Whois"));
62
63     registerAction(NickCtcpVersion, tr("Version"));
64     registerAction(NickCtcpTime, tr("Time"));
65     registerAction(NickCtcpPing, tr("Ping"));
66     registerAction(NickCtcpClientinfo, tr("Client info"));
67     registerAction(NickIgnoreCustom, tr("Custom..."));
68
69     // these texts are only dummies! don't think about tr() here!
70     registerAction(NickIgnoreUser, "*!ident@host.domain.tld");
71     registerAction(NickIgnoreHost, "*!*@host.domain.tld");
72     registerAction(NickIgnoreDomain, "*!ident@*.domain.tld");
73     registerAction(NickIgnoreToggleEnabled0, "Enable", true);
74     registerAction(NickIgnoreToggleEnabled1, "Enable", true);
75     registerAction(NickIgnoreToggleEnabled2, "Enable", true);
76     registerAction(NickIgnoreToggleEnabled3, "Enable", true);
77     registerAction(NickIgnoreToggleEnabled4, "Enable", true);
78
79     registerAction(NickOp, icon::get("irc-operator"), tr("Give Operator Status"));
80     registerAction(NickDeop, icon::get("irc-remove-operator"), tr("Take Operator Status"));
81     registerAction(NickHalfop, icon::get("irc-voice"), tr("Give Half-Operator Status"));
82     registerAction(NickDehalfop, icon::get("irc-unvoice"), tr("Take Half-Operator Status"));
83     registerAction(NickVoice, icon::get("irc-voice"), tr("Give Voice"));
84     registerAction(NickDevoice, icon::get("irc-unvoice"), tr("Take Voice"));
85     registerAction(NickKick, icon::get("im-kick-user"), tr("Kick From Channel"));
86     registerAction(NickBan, icon::get("im-ban-user"), tr("Ban From Channel"));
87     registerAction(NickKickBan, icon::get("im-ban-kick-user"), tr("Kick && Ban"));
88
89     registerAction(HideBufferTemporarily, tr("Hide Chat(s) Temporarily"));
90     registerAction(HideBufferPermanently, tr("Hide Chat(s) Permanently"));
91     registerAction(ShowChannelList, tr("Show Channel List"));
92     registerAction(ShowNetworkConfig, tr("Configure"));
93     registerAction(ShowIgnoreList, tr("Show Ignore List"));
94
95     auto *hideEventsMenu = new QMenu();
96     hideEventsMenu->addAction(action(HideJoinPartQuit));
97     hideEventsMenu->addSeparator();
98     hideEventsMenu->addAction(action(HideJoin));
99     hideEventsMenu->addAction(action(HidePart));
100     hideEventsMenu->addAction(action(HideQuit));
101     hideEventsMenu->addAction(action(HideNick));
102     hideEventsMenu->addAction(action(HideMode));
103     hideEventsMenu->addAction(action(HideTopic));
104     hideEventsMenu->addAction(action(HideDayChange));
105     hideEventsMenu->addSeparator();
106     hideEventsMenu->addAction(action(HideApplyToAll));
107     hideEventsMenu->addAction(action(HideUseDefaults));
108     _hideEventsMenuAction = new Action(tr("Hide Events"), nullptr);
109     _hideEventsMenuAction->setMenu(hideEventsMenu);
110
111     auto *nickCtcpMenu = new QMenu();
112     nickCtcpMenu->addAction(action(NickCtcpPing));
113     nickCtcpMenu->addAction(action(NickCtcpVersion));
114     nickCtcpMenu->addAction(action(NickCtcpTime));
115     nickCtcpMenu->addAction(action(NickCtcpClientinfo));
116     _nickCtcpMenuAction = new Action(tr("CTCP"), nullptr);
117     _nickCtcpMenuAction->setMenu(nickCtcpMenu);
118
119     auto *nickModeMenu = new QMenu();
120     nickModeMenu->addAction(action(NickOp));
121     nickModeMenu->addAction(action(NickDeop));
122     // this is where the halfops will be placed if available
123     nickModeMenu->addAction(action(NickHalfop));
124     nickModeMenu->addAction(action(NickDehalfop));
125     nickModeMenu->addAction(action(NickVoice));
126     nickModeMenu->addAction(action(NickDevoice));
127     nickModeMenu->addSeparator();
128     nickModeMenu->addAction(action(NickKick));
129     nickModeMenu->addAction(action(NickBan));
130     nickModeMenu->addAction(action(NickKickBan));
131     _nickModeMenuAction = new Action(tr("Actions"), nullptr);
132     _nickModeMenuAction->setMenu(nickModeMenu);
133
134     auto *ignoreMenu = new QMenu();
135     _nickIgnoreMenuAction = new Action(tr("Ignore"), nullptr);
136     _nickIgnoreMenuAction->setMenu(ignoreMenu);
137
138     // These are disabled actions used as descriptions
139     // They don't need any of the Action fancyness so we use plain QActions
140     _ignoreDescriptions << new QAction(tr("Add Ignore Rule"), this);
141     _ignoreDescriptions << new QAction(tr("Existing Rules"), this);
142     foreach(QAction *act, _ignoreDescriptions)
143     act->setEnabled(false);
144 }
145
146
147 ContextMenuActionProvider::~ContextMenuActionProvider()
148 {
149     _hideEventsMenuAction->menu()->deleteLater();
150     _hideEventsMenuAction->deleteLater();
151     _nickCtcpMenuAction->menu()->deleteLater();
152     _nickCtcpMenuAction->deleteLater();
153     _nickModeMenuAction->menu()->deleteLater();
154     _nickModeMenuAction->deleteLater();
155     _nickIgnoreMenuAction->menu()->deleteLater();
156     _nickIgnoreMenuAction->deleteLater();
157     qDeleteAll(_ignoreDescriptions);
158     _ignoreDescriptions.clear();
159 }
160
161
162 void ContextMenuActionProvider::addActions(QMenu *menu, BufferId bufId, ActionSlot slot)
163 {
164     if (!bufId.isValid())
165         return;
166     addActions(menu, Client::networkModel()->bufferIndex(bufId), std::move(slot));
167 }
168
169
170 void ContextMenuActionProvider::addActions(QMenu *menu, const QModelIndex &index, ActionSlot slot, bool isCustomBufferView)
171 {
172     if (!index.isValid())
173         return;
174     addActions(menu, QList<QModelIndex>() << index, nullptr, QString(), std::move(slot), isCustomBufferView);
175 }
176
177
178 void ContextMenuActionProvider::addActions(QMenu *menu, MessageFilter *filter, BufferId msgBuffer, ActionSlot slot)
179 {
180     addActions(menu, filter, msgBuffer, QString(), std::move(slot));
181 }
182
183
184 void ContextMenuActionProvider::addActions(QMenu *menu, MessageFilter *filter, BufferId msgBuffer, const QString &chanOrNick, ActionSlot slot)
185 {
186     if (!filter)
187         return;
188     addActions(menu, QList<QModelIndex>() << Client::networkModel()->bufferIndex(msgBuffer), filter, chanOrNick, std::move(slot), false);
189 }
190
191
192 void ContextMenuActionProvider::addActions(QMenu *menu, const QList<QModelIndex> &indexList, ActionSlot slot, bool isCustomBufferView)
193 {
194     addActions(menu, indexList, nullptr, QString(), std::move(slot), isCustomBufferView);
195 }
196
197
198 // add a list of actions sensible for the current item(s)
199 void ContextMenuActionProvider::addActions(QMenu *menu,
200                                            const QList<QModelIndex> &indexList_,
201                                            MessageFilter *filter_,
202                                            const QString &contextItem_,
203                                            ActionSlot actionSlot,
204                                            bool isCustomBufferView)
205 {
206     if (!indexList_.count())
207         return;
208
209     setIndexList(indexList_);
210     setMessageFilter(filter_);
211     setContextItem(contextItem_);
212     setSlot(std::move(actionSlot));
213
214     if (!messageFilter()) {
215         // this means we are in a BufferView (or NickView) rather than a ChatView
216
217         // first index in list determines the menu type (just in case we have both buffers and networks selected, for example)
218         QModelIndex index = indexList().at(0);
219         NetworkModel::ItemType itemType = static_cast<NetworkModel::ItemType>(index.data(NetworkModel::ItemTypeRole).toInt());
220
221         switch (itemType) {
222         case NetworkModel::NetworkItemType:
223             addNetworkItemActions(menu, index);
224             break;
225         case NetworkModel::BufferItemType:
226             addBufferItemActions(menu, index, isCustomBufferView);
227             break;
228         case NetworkModel::IrcUserItemType:
229             addIrcUserActions(menu, index);
230             break;
231         default:
232             return;
233         }
234     }
235     else {
236         // ChatView actions
237         if (contextItem().isEmpty()) {
238             // a) query buffer: handle like ircuser
239             // b) general chatview: handle like channel iff it displays a single buffer
240             // NOTE stuff breaks probably with merged buffers, need to rework a lot around here then
241             if (messageFilter()->containedBuffers().count() == 1) {
242                 // we can handle this like a single bufferItem
243                 QModelIndex index = Client::networkModel()->bufferIndex(messageFilter()->containedBuffers().values().at(0));
244                 setIndexList(index);
245                 addBufferItemActions(menu, index);
246                 return;
247             }
248             else {
249                 // TODO: actions for merged buffers... _indexList contains the index of the message we clicked on
250             }
251         }
252         else {
253             // context item = chan or nick, _indexList = buf where the msg clicked on originated
254             if (isChannelName(contextItem())) {
255                 QModelIndex msgIdx = indexList().at(0);
256                 if (!msgIdx.isValid())
257                     return;
258                 NetworkId networkId = msgIdx.data(NetworkModel::NetworkIdRole).value<NetworkId>();
259                 BufferId bufId = Client::networkModel()->bufferId(networkId, contextItem());
260                 if (bufId.isValid()) {
261                     QModelIndex targetIdx = Client::networkModel()->bufferIndex(bufId);
262                     setIndexList(targetIdx);
263                     addAction(BufferJoin, menu, targetIdx, InactiveState);
264                     addAction(BufferSwitchTo, menu, targetIdx, ActiveState);
265                 }
266                 else
267                     addAction(JoinChannel, menu);
268             }
269             else {
270                 // TODO: actions for a nick
271             }
272         }
273     }
274 }
275
276
277 void ContextMenuActionProvider::addNetworkItemActions(QMenu *menu, const QModelIndex &index)
278 {
279     NetworkId networkId = index.data(NetworkModel::NetworkIdRole).value<NetworkId>();
280     if (!networkId.isValid())
281         return;
282     const Network *network = Client::network(networkId);
283     Q_CHECK_PTR(network);
284     if (!network)
285         return;
286
287     addAction(ShowNetworkConfig, menu, index);
288     menu->addSeparator();
289     addAction(NetworkConnect, menu, network->connectionState() == Network::Disconnected);
290     addAction(NetworkDisconnect, menu, network->connectionState() != Network::Disconnected);
291     menu->addSeparator();
292     addAction(ShowChannelList, menu, index, ActiveState);
293     addAction(JoinChannel, menu, index, ActiveState);
294 }
295
296
297 void ContextMenuActionProvider::addBufferItemActions(QMenu *menu, const QModelIndex &index, bool isCustomBufferView)
298 {
299     BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
300
301     menu->addSeparator();
302     switch (bufferInfo.type()) {
303     case BufferInfo::ChannelBuffer:
304         addAction(BufferJoin, menu, index, InactiveState);
305         addAction(BufferPart, menu, index, ActiveState);
306         menu->addSeparator();
307         addHideEventsMenu(menu, bufferInfo.bufferId());
308         menu->addSeparator();
309         addAction(HideBufferTemporarily, menu, isCustomBufferView);
310         addAction(HideBufferPermanently, menu, isCustomBufferView);
311         addAction(BufferRemove, menu, index, InactiveState);
312         break;
313
314     case BufferInfo::QueryBuffer:
315     {
316         //IrcUser *ircUser = qobject_cast<IrcUser *>(index.data(NetworkModel::IrcUserRole).value<QObject *>());
317         //if(ircUser) {
318         addIrcUserActions(menu, index);
319         menu->addSeparator();
320         //}
321         addHideEventsMenu(menu, bufferInfo.bufferId());
322         menu->addSeparator();
323         addAction(HideBufferTemporarily, menu, isCustomBufferView);
324         addAction(HideBufferPermanently, menu, isCustomBufferView);
325         addAction(BufferRemove, menu, index);
326         break;
327     }
328
329     default:
330         addAction(HideBufferTemporarily, menu, isCustomBufferView);
331         addAction(HideBufferPermanently, menu, isCustomBufferView);
332     }
333 }
334
335
336 void ContextMenuActionProvider::addIrcUserActions(QMenu *menu, const QModelIndex &index)
337 {
338     // this can be called: a) as a nicklist context menu (index has IrcUserItemType)
339     //                     b) as a query buffer context menu (index has BufferItemType and is a QueryBufferItem)
340     //                     c) right-click in a query chatview (same as b), index will be the corresponding QueryBufferItem)
341     //                     d) right-click on some nickname (_contextItem will be non-null, _filter -> chatview, index -> message buffer)
342
343     if (contextItem().isNull()) {
344         // cases a, b, c
345         bool haveQuery = indexList().count() == 1 && findQueryBuffer(index).isValid();
346         NetworkModel::ItemType itemType = static_cast<NetworkModel::ItemType>(index.data(NetworkModel::ItemTypeRole).toInt());
347         addAction(_nickModeMenuAction, menu, itemType == NetworkModel::IrcUserItemType);
348         addAction(_nickCtcpMenuAction, menu);
349
350         auto *ircUser = qobject_cast<IrcUser *>(index.data(NetworkModel::IrcUserRole).value<QObject *>());
351         if (ircUser) {
352             Network *network = ircUser->network();
353             // only show entries for usermode +h if server supports it
354             if (network && network->prefixModes().contains('h')) {
355                 action(NickHalfop)->setVisible(true);
356                 action(NickDehalfop)->setVisible(true);
357             }
358             else {
359                 action(NickHalfop)->setVisible(false);
360                 action(NickDehalfop)->setVisible(false);
361             }
362             // ignoreliststuff
363             QString bufferName;
364             BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
365             if (bufferInfo.type() == BufferInfo::ChannelBuffer)
366                 bufferName = bufferInfo.bufferName();
367             QMap<QString, bool> ignoreMap = Client::ignoreListManager()->matchingRulesForHostmask(ircUser->hostmask(), ircUser->network()->networkName(), bufferName);
368             addIgnoreMenu(menu, ircUser->hostmask(), ignoreMap);
369             // end of ignoreliststuff
370         }
371         menu->addSeparator();
372         addAction(NickQuery, menu, itemType == NetworkModel::IrcUserItemType && !haveQuery && indexList().count() == 1);
373         addAction(NickSwitchTo, menu, itemType == NetworkModel::IrcUserItemType && haveQuery);
374         menu->addSeparator();
375         addAction(NickWhois, menu, true);
376     }
377     else if (!contextItem().isEmpty() && messageFilter()) {
378         // case d
379         // TODO
380     }
381 }
382
383
384 Action *ContextMenuActionProvider::addAction(ActionType type, QMenu *menu, const QModelIndex &index, ItemActiveStates requiredActiveState)
385 {
386     return addAction(action(type), menu, checkRequirements(index, requiredActiveState));
387 }
388
389
390 Action *ContextMenuActionProvider::addAction(Action *action, QMenu *menu, const QModelIndex &index, ItemActiveStates requiredActiveState)
391 {
392     return addAction(action, menu, checkRequirements(index, requiredActiveState));
393 }
394
395
396 Action *ContextMenuActionProvider::addAction(ActionType type, QMenu *menu, bool condition)
397 {
398     return addAction(action(type), menu, condition);
399 }
400
401
402 Action *ContextMenuActionProvider::addAction(Action *action, QMenu *menu, bool condition)
403 {
404     if (condition) {
405         menu->addAction(action);
406         action->setVisible(true);
407     }
408     else {
409         action->setVisible(false);
410     }
411     return action;
412 }
413
414
415 void ContextMenuActionProvider::addHideEventsMenu(QMenu *menu, BufferId bufferId)
416 {
417     if (BufferSettings(bufferId).hasFilter())
418         addHideEventsMenu(menu, BufferSettings(bufferId).messageFilter());
419     else
420         addHideEventsMenu(menu);
421 }
422
423
424 void ContextMenuActionProvider::addHideEventsMenu(QMenu *menu, MessageFilter *msgFilter)
425 {
426     if (BufferSettings(msgFilter->idString()).hasFilter())
427         addHideEventsMenu(menu, BufferSettings(msgFilter->idString()).messageFilter());
428     else
429         addHideEventsMenu(menu);
430 }
431
432
433 void ContextMenuActionProvider::addHideEventsMenu(QMenu *menu, int filter)
434 {
435     action(HideApplyToAll)->setEnabled(filter != -1);
436     action(HideUseDefaults)->setEnabled(filter != -1);
437     if (filter == -1)
438         filter = BufferSettings().messageFilter();
439
440     action(HideJoin)->setChecked(filter & Message::Join);
441     action(HidePart)->setChecked(filter & Message::Part);
442     action(HideQuit)->setChecked(filter & Message::Quit);
443     action(HideNick)->setChecked(filter & Message::Nick);
444     action(HideMode)->setChecked(filter & Message::Mode);
445     action(HideDayChange)->setChecked(filter & Message::DayChange);
446     action(HideTopic)->setChecked(filter & Message::Topic);
447
448     menu->addAction(_hideEventsMenuAction);
449 }
450
451
452 void ContextMenuActionProvider::addIgnoreMenu(QMenu *menu, const QString &hostmask, const QMap<QString, bool> &ignoreMap)
453 {
454     QMenu *ignoreMenu = _nickIgnoreMenuAction->menu();
455     ignoreMenu->clear();
456     QString nick = nickFromMask(hostmask);
457     QString ident = userFromMask(hostmask);
458     QString host = hostFromMask(hostmask);
459     QString domain = host;
460     QRegExp domainRx = QRegExp(R"((\.[^.]+\.\w+\D)$)");
461     if (domainRx.indexIn(host) != -1)
462         domain = domainRx.cap(1);
463     // we can't rely on who-data
464     // if we don't have the data, we skip actions where we would need it
465     bool haveWhoData = !ident.isEmpty() && !host.isEmpty();
466
467     // add "Add Ignore Rule" description
468     ignoreMenu->addAction(_ignoreDescriptions.at(0));
469
470     if (haveWhoData) {
471         QString text;
472         text = QString("*!%1@%2").arg(ident, host);
473         action(NickIgnoreUser)->setText(text);
474         action(NickIgnoreUser)->setProperty("ignoreRule", text);
475
476         text = QString("*!*@%1").arg(host);
477         action(NickIgnoreHost)->setText(text);
478         action(NickIgnoreHost)->setProperty("ignoreRule", text);
479
480         text = domain.at(0) == '.' ? QString("*!%1@*%2").arg(ident, domain)
481                : QString("*!%1@%2").arg(ident, domain);
482
483         action(NickIgnoreDomain)->setText(text);
484         action(NickIgnoreDomain)->setProperty("ignoreRule", text);
485
486         if (!ignoreMap.contains(action(NickIgnoreUser)->property("ignoreRule").toString()))
487             ignoreMenu->addAction(action(NickIgnoreUser));
488         if (!ignoreMap.contains(action(NickIgnoreHost)->property("ignoreRule").toString()))
489             ignoreMenu->addAction(action(NickIgnoreHost));
490         // we only add that NickIgnoreDomain if it isn't the same as NickIgnoreUser
491         // as happens with @foobar.com hostmasks and ips
492         if (!ignoreMap.contains(action(NickIgnoreDomain)->property("ignoreRule").toString())
493             && action(NickIgnoreUser)->property("ignoreRule").toString() != action(NickIgnoreDomain)->property("ignoreRule").toString())
494             ignoreMenu->addAction(action(NickIgnoreDomain));
495     }
496
497     action(NickIgnoreCustom)->setProperty("ignoreRule", hostmask);
498     ignoreMenu->addAction(action(NickIgnoreCustom));
499
500     ignoreMenu->addSeparator();
501
502     if (haveWhoData) {
503         QMap<QString, bool>::const_iterator ruleIter = ignoreMap.begin();
504         int counter = 0;
505         if (!ignoreMap.isEmpty())
506             // add "Existing Rules" description
507             ignoreMenu->addAction(_ignoreDescriptions.at(1));
508         while (ruleIter != ignoreMap.constEnd()) {
509             if (counter < 5) {
510                 auto type = static_cast<ActionType>(NickIgnoreToggleEnabled0 + counter*0x100000);
511                 Action *act = action(type);
512                 act->setText(ruleIter.key());
513                 act->setProperty("ignoreRule", ruleIter.key());
514                 act->setChecked(ruleIter.value());
515                 ignoreMenu->addAction(act);
516             }
517             counter++;
518             ++ruleIter;
519         }
520         if (counter)
521             ignoreMenu->addSeparator();
522     }
523     ignoreMenu->addAction(action(ShowIgnoreList));
524     addAction(_nickIgnoreMenuAction, menu);
525 }