cmake: avoid de-duplication of user's CXXFLAGS
[quassel.git] / src / qtui / settingspages / chatmonitorsettingspage.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2022 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 "chatmonitorsettingspage.h"
22
23 #include <QMessageBox>
24 #include <QVariant>
25
26 #include "backlogrequester.h"
27 #include "backlogsettings.h"
28 #include "buffermodel.h"
29 #include "bufferview.h"
30 #include "bufferviewconfig.h"
31 #include "bufferviewfilter.h"
32 #include "chatviewsettings.h"
33 #include "client.h"
34 #include "icon.h"
35 #include "networkmodel.h"
36 #include "util.h"
37
38 ChatMonitorSettingsPage::ChatMonitorSettingsPage(QWidget* parent)
39     : SettingsPage(tr("Interface"), tr("Chat Monitor"), parent)
40 {
41     ui.setupUi(this);
42
43     ui.activateBuffer->setIcon(icon::get("go-next"));
44     ui.deactivateBuffer->setIcon(icon::get("go-previous"));
45
46     // setup available buffers config (for the bufferview on the left)
47     _configAvailable = new BufferViewConfig(-667, this);
48     _configAvailable->setBufferViewName("tmpChatMonitorAvailableBuffers");
49     _configAvailable->setSortAlphabetically(true);
50     _configAvailable->setDisableDecoration(true);
51     _configAvailable->setNetworkId(NetworkId());
52     _configAvailable->setInitialized();
53
54     // setup active buffers config (for the bufferview on the right)
55     _configActive = new BufferViewConfig(-666, this);
56     _configActive->setBufferViewName("tmpChatMonitorActiveBuffers");
57     _configActive->setSortAlphabetically(true);
58     _configActive->setDisableDecoration(true);
59     _configActive->setNetworkId(NetworkId());
60     _configActive->setInitialized();
61
62     // fill combobox with operation modes
63     ui.operationMode->addItem(tr("Opt In"), ChatViewSettings::OptIn);
64     ui.operationMode->addItem(tr("Opt Out"), ChatViewSettings::OptOut);
65
66     // connect slots
67     connect(ui.operationMode, selectOverload<int>(&QComboBox::currentIndexChanged), this, &ChatMonitorSettingsPage::switchOperationMode);
68     connect(ui.showHighlights, &QAbstractButton::toggled, this, &ChatMonitorSettingsPage::widgetHasChanged);
69     connect(ui.showOwnMessages, &QAbstractButton::toggled, this, &ChatMonitorSettingsPage::widgetHasChanged);
70     connect(ui.alwaysOwn, &QAbstractButton::toggled, this, &ChatMonitorSettingsPage::widgetHasChanged);
71     connect(ui.showBacklog, &QAbstractButton::toggled, this, &ChatMonitorSettingsPage::widgetHasChanged);
72     connect(ui.includeRead, &QAbstractButton::toggled, this, &ChatMonitorSettingsPage::widgetHasChanged);
73
74     // AsNeededBacklogRequester conflicts with showing backlog in Chat Monitor
75     BacklogSettings backlogSettings;
76     backlogSettings.initAndNotify("RequesterType", this, &ChatMonitorSettingsPage::setRequesterType, BacklogRequester::AsNeeded);
77 }
78
79 bool ChatMonitorSettingsPage::hasDefaults() const
80 {
81     return true;
82 }
83
84 void ChatMonitorSettingsPage::defaults()
85 {
86     // NOTE: Whenever changing defaults here, also update ChatMonitorFilter::ChatMonitorFilter()
87     // and ChatMonitorSettingsPage::loadSettings() to match
88
89     settings["OperationMode"] = ChatViewSettings::OptOut;
90     settings["ShowHighlights"] = false;
91     settings["ShowOwnMsgs"] = true;
92     settings["AlwaysOwn"] = false;
93     settings["Buffers"] = QVariant();
94     settings["Default"] = true;
95     settings["ShowBacklog"] = true;
96     settings["IncludeRead"] = false;
97     load();
98     widgetHasChanged();
99 }
100
101 void ChatMonitorSettingsPage::load()
102 {
103     if (settings.contains("Default"))
104         settings.remove("Default");
105     else
106         loadSettings();
107
108     switchOperationMode(settings["OperationMode"].toInt() - 1);
109     ui.operationMode->setCurrentIndex(settings["OperationMode"].toInt() - 1);
110     ui.showHighlights->setChecked(settings["ShowHighlights"].toBool());
111     ui.showOwnMessages->setChecked(settings["ShowOwnMsgs"].toBool());
112     ui.alwaysOwn->setChecked(settings["AlwaysOwn"].toBool());
113     ui.showBacklog->setChecked(settings["ShowBacklog"].toBool());
114     ui.includeRead->setChecked(settings["IncludeRead"].toBool());
115
116     // get all available buffer Ids
117     QList<BufferId> allBufferIds = Client::networkModel()->allBufferIds();
118
119     if (!settings["Buffers"].toList().isEmpty()) {
120         QList<BufferId> bufferIdsFromConfig;
121         // remove all active buffers from the available config
122         foreach (QVariant v, settings["Buffers"].toList()) {
123             bufferIdsFromConfig << v.value<BufferId>();
124             allBufferIds.removeAll(v.value<BufferId>());
125         }
126         Client::networkModel()->sortBufferIds(bufferIdsFromConfig);
127         _configActive->setBufferList(bufferIdsFromConfig);
128     }
129     ui.activeBuffers->setFilteredModel(Client::bufferModel(), _configActive);
130
131     Client::networkModel()->sortBufferIds(allBufferIds);
132     _configAvailable->setBufferList(allBufferIds);
133     ui.availableBuffers->setFilteredModel(Client::bufferModel(), _configAvailable);
134
135     setChangedState(false);
136 }
137
138 void ChatMonitorSettingsPage::loadSettings()
139 {
140     // NOTE: Whenever changing defaults here, also update ChatMonitorFilter::ChatMonitorFilter()
141     // and ChatMonitorSettingsPage::defaults() to match
142     ChatViewSettings chatViewSettings("ChatMonitor");
143
144     settings["OperationMode"] = (ChatViewSettings::OperationMode)chatViewSettings.value("OperationMode", ChatViewSettings::OptOut).toInt();
145     settings["ShowHighlights"] = chatViewSettings.value("ShowHighlights", false);
146     settings["ShowOwnMsgs"] = chatViewSettings.value("ShowOwnMsgs", true);
147     settings["AlwaysOwn"] = chatViewSettings.value("AlwaysOwn", false);
148     settings["Buffers"] = chatViewSettings.value("Buffers", QVariantList());
149     settings["ShowBacklog"] = chatViewSettings.value("ShowBacklog", true);
150     settings["IncludeRead"] = chatViewSettings.value("IncludeRead", false);
151 }
152
153 void ChatMonitorSettingsPage::save()
154 {
155     ChatViewSettings chatViewSettings("ChatMonitor");
156     // save operation mode
157     chatViewSettings.setValue("OperationMode", ui.operationMode->currentIndex() + 1);
158     chatViewSettings.setValue("ShowHighlights", ui.showHighlights->isChecked());
159     chatViewSettings.setValue("ShowOwnMsgs", ui.showOwnMessages->isChecked());
160     chatViewSettings.setValue("AlwaysOwn", ui.alwaysOwn->isChecked());
161     chatViewSettings.setValue("ShowBacklog", ui.showBacklog->isChecked());
162     chatViewSettings.setValue("IncludeRead", ui.includeRead->isChecked());
163
164     // save list of active buffers
165     QVariantList saveableBufferIdList;
166     foreach (BufferId id, _configActive->bufferList()) {
167         saveableBufferIdList << QVariant::fromValue(id);
168     }
169
170     chatViewSettings.setValue("Buffers", saveableBufferIdList);
171     load();
172     setChangedState(false);
173 }
174
175 void ChatMonitorSettingsPage::widgetHasChanged()
176 {
177     bool changed = testHasChanged();
178     if (changed != hasChanged())
179         setChangedState(changed);
180 }
181
182 bool ChatMonitorSettingsPage::testHasChanged()
183 {
184     if (settings["OperationMode"].toInt() != ui.operationMode->currentIndex() + 1)
185         return true;
186     if (settings["ShowHighlights"].toBool() != ui.showHighlights->isChecked())
187         return true;
188     if (settings["ShowOwnMsgs"].toBool() != ui.showOwnMessages->isChecked())
189         return true;
190     if (settings["AlwaysOwn"].toBool() != ui.alwaysOwn->isChecked())
191         return true;
192     if (settings["ShowBacklog"].toBool() != ui.showBacklog->isChecked())
193         return true;
194     if (settings["IncludeRead"].toBool() != ui.includeRead->isChecked())
195         return true;
196
197     if (_configActive->bufferList().count() != settings["Buffers"].toList().count())
198         return true;
199
200     QSet<BufferId> uiBufs = toQSet(_configActive->bufferList());
201     QSet<BufferId> settingsBufs;
202     foreach (QVariant v, settings["Buffers"].toList())
203         settingsBufs << v.value<BufferId>();
204     if (uiBufs != settingsBufs)
205         return true;
206
207     return false;
208 }
209
210 // TODO: - support drag 'n drop
211 //      - adding of complete networks(?)
212
213 /*
214   toggleBuffers takes each a bufferView and its config for "input" and "output".
215   Any selected item will be moved over from the input to the output bufferview.
216 */
217 void ChatMonitorSettingsPage::toggleBuffers(BufferView* inView, BufferViewConfig* inCfg, BufferView* outView, BufferViewConfig* outCfg)
218 {
219     // Fill QMap with selected items ordered by selection row
220     QMap<int, QList<BufferId>> selectedBuffers;
221     foreach (QModelIndex index, inView->selectionModel()->selectedIndexes()) {
222         BufferId inBufferId = index.data(NetworkModel::BufferIdRole).value<BufferId>();
223         if (index.data(NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType) {
224             // TODO:
225             //  If item is a network: move over all children and skip other selected items of this node
226         }
227         else if (index.data(NetworkModel::ItemTypeRole) == NetworkModel::BufferItemType) {
228             selectedBuffers[index.parent().row()] << inBufferId;
229         }
230     }
231
232     // clear selection to be able to remove the bufferIds without errors
233     inView->selectionModel()->clearSelection();
234
235     /*
236       Invalidate the BufferViewFilters' configs to get constant add/remove times
237       even for huge lists.
238       This can probably be removed whenever BufferViewConfig::bulkAdd or something
239       like that is available.
240     */
241     qobject_cast<BufferViewFilter*>(outView->model())->setConfig(nullptr);
242     qobject_cast<BufferViewFilter*>(inView->model())->setConfig(nullptr);
243
244     // actually move the ids
245     foreach (QList<BufferId> list, selectedBuffers) {
246         foreach (BufferId buffer, list) {
247             outCfg->addBuffer(buffer, 0);
248             inCfg->removeBuffer(buffer);
249         }
250     }
251
252     outView->setFilteredModel(Client::bufferModel(), outCfg);
253     inView->setFilteredModel(Client::bufferModel(), inCfg);
254
255     widgetHasChanged();
256 }
257
258 void ChatMonitorSettingsPage::on_activateBuffer_clicked()
259 {
260     if (ui.availableBuffers->currentIndex().isValid() && ui.availableBuffers->selectionModel()->hasSelection()) {
261         toggleBuffers(ui.availableBuffers, _configAvailable, ui.activeBuffers, _configActive);
262         widgetHasChanged();
263     }
264 }
265
266 void ChatMonitorSettingsPage::on_deactivateBuffer_clicked()
267 {
268     if (ui.activeBuffers->currentIndex().isValid() && ui.activeBuffers->selectionModel()->hasSelection()) {
269         toggleBuffers(ui.activeBuffers, _configActive, ui.availableBuffers, _configAvailable);
270         widgetHasChanged();
271     }
272 }
273
274 /*
275   switchOperationMode gets called on combobox signal currentIndexChanged.
276   modeIndex is the row id in combobox itemlist
277 */
278 void ChatMonitorSettingsPage::switchOperationMode(int idx)
279 {
280     auto mode = (ChatViewSettings::OperationMode)(idx + 1);
281     if (mode == ChatViewSettings::OptIn) {
282         ui.labelActiveBuffers->setText(tr("Show:"));
283     }
284     else if (mode == ChatViewSettings::OptOut) {
285         ui.labelActiveBuffers->setText(tr("Ignore:"));
286     }
287     widgetHasChanged();
288 }
289
290 void ChatMonitorSettingsPage::setRequesterType(const QVariant& v)
291 {
292     bool usingAsNeededRequester = (v.toInt() == BacklogRequester::AsNeeded);
293     ui.showBacklogUnavailableDetails->setVisible(usingAsNeededRequester);
294     if (usingAsNeededRequester) {
295         ui.showBacklog->setText(tr("Show messages from backlog (not available)"));
296     }
297     else {
298         ui.showBacklog->setText(tr("Show messages from backlog"));
299     }
300 }
301
302 void ChatMonitorSettingsPage::on_showBacklogUnavailableDetails_clicked()
303 {
304     // Explain that backlog fetching is disabled, so backlog messages won't show up
305     //
306     // Technically, backlog messages *will* show up once fetched, e.g. after clicking on a buffer.
307     // This might be too trivial of a detail to warrant explaining, though.
308     QMessageBox::information(this,
309                              tr("Messages from backlog are not fetched"),
310                              QString("<p>%1</p><p>%2</p>")
311                                      .arg(tr("No initial backlog will be fetched when using the backlog request method of <i>%1</i>.")
312                                              .arg(tr("Only fetch when needed").replace(" ", "&nbsp;")),
313                                           tr("Configure this in the <i>%1</i> settings page.")
314                                              .arg(tr("Backlog Fetching").replace(" ", "&nbsp;"))
315                                      )
316     );
317     // Re-use translations of "Only fetch when needed" and "Backlog Fetching" as this is a
318     // word-for-word reference, forcing all spaces to be non-breaking
319 }