Adding some debug output for finding out why this crashes sometimes...
[quassel.git] / src / qtui / settingspages / networkssettingspage.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel IRC Team                         *
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  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
19  ***************************************************************************/
20
21 #include <QHeaderView>
22 #include <QMessageBox>
23 #include <QTextCodec>
24
25 #include "networkssettingspage.h"
26
27 #include "client.h"
28 #include "global.h"
29 #include "identity.h"
30 #include "network.h"
31
32
33 NetworksSettingsPage::NetworksSettingsPage(QWidget *parent) : SettingsPage(tr("General"), tr("Networks"), parent) {
34   ui.setupUi(this);
35
36   connectedIcon = QIcon(":/22x22/actions/network-connect");
37   connectingIcon = QIcon(":/22x22/actions/gear");
38   disconnectedIcon = QIcon(":/22x22/actions/network-disconnect");
39
40   foreach(int mib, QTextCodec::availableMibs()) {
41     QByteArray codec = QTextCodec::codecForMib(mib)->name();
42     ui.sendEncoding->addItem(codec);
43     ui.recvEncoding->addItem(codec);
44   }
45   ui.sendEncoding->model()->sort(0);
46   ui.recvEncoding->model()->sort(0);
47   currentId = 0;
48   setEnabled(Client::isConnected());  // need a core connection!
49   setWidgetStates();
50   connect(Client::instance(), SIGNAL(coreConnectionStateChanged(bool)), this, SLOT(coreConnectionStateChanged(bool)));
51   connect(Client::instance(), SIGNAL(networkCreated(NetworkId)), this, SLOT(clientNetworkAdded(NetworkId)));
52   connect(Client::instance(), SIGNAL(networkRemoved(NetworkId)), this, SLOT(clientNetworkRemoved(NetworkId)));
53   connect(Client::instance(), SIGNAL(identityCreated(IdentityId)), this, SLOT(clientIdentityAdded(IdentityId)));
54   connect(Client::instance(), SIGNAL(identityRemoved(IdentityId)), this, SLOT(clientIdentityRemoved(IdentityId)));
55
56   connect(ui.identityList, SIGNAL(currentIndexChanged(int)), this, SLOT(widgetHasChanged()));
57   connect(ui.randomServer, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
58   connect(ui.performEdit, SIGNAL(textChanged()), this, SLOT(widgetHasChanged()));
59   connect(ui.autoIdentify, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
60   connect(ui.autoIdentifyService, SIGNAL(textEdited(const QString &)), this, SLOT(widgetHasChanged()));
61   connect(ui.autoIdentifyPassword, SIGNAL(textEdited(const QString &)), this, SLOT(widgetHasChanged()));
62   connect(ui.useDefaultEncodings, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
63   connect(ui.sendEncoding, SIGNAL(currentIndexChanged(int)), this, SLOT(widgetHasChanged()));
64   connect(ui.recvEncoding, SIGNAL(currentIndexChanged(int)), this, SLOT(widgetHasChanged()));
65   connect(ui.autoReconnect, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
66   connect(ui.reconnectInterval, SIGNAL(valueChanged(int)), this, SLOT(widgetHasChanged()));
67   connect(ui.reconnectRetries, SIGNAL(valueChanged(int)), this, SLOT(widgetHasChanged()));
68   connect(ui.unlimitedRetries, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
69   connect(ui.rejoinOnReconnect, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
70   //connect(ui., SIGNAL(), this, SLOT(widgetHasChanged()));
71   //connect(ui., SIGNAL(), this, SLOT(widgetHasChanged()));
72
73   foreach(IdentityId id, Client::identityIds()) {
74     clientIdentityAdded(id);
75   }
76 }
77
78 void NetworksSettingsPage::save() {
79   setEnabled(false);
80   if(currentId != 0) saveToNetworkInfo(networkInfos[currentId]);
81
82   QList<NetworkInfo> toCreate, toUpdate;
83   QList<NetworkId> toRemove;
84   QHash<NetworkId, NetworkInfo>::iterator i = networkInfos.begin();
85   while(i != networkInfos.end()) {
86     NetworkId id = (*i).networkId;
87     if(id < 0) {
88       toCreate.append(*i);
89       //if(id == currentId) currentId = 0;
90       //QList<QListWidgetItem *> items = ui.networkList->findItems((*i).networkName, Qt::MatchExactly);
91       //if(items.count()) {
92       //  Q_ASSERT(items[0]->data(Qt::UserRole).value<NetworkId>() == id);
93       //  delete items[0];
94       //}
95       //i = networkInfos.erase(i);
96       ++i;
97     } else {
98       if((*i) != Client::network((*i).networkId)->networkInfo()) {
99         toUpdate.append(*i);
100       }
101       ++i;
102     }
103   }
104   foreach(NetworkId id, Client::networkIds()) {
105     if(!networkInfos.contains(id)) toRemove.append(id);
106   }
107   SaveNetworksDlg dlg(toCreate, toUpdate, toRemove, this);
108   int ret = dlg.exec();
109   if(ret == QDialog::Rejected) {
110     // canceled -> reload everything to be safe
111     load();
112   }
113   setChangedState(false);
114   setEnabled(true);
115 }
116
117 void NetworksSettingsPage::load() {
118   reset();
119   foreach(NetworkId netid, Client::networkIds()) {
120     clientNetworkAdded(netid);
121   }
122   ui.networkList->setCurrentRow(0);
123   setChangedState(false);
124 }
125
126 void NetworksSettingsPage::reset() {
127   currentId = 0;
128   ui.networkList->clear();
129   networkInfos.clear();
130
131 }
132
133 bool NetworksSettingsPage::aboutToSave() {
134   if(currentId != 0) saveToNetworkInfo(networkInfos[currentId]);
135   QList<int> errors;
136   foreach(NetworkInfo info, networkInfos.values()) {
137     if(!info.serverList.count()) errors.append(1);
138   }
139   if(!errors.count()) return true;
140   QString error(tr("<b>The following problems need to be corrected before your changes can be applied:</b><ul>"));
141   if(errors.contains(1)) error += tr("<li>All networks need at least one server defined</li>");
142   error += tr("</ul>");
143   QMessageBox::warning(this, tr("Invalid Network Settings"), error);
144   return false;
145 }
146
147 void NetworksSettingsPage::widgetHasChanged() {
148   bool changed = testHasChanged();
149   if(changed != hasChanged()) setChangedState(changed);
150 }
151
152 bool NetworksSettingsPage::testHasChanged() {
153   if(currentId != 0) {
154     saveToNetworkInfo(networkInfos[currentId]);
155   }
156   if(Client::networkIds().count() != networkInfos.count()) return true;
157   foreach(NetworkId id, networkInfos.keys()) {
158     if(id < 0) return true;
159     if(Client::network(id)->networkInfo() != networkInfos[id]) return true;
160   }
161   return false;
162 }
163
164 void NetworksSettingsPage::setWidgetStates() {
165   // network list
166   if(ui.networkList->selectedItems().count()) {
167     NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
168     ui.detailsBox->setEnabled(true);
169     ui.renameNetwork->setEnabled(true);
170     ui.deleteNetwork->setEnabled(true);
171     ui.connectNow->setEnabled(id > 0
172         && (Client::network(id)->connectionState() == Network::Initialized
173         || Client::network(id)->connectionState() == Network::Disconnected));
174     if(Client::network(id) && Client::network(id)->isConnected()) {
175       ui.connectNow->setIcon(disconnectedIcon);
176       ui.connectNow->setText(tr("Disconnect"));
177     } else {
178       ui.connectNow->setIcon(connectedIcon);
179       ui.connectNow->setText(tr("Connect"));
180     }
181   } else {
182     ui.renameNetwork->setEnabled(false);
183     ui.deleteNetwork->setEnabled(false);
184     ui.connectNow->setEnabled(false);
185     ui.detailsBox->setEnabled(false);
186   }
187   // network details
188   if(ui.serverList->selectedItems().count()) {
189     ui.editServer->setEnabled(true);
190     ui.deleteServer->setEnabled(true);
191     ui.upServer->setEnabled(ui.serverList->currentRow() > 0);
192     ui.downServer->setEnabled(ui.serverList->currentRow() < ui.serverList->count() - 1);
193   } else {
194     ui.editServer->setEnabled(false);
195     ui.deleteServer->setEnabled(false);
196     ui.upServer->setEnabled(false);
197     ui.downServer->setEnabled(false);
198   }
199 }
200
201 void NetworksSettingsPage::setItemState(NetworkId id, QListWidgetItem *item) {
202   if(!item && !(item = networkItem(id))) return;
203   const Network *net = Client::network(id);
204   if(!net || net->isInitialized()) item->setFlags(item->flags() | Qt::ItemIsEnabled);
205   else item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
206   if(net && net->connectionState() == Network::Initialized) {
207     item->setIcon(connectedIcon);
208   } else if(net && net->connectionState() != Network::Disconnected) {
209     item->setIcon(connectingIcon);
210   } else {
211     item->setIcon(disconnectedIcon);
212   }
213   if(net) {
214     bool select = false;
215     // check if we already have another net of this name in the list, and replace it
216     QList<QListWidgetItem *> items = ui.networkList->findItems(net->networkName(), Qt::MatchExactly);
217     if(items.count()) {
218       foreach(QListWidgetItem *i, items) {
219         NetworkId oldid = i->data(Qt::UserRole).value<NetworkId>();
220         if(oldid > 0) continue;  // only locally created nets should be replaced
221         if(oldid == currentId) select = true;
222         int row = ui.networkList->row(i);
223         if(row >= 0) {
224           qDebug() << "ABOUT TO REMOVE: id=" << oldid << "from row" << row;
225           QListWidgetItem *olditem = ui.networkList->takeItem(row);
226           qDebug() << "Successfully removed item from list.";
227           if(!olditem) {
228             qWarning() << "NetworksSettingsPage::setItemState(): Why the heck don't we have an itempointer here?";
229             Q_ASSERT(olditem);  // abort non-gracefully, I need to figure out what's causing this
230           }
231           else delete olditem;
232         }
233         networkInfos.remove(oldid);
234         break;
235       }
236     }
237     item->setText(net->networkName());
238     if(select) item->setSelected(true);
239   }
240 }
241
242 void NetworksSettingsPage::coreConnectionStateChanged(bool state) {
243   this->setEnabled(state);
244   if(state) {
245     load();
246   } else {
247     // reset
248     //currentId = 0;
249   }
250 }
251
252 void NetworksSettingsPage::clientIdentityAdded(IdentityId id) {
253   const Identity * identity = Client::identity(id);
254   connect(identity, SIGNAL(updatedRemotely()), this, SLOT(clientIdentityUpdated()));
255
256   if(id == 1) {
257     // default identity is always the first one!
258     ui.identityList->insertItem(0, identity->identityName(), id.toInt());
259   } else {
260     QString name = identity->identityName();
261     for(int j = 0; j < ui.identityList->count(); j++) {
262       if((j>0 || ui.identityList->itemData(0).toInt() != 1) && name.localeAwareCompare(ui.identityList->itemText(j)) < 0) {
263         ui.identityList->insertItem(j, name, id.toInt());
264         widgetHasChanged();
265         return;
266       }
267     }
268     // append
269     ui.identityList->insertItem(ui.identityList->count(), name, id.toInt());
270     widgetHasChanged();
271   }
272 }
273
274 void NetworksSettingsPage::clientIdentityUpdated() {
275   const Identity *identity = qobject_cast<const Identity *>(sender());
276   if(!identity) {
277     qWarning() << "NetworksSettingsPage: Invalid identity to update!";
278     return;
279   }
280   int row = ui.identityList->findData(identity->id().toInt());
281   if(row < 0) {
282     qWarning() << "NetworksSettingsPage: Invalid identity to update!";
283     return;
284   }
285   if(ui.identityList->itemText(row) != identity->identityName()) {
286     ui.identityList->setItemText(row, identity->identityName());
287   }
288 }
289
290 void NetworksSettingsPage::clientIdentityRemoved(IdentityId id) {
291   if(currentId != 0) saveToNetworkInfo(networkInfos[currentId]);
292   //ui.identityList->removeItem(ui.identityList->findData(id.toInt()));
293   foreach(NetworkInfo info, networkInfos.values()) {
294     //qDebug() << info.networkName << info.networkId << info.identity;
295     if(info.identity == id) {
296       if(info.networkId == currentId) ui.identityList->setCurrentIndex(0);
297       info.identity = 1; // set to default
298       networkInfos[info.networkId] = info;
299       if(info.networkId > 0) Client::updateNetwork(info);
300     }
301   }
302   ui.identityList->removeItem(ui.identityList->findData(id.toInt()));
303   widgetHasChanged();
304 }
305
306 QListWidgetItem *NetworksSettingsPage::networkItem(NetworkId id) const {
307   for(int i = 0; i < ui.networkList->count(); i++) { 
308     QListWidgetItem *item = ui.networkList->item(i);
309     if(item->data(Qt::UserRole).value<NetworkId>() == id) return item;
310   }
311   return 0;
312 }
313
314 void NetworksSettingsPage::clientNetworkAdded(NetworkId id) {
315   insertNetwork(id);
316   connect(Client::network(id), SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
317   connect(Client::network(id), SIGNAL(connectionStateSet(Network::ConnectionState)), this, SLOT(networkConnectionStateChanged(Network::ConnectionState)));
318   connect(Client::network(id), SIGNAL(connectionError(const QString &)), this, SLOT(networkConnectionError(const QString &)));
319 }
320
321 void NetworksSettingsPage::clientNetworkUpdated() {
322   const Network *net = qobject_cast<const Network *>(sender());
323   if(!net) {
324     qWarning() << "Update request for unknown network received!";
325     return;
326   }
327   networkInfos[net->networkId()] = net->networkInfo();
328   setItemState(net->networkId());
329   if(net->networkId() == currentId) displayNetwork(net->networkId());
330   setWidgetStates();
331   widgetHasChanged();
332 }
333
334 void NetworksSettingsPage::clientNetworkRemoved(NetworkId id) {
335   if(!networkInfos.contains(id)) return;
336   if(id == currentId) displayNetwork(0);
337   NetworkInfo info = networkInfos.take(id);
338   QList<QListWidgetItem *> items = ui.networkList->findItems(info.networkName, Qt::MatchExactly);
339   foreach(QListWidgetItem *item, items) {
340     if(item->data(Qt::UserRole).value<NetworkId>() == id)
341       delete ui.networkList->takeItem(ui.networkList->row(item));
342   }
343   setWidgetStates();
344   widgetHasChanged();
345 }
346
347 void NetworksSettingsPage::networkConnectionStateChanged(Network::ConnectionState state) {
348   const Network *net = qobject_cast<const Network *>(sender());
349   if(!net) return;
350   if(net->networkId() == currentId) {
351     ui.connectNow->setEnabled(state == Network::Initialized || state == Network::Disconnected);
352   }
353   setItemState(net->networkId());
354 }
355
356 void NetworksSettingsPage::networkConnectionError(const QString &) {
357
358 }
359
360 QListWidgetItem *NetworksSettingsPage::insertNetwork(NetworkId id) {
361   NetworkInfo info = Client::network(id)->networkInfo();
362   networkInfos[id] = info;
363   return insertNetwork(info);
364 }
365
366 QListWidgetItem *NetworksSettingsPage::insertNetwork(const NetworkInfo &info) {
367   QListWidgetItem *item = 0;
368   QList<QListWidgetItem *> items = ui.networkList->findItems(info.networkName, Qt::MatchExactly);
369   if(!items.count()) item = new QListWidgetItem(disconnectedIcon, info.networkName, ui.networkList);
370   else {
371     // we overwrite an existing net if it a) has the same name and b) has a negative ID meaning we created it locally before
372     // -> then we can be sure that this is the core-side replacement for the net we created
373     foreach(QListWidgetItem *i, items) {
374       NetworkId id = i->data(Qt::UserRole).value<NetworkId>();
375       if(id < 0) { item = i; break; }
376     }
377     if(!item) item = new QListWidgetItem(disconnectedIcon, info.networkName, ui.networkList);
378   }
379   item->setData(Qt::UserRole, QVariant::fromValue<NetworkId>(info.networkId));
380   setItemState(info.networkId, item);
381   widgetHasChanged();
382   return item;
383 }
384
385 void NetworksSettingsPage::displayNetwork(NetworkId id) {
386   if(id != 0) {
387     NetworkInfo info = networkInfos[id];
388     ui.identityList->setCurrentIndex(ui.identityList->findData(info.identity.toInt()));
389     ui.serverList->clear();
390     foreach(QVariant v, info.serverList) {
391       ui.serverList->addItem(QString("%1:%2").arg(v.toMap()["Host"].toString()).arg(v.toMap()["Port"].toUInt()));
392     }
393     setItemState(id);
394     ui.randomServer->setChecked(info.useRandomServer);
395     ui.performEdit->setPlainText(info.perform.join("\n"));
396     ui.autoIdentify->setChecked(info.useAutoIdentify);
397     ui.autoIdentifyService->setText(info.autoIdentifyService);
398     ui.autoIdentifyPassword->setText(info.autoIdentifyPassword);
399     if(info.codecForEncoding.isEmpty()) {
400       ui.sendEncoding->setCurrentIndex(ui.sendEncoding->findText(Network::defaultCodecForEncoding()));
401       ui.recvEncoding->setCurrentIndex(ui.recvEncoding->findText(Network::defaultCodecForDecoding()));
402       ui.useDefaultEncodings->setChecked(true);
403     } else {
404       ui.sendEncoding->setCurrentIndex(ui.sendEncoding->findText(info.codecForEncoding));
405       ui.recvEncoding->setCurrentIndex(ui.recvEncoding->findText(info.codecForDecoding));
406       ui.useDefaultEncodings->setChecked(false);
407     }
408     ui.autoReconnect->setChecked(info.useAutoReconnect);
409     ui.reconnectInterval->setValue(info.autoReconnectInterval);
410     ui.reconnectRetries->setValue(info.autoReconnectRetries);
411     ui.unlimitedRetries->setChecked(info.unlimitedReconnectRetries);
412     ui.rejoinOnReconnect->setChecked(info.rejoinChannels);
413   } else {
414     // just clear widgets
415     ui.identityList->setCurrentIndex(-1);
416     ui.serverList->clear();
417     ui.performEdit->clear();
418     setWidgetStates();
419   }
420   currentId = id;
421 }
422
423 void NetworksSettingsPage::saveToNetworkInfo(NetworkInfo &info) {
424   info.identity = ui.identityList->itemData(ui.identityList->currentIndex()).toInt();
425   info.useRandomServer = ui.randomServer->isChecked();
426   info.perform = ui.performEdit->toPlainText().split("\n");
427   info.useAutoIdentify = ui.autoIdentify->isChecked();
428   info.autoIdentifyService = ui.autoIdentifyService->text();
429   info.autoIdentifyPassword = ui.autoIdentifyPassword->text();
430   if(ui.useDefaultEncodings->isChecked()) {
431     info.codecForEncoding.clear();
432     info.codecForDecoding.clear();
433   } else {
434     info.codecForEncoding = ui.sendEncoding->currentText().toLatin1();
435     info.codecForDecoding = ui.recvEncoding->currentText().toLatin1();
436   }
437   info.useAutoReconnect = ui.autoReconnect->isChecked();
438   info.autoReconnectInterval = ui.reconnectInterval->value();
439   info.autoReconnectRetries = ui.reconnectRetries->value();
440   info.unlimitedReconnectRetries = ui.unlimitedRetries->isChecked();
441   info.rejoinChannels = ui.rejoinOnReconnect->isChecked();
442 }
443 /*** Network list ***/
444
445 void NetworksSettingsPage::on_networkList_itemSelectionChanged() {
446   if(currentId != 0) {
447     saveToNetworkInfo(networkInfos[currentId]);
448   }
449   if(ui.networkList->selectedItems().count()) {
450     NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
451     currentId = id;
452     displayNetwork(id);
453     ui.serverList->setCurrentRow(0);
454   } else {
455     currentId = 0;
456   }
457   setWidgetStates();
458 }
459
460 void NetworksSettingsPage::on_addNetwork_clicked() {
461   QStringList existing;
462   for(int i = 0; i < ui.networkList->count(); i++) existing << ui.networkList->item(i)->text();
463   NetworkEditDlg dlg(QString(), existing, this);
464   if(dlg.exec() == QDialog::Accepted) {
465     NetworkId id;
466     for(id = 1; id <= networkInfos.count(); id++) {
467       widgetHasChanged();
468       if(!networkInfos.keys().contains(-id.toInt())) break;
469     }
470     id = -id.toInt();
471     NetworkInfo info;
472     info.networkId = id;
473     info.networkName = dlg.networkName();
474     info.identity = 1;
475
476     // defaults
477     info.useRandomServer = false;
478     info.useAutoReconnect = true;
479     info.autoReconnectInterval = 60;
480     info.autoReconnectRetries = 20;
481     info.unlimitedReconnectRetries = false;
482     info.useAutoIdentify = false;
483     info.autoIdentifyService = "NickServ";
484     info.rejoinChannels = true;
485
486     networkInfos[id] = info;
487     QListWidgetItem *item = insertNetwork(info);
488     ui.networkList->setCurrentItem(item);
489     setWidgetStates();
490   }
491 }
492
493 void NetworksSettingsPage::on_deleteNetwork_clicked() {
494   if(ui.networkList->selectedItems().count()) {
495     NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
496     int ret = QMessageBox::question(this, tr("Delete Network?"),
497                                     tr("Do you really want to delete the network \"%1\" and all related settings, including the backlog?").arg(networkInfos[netid].networkName),
498                                     QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
499     if(ret == QMessageBox::Yes) {
500       currentId = 0;
501       networkInfos.remove(netid);
502       delete ui.networkList->takeItem(ui.networkList->row(ui.networkList->selectedItems()[0]));
503       ui.networkList->setCurrentRow(qMin(ui.networkList->currentRow()+1, ui.networkList->count()-1));
504       setWidgetStates();
505       widgetHasChanged();
506     }
507   }
508 }
509
510 void NetworksSettingsPage::on_renameNetwork_clicked() {
511   if(!ui.networkList->selectedItems().count()) return;
512   QString old = ui.networkList->selectedItems()[0]->text();
513   QStringList existing;
514   for(int i = 0; i < ui.networkList->count(); i++) existing << ui.networkList->item(i)->text();
515   NetworkEditDlg dlg(old, existing, this);
516   if(dlg.exec() == QDialog::Accepted) {
517     ui.networkList->selectedItems()[0]->setText(dlg.networkName());
518     NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
519     networkInfos[netid].networkName = dlg.networkName();
520     widgetHasChanged();
521   }
522 }
523
524 void NetworksSettingsPage::on_connectNow_clicked() {
525   if(!ui.networkList->selectedItems().count()) return;
526   NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
527   const Network *net = Client::network(id);
528   if(!net) return;
529   if(!net->isConnected()) net->requestConnect();
530   else net->requestDisconnect();
531 }
532
533 /*** Server list ***/
534
535 void NetworksSettingsPage::on_serverList_itemSelectionChanged() {
536   setWidgetStates();
537 }
538
539 void NetworksSettingsPage::on_addServer_clicked() {
540   if(currentId == 0) return;
541   ServerEditDlg dlg(QVariantMap(), this);
542   if(dlg.exec() == QDialog::Accepted) {
543     networkInfos[currentId].serverList.append(dlg.serverData());
544     displayNetwork(currentId);
545     ui.serverList->setCurrentRow(ui.serverList->count()-1);
546     widgetHasChanged();
547   }
548
549 }
550
551 void NetworksSettingsPage::on_editServer_clicked() {
552   if(currentId == 0) return;
553   int cur = ui.serverList->currentRow();
554   ServerEditDlg dlg(networkInfos[currentId].serverList[cur], this);
555   if(dlg.exec() == QDialog::Accepted) {
556     networkInfos[currentId].serverList[cur] = dlg.serverData();
557     displayNetwork(currentId);
558     ui.serverList->setCurrentRow(cur);
559     widgetHasChanged();
560   }
561 }
562
563 void NetworksSettingsPage::on_deleteServer_clicked() {
564   if(currentId == 0) return;
565   int cur = ui.serverList->currentRow();
566   networkInfos[currentId].serverList.removeAt(cur);
567   displayNetwork(currentId);
568   ui.serverList->setCurrentRow(qMin(cur, ui.serverList->count()-1));
569   widgetHasChanged();
570 }
571
572 void NetworksSettingsPage::on_upServer_clicked() {
573   int cur = ui.serverList->currentRow();
574   QVariant foo = networkInfos[currentId].serverList.takeAt(cur);
575   networkInfos[currentId].serverList.insert(cur-1, foo);
576   displayNetwork(currentId);
577   ui.serverList->setCurrentRow(cur-1);
578   widgetHasChanged();
579 }
580
581 void NetworksSettingsPage::on_downServer_clicked() {
582   int cur = ui.serverList->currentRow();
583   QVariant foo = networkInfos[currentId].serverList.takeAt(cur);
584   networkInfos[currentId].serverList.insert(cur+1, foo);
585   displayNetwork(currentId);
586   ui.serverList->setCurrentRow(cur+1);
587   widgetHasChanged();
588 }
589
590 /**************************************************************************
591  * NetworkEditDlg
592  *************************************************************************/
593
594 NetworkEditDlg::NetworkEditDlg(const QString &old, const QStringList &exist, QWidget *parent) : QDialog(parent), existing(exist) {
595   ui.setupUi(this);
596
597   if(old.isEmpty()) {
598     // new network
599     setWindowTitle(tr("Add Network"));
600     on_networkEdit_textChanged(""); // disable ok button
601   } else ui.networkEdit->setText(old);
602 }
603
604 QString NetworkEditDlg::networkName() const {
605   return ui.networkEdit->text();
606
607 }
608
609 void NetworkEditDlg::on_networkEdit_textChanged(const QString &text) {
610   ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(text.isEmpty() || existing.contains(text));
611 }
612
613
614 /**************************************************************************
615  * ServerEditDlg
616  *************************************************************************/
617
618 ServerEditDlg::ServerEditDlg(const QVariant &_serverData, QWidget *parent) : QDialog(parent) {
619   ui.setupUi(this);
620   QVariantMap serverData = _serverData.toMap();
621   if(serverData.count()) {
622     ui.host->setText(serverData["Host"].toString());
623     ui.port->setValue(serverData["Port"].toUInt());
624     ui.password->setText(serverData["Password"].toString());
625     ui.useSSL->setChecked(serverData["UseSSL"].toBool());
626   } else {
627     ui.port->setValue(6667);
628   }
629   on_host_textChanged();
630 }
631
632 QVariant ServerEditDlg::serverData() const {
633   QVariantMap _serverData;
634   _serverData["Host"] = ui.host->text();
635   _serverData["Port"] = ui.port->value();
636   _serverData["Password"] = ui.password->text();
637   _serverData["UseSSL"] = ui.useSSL->isChecked();
638   return _serverData;
639 }
640
641 void ServerEditDlg::on_host_textChanged() {
642   ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(ui.host->text().isEmpty());
643 }
644
645 /**************************************************************************
646  * SaveNetworksDlg
647  *************************************************************************/
648
649 SaveNetworksDlg::SaveNetworksDlg(const QList<NetworkInfo> &toCreate, const QList<NetworkInfo> &toUpdate, const QList<NetworkId> &toRemove, QWidget *parent) : QDialog(parent)
650 {
651   ui.setupUi(this);
652
653   numevents = toCreate.count() + toUpdate.count() + toRemove.count();
654   rcvevents = 0;
655   if(numevents) {
656     ui.progressBar->setMaximum(numevents);
657     ui.progressBar->setValue(0);
658
659     connect(Client::instance(), SIGNAL(networkCreated(NetworkId)), this, SLOT(clientEvent()));
660     connect(Client::instance(), SIGNAL(networkRemoved(NetworkId)), this, SLOT(clientEvent()));
661
662     foreach(NetworkInfo info, toCreate) {
663       Client::createNetwork(info);
664     }
665     foreach(NetworkInfo info, toUpdate) {
666       const Network *net = Client::network(info.networkId);
667       if(!net) {
668         qWarning() << "Invalid client network!";
669         numevents--;
670         continue;
671       }
672       // FIXME this only checks for one changed item rather than all!
673       connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientEvent()));
674       Client::updateNetwork(info);
675     }
676     foreach(NetworkId id, toRemove) {
677       Client::removeNetwork(id);
678     }
679   } else {
680     qWarning() << "Sync dialog called without stuff to change!";
681     accept();
682   }
683 }
684
685 void SaveNetworksDlg::clientEvent() {
686   ui.progressBar->setValue(++rcvevents);
687   if(rcvevents >= numevents) accept();
688 }