settings: Add server-time to Network Features tab
[quassel.git] / src / qtui / settingspages / networkssettingspage.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2020 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 "networkssettingspage.h"
22
23 #include <utility>
24
25 #include <QHeaderView>
26 #include <QMessageBox>
27 #include <QTextCodec>
28
29 #include "client.h"
30 #include "icon.h"
31 #include "identity.h"
32 #include "network.h"
33 #include "presetnetworks.h"
34 #include "settingspagedlg.h"
35 #include "util.h"
36 #include "widgethelpers.h"
37
38 // IRCv3 capabilities
39 #include "irccap.h"
40
41 #include "settingspages/identitiessettingspage.h"
42
43 NetworksSettingsPage::NetworksSettingsPage(QWidget* parent)
44     : SettingsPage(tr("IRC"), tr("Networks"), parent)
45 {
46     ui.setupUi(this);
47
48     // hide SASL options for older cores
49     if (!Client::isCoreFeatureEnabled(Quassel::Feature::SaslAuthentication))
50         ui.sasl->hide();
51     if (!Client::isCoreFeatureEnabled(Quassel::Feature::SaslExternal))
52         ui.saslExtInfo->hide();
53
54     // set up icons
55     ui.renameNetwork->setIcon(icon::get("edit-rename"));
56     ui.addNetwork->setIcon(icon::get("list-add"));
57     ui.deleteNetwork->setIcon(icon::get("edit-delete"));
58     ui.addServer->setIcon(icon::get("list-add"));
59     ui.deleteServer->setIcon(icon::get("edit-delete"));
60     ui.editServer->setIcon(icon::get("configure"));
61     ui.upServer->setIcon(icon::get("go-up"));
62     ui.downServer->setIcon(icon::get("go-down"));
63     ui.editIdentities->setIcon(icon::get("configure"));
64
65     connectedIcon = icon::get("network-connect");
66     connectingIcon = icon::get("network-wired");  // FIXME network-connecting
67     disconnectedIcon = icon::get("network-disconnect");
68
69     // Status icons
70     infoIcon = icon::get({"emblem-information", "dialog-information"});
71     successIcon = icon::get({"emblem-success", "dialog-information"});
72     unavailableIcon = icon::get({"emblem-unavailable", "dialog-warning"});
73     questionIcon = icon::get({"emblem-question", "dialog-question", "dialog-information"});
74
75     foreach (int mib, QTextCodec::availableMibs()) {
76         QByteArray codec = QTextCodec::codecForMib(mib)->name();
77         ui.sendEncoding->addItem(codec);
78         ui.recvEncoding->addItem(codec);
79         ui.serverEncoding->addItem(codec);
80     }
81     ui.sendEncoding->model()->sort(0);
82     ui.recvEncoding->model()->sort(0);
83     ui.serverEncoding->model()->sort(0);
84     currentId = 0;
85     setEnabled(Client::isConnected());  // need a core connection!
86     setWidgetStates();
87
88     connectToWidgetsChangedSignals({ui.identityList,         ui.performEdit,          ui.sasl,
89                                     ui.saslAccount,          ui.saslPassword,         ui.autoIdentify,
90                                     ui.autoIdentifyService,  ui.autoIdentifyPassword, ui.useCustomEncodings,
91                                     ui.sendEncoding,         ui.recvEncoding,         ui.serverEncoding,
92                                     ui.autoReconnect,        ui.reconnectInterval,    ui.reconnectRetries,
93                                     ui.unlimitedRetries,     ui.rejoinOnReconnect,    ui.useCustomMessageRate,
94                                     ui.messageRateBurstSize, ui.messageRateDelay,     ui.unlimitedMessageRate,
95                                     ui.enableCapServerTime},
96                                    this,
97                                    &NetworksSettingsPage::widgetHasChanged);
98
99     connect(Client::instance(), &Client::coreConnectionStateChanged, this, &NetworksSettingsPage::coreConnectionStateChanged);
100     connect(Client::instance(), &Client::networkCreated, this, &NetworksSettingsPage::clientNetworkAdded);
101     connect(Client::instance(), &Client::networkRemoved, this, &NetworksSettingsPage::clientNetworkRemoved);
102     connect(Client::instance(), &Client::identityCreated, this, &NetworksSettingsPage::clientIdentityAdded);
103     connect(Client::instance(), &Client::identityRemoved, this, &NetworksSettingsPage::clientIdentityRemoved);
104
105     foreach (IdentityId id, Client::identityIds()) {
106         clientIdentityAdded(id);
107     }
108 }
109
110 void NetworksSettingsPage::save()
111 {
112     setEnabled(false);
113     if (currentId != 0)
114         saveToNetworkInfo(networkInfos[currentId]);
115
116     QList<NetworkInfo> toCreate, toUpdate;
117     QList<NetworkId> toRemove;
118     QHash<NetworkId, NetworkInfo>::iterator i = networkInfos.begin();
119     while (i != networkInfos.end()) {
120         NetworkId id = (*i).networkId;
121         if (id < 0) {
122             toCreate.append(*i);
123             // if(id == currentId) currentId = 0;
124             // QList<QListWidgetItem *> items = ui.networkList->findItems((*i).networkName, Qt::MatchExactly);
125             // if(items.count()) {
126             //  Q_ASSERT(items[0]->data(Qt::UserRole).value<NetworkId>() == id);
127             //  delete items[0];
128             //}
129             // i = networkInfos.erase(i);
130             ++i;
131         }
132         else {
133             if ((*i) != Client::network((*i).networkId)->networkInfo()) {
134                 toUpdate.append(*i);
135             }
136             ++i;
137         }
138     }
139     foreach (NetworkId id, Client::networkIds()) {
140         if (!networkInfos.contains(id))
141             toRemove.append(id);
142     }
143     SaveNetworksDlg dlg(toCreate, toUpdate, toRemove, this);
144     int ret = dlg.exec();
145     if (ret == QDialog::Rejected) {
146         // canceled -> reload everything to be safe
147         load();
148     }
149     setChangedState(false);
150     setEnabled(true);
151 }
152
153 void NetworksSettingsPage::load()
154 {
155     reset();
156
157     // Handle UI dependent on core feature flags here
158     if (Client::isCoreFeatureEnabled(Quassel::Feature::CustomRateLimits)) {
159         // Custom rate limiting supported, allow toggling
160         ui.useCustomMessageRate->setEnabled(true);
161         // Reset tooltip to default.
162         ui.useCustomMessageRate->setToolTip(QString("%1").arg(tr("<p>Override default message rate limiting.</p>"
163                                                                  "<p><b>Setting limits too low may get you disconnected"
164                                                                  " from the server!</b></p>")));
165         // If changed, update the message below!
166     }
167     else {
168         // Custom rate limiting not supported, disallow toggling
169         ui.useCustomMessageRate->setEnabled(false);
170         // Split up the message to allow re-using translations:
171         // [Original tool-tip]
172         // [Bold 'does not support feature' message]
173         // [Specific version needed and feature details]
174         ui.useCustomMessageRate->setToolTip(QString("%1<br/><b>%2</b><br/>%3")
175                                                 .arg(tr("<p>Override default message rate limiting.</p>"
176                                                         "<p><b>Setting limits too low may get you disconnected"
177                                                         " from the server!</b></p>"),
178                                                      tr("Your Quassel core does not support this feature"),
179                                                      tr("You need a Quassel core v0.13.0 or newer in order to "
180                                                         "modify message rate limits.")));
181     }
182
183     if (!Client::isConnected() || Client::isCoreFeatureEnabled(Quassel::Feature::SkipIrcCaps)) {
184         // Either disconnected or IRCv3 capability skippping supported, enable configuration and
185         // hide warning.  Don't show the warning needlessly when disconnected.
186         ui.enableCapsConfigWidget->setEnabled(true);
187         ui.enableCapsStatusLabel->setText(tr("These features require support from the network"));
188         ui.enableCapsStatusIcon->setPixmap(infoIcon.pixmap(16));
189     }
190     else {
191         // Core does not IRCv3 capability skipping, show warning and disable configuration
192         ui.enableCapsConfigWidget->setEnabled(false);
193         ui.enableCapsStatusLabel->setText(tr("Your Quassel core is too old to configure IRCv3 features"));
194         ui.enableCapsStatusIcon->setPixmap(unavailableIcon.pixmap(16));
195     }
196
197     // Hide the SASL EXTERNAL notice until a network's shown.  Stops it from showing while loading
198     // backlog from the core.
199     sslUpdated();
200
201     // Reset network capability status in case no valid networks get selected (a rare situation)
202     resetNetworkCapStates();
203
204     foreach (NetworkId netid, Client::networkIds()) {
205         clientNetworkAdded(netid);
206     }
207     ui.networkList->setCurrentRow(0);
208
209     setChangedState(false);
210 }
211
212 void NetworksSettingsPage::reset()
213 {
214     currentId = 0;
215     ui.networkList->clear();
216     networkInfos.clear();
217 }
218
219 bool NetworksSettingsPage::aboutToSave()
220 {
221     if (currentId != 0)
222         saveToNetworkInfo(networkInfos[currentId]);
223     QList<int> errors;
224     foreach (NetworkInfo info, networkInfos.values()) {
225         if (!info.serverList.count())
226             errors.append(1);
227     }
228     if (!errors.count())
229         return true;
230     QString error(tr("<b>The following problems need to be corrected before your changes can be applied:</b><ul>"));
231     if (errors.contains(1))
232         error += tr("<li>All networks need at least one server defined</li>");
233     error += tr("</ul>");
234     QMessageBox::warning(this, tr("Invalid Network Settings"), error);
235     return false;
236 }
237
238 void NetworksSettingsPage::widgetHasChanged()
239 {
240     if (_ignoreWidgetChanges)
241         return;
242     bool changed = testHasChanged();
243     if (changed != hasChanged())
244         setChangedState(changed);
245 }
246
247 bool NetworksSettingsPage::testHasChanged()
248 {
249     if (currentId != 0) {
250         saveToNetworkInfo(networkInfos[currentId]);
251     }
252     if (Client::networkIds().count() != networkInfos.count())
253         return true;
254     foreach (NetworkId id, networkInfos.keys()) {
255         if (id < 0)
256             return true;
257         if (Client::network(id)->networkInfo() != networkInfos[id])
258             return true;
259     }
260     return false;
261 }
262
263 void NetworksSettingsPage::setWidgetStates()
264 {
265     // network list
266     if (ui.networkList->selectedItems().count()) {
267         ui.detailsBox->setEnabled(true);
268         ui.renameNetwork->setEnabled(true);
269         ui.deleteNetwork->setEnabled(true);
270
271         /* button disabled for now
272         NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
273         const Network *net = id > 0 ? Client::network(id) : 0;
274         ui.connectNow->setEnabled(net);
275         //    && (Client::network(id)->connectionState() == Network::Initialized
276         //    || Client::network(id)->connectionState() == Network::Disconnected));
277         if(net) {
278           if(net->connectionState() == Network::Disconnected) {
279             ui.connectNow->setIcon(connectedIcon);
280             ui.connectNow->setText(tr("Connect"));
281           } else {
282             ui.connectNow->setIcon(disconnectedIcon);
283             ui.connectNow->setText(tr("Disconnect"));
284           }
285         } else {
286           ui.connectNow->setIcon(QIcon());
287           ui.connectNow->setText(tr("Apply first!"));
288         } */
289     }
290     else {
291         ui.renameNetwork->setEnabled(false);
292         ui.deleteNetwork->setEnabled(false);
293         // ui.connectNow->setEnabled(false);
294         ui.detailsBox->setEnabled(false);
295     }
296     // network details
297     if (ui.serverList->selectedItems().count()) {
298         ui.editServer->setEnabled(true);
299         ui.deleteServer->setEnabled(true);
300         ui.upServer->setEnabled(ui.serverList->currentRow() > 0);
301         ui.downServer->setEnabled(ui.serverList->currentRow() < ui.serverList->count() - 1);
302     }
303     else {
304         ui.editServer->setEnabled(false);
305         ui.deleteServer->setEnabled(false);
306         ui.upServer->setEnabled(false);
307         ui.downServer->setEnabled(false);
308     }
309 }
310
311 void NetworksSettingsPage::setItemState(NetworkId id, QListWidgetItem* item)
312 {
313     if (!item && !(item = networkItem(id)))
314         return;
315     const Network* net = Client::network(id);
316     if (!net || net->isInitialized())
317         item->setFlags(item->flags() | Qt::ItemIsEnabled);
318     else
319         item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
320     if (net && net->connectionState() == Network::Initialized) {
321         item->setIcon(connectedIcon);
322     }
323     else if (net && net->connectionState() != Network::Disconnected) {
324         item->setIcon(connectingIcon);
325     }
326     else {
327         item->setIcon(disconnectedIcon);
328     }
329     if (net) {
330         bool select = false;
331         // check if we already have another net of this name in the list, and replace it
332         QList<QListWidgetItem*> items = ui.networkList->findItems(net->networkName(), Qt::MatchExactly);
333         if (items.count()) {
334             foreach (QListWidgetItem* i, items) {
335                 NetworkId oldid = i->data(Qt::UserRole).value<NetworkId>();
336                 if (oldid > 0)
337                     continue;  // only locally created nets should be replaced
338                 if (oldid == currentId) {
339                     select = true;
340                     currentId = 0;
341                     ui.networkList->clearSelection();
342                 }
343                 int row = ui.networkList->row(i);
344                 if (row >= 0) {
345                     QListWidgetItem* olditem = ui.networkList->takeItem(row);
346                     Q_ASSERT(olditem);
347                     delete olditem;
348                 }
349                 networkInfos.remove(oldid);
350                 break;
351             }
352         }
353         item->setText(net->networkName());
354         if (select)
355             item->setSelected(true);
356     }
357 }
358
359 void NetworksSettingsPage::resetNetworkCapStates()
360 {
361     // Set the status to a blank (invalid) network ID, reseting all UI
362     setNetworkCapStates(NetworkId());
363 }
364
365 void NetworksSettingsPage::setNetworkCapStates(NetworkId id)
366 {
367     const Network* net = Client::network(id);
368     if (net && Client::isCoreFeatureEnabled(Quassel::Feature::CapNegotiation)) {
369         // Capability negotiation is supported, network exists.
370         // Check if the network is connected.  Don't use net->isConnected() as that won't be true
371         // during capability negotiation when capabilities are added and removed.
372         if (net->connectionState() != Network::Disconnected) {
373             // Network exists and is connected, check available capabilities...
374             // [SASL]
375             if (net->saslMaybeSupports(IrcCap::SaslMech::PLAIN)) {
376                 setSASLStatus(CapSupportStatus::MaybeSupported);
377             }
378             else {
379                 setSASLStatus(CapSupportStatus::MaybeUnsupported);
380             }
381
382             // Add additional capability-dependent interface updates here
383         }
384         else {
385             // Network is disconnected
386             // [SASL]
387             setSASLStatus(CapSupportStatus::Disconnected);
388
389             // Add additional capability-dependent interface updates here
390         }
391     }
392     else {
393         // Capability negotiation is not supported and/or network doesn't exist.
394         // Don't assume anything and reset all capability-dependent interface elements to neutral.
395         // [SASL]
396         setSASLStatus(CapSupportStatus::Unknown);
397
398         // Add additional capability-dependent interface updates here
399     }
400 }
401
402 void NetworksSettingsPage::coreConnectionStateChanged(bool state)
403 {
404     this->setEnabled(state);
405     if (state) {
406         load();
407     }
408     else {
409         // reset
410         // currentId = 0;
411     }
412 }
413
414 void NetworksSettingsPage::clientIdentityAdded(IdentityId id)
415 {
416     const Identity* identity = Client::identity(id);
417     connect(identity, &SyncableObject::updatedRemotely, this, &NetworksSettingsPage::clientIdentityUpdated);
418
419     QString name = identity->identityName();
420     for (int j = 0; j < ui.identityList->count(); j++) {
421         if ((j > 0 || ui.identityList->itemData(0).toInt() != 1) && name.localeAwareCompare(ui.identityList->itemText(j)) < 0) {
422             ui.identityList->insertItem(j, name, id.toInt());
423             widgetHasChanged();
424             return;
425         }
426     }
427     // append
428     ui.identityList->insertItem(ui.identityList->count(), name, id.toInt());
429     widgetHasChanged();
430 }
431
432 void NetworksSettingsPage::clientIdentityUpdated()
433 {
434     const auto* identity = qobject_cast<const Identity*>(sender());
435     if (!identity) {
436         qWarning() << "NetworksSettingsPage: Invalid identity to update!";
437         return;
438     }
439     int row = ui.identityList->findData(identity->id().toInt());
440     if (row < 0) {
441         qWarning() << "NetworksSettingsPage: Invalid identity to update!";
442         return;
443     }
444     if (ui.identityList->itemText(row) != identity->identityName()) {
445         ui.identityList->setItemText(row, identity->identityName());
446     }
447 }
448
449 void NetworksSettingsPage::clientIdentityRemoved(IdentityId id)
450 {
451     IdentityId defaultId = defaultIdentity();
452     if (currentId != 0)
453         saveToNetworkInfo(networkInfos[currentId]);
454     foreach (NetworkInfo info, networkInfos.values()) {
455         if (info.identity == id) {
456             if (info.networkId == currentId)
457                 ui.identityList->setCurrentIndex(0);
458             info.identity = defaultId;
459             networkInfos[info.networkId] = info;
460             if (info.networkId > 0)
461                 Client::updateNetwork(info);
462         }
463     }
464     ui.identityList->removeItem(ui.identityList->findData(id.toInt()));
465     widgetHasChanged();
466 }
467
468 QListWidgetItem* NetworksSettingsPage::networkItem(NetworkId id) const
469 {
470     for (int i = 0; i < ui.networkList->count(); i++) {
471         QListWidgetItem* item = ui.networkList->item(i);
472         if (item->data(Qt::UserRole).value<NetworkId>() == id)
473             return item;
474     }
475     return nullptr;
476 }
477
478 void NetworksSettingsPage::clientNetworkAdded(NetworkId id)
479 {
480     insertNetwork(id);
481     // connect(Client::network(id), &Network::updatedRemotely, this, &NetworksSettingsPage::clientNetworkUpdated);
482     connect(Client::network(id), &Network::configChanged, this, &NetworksSettingsPage::clientNetworkUpdated);
483
484     connect(Client::network(id), &Network::connectionStateSet, this, &NetworksSettingsPage::networkConnectionStateChanged);
485     connect(Client::network(id), &Network::connectionError, this, &NetworksSettingsPage::networkConnectionError);
486
487     // Handle capability changes in case a server dis/connects with the settings window open.
488     connect(Client::network(id), &Network::capAdded, this, &NetworksSettingsPage::clientNetworkCapsUpdated);
489     connect(Client::network(id), &Network::capRemoved, this, &NetworksSettingsPage::clientNetworkCapsUpdated);
490 }
491
492 void NetworksSettingsPage::clientNetworkUpdated()
493 {
494     const auto* net = qobject_cast<const Network*>(sender());
495     if (!net) {
496         qWarning() << "Update request for unknown network received!";
497         return;
498     }
499     networkInfos[net->networkId()] = net->networkInfo();
500     setItemState(net->networkId());
501     if (net->networkId() == currentId)
502         displayNetwork(net->networkId());
503     setWidgetStates();
504     widgetHasChanged();
505 }
506
507 void NetworksSettingsPage::clientNetworkRemoved(NetworkId id)
508 {
509     if (!networkInfos.contains(id))
510         return;
511     if (id == currentId)
512         displayNetwork(0);
513     NetworkInfo info = networkInfos.take(id);
514     QList<QListWidgetItem*> items = ui.networkList->findItems(info.networkName, Qt::MatchExactly);
515     foreach (QListWidgetItem* item, items) {
516         if (item->data(Qt::UserRole).value<NetworkId>() == id)
517             delete ui.networkList->takeItem(ui.networkList->row(item));
518     }
519     setWidgetStates();
520     widgetHasChanged();
521 }
522
523 void NetworksSettingsPage::networkConnectionStateChanged(Network::ConnectionState state)
524 {
525     Q_UNUSED(state);
526     const auto* net = qobject_cast<const Network*>(sender());
527     if (!net)
528         return;
529     /*
530     if(net->networkId() == currentId) {
531       ui.connectNow->setEnabled(state == Network::Initialized || state == Network::Disconnected);
532     }
533     */
534     setItemState(net->networkId());
535     if (net->networkId() == currentId) {
536         // Network is currently shown.  Update the capability-dependent UI in case capabilities have
537         // changed.
538         setNetworkCapStates(currentId);
539     }
540     setWidgetStates();
541 }
542
543 void NetworksSettingsPage::networkConnectionError(const QString&) {}
544
545 QListWidgetItem* NetworksSettingsPage::insertNetwork(NetworkId id)
546 {
547     NetworkInfo info = Client::network(id)->networkInfo();
548     networkInfos[id] = info;
549     return insertNetwork(info);
550 }
551
552 QListWidgetItem* NetworksSettingsPage::insertNetwork(const NetworkInfo& info)
553 {
554     QListWidgetItem* item = nullptr;
555     QList<QListWidgetItem*> items = ui.networkList->findItems(info.networkName, Qt::MatchExactly);
556     if (!items.count())
557         item = new QListWidgetItem(disconnectedIcon, info.networkName, ui.networkList);
558     else {
559         // we overwrite an existing net if it a) has the same name and b) has a negative ID meaning we created it locally before
560         // -> then we can be sure that this is the core-side replacement for the net we created
561         foreach (QListWidgetItem* i, items) {
562             NetworkId id = i->data(Qt::UserRole).value<NetworkId>();
563             if (id < 0) {
564                 item = i;
565                 break;
566             }
567         }
568         if (!item)
569             item = new QListWidgetItem(disconnectedIcon, info.networkName, ui.networkList);
570     }
571     item->setData(Qt::UserRole, QVariant::fromValue(info.networkId));
572     setItemState(info.networkId, item);
573     widgetHasChanged();
574     return item;
575 }
576
577 // Called when selecting 'Configure' from the buffer list
578 void NetworksSettingsPage::bufferList_Open(NetworkId netId)
579 {
580     QListWidgetItem* item = networkItem(netId);
581     ui.networkList->setCurrentItem(item, QItemSelectionModel::SelectCurrent);
582 }
583
584 void NetworksSettingsPage::displayNetwork(NetworkId id)
585 {
586     _ignoreWidgetChanges = true;
587     if (id != 0) {
588         NetworkInfo info = networkInfos[id];
589
590         // this is only needed when the core supports SASL EXTERNAL
591         if (Client::isCoreFeatureEnabled(Quassel::Feature::SaslExternal)) {
592             if (_cid) {
593                 disconnect(_cid, &CertIdentity::sslSettingsUpdated, this, &NetworksSettingsPage::sslUpdated);
594                 delete _cid;
595             }
596             _cid = new CertIdentity(*Client::identity(info.identity), this);
597             _cid->enableEditSsl(true);
598             connect(_cid, &CertIdentity::sslSettingsUpdated, this, &NetworksSettingsPage::sslUpdated);
599         }
600
601         ui.identityList->setCurrentIndex(ui.identityList->findData(info.identity.toInt()));
602         ui.serverList->clear();
603         foreach (Network::Server server, info.serverList) {
604             QListWidgetItem* item = new QListWidgetItem(QString("%1:%2").arg(server.host).arg(server.port));
605             if (server.useSsl)
606                 item->setIcon(icon::get("document-encrypt"));
607             ui.serverList->addItem(item);
608         }
609         // setItemState(id);
610         // ui.randomServer->setChecked(info.useRandomServer);
611         // Update the capability-dependent UI in case capabilities have changed.
612         setNetworkCapStates(id);
613         ui.performEdit->setPlainText(info.perform.join("\n"));
614         ui.autoIdentify->setChecked(info.useAutoIdentify);
615         ui.autoIdentifyService->setText(info.autoIdentifyService);
616         ui.autoIdentifyPassword->setText(info.autoIdentifyPassword);
617         ui.sasl->setChecked(info.useSasl);
618         ui.saslAccount->setText(info.saslAccount);
619         ui.saslPassword->setText(info.saslPassword);
620         if (info.codecForEncoding.isEmpty()) {
621             ui.sendEncoding->setCurrentIndex(ui.sendEncoding->findText(Network::defaultCodecForEncoding()));
622             ui.recvEncoding->setCurrentIndex(ui.recvEncoding->findText(Network::defaultCodecForDecoding()));
623             ui.serverEncoding->setCurrentIndex(ui.serverEncoding->findText(Network::defaultCodecForServer()));
624             ui.useCustomEncodings->setChecked(false);
625         }
626         else {
627             ui.sendEncoding->setCurrentIndex(ui.sendEncoding->findText(info.codecForEncoding));
628             ui.recvEncoding->setCurrentIndex(ui.recvEncoding->findText(info.codecForDecoding));
629             ui.serverEncoding->setCurrentIndex(ui.serverEncoding->findText(info.codecForServer));
630             ui.useCustomEncodings->setChecked(true);
631         }
632         ui.autoReconnect->setChecked(info.useAutoReconnect);
633         ui.reconnectInterval->setValue(info.autoReconnectInterval);
634         ui.reconnectRetries->setValue(info.autoReconnectRetries);
635         ui.unlimitedRetries->setChecked(info.unlimitedReconnectRetries);
636         ui.rejoinOnReconnect->setChecked(info.rejoinChannels);
637         // Custom rate limiting
638         ui.unlimitedMessageRate->setChecked(info.unlimitedMessageRate);
639         // Set 'ui.useCustomMessageRate' after 'ui.unlimitedMessageRate' so if the latter is
640         // disabled, 'ui.messageRateDelayFrame' will remain disabled.
641         ui.useCustomMessageRate->setChecked(info.useCustomMessageRate);
642         ui.messageRateBurstSize->setValue(info.messageRateBurstSize);
643         // Convert milliseconds (integer) into seconds (double)
644         ui.messageRateDelay->setValue(info.messageRateDelay / 1000.0f);
645         // Skipped IRCv3 capabilities
646         ui.enableCapServerTime->setChecked(!info.skipCaps.contains(IrcCap::SERVER_TIME));
647     }
648     else {
649         // just clear widgets
650         if (_cid) {
651             disconnect(_cid, &CertIdentity::sslSettingsUpdated, this, &NetworksSettingsPage::sslUpdated);
652             delete _cid;
653         }
654         ui.identityList->setCurrentIndex(-1);
655         ui.serverList->clear();
656         ui.performEdit->clear();
657         ui.autoIdentifyService->clear();
658         ui.autoIdentifyPassword->clear();
659         ui.saslAccount->clear();
660         ui.saslPassword->clear();
661         setWidgetStates();
662     }
663     _ignoreWidgetChanges = false;
664     currentId = id;
665 }
666
667 void NetworksSettingsPage::saveToNetworkInfo(NetworkInfo& info)
668 {
669     info.identity = ui.identityList->itemData(ui.identityList->currentIndex()).toInt();
670     // info.useRandomServer = ui.randomServer->isChecked();
671     info.perform = ui.performEdit->toPlainText().split("\n");
672     info.useAutoIdentify = ui.autoIdentify->isChecked();
673     info.autoIdentifyService = ui.autoIdentifyService->text();
674     info.autoIdentifyPassword = ui.autoIdentifyPassword->text();
675     info.useSasl = ui.sasl->isChecked();
676     info.saslAccount = ui.saslAccount->text();
677     info.saslPassword = ui.saslPassword->text();
678     if (!ui.useCustomEncodings->isChecked()) {
679         info.codecForEncoding.clear();
680         info.codecForDecoding.clear();
681         info.codecForServer.clear();
682     }
683     else {
684         info.codecForEncoding = ui.sendEncoding->currentText().toLatin1();
685         info.codecForDecoding = ui.recvEncoding->currentText().toLatin1();
686         info.codecForServer = ui.serverEncoding->currentText().toLatin1();
687     }
688     info.useAutoReconnect = ui.autoReconnect->isChecked();
689     info.autoReconnectInterval = ui.reconnectInterval->value();
690     info.autoReconnectRetries = ui.reconnectRetries->value();
691     info.unlimitedReconnectRetries = ui.unlimitedRetries->isChecked();
692     info.rejoinChannels = ui.rejoinOnReconnect->isChecked();
693     // Custom rate limiting
694     info.useCustomMessageRate = ui.useCustomMessageRate->isChecked();
695     info.messageRateBurstSize = ui.messageRateBurstSize->value();
696     // Convert seconds (double) into milliseconds (integer)
697     info.messageRateDelay = static_cast<quint32>((ui.messageRateDelay->value() * 1000));
698     info.unlimitedMessageRate = ui.unlimitedMessageRate->isChecked();
699     // Skipped IRCv3 capabilities
700     if (ui.enableCapServerTime->isChecked()) {
701         // Capability enabled, remove it from the skip list
702         info.skipCaps.removeAll(IrcCap::SERVER_TIME);
703     } else if (!info.skipCaps.contains(IrcCap::SERVER_TIME)) {
704         // Capability disabled and not in the skip list, add it
705         info.skipCaps.append(IrcCap::SERVER_TIME);
706     }
707 }
708
709 void NetworksSettingsPage::clientNetworkCapsUpdated()
710 {
711     // Grab the updated network
712     const auto* net = qobject_cast<const Network*>(sender());
713     if (!net) {
714         qWarning() << "Update request for unknown network received!";
715         return;
716     }
717     if (net->networkId() == currentId) {
718         // Network is currently shown.  Update the capability-dependent UI in case capabilities have
719         // changed.
720         setNetworkCapStates(currentId);
721     }
722 }
723
724 void NetworksSettingsPage::setSASLStatus(const CapSupportStatus saslStatus)
725 {
726     if (_saslStatusSelected != saslStatus) {
727         // Update the cached copy of SASL status used with the Details dialog
728         _saslStatusSelected = saslStatus;
729
730         // Update the user interface
731         switch (saslStatus) {
732         case CapSupportStatus::Unknown:
733             // There's no capability negotiation or network doesn't exist.  Don't assume
734             // anything.
735             ui.saslStatusLabel->setText(QString("<i>%1</i>").arg(tr("Could not check if supported by network")));
736             ui.saslStatusIcon->setPixmap(questionIcon.pixmap(16));
737             break;
738         case CapSupportStatus::Disconnected:
739             // Disconnected from network, no way to check.
740             ui.saslStatusLabel->setText(QString("<i>%1</i>").arg(tr("Cannot check if supported when disconnected")));
741             ui.saslStatusIcon->setPixmap(questionIcon.pixmap(16));
742             break;
743         case CapSupportStatus::MaybeUnsupported:
744             // The network doesn't advertise support for SASL PLAIN.  Here be dragons.
745             ui.saslStatusLabel->setText(QString("<i>%1</i>").arg(tr("Not currently supported by network")));
746             ui.saslStatusIcon->setPixmap(unavailableIcon.pixmap(16));
747             break;
748         case CapSupportStatus::MaybeSupported:
749             // The network advertises support for SASL PLAIN.  Encourage using it!
750             // Unfortunately we don't know for sure if it's desired or functional.
751             ui.saslStatusLabel->setText(QString("<i>%1</i>").arg(tr("Supported by network")));
752             ui.saslStatusIcon->setPixmap(successIcon.pixmap(16));
753             break;
754         }
755     }
756 }
757
758 void NetworksSettingsPage::sslUpdated()
759 {
760     if (_cid && !_cid->sslKey().isNull()) {
761         ui.saslContents->setDisabled(true);
762         ui.saslExtInfo->setHidden(false);
763     }
764     else {
765         ui.saslContents->setDisabled(false);
766         // Directly re-enabling causes the widgets to ignore the parent "Use SASL Authentication"
767         // state to indicate whether or not it's disabled.  To workaround this, keep track of
768         // whether or not "Use SASL Authentication" is enabled, then quickly uncheck/recheck the
769         // group box.
770         if (!ui.sasl->isChecked()) {
771             // SASL is not enabled, uncheck/recheck the group box to re-disable saslContents.
772             // Leaving saslContents disabled doesn't work as that prevents it from re-enabling if
773             // sasl is later checked.
774             ui.sasl->setChecked(true);
775             ui.sasl->setChecked(false);
776         }
777         ui.saslExtInfo->setHidden(true);
778     }
779 }
780
781 /*** Network list ***/
782
783 void NetworksSettingsPage::on_networkList_itemSelectionChanged()
784 {
785     if (currentId != 0) {
786         saveToNetworkInfo(networkInfos[currentId]);
787     }
788     if (ui.networkList->selectedItems().count()) {
789         NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
790         currentId = id;
791         displayNetwork(id);
792         ui.serverList->setCurrentRow(0);
793     }
794     else {
795         currentId = 0;
796     }
797     setWidgetStates();
798 }
799
800 void NetworksSettingsPage::on_addNetwork_clicked()
801 {
802     QStringList existing;
803     for (int i = 0; i < ui.networkList->count(); i++)
804         existing << ui.networkList->item(i)->text();
805     NetworkAddDlg dlg(existing, this);
806     if (dlg.exec() == QDialog::Accepted) {
807         NetworkInfo info = dlg.networkInfo();
808         if (info.networkName.isEmpty())
809             return;  // sanity check
810
811         NetworkId id;
812         for (id = 1; id <= networkInfos.count(); id++) {
813             widgetHasChanged();
814             if (!networkInfos.keys().contains(-id.toInt()))
815                 break;
816         }
817         id = -id.toInt();
818         info.networkId = id;
819         info.identity = defaultIdentity();
820         networkInfos[id] = info;
821         QListWidgetItem* item = insertNetwork(info);
822         ui.networkList->setCurrentItem(item);
823         setWidgetStates();
824     }
825 }
826
827 void NetworksSettingsPage::on_deleteNetwork_clicked()
828 {
829     if (ui.networkList->selectedItems().count()) {
830         NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
831         int ret
832             = QMessageBox::question(this,
833                                     tr("Delete Network?"),
834                                     tr("Do you really want to delete the network \"%1\" and all related settings, including the backlog?")
835                                         .arg(networkInfos[netid].networkName),
836                                     QMessageBox::Yes | QMessageBox::No,
837                                     QMessageBox::No);
838         if (ret == QMessageBox::Yes) {
839             currentId = 0;
840             networkInfos.remove(netid);
841             delete ui.networkList->takeItem(ui.networkList->row(ui.networkList->selectedItems()[0]));
842             ui.networkList->setCurrentRow(qMin(ui.networkList->currentRow() + 1, ui.networkList->count() - 1));
843             setWidgetStates();
844             widgetHasChanged();
845         }
846     }
847 }
848
849 void NetworksSettingsPage::on_renameNetwork_clicked()
850 {
851     if (!ui.networkList->selectedItems().count())
852         return;
853     QString old = ui.networkList->selectedItems()[0]->text();
854     QStringList existing;
855     for (int i = 0; i < ui.networkList->count(); i++)
856         existing << ui.networkList->item(i)->text();
857     NetworkEditDlg dlg(old, existing, this);
858     if (dlg.exec() == QDialog::Accepted) {
859         ui.networkList->selectedItems()[0]->setText(dlg.networkName());
860         NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
861         networkInfos[netid].networkName = dlg.networkName();
862         widgetHasChanged();
863     }
864 }
865
866 /*
867 void NetworksSettingsPage::on_connectNow_clicked() {
868   if(!ui.networkList->selectedItems().count()) return;
869   NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
870   const Network *net = Client::network(id);
871   if(!net) return;
872   if(net->connectionState() == Network::Disconnected) net->requestConnect();
873   else net->requestDisconnect();
874 }
875 */
876
877 /*** Server list ***/
878
879 void NetworksSettingsPage::on_serverList_itemSelectionChanged()
880 {
881     setWidgetStates();
882 }
883
884 void NetworksSettingsPage::on_addServer_clicked()
885 {
886     if (currentId == 0)
887         return;
888     ServerEditDlg dlg(Network::Server(), this);
889     if (dlg.exec() == QDialog::Accepted) {
890         networkInfos[currentId].serverList.append(dlg.serverData());
891         displayNetwork(currentId);
892         ui.serverList->setCurrentRow(ui.serverList->count() - 1);
893         widgetHasChanged();
894     }
895 }
896
897 void NetworksSettingsPage::on_editServer_clicked()
898 {
899     if (currentId == 0)
900         return;
901     int cur = ui.serverList->currentRow();
902     ServerEditDlg dlg(networkInfos[currentId].serverList[cur], this);
903     if (dlg.exec() == QDialog::Accepted) {
904         networkInfos[currentId].serverList[cur] = dlg.serverData();
905         displayNetwork(currentId);
906         ui.serverList->setCurrentRow(cur);
907         widgetHasChanged();
908     }
909 }
910
911 void NetworksSettingsPage::on_deleteServer_clicked()
912 {
913     if (currentId == 0)
914         return;
915     int cur = ui.serverList->currentRow();
916     networkInfos[currentId].serverList.removeAt(cur);
917     displayNetwork(currentId);
918     ui.serverList->setCurrentRow(qMin(cur, ui.serverList->count() - 1));
919     widgetHasChanged();
920 }
921
922 void NetworksSettingsPage::on_upServer_clicked()
923 {
924     int cur = ui.serverList->currentRow();
925     Network::Server server = networkInfos[currentId].serverList.takeAt(cur);
926     networkInfos[currentId].serverList.insert(cur - 1, server);
927     displayNetwork(currentId);
928     ui.serverList->setCurrentRow(cur - 1);
929     widgetHasChanged();
930 }
931
932 void NetworksSettingsPage::on_downServer_clicked()
933 {
934     int cur = ui.serverList->currentRow();
935     Network::Server server = networkInfos[currentId].serverList.takeAt(cur);
936     networkInfos[currentId].serverList.insert(cur + 1, server);
937     displayNetwork(currentId);
938     ui.serverList->setCurrentRow(cur + 1);
939     widgetHasChanged();
940 }
941
942 void NetworksSettingsPage::on_editIdentities_clicked()
943 {
944     SettingsPageDlg dlg(new IdentitiesSettingsPage(this), this);
945     dlg.exec();
946 }
947
948 void NetworksSettingsPage::on_saslStatusDetails_clicked()
949 {
950     if (ui.networkList->selectedItems().count()) {
951         NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
952         QString& netName = networkInfos[netid].networkName;
953
954         // If these strings are visible, one of the status messages wasn't detected below.
955         QString saslStatusHeader = "[header unintentionally left blank]";
956         QString saslStatusExplanation = "[explanation unintentionally left blank]";
957
958         // If true, show a warning icon instead of an information icon
959         bool useWarningIcon = false;
960
961         // Determine which explanation to show
962         switch (_saslStatusSelected) {
963         case CapSupportStatus::Unknown:
964             saslStatusHeader = tr("Could not check if SASL supported by network");
965             saslStatusExplanation = tr("Quassel could not check if \"%1\" supports SASL.  This may "
966                                        "be due to unsaved changes or an older Quassel core.  You "
967                                        "can still try using SASL.")
968                                         .arg(netName);
969             break;
970         case CapSupportStatus::Disconnected:
971             saslStatusHeader = tr("Cannot check if SASL supported when disconnected");
972             saslStatusExplanation = tr("Quassel cannot check if \"%1\" supports SASL when "
973                                        "disconnected.  Connect to the network, or try using SASL "
974                                        "anyways.")
975                                         .arg(netName);
976             break;
977         case CapSupportStatus::MaybeUnsupported:
978             saslStatusHeader = tr("SASL not currently supported by network");
979             saslStatusExplanation = tr("The network \"%1\" does not currently support SASL.  "
980                                        "However, support might be added later on.")
981                                         .arg(netName);
982             useWarningIcon = true;
983             break;
984         case CapSupportStatus::MaybeSupported:
985             saslStatusHeader = tr("SASL supported by network");
986             saslStatusExplanation = tr("The network \"%1\" supports SASL.  In most cases, you "
987                                        "should use SASL instead of NickServ identification.")
988                                         .arg(netName);
989             break;
990         }
991
992         // Process this in advance for reusability below
993         const QString saslStatusMsgTitle = tr("SASL support for \"%1\"").arg(netName);
994         const QString saslStatusMsgText = QString("<p><b>%1</b></p></br><p>%2</p></br><p><i>%3</i></p>")
995                                               .arg(saslStatusHeader,
996                                                    saslStatusExplanation,
997                                                    tr("SASL is a standardized way to log in and identify yourself to "
998                                                       "IRC servers."));
999
1000         if (useWarningIcon) {
1001             // Show as a warning dialog box
1002             QMessageBox::warning(this, saslStatusMsgTitle, saslStatusMsgText);
1003         }
1004         else {
1005             // Show as an information dialog box
1006             QMessageBox::information(this, saslStatusMsgTitle, saslStatusMsgText);
1007         }
1008     }
1009 }
1010
1011 void NetworksSettingsPage::on_enableCapsStatusDetails_clicked()
1012 {
1013     if (!Client::isConnected() || Client::isCoreFeatureEnabled(Quassel::Feature::SkipIrcCaps)) {
1014         // Either disconnected or IRCv3 capability skippping supported
1015
1016         // Try to get a list of currently enabled features
1017         QStringList sortedCapsEnabled;
1018         // Check if a network is selected
1019         if (ui.networkList->selectedItems().count()) {
1020             // Get the underlying Network from the selected network
1021             NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
1022             const Network* net = Client::network(netid);
1023             if (net && Client::isCoreFeatureEnabled(Quassel::Feature::CapNegotiation)) {
1024                 // Capability negotiation is supported, network exists.
1025                 // If the network is disconnected, the list of enabled capabilities will be empty,
1026                 // no need to check for that specifically.
1027                 // Sorting isn't required, but it looks nicer.
1028                 sortedCapsEnabled = net->capsEnabled();
1029                 sortedCapsEnabled.sort();
1030             }
1031         }
1032
1033         // Try to explain IRCv3 network features in a friendly way, including showing the currently
1034         // enabled features if available
1035         auto messageText = QString("<p>%1</p></br><p>%2</p>")
1036                 .arg(tr("Quassel makes use of newer IRC features when supported by the IRC network."
1037                         "  If desired, you can disable unwanted or problematic features here."),
1038                      tr("The <a href=\"https://ircv3.net/irc/\">IRCv3 website</a> provides more "
1039                         "technical details on the IRCv3 capabilities powering these features."));
1040
1041         if (!sortedCapsEnabled.isEmpty()) {
1042             // Format the capabilities within <code></code> blocks
1043             auto formattedCaps = QString("<code>%1</code>")
1044                     .arg(sortedCapsEnabled.join("</code>, <code>"));
1045
1046             // Add the currently enabled capabilities to the list
1047             // This creates a new QString, but this code is not performance-critical.
1048             messageText = messageText.append(QString("<p><i>%1</i></p>").arg(
1049                                                  tr("Currently enabled IRCv3 capabilities for this "
1050                                                     "network: %1").arg(formattedCaps)));
1051         }
1052
1053         QMessageBox::information(this, tr("Configuring network features"), messageText);
1054     }
1055     else {
1056         // Core does not IRCv3 capability skipping, show warning
1057         QMessageBox::warning(this, tr("Configuring network features unsupported"),
1058                              QString("<p><b>%1</b></p></br><p>%2</p>")
1059                              .arg(tr("Your Quassel core is too old to configure IRCv3 network features"),
1060                                   tr("You need a Quassel core v0.14.0 or newer to control what network "
1061                                      "features Quassel will use.")));
1062     }
1063 }
1064
1065 void NetworksSettingsPage::on_enableCapsAdvanced_clicked()
1066 {
1067     if (currentId == 0)
1068         return;
1069
1070     CapsEditDlg dlg(networkInfos[currentId].skipCapsToString(), this);
1071     if (dlg.exec() == QDialog::Accepted) {
1072         networkInfos[currentId].skipCapsFromString(dlg.skipCapsString());
1073         displayNetwork(currentId);
1074         widgetHasChanged();
1075     }
1076 }
1077
1078 IdentityId NetworksSettingsPage::defaultIdentity() const
1079 {
1080     IdentityId defaultId = 0;
1081     QList<IdentityId> ids = Client::identityIds();
1082     foreach (IdentityId id, ids) {
1083         if (defaultId == 0 || id < defaultId)
1084             defaultId = id;
1085     }
1086     return defaultId;
1087 }
1088
1089 /**************************************************************************
1090  * NetworkAddDlg
1091  *************************************************************************/
1092
1093 NetworkAddDlg::NetworkAddDlg(QStringList exist, QWidget* parent)
1094     : QDialog(parent)
1095     , existing(std::move(exist))
1096 {
1097     ui.setupUi(this);
1098     ui.useSSL->setIcon(icon::get("document-encrypt"));
1099
1100     // Whenever useSSL is toggled, update the port number if not changed from the default
1101     connect(ui.useSSL, &QAbstractButton::toggled, this, &NetworkAddDlg::updateSslPort);
1102     // Do NOT call updateSslPort when loading settings, otherwise port settings may be overriden.
1103     // If useSSL is later changed to be checked by default, change port's default value, too.
1104
1105     if (Client::isCoreFeatureEnabled(Quassel::Feature::VerifyServerSSL)) {
1106         // Synchronize requiring SSL with the use SSL checkbox
1107         ui.sslVerify->setEnabled(ui.useSSL->isChecked());
1108         connect(ui.useSSL, &QAbstractButton::toggled, ui.sslVerify, &QWidget::setEnabled);
1109     }
1110     else {
1111         // Core isn't new enough to allow requiring SSL; disable checkbox and uncheck
1112         ui.sslVerify->setEnabled(false);
1113         ui.sslVerify->setChecked(false);
1114         // Split up the message to allow re-using translations:
1115         // [Original tool-tip]
1116         // [Bold 'does not support feature' message]
1117         // [Specific version needed and feature details]
1118         ui.sslVerify->setToolTip(QString("%1<br/><b>%2</b><br/>%3")
1119                                      .arg(ui.sslVerify->toolTip(),
1120                                           tr("Your Quassel core does not support this feature"),
1121                                           tr("You need a Quassel core v0.13.0 or newer in order to "
1122                                              "verify connection security.")));
1123     }
1124
1125     // read preset networks
1126     QStringList networks = PresetNetworks::names();
1127     foreach (QString s, existing)
1128         networks.removeAll(s);
1129     if (networks.count())
1130         ui.presetList->addItems(networks);
1131     else {
1132         ui.useManual->setChecked(true);
1133         ui.usePreset->setEnabled(false);
1134     }
1135     connect(ui.networkName, &QLineEdit::textChanged, this, &NetworkAddDlg::setButtonStates);
1136     connect(ui.serverAddress, &QLineEdit::textChanged, this, &NetworkAddDlg::setButtonStates);
1137     connect(ui.usePreset, &QRadioButton::toggled, this, &NetworkAddDlg::setButtonStates);
1138     connect(ui.useManual, &QRadioButton::toggled, this, &NetworkAddDlg::setButtonStates);
1139     setButtonStates();
1140 }
1141
1142 NetworkInfo NetworkAddDlg::networkInfo() const
1143 {
1144     if (ui.useManual->isChecked()) {
1145         NetworkInfo info;
1146         info.networkName = ui.networkName->text().trimmed();
1147         info.serverList << Network::Server(ui.serverAddress->text().trimmed(),
1148                                            ui.port->value(),
1149                                            ui.serverPassword->text(),
1150                                            ui.useSSL->isChecked(),
1151                                            ui.sslVerify->isChecked());
1152         return info;
1153     }
1154     else
1155         return PresetNetworks::networkInfo(ui.presetList->currentText());
1156 }
1157
1158 void NetworkAddDlg::setButtonStates()
1159 {
1160     bool ok = false;
1161     if (ui.usePreset->isChecked() && ui.presetList->count())
1162         ok = true;
1163     else if (ui.useManual->isChecked()) {
1164         ok = !ui.networkName->text().trimmed().isEmpty() && !existing.contains(ui.networkName->text().trimmed())
1165              && !ui.serverAddress->text().isEmpty();
1166     }
1167     ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(ok);
1168 }
1169
1170 void NetworkAddDlg::updateSslPort(bool isChecked)
1171 {
1172     // "Use encrypted connection" was toggled, check the state...
1173     if (isChecked && ui.port->value() == Network::PORT_PLAINTEXT) {
1174         // Had been using the plain-text port, use the SSL default
1175         ui.port->setValue(Network::PORT_SSL);
1176     }
1177     else if (!isChecked && ui.port->value() == Network::PORT_SSL) {
1178         // Had been using the SSL port, use the plain-text default
1179         ui.port->setValue(Network::PORT_PLAINTEXT);
1180     }
1181 }
1182
1183 /**************************************************************************
1184  * NetworkEditDlg
1185  *************************************************************************/
1186
1187 NetworkEditDlg::NetworkEditDlg(const QString& old, QStringList exist, QWidget* parent)
1188     : QDialog(parent)
1189     , existing(std::move(exist))
1190 {
1191     ui.setupUi(this);
1192
1193     if (old.isEmpty()) {
1194         // new network
1195         setWindowTitle(tr("Add Network"));
1196         on_networkEdit_textChanged("");  // disable ok button
1197     }
1198     else
1199         ui.networkEdit->setText(old);
1200 }
1201
1202 QString NetworkEditDlg::networkName() const
1203 {
1204     return ui.networkEdit->text().trimmed();
1205 }
1206
1207 void NetworkEditDlg::on_networkEdit_textChanged(const QString& text)
1208 {
1209     ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(text.isEmpty() || existing.contains(text.trimmed()));
1210 }
1211
1212 /**************************************************************************
1213  * ServerEditDlg
1214  *************************************************************************/
1215 ServerEditDlg::ServerEditDlg(const Network::Server& server, QWidget* parent)
1216     : QDialog(parent)
1217 {
1218     ui.setupUi(this);
1219     ui.useSSL->setIcon(icon::get("document-encrypt"));
1220     ui.host->setText(server.host);
1221     ui.host->setFocus();
1222     ui.port->setValue(server.port);
1223     ui.password->setText(server.password);
1224     ui.useSSL->setChecked(server.useSsl);
1225     ui.sslVerify->setChecked(server.sslVerify);
1226     ui.sslVersion->setCurrentIndex(server.sslVersion);
1227     ui.useProxy->setChecked(server.useProxy);
1228     ui.proxyType->setCurrentIndex(server.proxyType == QNetworkProxy::Socks5Proxy ? 0 : 1);
1229     ui.proxyHost->setText(server.proxyHost);
1230     ui.proxyPort->setValue(server.proxyPort);
1231     ui.proxyUsername->setText(server.proxyUser);
1232     ui.proxyPassword->setText(server.proxyPass);
1233
1234     // This is a dirty hack to display the core->IRC SSL protocol dropdown
1235     // only if the core won't use autonegotiation to determine the best
1236     // protocol.  When autonegotiation was introduced, it would have been
1237     // a good idea to use the CoreFeatures enum to accomplish this.
1238     // However, since multiple versions have been released since then, that
1239     // is no longer possible.  Instead, we rely on the fact that the
1240     // Datastream protocol was introduced in the same version (0.10) as SSL
1241     // autonegotiation.  Because of that, we can display the dropdown only
1242     // if the Legacy protocol is in use.  If any other RemotePeer protocol
1243     // is in use, that means a newer protocol is in use and therefore the
1244     // core will use autonegotiation.
1245     if (Client::coreConnection()->peer()->protocol() != Protocol::LegacyProtocol) {
1246         ui.label_3->hide();
1247         ui.sslVersion->hide();
1248     }
1249
1250     // Whenever useSSL is toggled, update the port number if not changed from the default
1251     connect(ui.useSSL, &QAbstractButton::toggled, this, &ServerEditDlg::updateSslPort);
1252     // Do NOT call updateSslPort when loading settings, otherwise port settings may be overriden.
1253     // If useSSL is later changed to be checked by default, change port's default value, too.
1254
1255     if (Client::isCoreFeatureEnabled(Quassel::Feature::VerifyServerSSL)) {
1256         // Synchronize requiring SSL with the use SSL checkbox
1257         ui.sslVerify->setEnabled(ui.useSSL->isChecked());
1258         connect(ui.useSSL, &QAbstractButton::toggled, ui.sslVerify, &QWidget::setEnabled);
1259     }
1260     else {
1261         // Core isn't new enough to allow requiring SSL; disable checkbox and uncheck
1262         ui.sslVerify->setEnabled(false);
1263         ui.sslVerify->setChecked(false);
1264         // Split up the message to allow re-using translations:
1265         // [Original tool-tip]
1266         // [Bold 'does not support feature' message]
1267         // [Specific version needed and feature details]
1268         ui.sslVerify->setToolTip(QString("%1<br/><b>%2</b><br/>%3")
1269                                      .arg(ui.sslVerify->toolTip(),
1270                                           tr("Your Quassel core does not support this feature"),
1271                                           tr("You need a Quassel core v0.13.0 or newer in order to "
1272                                              "verify connection security.")));
1273     }
1274
1275     on_host_textChanged();
1276 }
1277
1278 Network::Server ServerEditDlg::serverData() const
1279 {
1280     Network::Server server(ui.host->text().trimmed(), ui.port->value(), ui.password->text(), ui.useSSL->isChecked(), ui.sslVerify->isChecked());
1281     server.sslVersion = ui.sslVersion->currentIndex();
1282     server.useProxy = ui.useProxy->isChecked();
1283     server.proxyType = ui.proxyType->currentIndex() == 0 ? QNetworkProxy::Socks5Proxy : QNetworkProxy::HttpProxy;
1284     server.proxyHost = ui.proxyHost->text();
1285     server.proxyPort = ui.proxyPort->value();
1286     server.proxyUser = ui.proxyUsername->text();
1287     server.proxyPass = ui.proxyPassword->text();
1288     return server;
1289 }
1290
1291 void ServerEditDlg::on_host_textChanged()
1292 {
1293     ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(ui.host->text().trimmed().isEmpty());
1294 }
1295
1296 void ServerEditDlg::updateSslPort(bool isChecked)
1297 {
1298     // "Use encrypted connection" was toggled, check the state...
1299     if (isChecked && ui.port->value() == Network::PORT_PLAINTEXT) {
1300         // Had been using the plain-text port, use the SSL default
1301         ui.port->setValue(Network::PORT_SSL);
1302     }
1303     else if (!isChecked && ui.port->value() == Network::PORT_SSL) {
1304         // Had been using the SSL port, use the plain-text default
1305         ui.port->setValue(Network::PORT_PLAINTEXT);
1306     }
1307 }
1308
1309 /**************************************************************************
1310  * CapsEditDlg
1311  *************************************************************************/
1312
1313 CapsEditDlg::CapsEditDlg(const QString& oldSkipCapsString, QWidget* parent)
1314     : QDialog(parent)
1315     , oldSkipCapsString(oldSkipCapsString)
1316 {
1317     ui.setupUi(this);
1318
1319     // Connect to the reset button to reset the text
1320     // This provides an explicit way to "get back to defaults" in case someone changes settings to
1321     // experiment
1322     QPushButton* defaultsButton = ui.buttonBox->button(QDialogButtonBox::RestoreDefaults);
1323     connect(defaultsButton, &QPushButton::clicked, this, &CapsEditDlg::defaultSkipCaps);
1324
1325     if (oldSkipCapsString.isEmpty()) {
1326         // Disable Reset button
1327         on_skipCapsEdit_textChanged("");
1328     }
1329     else {
1330         ui.skipCapsEdit->setText(oldSkipCapsString);
1331     }
1332 }
1333
1334
1335 QString CapsEditDlg::skipCapsString() const
1336 {
1337     return ui.skipCapsEdit->text();
1338 }
1339
1340 void CapsEditDlg::defaultSkipCaps()
1341 {
1342     ui.skipCapsEdit->setText("");
1343 }
1344
1345 void CapsEditDlg::on_skipCapsEdit_textChanged(const QString& text)
1346 {
1347     ui.buttonBox->button(QDialogButtonBox::RestoreDefaults)->setDisabled(text.isEmpty());
1348 }
1349
1350 /**************************************************************************
1351  * SaveNetworksDlg
1352  *************************************************************************/
1353
1354 SaveNetworksDlg::SaveNetworksDlg(const QList<NetworkInfo>& toCreate,
1355                                  const QList<NetworkInfo>& toUpdate,
1356                                  const QList<NetworkId>& toRemove,
1357                                  QWidget* parent)
1358     : QDialog(parent)
1359 {
1360     ui.setupUi(this);
1361
1362     numevents = toCreate.count() + toUpdate.count() + toRemove.count();
1363     rcvevents = 0;
1364     if (numevents) {
1365         ui.progressBar->setMaximum(numevents);
1366         ui.progressBar->setValue(0);
1367
1368         connect(Client::instance(), &Client::networkCreated, this, &SaveNetworksDlg::clientEvent);
1369         connect(Client::instance(), &Client::networkRemoved, this, &SaveNetworksDlg::clientEvent);
1370
1371         foreach (NetworkId id, toRemove) {
1372             Client::removeNetwork(id);
1373         }
1374         foreach (NetworkInfo info, toCreate) {
1375             Client::createNetwork(info);
1376         }
1377         foreach (NetworkInfo info, toUpdate) {
1378             const Network* net = Client::network(info.networkId);
1379             if (!net) {
1380                 qWarning() << "Invalid client network!";
1381                 numevents--;
1382                 continue;
1383             }
1384             // FIXME this only checks for one changed item rather than all!
1385             connect(net, &SyncableObject::updatedRemotely, this, &SaveNetworksDlg::clientEvent);
1386             Client::updateNetwork(info);
1387         }
1388     }
1389     else {
1390         qWarning() << "Sync dialog called without stuff to change!";
1391         accept();
1392     }
1393 }
1394
1395 void SaveNetworksDlg::clientEvent()
1396 {
1397     ui.progressBar->setValue(++rcvevents);
1398     if (rcvevents >= numevents)
1399         accept();
1400 }