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