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