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