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