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