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