8e03ce6204f2bc1202ed35ab345df844973ed08b
[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         }
234         int row = ui.networkList->row(i);
235         if(row >= 0) {
236           qDebug() << "ABOUT TO REMOVE: id=" << oldid << "from row" << row;
237           QListWidgetItem *olditem = ui.networkList->takeItem(row);
238           qDebug() << "Successfully removed item from list.";
239           if(!olditem) {
240             qWarning() << "NetworksSettingsPage::setItemState(): Why the heck don't we have an itempointer here?";
241             Q_ASSERT(olditem);  // abort non-gracefully, I need to figure out what's causing this
242           }
243           else delete olditem;
244         }
245         networkInfos.remove(oldid);
246         break;
247       }
248     }
249     item->setText(net->networkName());
250     if(select) item->setSelected(true);
251   }
252 }
253
254 void NetworksSettingsPage::coreConnectionStateChanged(bool state) {
255   this->setEnabled(state);
256   if(state) {
257     load();
258   } else {
259     // reset
260     //currentId = 0;
261   }
262 }
263
264 void NetworksSettingsPage::clientIdentityAdded(IdentityId id) {
265   const Identity * identity = Client::identity(id);
266   connect(identity, SIGNAL(updatedRemotely()), this, SLOT(clientIdentityUpdated()));
267
268   if(id == 1) {
269     // default identity is always the first one!
270     ui.identityList->insertItem(0, identity->identityName(), id.toInt());
271   } else {
272     QString name = identity->identityName();
273     for(int j = 0; j < ui.identityList->count(); j++) {
274       if((j>0 || ui.identityList->itemData(0).toInt() != 1) && name.localeAwareCompare(ui.identityList->itemText(j)) < 0) {
275         ui.identityList->insertItem(j, name, id.toInt());
276         widgetHasChanged();
277         return;
278       }
279     }
280     // append
281     ui.identityList->insertItem(ui.identityList->count(), name, id.toInt());
282     widgetHasChanged();
283   }
284 }
285
286 void NetworksSettingsPage::clientIdentityUpdated() {
287   const Identity *identity = qobject_cast<const Identity *>(sender());
288   if(!identity) {
289     qWarning() << "NetworksSettingsPage: Invalid identity to update!";
290     return;
291   }
292   int row = ui.identityList->findData(identity->id().toInt());
293   if(row < 0) {
294     qWarning() << "NetworksSettingsPage: Invalid identity to update!";
295     return;
296   }
297   if(ui.identityList->itemText(row) != identity->identityName()) {
298     ui.identityList->setItemText(row, identity->identityName());
299   }
300 }
301
302 void NetworksSettingsPage::clientIdentityRemoved(IdentityId id) {
303   if(currentId != 0) saveToNetworkInfo(networkInfos[currentId]);
304   //ui.identityList->removeItem(ui.identityList->findData(id.toInt()));
305   foreach(NetworkInfo info, networkInfos.values()) {
306     //qDebug() << info.networkName << info.networkId << info.identity;
307     if(info.identity == id) {
308       if(info.networkId == currentId) ui.identityList->setCurrentIndex(0);
309       info.identity = 1; // set to default
310       networkInfos[info.networkId] = info;
311       if(info.networkId > 0) Client::updateNetwork(info);
312     }
313   }
314   ui.identityList->removeItem(ui.identityList->findData(id.toInt()));
315   widgetHasChanged();
316 }
317
318 QListWidgetItem *NetworksSettingsPage::networkItem(NetworkId id) const {
319   for(int i = 0; i < ui.networkList->count(); i++) { 
320     QListWidgetItem *item = ui.networkList->item(i);
321     if(item->data(Qt::UserRole).value<NetworkId>() == id) return item;
322   }
323   return 0;
324 }
325
326 void NetworksSettingsPage::clientNetworkAdded(NetworkId id) {
327   insertNetwork(id);
328   connect(Client::network(id), SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
329   connect(Client::network(id), SIGNAL(connectionStateSet(Network::ConnectionState)), this, SLOT(networkConnectionStateChanged(Network::ConnectionState)));
330   connect(Client::network(id), SIGNAL(connectionError(const QString &)), this, SLOT(networkConnectionError(const QString &)));
331 }
332
333 void NetworksSettingsPage::clientNetworkUpdated() {
334   const Network *net = qobject_cast<const Network *>(sender());
335   if(!net) {
336     qWarning() << "Update request for unknown network received!";
337     return;
338   }
339   networkInfos[net->networkId()] = net->networkInfo();
340   setItemState(net->networkId());
341   if(net->networkId() == currentId) displayNetwork(net->networkId());
342   setWidgetStates();
343   widgetHasChanged();
344 }
345
346 void NetworksSettingsPage::clientNetworkRemoved(NetworkId id) {
347   if(!networkInfos.contains(id)) return;
348   if(id == currentId) displayNetwork(0);
349   NetworkInfo info = networkInfos.take(id);
350   QList<QListWidgetItem *> items = ui.networkList->findItems(info.networkName, Qt::MatchExactly);
351   foreach(QListWidgetItem *item, items) {
352     if(item->data(Qt::UserRole).value<NetworkId>() == id)
353       delete ui.networkList->takeItem(ui.networkList->row(item));
354   }
355   setWidgetStates();
356   widgetHasChanged();
357 }
358
359 void NetworksSettingsPage::networkConnectionStateChanged(Network::ConnectionState state) {
360   const Network *net = qobject_cast<const Network *>(sender());
361   if(!net) return;
362   if(net->networkId() == currentId) {
363     ui.connectNow->setEnabled(state == Network::Initialized || state == Network::Disconnected);
364   }
365   setItemState(net->networkId());
366 }
367
368 void NetworksSettingsPage::networkConnectionError(const QString &) {
369
370 }
371
372 QListWidgetItem *NetworksSettingsPage::insertNetwork(NetworkId id) {
373   NetworkInfo info = Client::network(id)->networkInfo();
374   networkInfos[id] = info;
375   return insertNetwork(info);
376 }
377
378 QListWidgetItem *NetworksSettingsPage::insertNetwork(const NetworkInfo &info) {
379   QListWidgetItem *item = 0;
380   QList<QListWidgetItem *> items = ui.networkList->findItems(info.networkName, Qt::MatchExactly);
381   if(!items.count()) item = new QListWidgetItem(disconnectedIcon, info.networkName, ui.networkList);
382   else {
383     // we overwrite an existing net if it a) has the same name and b) has a negative ID meaning we created it locally before
384     // -> then we can be sure that this is the core-side replacement for the net we created
385     foreach(QListWidgetItem *i, items) {
386       NetworkId id = i->data(Qt::UserRole).value<NetworkId>();
387       if(id < 0) { item = i; break; }
388     }
389     if(!item) item = new QListWidgetItem(disconnectedIcon, info.networkName, ui.networkList);
390   }
391   item->setData(Qt::UserRole, QVariant::fromValue<NetworkId>(info.networkId));
392   setItemState(info.networkId, item);
393   widgetHasChanged();
394   return item;
395 }
396
397 void NetworksSettingsPage::displayNetwork(NetworkId id) {
398   _ignoreWidgetChanges = true;
399   if(id != 0) {
400     NetworkInfo info = networkInfos[id];
401     ui.identityList->setCurrentIndex(ui.identityList->findData(info.identity.toInt()));
402     ui.serverList->clear();
403     foreach(QVariant v, info.serverList) {
404       ui.serverList->addItem(QString("%1:%2").arg(v.toMap()["Host"].toString()).arg(v.toMap()["Port"].toUInt()));
405     }
406     setItemState(id);
407     ui.randomServer->setChecked(info.useRandomServer);
408     ui.performEdit->setPlainText(info.perform.join("\n"));
409     ui.autoIdentify->setChecked(info.useAutoIdentify);
410     ui.autoIdentifyService->setText(info.autoIdentifyService);
411     ui.autoIdentifyPassword->setText(info.autoIdentifyPassword);
412     if(info.codecForEncoding.isEmpty()) {
413       ui.sendEncoding->setCurrentIndex(ui.sendEncoding->findText(Network::defaultCodecForEncoding()));
414       ui.recvEncoding->setCurrentIndex(ui.recvEncoding->findText(Network::defaultCodecForDecoding()));
415       ui.useDefaultEncodings->setChecked(true);
416     } else {
417       ui.sendEncoding->setCurrentIndex(ui.sendEncoding->findText(info.codecForEncoding));
418       ui.recvEncoding->setCurrentIndex(ui.recvEncoding->findText(info.codecForDecoding));
419       ui.useDefaultEncodings->setChecked(false);
420     }
421     ui.autoReconnect->setChecked(info.useAutoReconnect);
422     ui.reconnectInterval->setValue(info.autoReconnectInterval);
423     ui.reconnectRetries->setValue(info.autoReconnectRetries);
424     ui.unlimitedRetries->setChecked(info.unlimitedReconnectRetries);
425     ui.rejoinOnReconnect->setChecked(info.rejoinChannels);
426   } else {
427     // just clear widgets
428     ui.identityList->setCurrentIndex(-1);
429     ui.serverList->clear();
430     ui.performEdit->clear();
431     ui.autoIdentifyService->clear();
432     ui.autoIdentifyPassword->clear();
433     setWidgetStates();
434   }
435   _ignoreWidgetChanges = false;
436   currentId = id;
437 }
438
439 void NetworksSettingsPage::saveToNetworkInfo(NetworkInfo &info) {
440   info.identity = ui.identityList->itemData(ui.identityList->currentIndex()).toInt();
441   info.useRandomServer = ui.randomServer->isChecked();
442   info.perform = ui.performEdit->toPlainText().split("\n");
443   info.useAutoIdentify = ui.autoIdentify->isChecked();
444   info.autoIdentifyService = ui.autoIdentifyService->text();
445   info.autoIdentifyPassword = ui.autoIdentifyPassword->text();
446   if(ui.useDefaultEncodings->isChecked()) {
447     info.codecForEncoding.clear();
448     info.codecForDecoding.clear();
449   } else {
450     info.codecForEncoding = ui.sendEncoding->currentText().toLatin1();
451     info.codecForDecoding = ui.recvEncoding->currentText().toLatin1();
452   }
453   info.useAutoReconnect = ui.autoReconnect->isChecked();
454   info.autoReconnectInterval = ui.reconnectInterval->value();
455   info.autoReconnectRetries = ui.reconnectRetries->value();
456   info.unlimitedReconnectRetries = ui.unlimitedRetries->isChecked();
457   info.rejoinChannels = ui.rejoinOnReconnect->isChecked();
458 }
459 /*** Network list ***/
460
461 void NetworksSettingsPage::on_networkList_itemSelectionChanged() {
462   if(currentId != 0) {
463     saveToNetworkInfo(networkInfos[currentId]);
464   }
465   if(ui.networkList->selectedItems().count()) {
466     NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
467     currentId = id;
468     displayNetwork(id);
469     ui.serverList->setCurrentRow(0);
470   } else {
471     currentId = 0;
472   }
473   setWidgetStates();
474 }
475
476 void NetworksSettingsPage::on_addNetwork_clicked() {
477   QStringList existing;
478   for(int i = 0; i < ui.networkList->count(); i++) existing << ui.networkList->item(i)->text();
479   NetworkEditDlg dlg(QString(), existing, this);
480   if(dlg.exec() == QDialog::Accepted) {
481     NetworkId id;
482     for(id = 1; id <= networkInfos.count(); id++) {
483       widgetHasChanged();
484       if(!networkInfos.keys().contains(-id.toInt())) break;
485     }
486     id = -id.toInt();
487     NetworkInfo info;
488     info.networkId = id;
489     info.networkName = dlg.networkName();
490     info.identity = 1;
491
492     // defaults
493     info.useRandomServer = false;
494     info.useAutoReconnect = true;
495     info.autoReconnectInterval = 60;
496     info.autoReconnectRetries = 20;
497     info.unlimitedReconnectRetries = false;
498     info.useAutoIdentify = false;
499     info.autoIdentifyService = "NickServ";
500     info.rejoinChannels = true;
501
502     networkInfos[id] = info;
503     QListWidgetItem *item = insertNetwork(info);
504     ui.networkList->setCurrentItem(item);
505     setWidgetStates();
506   }
507 }
508
509 void NetworksSettingsPage::on_deleteNetwork_clicked() {
510   if(ui.networkList->selectedItems().count()) {
511     NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
512     int ret = QMessageBox::question(this, tr("Delete Network?"),
513                                     tr("Do you really want to delete the network \"%1\" and all related settings, including the backlog?").arg(networkInfos[netid].networkName),
514                                     QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
515     if(ret == QMessageBox::Yes) {
516       currentId = 0;
517       networkInfos.remove(netid);
518       delete ui.networkList->takeItem(ui.networkList->row(ui.networkList->selectedItems()[0]));
519       ui.networkList->setCurrentRow(qMin(ui.networkList->currentRow()+1, ui.networkList->count()-1));
520       setWidgetStates();
521       widgetHasChanged();
522     }
523   }
524 }
525
526 void NetworksSettingsPage::on_renameNetwork_clicked() {
527   if(!ui.networkList->selectedItems().count()) return;
528   QString old = ui.networkList->selectedItems()[0]->text();
529   QStringList existing;
530   for(int i = 0; i < ui.networkList->count(); i++) existing << ui.networkList->item(i)->text();
531   NetworkEditDlg dlg(old, existing, this);
532   if(dlg.exec() == QDialog::Accepted) {
533     ui.networkList->selectedItems()[0]->setText(dlg.networkName());
534     NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
535     networkInfos[netid].networkName = dlg.networkName();
536     widgetHasChanged();
537   }
538 }
539
540 void NetworksSettingsPage::on_connectNow_clicked() {
541   if(!ui.networkList->selectedItems().count()) return;
542   NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
543   const Network *net = Client::network(id);
544   if(!net) return;
545   if(net->connectionState() == Network::Disconnected) net->requestConnect();
546   else net->requestDisconnect();
547 }
548
549 /*** Server list ***/
550
551 void NetworksSettingsPage::on_serverList_itemSelectionChanged() {
552   setWidgetStates();
553 }
554
555 void NetworksSettingsPage::on_addServer_clicked() {
556   if(currentId == 0) return;
557   ServerEditDlg dlg(QVariantMap(), this);
558   if(dlg.exec() == QDialog::Accepted) {
559     networkInfos[currentId].serverList.append(dlg.serverData());
560     displayNetwork(currentId);
561     ui.serverList->setCurrentRow(ui.serverList->count()-1);
562     widgetHasChanged();
563   }
564
565 }
566
567 void NetworksSettingsPage::on_editServer_clicked() {
568   if(currentId == 0) return;
569   int cur = ui.serverList->currentRow();
570   ServerEditDlg dlg(networkInfos[currentId].serverList[cur], this);
571   if(dlg.exec() == QDialog::Accepted) {
572     networkInfos[currentId].serverList[cur] = dlg.serverData();
573     displayNetwork(currentId);
574     ui.serverList->setCurrentRow(cur);
575     widgetHasChanged();
576   }
577 }
578
579 void NetworksSettingsPage::on_deleteServer_clicked() {
580   if(currentId == 0) return;
581   int cur = ui.serverList->currentRow();
582   networkInfos[currentId].serverList.removeAt(cur);
583   displayNetwork(currentId);
584   ui.serverList->setCurrentRow(qMin(cur, ui.serverList->count()-1));
585   widgetHasChanged();
586 }
587
588 void NetworksSettingsPage::on_upServer_clicked() {
589   int cur = ui.serverList->currentRow();
590   QVariant foo = networkInfos[currentId].serverList.takeAt(cur);
591   networkInfos[currentId].serverList.insert(cur-1, foo);
592   displayNetwork(currentId);
593   ui.serverList->setCurrentRow(cur-1);
594   widgetHasChanged();
595 }
596
597 void NetworksSettingsPage::on_downServer_clicked() {
598   int cur = ui.serverList->currentRow();
599   QVariant foo = networkInfos[currentId].serverList.takeAt(cur);
600   networkInfos[currentId].serverList.insert(cur+1, foo);
601   displayNetwork(currentId);
602   ui.serverList->setCurrentRow(cur+1);
603   widgetHasChanged();
604 }
605
606 /**************************************************************************
607  * NetworkEditDlg
608  *************************************************************************/
609
610 NetworkEditDlg::NetworkEditDlg(const QString &old, const QStringList &exist, QWidget *parent) : QDialog(parent), existing(exist) {
611   ui.setupUi(this);
612
613   if(old.isEmpty()) {
614     // new network
615     setWindowTitle(tr("Add Network"));
616     on_networkEdit_textChanged(""); // disable ok button
617   } else ui.networkEdit->setText(old);
618 }
619
620 QString NetworkEditDlg::networkName() const {
621   return ui.networkEdit->text();
622
623 }
624
625 void NetworkEditDlg::on_networkEdit_textChanged(const QString &text) {
626   ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(text.isEmpty() || existing.contains(text));
627 }
628
629
630 /**************************************************************************
631  * ServerEditDlg
632  *************************************************************************/
633
634 ServerEditDlg::ServerEditDlg(const QVariant &_serverData, QWidget *parent) : QDialog(parent) {
635   ui.setupUi(this);
636   QVariantMap serverData = _serverData.toMap();
637   if(serverData.count()) {
638     ui.host->setText(serverData["Host"].toString());
639     ui.port->setValue(serverData["Port"].toUInt());
640     ui.password->setText(serverData["Password"].toString());
641     ui.useSSL->setChecked(serverData["UseSSL"].toBool());
642   } else {
643     ui.port->setValue(6667);
644   }
645   on_host_textChanged();
646 }
647
648 QVariant ServerEditDlg::serverData() const {
649   QVariantMap _serverData;
650   _serverData["Host"] = ui.host->text().trimmed();
651   _serverData["Port"] = ui.port->value();
652   _serverData["Password"] = ui.password->text();
653   _serverData["UseSSL"] = ui.useSSL->isChecked();
654   return _serverData;
655 }
656
657 void ServerEditDlg::on_host_textChanged() {
658   ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(ui.host->text().trimmed().isEmpty());
659 }
660
661 /**************************************************************************
662  * SaveNetworksDlg
663  *************************************************************************/
664
665 SaveNetworksDlg::SaveNetworksDlg(const QList<NetworkInfo> &toCreate, const QList<NetworkInfo> &toUpdate, const QList<NetworkId> &toRemove, QWidget *parent) : QDialog(parent)
666 {
667   ui.setupUi(this);
668
669   numevents = toCreate.count() + toUpdate.count() + toRemove.count();
670   rcvevents = 0;
671   if(numevents) {
672     ui.progressBar->setMaximum(numevents);
673     ui.progressBar->setValue(0);
674
675     connect(Client::instance(), SIGNAL(networkCreated(NetworkId)), this, SLOT(clientEvent()));
676     connect(Client::instance(), SIGNAL(networkRemoved(NetworkId)), this, SLOT(clientEvent()));
677
678     foreach(NetworkInfo info, toCreate) {
679       Client::createNetwork(info);
680     }
681     foreach(NetworkInfo info, toUpdate) {
682       const Network *net = Client::network(info.networkId);
683       if(!net) {
684         qWarning() << "Invalid client network!";
685         numevents--;
686         continue;
687       }
688       // FIXME this only checks for one changed item rather than all!
689       connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientEvent()));
690       Client::updateNetwork(info);
691     }
692     foreach(NetworkId id, toRemove) {
693       Client::removeNetwork(id);
694     }
695   } else {
696     qWarning() << "Sync dialog called without stuff to change!";
697     accept();
698   }
699 }
700
701 void SaveNetworksDlg::clientEvent() {
702   ui.progressBar->setValue(++rcvevents);
703   if(rcvevents >= numevents) accept();
704 }