Merge pull request #5 from Tucos/feat-keyx
[quassel.git] / src / qtui / settingspages / networkssettingspage.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2013 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 <QHeaderView>
22 #include <QMessageBox>
23 #include <QTextCodec>
24
25 #include "networkssettingspage.h"
26
27 #include "client.h"
28 #include "iconloader.h"
29 #include "identity.h"
30 #include "network.h"
31 #include "settingspagedlg.h"
32 #include "util.h"
33
34 #include "settingspages/identitiessettingspage.h"
35
36 NetworksSettingsPage::NetworksSettingsPage(QWidget *parent)
37     : SettingsPage(tr("IRC"), tr("Networks"), parent)
38 #ifdef HAVE_SSL
39       , _cid(0)
40 #endif
41 {
42     ui.setupUi(this);
43
44     // hide SASL options for older cores
45     if (!(Client::coreFeatures() & Quassel::SaslAuthentication))
46         ui.sasl->hide();
47     if (!(Client::coreFeatures() & Quassel::SaslExternal))
48         ui.saslExtInfo->hide();
49 #ifndef HAVE_SSL
50     ui.saslExtInfo->hide();
51 #endif
52
53     // set up icons
54     ui.renameNetwork->setIcon(SmallIcon("edit-rename"));
55     ui.addNetwork->setIcon(SmallIcon("list-add"));
56     ui.deleteNetwork->setIcon(SmallIcon("edit-delete"));
57     ui.addServer->setIcon(SmallIcon("list-add"));
58     ui.deleteServer->setIcon(SmallIcon("edit-delete"));
59     ui.editServer->setIcon(SmallIcon("configure"));
60     ui.upServer->setIcon(SmallIcon("go-up"));
61     ui.downServer->setIcon(SmallIcon("go-down"));
62     ui.editIdentities->setIcon(SmallIcon("configure"));
63
64     _ignoreWidgetChanges = false;
65
66     connectedIcon = SmallIcon("network-connect");
67     connectingIcon = SmallIcon("network-wired"); // FIXME network-connecting
68     disconnectedIcon = SmallIcon("network-disconnect");
69
70     foreach(int mib, QTextCodec::availableMibs()) {
71         QByteArray codec = QTextCodec::codecForMib(mib)->name();
72         ui.sendEncoding->addItem(codec);
73         ui.recvEncoding->addItem(codec);
74         ui.serverEncoding->addItem(codec);
75     }
76     ui.sendEncoding->model()->sort(0);
77     ui.recvEncoding->model()->sort(0);
78     ui.serverEncoding->model()->sort(0);
79     currentId = 0;
80     setEnabled(Client::isConnected()); // need a core connection!
81     setWidgetStates();
82     connect(Client::instance(), SIGNAL(coreConnectionStateChanged(bool)), this, SLOT(coreConnectionStateChanged(bool)));
83     connect(Client::instance(), SIGNAL(networkCreated(NetworkId)), this, SLOT(clientNetworkAdded(NetworkId)));
84     connect(Client::instance(), SIGNAL(networkRemoved(NetworkId)), this, SLOT(clientNetworkRemoved(NetworkId)));
85     connect(Client::instance(), SIGNAL(identityCreated(IdentityId)), this, SLOT(clientIdentityAdded(IdentityId)));
86     connect(Client::instance(), SIGNAL(identityRemoved(IdentityId)), this, SLOT(clientIdentityRemoved(IdentityId)));
87
88     connect(ui.identityList, SIGNAL(currentIndexChanged(int)), this, SLOT(widgetHasChanged()));
89     //connect(ui.randomServer, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
90     connect(ui.performEdit, SIGNAL(textChanged()), this, SLOT(widgetHasChanged()));
91     connect(ui.autoIdentify, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
92     connect(ui.autoIdentifyService, SIGNAL(textEdited(const QString &)), this, SLOT(widgetHasChanged()));
93     connect(ui.autoIdentifyPassword, SIGNAL(textEdited(const QString &)), this, SLOT(widgetHasChanged()));
94     connect(ui.sasl, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
95     connect(ui.saslAccount, SIGNAL(textEdited(QString)), this, SLOT(widgetHasChanged()));
96     connect(ui.saslPassword, SIGNAL(textEdited(QString)), this, SLOT(widgetHasChanged()));
97     connect(ui.useCustomEncodings, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
98     connect(ui.sendEncoding, SIGNAL(currentIndexChanged(int)), this, SLOT(widgetHasChanged()));
99     connect(ui.recvEncoding, SIGNAL(currentIndexChanged(int)), this, SLOT(widgetHasChanged()));
100     connect(ui.serverEncoding, SIGNAL(currentIndexChanged(int)), this, SLOT(widgetHasChanged()));
101     connect(ui.autoReconnect, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
102     connect(ui.reconnectInterval, SIGNAL(valueChanged(int)), this, SLOT(widgetHasChanged()));
103     connect(ui.reconnectRetries, SIGNAL(valueChanged(int)), this, SLOT(widgetHasChanged()));
104     connect(ui.unlimitedRetries, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
105     connect(ui.rejoinOnReconnect, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
106     //connect(ui., SIGNAL(), this, SLOT(widgetHasChanged()));
107     //connect(ui., SIGNAL(), this, SLOT(widgetHasChanged()));
108
109     foreach(IdentityId id, Client::identityIds()) {
110         clientIdentityAdded(id);
111     }
112 }
113
114
115 void NetworksSettingsPage::save()
116 {
117     setEnabled(false);
118     if (currentId != 0) saveToNetworkInfo(networkInfos[currentId]);
119
120     QList<NetworkInfo> toCreate, toUpdate;
121     QList<NetworkId> toRemove;
122     QHash<NetworkId, NetworkInfo>::iterator i = networkInfos.begin();
123     while (i != networkInfos.end()) {
124         NetworkId id = (*i).networkId;
125         if (id < 0) {
126             toCreate.append(*i);
127             //if(id == currentId) currentId = 0;
128             //QList<QListWidgetItem *> items = ui.networkList->findItems((*i).networkName, Qt::MatchExactly);
129             //if(items.count()) {
130             //  Q_ASSERT(items[0]->data(Qt::UserRole).value<NetworkId>() == id);
131             //  delete items[0];
132             //}
133             //i = networkInfos.erase(i);
134             ++i;
135         }
136         else {
137             if ((*i) != Client::network((*i).networkId)->networkInfo()) {
138                 toUpdate.append(*i);
139             }
140             ++i;
141         }
142     }
143     foreach(NetworkId id, Client::networkIds()) {
144         if (!networkInfos.contains(id)) toRemove.append(id);
145     }
146     SaveNetworksDlg dlg(toCreate, toUpdate, toRemove, this);
147     int ret = dlg.exec();
148     if (ret == QDialog::Rejected) {
149         // canceled -> reload everything to be safe
150         load();
151     }
152     setChangedState(false);
153     setEnabled(true);
154 }
155
156
157 void NetworksSettingsPage::load()
158 {
159     reset();
160     foreach(NetworkId netid, Client::networkIds()) {
161         clientNetworkAdded(netid);
162     }
163     ui.networkList->setCurrentRow(0);
164     setChangedState(false);
165 }
166
167
168 void NetworksSettingsPage::reset()
169 {
170     currentId = 0;
171     ui.networkList->clear();
172     networkInfos.clear();
173 }
174
175
176 bool NetworksSettingsPage::aboutToSave()
177 {
178     if (currentId != 0) saveToNetworkInfo(networkInfos[currentId]);
179     QList<int> errors;
180     foreach(NetworkInfo info, networkInfos.values()) {
181         if (!info.serverList.count()) errors.append(1);
182     }
183     if (!errors.count()) return true;
184     QString error(tr("<b>The following problems need to be corrected before your changes can be applied:</b><ul>"));
185     if (errors.contains(1)) error += tr("<li>All networks need at least one server defined</li>");
186     error += tr("</ul>");
187     QMessageBox::warning(this, tr("Invalid Network Settings"), error);
188     return false;
189 }
190
191
192 void NetworksSettingsPage::widgetHasChanged()
193 {
194     if (_ignoreWidgetChanges) return;
195     bool changed = testHasChanged();
196     if (changed != hasChanged()) setChangedState(changed);
197 }
198
199
200 bool NetworksSettingsPage::testHasChanged()
201 {
202     if (currentId != 0) {
203         saveToNetworkInfo(networkInfos[currentId]);
204     }
205     if (Client::networkIds().count() != networkInfos.count()) return true;
206     foreach(NetworkId id, networkInfos.keys()) {
207         if (id < 0) return true;
208         if (Client::network(id)->networkInfo() != networkInfos[id]) return true;
209     }
210     return false;
211 }
212
213
214 void NetworksSettingsPage::setWidgetStates()
215 {
216     // network list
217     if (ui.networkList->selectedItems().count()) {
218         ui.detailsBox->setEnabled(true);
219         ui.renameNetwork->setEnabled(true);
220         ui.deleteNetwork->setEnabled(true);
221
222         /* button disabled for now
223         NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
224         const Network *net = id > 0 ? Client::network(id) : 0;
225         ui.connectNow->setEnabled(net);
226         //    && (Client::network(id)->connectionState() == Network::Initialized
227         //    || Client::network(id)->connectionState() == Network::Disconnected));
228         if(net) {
229           if(net->connectionState() == Network::Disconnected) {
230             ui.connectNow->setIcon(connectedIcon);
231             ui.connectNow->setText(tr("Connect"));
232           } else {
233             ui.connectNow->setIcon(disconnectedIcon);
234             ui.connectNow->setText(tr("Disconnect"));
235           }
236         } else {
237           ui.connectNow->setIcon(QIcon());
238           ui.connectNow->setText(tr("Apply first!"));
239         } */
240     }
241     else {
242         ui.renameNetwork->setEnabled(false);
243         ui.deleteNetwork->setEnabled(false);
244         //ui.connectNow->setEnabled(false);
245         ui.detailsBox->setEnabled(false);
246     }
247     // network details
248     if (ui.serverList->selectedItems().count()) {
249         ui.editServer->setEnabled(true);
250         ui.deleteServer->setEnabled(true);
251         ui.upServer->setEnabled(ui.serverList->currentRow() > 0);
252         ui.downServer->setEnabled(ui.serverList->currentRow() < ui.serverList->count() - 1);
253     }
254     else {
255         ui.editServer->setEnabled(false);
256         ui.deleteServer->setEnabled(false);
257         ui.upServer->setEnabled(false);
258         ui.downServer->setEnabled(false);
259     }
260 }
261
262
263 void NetworksSettingsPage::setItemState(NetworkId id, QListWidgetItem *item)
264 {
265     if (!item && !(item = networkItem(id))) return;
266     const Network *net = Client::network(id);
267     if (!net || net->isInitialized()) item->setFlags(item->flags() | Qt::ItemIsEnabled);
268     else item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
269     if (net && net->connectionState() == Network::Initialized) {
270         item->setIcon(connectedIcon);
271     }
272     else if (net && net->connectionState() != Network::Disconnected) {
273         item->setIcon(connectingIcon);
274     }
275     else {
276         item->setIcon(disconnectedIcon);
277     }
278     if (net) {
279         bool select = false;
280         // check if we already have another net of this name in the list, and replace it
281         QList<QListWidgetItem *> items = ui.networkList->findItems(net->networkName(), Qt::MatchExactly);
282         if (items.count()) {
283             foreach(QListWidgetItem *i, items) {
284                 NetworkId oldid = i->data(Qt::UserRole).value<NetworkId>();
285                 if (oldid > 0) continue;  // only locally created nets should be replaced
286                 if (oldid == currentId) {
287                     select = true;
288                     currentId = 0;
289                     ui.networkList->clearSelection();
290                 }
291                 int row = ui.networkList->row(i);
292                 if (row >= 0) {
293                     QListWidgetItem *olditem = ui.networkList->takeItem(row);
294                     Q_ASSERT(olditem);
295                     delete olditem;
296                 }
297                 networkInfos.remove(oldid);
298                 break;
299             }
300         }
301         item->setText(net->networkName());
302         if (select) item->setSelected(true);
303     }
304 }
305
306
307 void NetworksSettingsPage::coreConnectionStateChanged(bool state)
308 {
309     this->setEnabled(state);
310     if (state) {
311         load();
312     }
313     else {
314         // reset
315         //currentId = 0;
316     }
317 }
318
319
320 void NetworksSettingsPage::clientIdentityAdded(IdentityId id)
321 {
322     const Identity *identity = Client::identity(id);
323     connect(identity, SIGNAL(updatedRemotely()), this, SLOT(clientIdentityUpdated()));
324
325     QString name = identity->identityName();
326     for (int j = 0; j < ui.identityList->count(); j++) {
327         if ((j > 0 || ui.identityList->itemData(0).toInt() != 1) && name.localeAwareCompare(ui.identityList->itemText(j)) < 0) {
328             ui.identityList->insertItem(j, name, id.toInt());
329             widgetHasChanged();
330             return;
331         }
332     }
333     // append
334     ui.identityList->insertItem(ui.identityList->count(), name, id.toInt());
335     widgetHasChanged();
336 }
337
338
339 void NetworksSettingsPage::clientIdentityUpdated()
340 {
341     const Identity *identity = qobject_cast<const Identity *>(sender());
342     if (!identity) {
343         qWarning() << "NetworksSettingsPage: Invalid identity to update!";
344         return;
345     }
346     int row = ui.identityList->findData(identity->id().toInt());
347     if (row < 0) {
348         qWarning() << "NetworksSettingsPage: Invalid identity to update!";
349         return;
350     }
351     if (ui.identityList->itemText(row) != identity->identityName()) {
352         ui.identityList->setItemText(row, identity->identityName());
353     }
354 }
355
356
357 void NetworksSettingsPage::clientIdentityRemoved(IdentityId id)
358 {
359     IdentityId defaultId = defaultIdentity();
360     if (currentId != 0) saveToNetworkInfo(networkInfos[currentId]);
361     foreach(NetworkInfo info, networkInfos.values()) {
362         if (info.identity == id) {
363             if (info.networkId == currentId)
364                 ui.identityList->setCurrentIndex(0);
365             info.identity = defaultId;
366             networkInfos[info.networkId] = info;
367             if (info.networkId > 0) Client::updateNetwork(info);
368         }
369     }
370     ui.identityList->removeItem(ui.identityList->findData(id.toInt()));
371     widgetHasChanged();
372 }
373
374
375 QListWidgetItem *NetworksSettingsPage::networkItem(NetworkId id) const
376 {
377     for (int i = 0; i < ui.networkList->count(); i++) {
378         QListWidgetItem *item = ui.networkList->item(i);
379         if (item->data(Qt::UserRole).value<NetworkId>() == id) return item;
380     }
381     return 0;
382 }
383
384
385 void NetworksSettingsPage::clientNetworkAdded(NetworkId id)
386 {
387     insertNetwork(id);
388     //connect(Client::network(id), SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
389     connect(Client::network(id), SIGNAL(configChanged()), this, SLOT(clientNetworkUpdated()));
390
391     connect(Client::network(id), SIGNAL(connectionStateSet(Network::ConnectionState)), this, SLOT(networkConnectionStateChanged(Network::ConnectionState)));
392     connect(Client::network(id), SIGNAL(connectionError(const QString &)), this, SLOT(networkConnectionError(const QString &)));
393 }
394
395
396 void NetworksSettingsPage::clientNetworkUpdated()
397 {
398     const Network *net = qobject_cast<const Network *>(sender());
399     if (!net) {
400         qWarning() << "Update request for unknown network received!";
401         return;
402     }
403     networkInfos[net->networkId()] = net->networkInfo();
404     setItemState(net->networkId());
405     if (net->networkId() == currentId) displayNetwork(net->networkId());
406     setWidgetStates();
407     widgetHasChanged();
408 }
409
410
411 void NetworksSettingsPage::clientNetworkRemoved(NetworkId id)
412 {
413     if (!networkInfos.contains(id)) return;
414     if (id == currentId) displayNetwork(0);
415     NetworkInfo info = networkInfos.take(id);
416     QList<QListWidgetItem *> items = ui.networkList->findItems(info.networkName, Qt::MatchExactly);
417     foreach(QListWidgetItem *item, items) {
418         if (item->data(Qt::UserRole).value<NetworkId>() == id)
419             delete ui.networkList->takeItem(ui.networkList->row(item));
420     }
421     setWidgetStates();
422     widgetHasChanged();
423 }
424
425
426 void NetworksSettingsPage::networkConnectionStateChanged(Network::ConnectionState state)
427 {
428     Q_UNUSED(state);
429     const Network *net = qobject_cast<const Network *>(sender());
430     if (!net) return;
431     /*
432     if(net->networkId() == currentId) {
433       ui.connectNow->setEnabled(state == Network::Initialized || state == Network::Disconnected);
434     }
435     */
436     setItemState(net->networkId());
437     setWidgetStates();
438 }
439
440
441 void NetworksSettingsPage::networkConnectionError(const QString &)
442 {
443 }
444
445
446 QListWidgetItem *NetworksSettingsPage::insertNetwork(NetworkId id)
447 {
448     NetworkInfo info = Client::network(id)->networkInfo();
449     networkInfos[id] = info;
450     return insertNetwork(info);
451 }
452
453
454 QListWidgetItem *NetworksSettingsPage::insertNetwork(const NetworkInfo &info)
455 {
456     QListWidgetItem *item = 0;
457     QList<QListWidgetItem *> items = ui.networkList->findItems(info.networkName, Qt::MatchExactly);
458     if (!items.count()) item = new QListWidgetItem(disconnectedIcon, info.networkName, ui.networkList);
459     else {
460         // we overwrite an existing net if it a) has the same name and b) has a negative ID meaning we created it locally before
461         // -> then we can be sure that this is the core-side replacement for the net we created
462         foreach(QListWidgetItem *i, items) {
463             NetworkId id = i->data(Qt::UserRole).value<NetworkId>();
464             if (id < 0) { item = i; break; }
465         }
466         if (!item) item = new QListWidgetItem(disconnectedIcon, info.networkName, ui.networkList);
467     }
468     item->setData(Qt::UserRole, QVariant::fromValue<NetworkId>(info.networkId));
469     setItemState(info.networkId, item);
470     widgetHasChanged();
471     return item;
472 }
473
474
475 void NetworksSettingsPage::displayNetwork(NetworkId id)
476 {
477     _ignoreWidgetChanges = true;
478     if (id != 0) {
479         NetworkInfo info = networkInfos[id];
480
481 #ifdef HAVE_SSL
482         // this is only needed when the core supports SASL EXTERNAL
483         if (Client::coreFeatures() & Quassel::SaslExternal) {
484             if (_cid) {
485                 disconnect(_cid, SIGNAL(sslSettingsUpdated()), this, SLOT(sslUpdated()));
486                 delete _cid;
487             }
488             _cid = new CertIdentity(*Client::identity(info.identity), this);
489             _cid->enableEditSsl(true);
490             connect(_cid, SIGNAL(sslSettingsUpdated()), this, SLOT(sslUpdated()));
491         }
492 #endif
493
494         ui.identityList->setCurrentIndex(ui.identityList->findData(info.identity.toInt()));
495         ui.serverList->clear();
496         foreach(Network::Server server, info.serverList) {
497             QListWidgetItem *item = new QListWidgetItem(QString("%1:%2").arg(server.host).arg(server.port));
498             if (server.useSsl)
499                 item->setIcon(SmallIcon("document-encrypt"));
500             ui.serverList->addItem(item);
501         }
502         //setItemState(id);
503         //ui.randomServer->setChecked(info.useRandomServer);
504         ui.performEdit->setPlainText(info.perform.join("\n"));
505         ui.autoIdentify->setChecked(info.useAutoIdentify);
506         ui.autoIdentifyService->setText(info.autoIdentifyService);
507         ui.autoIdentifyPassword->setText(info.autoIdentifyPassword);
508         ui.sasl->setChecked(info.useSasl);
509         ui.saslAccount->setText(info.saslAccount);
510         ui.saslPassword->setText(info.saslPassword);
511         if (info.codecForEncoding.isEmpty()) {
512             ui.sendEncoding->setCurrentIndex(ui.sendEncoding->findText(Network::defaultCodecForEncoding()));
513             ui.recvEncoding->setCurrentIndex(ui.recvEncoding->findText(Network::defaultCodecForDecoding()));
514             ui.serverEncoding->setCurrentIndex(ui.serverEncoding->findText(Network::defaultCodecForServer()));
515             ui.useCustomEncodings->setChecked(false);
516         }
517         else {
518             ui.sendEncoding->setCurrentIndex(ui.sendEncoding->findText(info.codecForEncoding));
519             ui.recvEncoding->setCurrentIndex(ui.recvEncoding->findText(info.codecForDecoding));
520             ui.serverEncoding->setCurrentIndex(ui.serverEncoding->findText(info.codecForServer));
521             ui.useCustomEncodings->setChecked(true);
522         }
523         ui.autoReconnect->setChecked(info.useAutoReconnect);
524         ui.reconnectInterval->setValue(info.autoReconnectInterval);
525         ui.reconnectRetries->setValue(info.autoReconnectRetries);
526         ui.unlimitedRetries->setChecked(info.unlimitedReconnectRetries);
527         ui.rejoinOnReconnect->setChecked(info.rejoinChannels);
528     }
529     else {
530         // just clear widgets
531 #ifdef HAVE_SSL
532         if (_cid) {
533             disconnect(_cid, SIGNAL(sslSettingsUpdated()), this, SLOT(sslUpdated()));
534             delete _cid;
535         }
536 #endif
537         ui.identityList->setCurrentIndex(-1);
538         ui.serverList->clear();
539         ui.performEdit->clear();
540         ui.autoIdentifyService->clear();
541         ui.autoIdentifyPassword->clear();
542         ui.saslAccount->clear();
543         ui.saslPassword->clear();
544         setWidgetStates();
545     }
546     _ignoreWidgetChanges = false;
547     currentId = id;
548 }
549
550
551 void NetworksSettingsPage::saveToNetworkInfo(NetworkInfo &info)
552 {
553     info.identity = ui.identityList->itemData(ui.identityList->currentIndex()).toInt();
554     //info.useRandomServer = ui.randomServer->isChecked();
555     info.perform = ui.performEdit->toPlainText().split("\n");
556     info.useAutoIdentify = ui.autoIdentify->isChecked();
557     info.autoIdentifyService = ui.autoIdentifyService->text();
558     info.autoIdentifyPassword = ui.autoIdentifyPassword->text();
559     info.useSasl = ui.sasl->isChecked();
560     info.saslAccount = ui.saslAccount->text();
561     info.saslPassword = ui.saslPassword->text();
562     if (!ui.useCustomEncodings->isChecked()) {
563         info.codecForEncoding.clear();
564         info.codecForDecoding.clear();
565         info.codecForServer.clear();
566     }
567     else {
568         info.codecForEncoding = ui.sendEncoding->currentText().toLatin1();
569         info.codecForDecoding = ui.recvEncoding->currentText().toLatin1();
570         info.codecForServer = ui.serverEncoding->currentText().toLatin1();
571     }
572     info.useAutoReconnect = ui.autoReconnect->isChecked();
573     info.autoReconnectInterval = ui.reconnectInterval->value();
574     info.autoReconnectRetries = ui.reconnectRetries->value();
575     info.unlimitedReconnectRetries = ui.unlimitedRetries->isChecked();
576     info.rejoinChannels = ui.rejoinOnReconnect->isChecked();
577 }
578
579
580 #ifdef HAVE_SSL
581 void NetworksSettingsPage::sslUpdated()
582 {
583     if (_cid && !_cid->sslKey().isNull()) {
584         ui.saslAccount->setDisabled(true);
585         ui.saslAccountLabel->setDisabled(true);
586         ui.saslPassword->setDisabled(true);
587         ui.saslPasswordLabel->setDisabled(true);
588         ui.saslExtInfo->setHidden(false);
589     } else {
590         ui.saslAccount->setDisabled(false);
591         ui.saslAccountLabel->setDisabled(false);
592         ui.saslPassword->setDisabled(false);
593         ui.saslPasswordLabel->setDisabled(false);
594         ui.saslExtInfo->setHidden(true);
595     }
596 }
597 #endif
598
599
600 /*** Network list ***/
601
602 void NetworksSettingsPage::on_networkList_itemSelectionChanged()
603 {
604     if (currentId != 0) {
605         saveToNetworkInfo(networkInfos[currentId]);
606     }
607     if (ui.networkList->selectedItems().count()) {
608         NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
609         currentId = id;
610         displayNetwork(id);
611         ui.serverList->setCurrentRow(0);
612     }
613     else {
614         currentId = 0;
615     }
616     setWidgetStates();
617 }
618
619
620 void NetworksSettingsPage::on_addNetwork_clicked()
621 {
622     QStringList existing;
623     for (int i = 0; i < ui.networkList->count(); i++) existing << ui.networkList->item(i)->text();
624     NetworkAddDlg dlg(existing, this);
625     if (dlg.exec() == QDialog::Accepted) {
626         NetworkInfo info = dlg.networkInfo();
627         if (info.networkName.isEmpty())
628             return;  // sanity check
629
630         NetworkId id;
631         for (id = 1; id <= networkInfos.count(); id++) {
632             widgetHasChanged();
633             if (!networkInfos.keys().contains(-id.toInt())) break;
634         }
635         id = -id.toInt();
636         info.networkId = id;
637         info.identity = defaultIdentity();
638         networkInfos[id] = info;
639         QListWidgetItem *item = insertNetwork(info);
640         ui.networkList->setCurrentItem(item);
641         setWidgetStates();
642     }
643 }
644
645
646 void NetworksSettingsPage::on_deleteNetwork_clicked()
647 {
648     if (ui.networkList->selectedItems().count()) {
649         NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
650         int ret = QMessageBox::question(this, tr("Delete Network?"),
651             tr("Do you really want to delete the network \"%1\" and all related settings, including the backlog?").arg(networkInfos[netid].networkName),
652             QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
653         if (ret == QMessageBox::Yes) {
654             currentId = 0;
655             networkInfos.remove(netid);
656             delete ui.networkList->takeItem(ui.networkList->row(ui.networkList->selectedItems()[0]));
657             ui.networkList->setCurrentRow(qMin(ui.networkList->currentRow()+1, ui.networkList->count()-1));
658             setWidgetStates();
659             widgetHasChanged();
660         }
661     }
662 }
663
664
665 void NetworksSettingsPage::on_renameNetwork_clicked()
666 {
667     if (!ui.networkList->selectedItems().count()) return;
668     QString old = ui.networkList->selectedItems()[0]->text();
669     QStringList existing;
670     for (int i = 0; i < ui.networkList->count(); i++) existing << ui.networkList->item(i)->text();
671     NetworkEditDlg dlg(old, existing, this);
672     if (dlg.exec() == QDialog::Accepted) {
673         ui.networkList->selectedItems()[0]->setText(dlg.networkName());
674         NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
675         networkInfos[netid].networkName = dlg.networkName();
676         widgetHasChanged();
677     }
678 }
679
680
681 /*
682 void NetworksSettingsPage::on_connectNow_clicked() {
683   if(!ui.networkList->selectedItems().count()) return;
684   NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
685   const Network *net = Client::network(id);
686   if(!net) return;
687   if(net->connectionState() == Network::Disconnected) net->requestConnect();
688   else net->requestDisconnect();
689 }
690 */
691
692 /*** Server list ***/
693
694 void NetworksSettingsPage::on_serverList_itemSelectionChanged()
695 {
696     setWidgetStates();
697 }
698
699
700 void NetworksSettingsPage::on_addServer_clicked()
701 {
702     if (currentId == 0) return;
703     ServerEditDlg dlg(Network::Server(), this);
704     if (dlg.exec() == QDialog::Accepted) {
705         networkInfos[currentId].serverList.append(dlg.serverData());
706         displayNetwork(currentId);
707         ui.serverList->setCurrentRow(ui.serverList->count()-1);
708         widgetHasChanged();
709     }
710 }
711
712
713 void NetworksSettingsPage::on_editServer_clicked()
714 {
715     if (currentId == 0) return;
716     int cur = ui.serverList->currentRow();
717     ServerEditDlg dlg(networkInfos[currentId].serverList[cur], this);
718     if (dlg.exec() == QDialog::Accepted) {
719         networkInfos[currentId].serverList[cur] = dlg.serverData();
720         displayNetwork(currentId);
721         ui.serverList->setCurrentRow(cur);
722         widgetHasChanged();
723     }
724 }
725
726
727 void NetworksSettingsPage::on_deleteServer_clicked()
728 {
729     if (currentId == 0) return;
730     int cur = ui.serverList->currentRow();
731     networkInfos[currentId].serverList.removeAt(cur);
732     displayNetwork(currentId);
733     ui.serverList->setCurrentRow(qMin(cur, ui.serverList->count()-1));
734     widgetHasChanged();
735 }
736
737
738 void NetworksSettingsPage::on_upServer_clicked()
739 {
740     int cur = ui.serverList->currentRow();
741     Network::Server server = networkInfos[currentId].serverList.takeAt(cur);
742     networkInfos[currentId].serverList.insert(cur-1, server);
743     displayNetwork(currentId);
744     ui.serverList->setCurrentRow(cur-1);
745     widgetHasChanged();
746 }
747
748
749 void NetworksSettingsPage::on_downServer_clicked()
750 {
751     int cur = ui.serverList->currentRow();
752     Network::Server server = networkInfos[currentId].serverList.takeAt(cur);
753     networkInfos[currentId].serverList.insert(cur+1, server);
754     displayNetwork(currentId);
755     ui.serverList->setCurrentRow(cur+1);
756     widgetHasChanged();
757 }
758
759
760 void NetworksSettingsPage::on_editIdentities_clicked()
761 {
762     SettingsPageDlg dlg(new IdentitiesSettingsPage(this), this);
763     dlg.exec();
764 }
765
766
767 IdentityId NetworksSettingsPage::defaultIdentity() const
768 {
769     IdentityId defaultId = 0;
770     QList<IdentityId> ids = Client::identityIds();
771     foreach(IdentityId id, ids) {
772         if (defaultId == 0 || id < defaultId)
773             defaultId = id;
774     }
775     return defaultId;
776 }
777
778
779 /**************************************************************************
780 * NetworkAddDlg
781 *************************************************************************/
782
783 NetworkAddDlg::NetworkAddDlg(const QStringList &exist, QWidget *parent) : QDialog(parent), existing(exist)
784 {
785     ui.setupUi(this);
786     ui.useSSL->setIcon(SmallIcon("document-encrypt"));
787
788     // read preset networks
789     QStringList networks = Network::presetNetworks();
790     foreach(QString s, existing)
791     networks.removeAll(s);
792     if (networks.count())
793         ui.presetList->addItems(networks);
794     else {
795         ui.useManual->setChecked(true);
796         ui.usePreset->setEnabled(false);
797     }
798     connect(ui.networkName, SIGNAL(textChanged(const QString &)), SLOT(setButtonStates()));
799     connect(ui.serverAddress, SIGNAL(textChanged(const QString &)), SLOT(setButtonStates()));
800     setButtonStates();
801 }
802
803
804 NetworkInfo NetworkAddDlg::networkInfo() const
805 {
806     if (ui.useManual->isChecked()) {
807         NetworkInfo info;
808         info.networkName = ui.networkName->text().trimmed();
809         info.serverList << Network::Server(ui.serverAddress->text().trimmed(), ui.port->value(), ui.serverPassword->text(), ui.useSSL->isChecked());
810         return info;
811     }
812     else
813         return Network::networkInfoFromPreset(ui.presetList->currentText());
814 }
815
816
817 void NetworkAddDlg::setButtonStates()
818 {
819     bool ok = false;
820     if (ui.usePreset->isChecked() && ui.presetList->count())
821         ok = true;
822     else if (ui.useManual->isChecked()) {
823         ok = !ui.networkName->text().trimmed().isEmpty() && !existing.contains(ui.networkName->text().trimmed())
824              && !ui.serverAddress->text().isEmpty();
825     }
826     ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(ok);
827 }
828
829
830 /**************************************************************************
831  * NetworkEditDlg
832  *************************************************************************/
833
834 NetworkEditDlg::NetworkEditDlg(const QString &old, const QStringList &exist, QWidget *parent) : QDialog(parent), existing(exist)
835 {
836     ui.setupUi(this);
837
838     if (old.isEmpty()) {
839         // new network
840         setWindowTitle(tr("Add Network"));
841         on_networkEdit_textChanged(""); // disable ok button
842     }
843     else ui.networkEdit->setText(old);
844 }
845
846
847 QString NetworkEditDlg::networkName() const
848 {
849     return ui.networkEdit->text().trimmed();
850 }
851
852
853 void NetworkEditDlg::on_networkEdit_textChanged(const QString &text)
854 {
855     ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(text.isEmpty() || existing.contains(text.trimmed()));
856 }
857
858
859 /**************************************************************************
860  * ServerEditDlg
861  *************************************************************************/
862 ServerEditDlg::ServerEditDlg(const Network::Server &server, QWidget *parent) : QDialog(parent)
863 {
864     ui.setupUi(this);
865     ui.useSSL->setIcon(SmallIcon("document-encrypt"));
866     ui.host->setText(server.host);
867     ui.port->setValue(server.port);
868     ui.password->setText(server.password);
869     ui.useSSL->setChecked(server.useSsl);
870     ui.sslVersion->setCurrentIndex(server.sslVersion);
871     ui.useProxy->setChecked(server.useProxy);
872     ui.proxyType->setCurrentIndex(server.proxyType == QNetworkProxy::Socks5Proxy ? 0 : 1);
873     ui.proxyHost->setText(server.proxyHost);
874     ui.proxyPort->setValue(server.proxyPort);
875     ui.proxyUsername->setText(server.proxyUser);
876     ui.proxyPassword->setText(server.proxyPass);
877     on_host_textChanged();
878 }
879
880
881 Network::Server ServerEditDlg::serverData() const
882 {
883     Network::Server server(ui.host->text().trimmed(), ui.port->value(), ui.password->text(), ui.useSSL->isChecked());
884     server.sslVersion = ui.sslVersion->currentIndex();
885     server.useProxy = ui.useProxy->isChecked();
886     server.proxyType = ui.proxyType->currentIndex() == 0 ? QNetworkProxy::Socks5Proxy : QNetworkProxy::HttpProxy;
887     server.proxyHost = ui.proxyHost->text();
888     server.proxyPort = ui.proxyPort->value();
889     server.proxyUser = ui.proxyUsername->text();
890     server.proxyPass = ui.proxyPassword->text();
891     return server;
892 }
893
894
895 void ServerEditDlg::on_host_textChanged()
896 {
897     ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(ui.host->text().trimmed().isEmpty());
898 }
899
900
901 /**************************************************************************
902  * SaveNetworksDlg
903  *************************************************************************/
904
905 SaveNetworksDlg::SaveNetworksDlg(const QList<NetworkInfo> &toCreate, const QList<NetworkInfo> &toUpdate, const QList<NetworkId> &toRemove, QWidget *parent) : QDialog(parent)
906 {
907     ui.setupUi(this);
908
909     numevents = toCreate.count() + toUpdate.count() + toRemove.count();
910     rcvevents = 0;
911     if (numevents) {
912         ui.progressBar->setMaximum(numevents);
913         ui.progressBar->setValue(0);
914
915         connect(Client::instance(), SIGNAL(networkCreated(NetworkId)), this, SLOT(clientEvent()));
916         connect(Client::instance(), SIGNAL(networkRemoved(NetworkId)), this, SLOT(clientEvent()));
917
918         foreach(NetworkId id, toRemove) {
919             Client::removeNetwork(id);
920         }
921         foreach(NetworkInfo info, toCreate) {
922             Client::createNetwork(info);
923         }
924         foreach(NetworkInfo info, toUpdate) {
925             const Network *net = Client::network(info.networkId);
926             if (!net) {
927                 qWarning() << "Invalid client network!";
928                 numevents--;
929                 continue;
930             }
931             // FIXME this only checks for one changed item rather than all!
932             connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientEvent()));
933             Client::updateNetwork(info);
934         }
935     }
936     else {
937         qWarning() << "Sync dialog called without stuff to change!";
938         accept();
939     }
940 }
941
942
943 void SaveNetworksDlg::clientEvent()
944 {
945     ui.progressBar->setValue(++rcvevents);
946     if (rcvevents >= numevents) accept();
947 }