Font of the Inputline is now configurable. Closing BR #121.
[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 }
383
384 void NetworksSettingsPage::networkConnectionError(const QString &) {
385
386 }
387
388 QListWidgetItem *NetworksSettingsPage::insertNetwork(NetworkId id) {
389   NetworkInfo info = Client::network(id)->networkInfo();
390   networkInfos[id] = info;
391   return insertNetwork(info);
392 }
393
394 QListWidgetItem *NetworksSettingsPage::insertNetwork(const NetworkInfo &info) {
395   QListWidgetItem *item = 0;
396   QList<QListWidgetItem *> items = ui.networkList->findItems(info.networkName, Qt::MatchExactly);
397   if(!items.count()) item = new QListWidgetItem(disconnectedIcon, info.networkName, ui.networkList);
398   else {
399     // we overwrite an existing net if it a) has the same name and b) has a negative ID meaning we created it locally before
400     // -> then we can be sure that this is the core-side replacement for the net we created
401     foreach(QListWidgetItem *i, items) {
402       NetworkId id = i->data(Qt::UserRole).value<NetworkId>();
403       if(id < 0) { item = i; break; }
404     }
405     if(!item) item = new QListWidgetItem(disconnectedIcon, info.networkName, ui.networkList);
406   }
407   item->setData(Qt::UserRole, QVariant::fromValue<NetworkId>(info.networkId));
408   setItemState(info.networkId, item);
409   widgetHasChanged();
410   return item;
411 }
412
413 void NetworksSettingsPage::displayNetwork(NetworkId id) {
414   _ignoreWidgetChanges = true;
415   if(id != 0) {
416     NetworkInfo info = networkInfos[id];
417     ui.identityList->setCurrentIndex(ui.identityList->findData(info.identity.toInt()));
418     ui.serverList->clear();
419     foreach(QVariant v, info.serverList) {
420       ui.serverList->addItem(QString("%1:%2").arg(v.toMap()["Host"].toString()).arg(v.toMap()["Port"].toUInt()));
421     }
422     //setItemState(id);
423     ui.randomServer->setChecked(info.useRandomServer);
424     ui.performEdit->setPlainText(info.perform.join("\n"));
425     ui.autoIdentify->setChecked(info.useAutoIdentify);
426     ui.autoIdentifyService->setText(info.autoIdentifyService);
427     ui.autoIdentifyPassword->setText(info.autoIdentifyPassword);
428     if(info.codecForEncoding.isEmpty()) {
429       ui.sendEncoding->setCurrentIndex(ui.sendEncoding->findText(Network::defaultCodecForEncoding()));
430       ui.recvEncoding->setCurrentIndex(ui.recvEncoding->findText(Network::defaultCodecForDecoding()));
431       ui.serverEncoding->setCurrentIndex(ui.serverEncoding->findText(Network::defaultCodecForServer()));
432       ui.useDefaultEncodings->setChecked(true);
433     } else {
434       ui.sendEncoding->setCurrentIndex(ui.sendEncoding->findText(info.codecForEncoding));
435       ui.recvEncoding->setCurrentIndex(ui.recvEncoding->findText(info.codecForDecoding));
436       ui.serverEncoding->setCurrentIndex(ui.serverEncoding->findText(info.codecForServer));
437       ui.useDefaultEncodings->setChecked(false);
438     }
439     ui.autoReconnect->setChecked(info.useAutoReconnect);
440     ui.reconnectInterval->setValue(info.autoReconnectInterval);
441     ui.reconnectRetries->setValue(info.autoReconnectRetries);
442     ui.unlimitedRetries->setChecked(info.unlimitedReconnectRetries);
443     ui.rejoinOnReconnect->setChecked(info.rejoinChannels);
444   } else {
445     // just clear widgets
446     ui.identityList->setCurrentIndex(-1);
447     ui.serverList->clear();
448     ui.performEdit->clear();
449     ui.autoIdentifyService->clear();
450     ui.autoIdentifyPassword->clear();
451     setWidgetStates();
452   }
453   _ignoreWidgetChanges = false;
454   currentId = id;
455 }
456
457 void NetworksSettingsPage::saveToNetworkInfo(NetworkInfo &info) {
458   info.identity = ui.identityList->itemData(ui.identityList->currentIndex()).toInt();
459   info.useRandomServer = ui.randomServer->isChecked();
460   info.perform = ui.performEdit->toPlainText().split("\n");
461   info.useAutoIdentify = ui.autoIdentify->isChecked();
462   info.autoIdentifyService = ui.autoIdentifyService->text();
463   info.autoIdentifyPassword = ui.autoIdentifyPassword->text();
464   if(ui.useDefaultEncodings->isChecked()) {
465     info.codecForEncoding.clear();
466     info.codecForDecoding.clear();
467     info.codecForServer.clear();
468   } else {
469     info.codecForEncoding = ui.sendEncoding->currentText().toLatin1();
470     info.codecForDecoding = ui.recvEncoding->currentText().toLatin1();
471     info.codecForServer = ui.serverEncoding->currentText().toLatin1();
472   }
473   info.useAutoReconnect = ui.autoReconnect->isChecked();
474   info.autoReconnectInterval = ui.reconnectInterval->value();
475   info.autoReconnectRetries = ui.reconnectRetries->value();
476   info.unlimitedReconnectRetries = ui.unlimitedRetries->isChecked();
477   info.rejoinChannels = ui.rejoinOnReconnect->isChecked();
478 }
479 /*** Network list ***/
480
481 void NetworksSettingsPage::on_networkList_itemSelectionChanged() {
482   if(currentId != 0) {
483     saveToNetworkInfo(networkInfos[currentId]);
484   }
485   if(ui.networkList->selectedItems().count()) {
486     NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
487     currentId = id;
488     displayNetwork(id);
489     ui.serverList->setCurrentRow(0);
490   } else {
491     currentId = 0;
492   }
493   setWidgetStates();
494 }
495
496 void NetworksSettingsPage::on_addNetwork_clicked() {
497   QStringList existing;
498   for(int i = 0; i < ui.networkList->count(); i++) existing << ui.networkList->item(i)->text();
499   NetworkEditDlg dlg(QString(), existing, this);
500   if(dlg.exec() == QDialog::Accepted) {
501     NetworkId id;
502     for(id = 1; id <= networkInfos.count(); id++) {
503       widgetHasChanged();
504       if(!networkInfos.keys().contains(-id.toInt())) break;
505     }
506     id = -id.toInt();
507     NetworkInfo info;
508     info.networkId = id;
509     info.networkName = dlg.networkName();
510     info.identity = 1;
511
512     // defaults
513     info.useRandomServer = false;
514     info.useAutoReconnect = true;
515     info.autoReconnectInterval = 60;
516     info.autoReconnectRetries = 20;
517     info.unlimitedReconnectRetries = false;
518     info.useAutoIdentify = false;
519     info.autoIdentifyService = "NickServ";
520     info.rejoinChannels = true;
521
522     networkInfos[id] = info;
523     QListWidgetItem *item = insertNetwork(info);
524     ui.networkList->setCurrentItem(item);
525     setWidgetStates();
526   }
527 }
528
529 void NetworksSettingsPage::on_deleteNetwork_clicked() {
530   if(ui.networkList->selectedItems().count()) {
531     NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
532     int ret = QMessageBox::question(this, tr("Delete Network?"),
533                                     tr("Do you really want to delete the network \"%1\" and all related settings, including the backlog?").arg(networkInfos[netid].networkName),
534                                     QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
535     if(ret == QMessageBox::Yes) {
536       currentId = 0;
537       networkInfos.remove(netid);
538       delete ui.networkList->takeItem(ui.networkList->row(ui.networkList->selectedItems()[0]));
539       ui.networkList->setCurrentRow(qMin(ui.networkList->currentRow()+1, ui.networkList->count()-1));
540       setWidgetStates();
541       widgetHasChanged();
542     }
543   }
544 }
545
546 void NetworksSettingsPage::on_renameNetwork_clicked() {
547   if(!ui.networkList->selectedItems().count()) return;
548   QString old = ui.networkList->selectedItems()[0]->text();
549   QStringList existing;
550   for(int i = 0; i < ui.networkList->count(); i++) existing << ui.networkList->item(i)->text();
551   NetworkEditDlg dlg(old, existing, this);
552   if(dlg.exec() == QDialog::Accepted) {
553     ui.networkList->selectedItems()[0]->setText(dlg.networkName());
554     NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
555     networkInfos[netid].networkName = dlg.networkName();
556     widgetHasChanged();
557   }
558 }
559
560 void NetworksSettingsPage::on_connectNow_clicked() {
561   if(!ui.networkList->selectedItems().count()) return;
562   NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
563   const Network *net = Client::network(id);
564   if(!net) return;
565   if(net->connectionState() == Network::Disconnected) net->requestConnect();
566   else net->requestDisconnect();
567 }
568
569 /*** Server list ***/
570
571 void NetworksSettingsPage::on_serverList_itemSelectionChanged() {
572   setWidgetStates();
573 }
574
575 void NetworksSettingsPage::on_addServer_clicked() {
576   if(currentId == 0) return;
577   ServerEditDlg dlg(QVariantMap(), this);
578   if(dlg.exec() == QDialog::Accepted) {
579     networkInfos[currentId].serverList.append(dlg.serverData());
580     displayNetwork(currentId);
581     ui.serverList->setCurrentRow(ui.serverList->count()-1);
582     widgetHasChanged();
583   }
584
585 }
586
587 void NetworksSettingsPage::on_editServer_clicked() {
588   if(currentId == 0) return;
589   int cur = ui.serverList->currentRow();
590   ServerEditDlg dlg(networkInfos[currentId].serverList[cur], this);
591   if(dlg.exec() == QDialog::Accepted) {
592     networkInfos[currentId].serverList[cur] = dlg.serverData();
593     displayNetwork(currentId);
594     ui.serverList->setCurrentRow(cur);
595     widgetHasChanged();
596   }
597 }
598
599 void NetworksSettingsPage::on_deleteServer_clicked() {
600   if(currentId == 0) return;
601   int cur = ui.serverList->currentRow();
602   networkInfos[currentId].serverList.removeAt(cur);
603   displayNetwork(currentId);
604   ui.serverList->setCurrentRow(qMin(cur, ui.serverList->count()-1));
605   widgetHasChanged();
606 }
607
608 void NetworksSettingsPage::on_upServer_clicked() {
609   int cur = ui.serverList->currentRow();
610   QVariant foo = networkInfos[currentId].serverList.takeAt(cur);
611   networkInfos[currentId].serverList.insert(cur-1, foo);
612   displayNetwork(currentId);
613   ui.serverList->setCurrentRow(cur-1);
614   widgetHasChanged();
615 }
616
617 void NetworksSettingsPage::on_downServer_clicked() {
618   int cur = ui.serverList->currentRow();
619   QVariant foo = networkInfos[currentId].serverList.takeAt(cur);
620   networkInfos[currentId].serverList.insert(cur+1, foo);
621   displayNetwork(currentId);
622   ui.serverList->setCurrentRow(cur+1);
623   widgetHasChanged();
624 }
625
626 /**************************************************************************
627  * NetworkEditDlg
628  *************************************************************************/
629
630 NetworkEditDlg::NetworkEditDlg(const QString &old, const QStringList &exist, QWidget *parent) : QDialog(parent), existing(exist) {
631   ui.setupUi(this);
632
633   if(old.isEmpty()) {
634     // new network
635     setWindowTitle(tr("Add Network"));
636     on_networkEdit_textChanged(""); // disable ok button
637   } else ui.networkEdit->setText(old);
638 }
639
640 QString NetworkEditDlg::networkName() const {
641   return ui.networkEdit->text();
642
643 }
644
645 void NetworkEditDlg::on_networkEdit_textChanged(const QString &text) {
646   ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(text.isEmpty() || existing.contains(text));
647 }
648
649
650 /**************************************************************************
651  * ServerEditDlg
652  *************************************************************************/
653
654 ServerEditDlg::ServerEditDlg(const QVariant &_serverData, QWidget *parent) : QDialog(parent) {
655   ui.setupUi(this);
656   QVariantMap serverData = _serverData.toMap();
657   if(serverData.count()) {
658     ui.host->setText(serverData["Host"].toString());
659     ui.port->setValue(serverData["Port"].toUInt());
660     ui.password->setText(serverData["Password"].toString());
661     ui.useSSL->setChecked(serverData["UseSSL"].toBool());
662   } else {
663     ui.port->setValue(6667);
664   }
665   on_host_textChanged();
666 }
667
668 QVariant ServerEditDlg::serverData() const {
669   QVariantMap _serverData;
670   _serverData["Host"] = ui.host->text().trimmed();
671   _serverData["Port"] = ui.port->value();
672   _serverData["Password"] = ui.password->text();
673   _serverData["UseSSL"] = ui.useSSL->isChecked();
674   return _serverData;
675 }
676
677 void ServerEditDlg::on_host_textChanged() {
678   ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(ui.host->text().trimmed().isEmpty());
679 }
680
681 /**************************************************************************
682  * SaveNetworksDlg
683  *************************************************************************/
684
685 SaveNetworksDlg::SaveNetworksDlg(const QList<NetworkInfo> &toCreate, const QList<NetworkInfo> &toUpdate, const QList<NetworkId> &toRemove, QWidget *parent) : QDialog(parent)
686 {
687   ui.setupUi(this);
688
689   numevents = toCreate.count() + toUpdate.count() + toRemove.count();
690   rcvevents = 0;
691   if(numevents) {
692     ui.progressBar->setMaximum(numevents);
693     ui.progressBar->setValue(0);
694
695     connect(Client::instance(), SIGNAL(networkCreated(NetworkId)), this, SLOT(clientEvent()));
696     connect(Client::instance(), SIGNAL(networkRemoved(NetworkId)), this, SLOT(clientEvent()));
697
698     foreach(NetworkInfo info, toCreate) {
699       Client::createNetwork(info);
700     }
701     foreach(NetworkInfo info, toUpdate) {
702       const Network *net = Client::network(info.networkId);
703       if(!net) {
704         qWarning() << "Invalid client network!";
705         numevents--;
706         continue;
707       }
708       // FIXME this only checks for one changed item rather than all!
709       connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientEvent()));
710       Client::updateNetwork(info);
711     }
712     foreach(NetworkId id, toRemove) {
713       Client::removeNetwork(id);
714     }
715   } else {
716     qWarning() << "Sync dialog called without stuff to change!";
717     accept();
718   }
719 }
720
721 void SaveNetworksDlg::clientEvent() {
722   ui.progressBar->setValue(++rcvevents);
723   if(rcvevents >= numevents) accept();
724 }