Categories in the settings dialog are now clickable
[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("Misc"), 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   if(id == 1) {
285     // default identity is always the first one!
286     ui.identityList->insertItem(0, identity->identityName(), id.toInt());
287   } else {
288     QString name = identity->identityName();
289     for(int j = 0; j < ui.identityList->count(); j++) {
290       if((j>0 || ui.identityList->itemData(0).toInt() != 1) && name.localeAwareCompare(ui.identityList->itemText(j)) < 0) {
291         ui.identityList->insertItem(j, name, id.toInt());
292         widgetHasChanged();
293         return;
294       }
295     }
296     // append
297     ui.identityList->insertItem(ui.identityList->count(), name, id.toInt());
298     widgetHasChanged();
299   }
300 }
301
302 void NetworksSettingsPage::clientIdentityUpdated() {
303   const Identity *identity = qobject_cast<const Identity *>(sender());
304   if(!identity) {
305     qWarning() << "NetworksSettingsPage: Invalid identity to update!";
306     return;
307   }
308   int row = ui.identityList->findData(identity->id().toInt());
309   if(row < 0) {
310     qWarning() << "NetworksSettingsPage: Invalid identity to update!";
311     return;
312   }
313   if(ui.identityList->itemText(row) != identity->identityName()) {
314     ui.identityList->setItemText(row, identity->identityName());
315   }
316 }
317
318 void NetworksSettingsPage::clientIdentityRemoved(IdentityId id) {
319   if(currentId != 0) saveToNetworkInfo(networkInfos[currentId]);
320   //ui.identityList->removeItem(ui.identityList->findData(id.toInt()));
321   foreach(NetworkInfo info, networkInfos.values()) {
322     //qDebug() << info.networkName << info.networkId << info.identity;
323     if(info.identity == id) {
324       if(info.networkId == currentId) ui.identityList->setCurrentIndex(0);
325       info.identity = 1; // set to default
326       networkInfos[info.networkId] = info;
327       if(info.networkId > 0) Client::updateNetwork(info);
328     }
329   }
330   ui.identityList->removeItem(ui.identityList->findData(id.toInt()));
331   widgetHasChanged();
332 }
333
334 QListWidgetItem *NetworksSettingsPage::networkItem(NetworkId id) const {
335   for(int i = 0; i < ui.networkList->count(); i++) {
336     QListWidgetItem *item = ui.networkList->item(i);
337     if(item->data(Qt::UserRole).value<NetworkId>() == id) return item;
338   }
339   return 0;
340 }
341
342 void NetworksSettingsPage::clientNetworkAdded(NetworkId id) {
343   insertNetwork(id);
344   //connect(Client::network(id), SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
345   connect(Client::network(id), SIGNAL(identitySet(IdentityId)), this, SLOT(clientNetworkUpdated()));
346   connect(Client::network(id), SIGNAL(networkNameSet(const QString &)), this, SLOT(clientNetworkUpdated()));
347   connect(Client::network(id), SIGNAL(serverListSet(QVariantList)), this, SLOT(clientNetworkUpdated()));
348   connect(Client::network(id), SIGNAL(useRandomServerSet(bool)), this, SLOT(clientNetworkUpdated()));
349   connect(Client::network(id), SIGNAL(performSet(const QStringList &)), this, SLOT(clientNetworkUpdated()));
350   connect(Client::network(id), SIGNAL(useAutoIdentifySet(bool)), this, SLOT(clientNetworkUpdated()));
351   connect(Client::network(id), SIGNAL(autoIdentifyServiceSet(const QString &)), this, SLOT(clientNetworkUpdated()));
352   connect(Client::network(id), SIGNAL(autoIdentifyPasswordSet(const QString &)), this, SLOT(clientNetworkUpdated()));
353   connect(Client::network(id), SIGNAL(useAutoReconnectSet(bool)), this, SLOT(clientNetworkUpdated()));
354   connect(Client::network(id), SIGNAL(autoReconnectIntervalSet(quint32)), this, SLOT(clientNetworkUpdated()));
355   connect(Client::network(id), SIGNAL(autoReconnectRetriesSet(quint16)), this, SLOT(clientNetworkUpdated()));
356   connect(Client::network(id), SIGNAL(unlimitedReconnectRetriesSet(bool)), this, SLOT(clientNetworkUpdated()));
357   connect(Client::network(id), SIGNAL(rejoinChannelsSet(bool)), this, SLOT(clientNetworkUpdated()));
358   connect(Client::network(id), SIGNAL(codecForServerSet(const QByteArray &)), this, SLOT(clientNetworkUpdated()));
359   connect(Client::network(id), SIGNAL(codecForEncodingSet(const QByteArray &)), this, SLOT(clientNetworkUpdated()));
360   connect(Client::network(id), SIGNAL(codecForDecodingSet(const QByteArray &)), this, SLOT(clientNetworkUpdated()));
361
362   connect(Client::network(id), SIGNAL(connectionStateSet(Network::ConnectionState)), this, SLOT(networkConnectionStateChanged(Network::ConnectionState)));
363   connect(Client::network(id), SIGNAL(connectionError(const QString &)), this, SLOT(networkConnectionError(const QString &)));
364 }
365
366 void NetworksSettingsPage::clientNetworkUpdated() {
367   const Network *net = qobject_cast<const Network *>(sender());
368   if(!net) {
369     qWarning() << "Update request for unknown network received!";
370     return;
371   }
372   networkInfos[net->networkId()] = net->networkInfo();
373   setItemState(net->networkId());
374   if(net->networkId() == currentId) displayNetwork(net->networkId());
375   setWidgetStates();
376   widgetHasChanged();
377 }
378
379 void NetworksSettingsPage::clientNetworkRemoved(NetworkId id) {
380   if(!networkInfos.contains(id)) return;
381   if(id == currentId) displayNetwork(0);
382   NetworkInfo info = networkInfos.take(id);
383   QList<QListWidgetItem *> items = ui.networkList->findItems(info.networkName, Qt::MatchExactly);
384   foreach(QListWidgetItem *item, items) {
385     if(item->data(Qt::UserRole).value<NetworkId>() == id)
386       delete ui.networkList->takeItem(ui.networkList->row(item));
387   }
388   setWidgetStates();
389   widgetHasChanged();
390 }
391
392 void NetworksSettingsPage::networkConnectionStateChanged(Network::ConnectionState state) {
393   Q_UNUSED(state);
394   const Network *net = qobject_cast<const Network *>(sender());
395   if(!net) return;
396   /*
397   if(net->networkId() == currentId) {
398     ui.connectNow->setEnabled(state == Network::Initialized || state == Network::Disconnected);
399   }
400   */
401   setItemState(net->networkId());
402   setWidgetStates();
403 }
404
405 void NetworksSettingsPage::networkConnectionError(const QString &) {
406
407 }
408
409 QListWidgetItem *NetworksSettingsPage::insertNetwork(NetworkId id) {
410   NetworkInfo info = Client::network(id)->networkInfo();
411   networkInfos[id] = info;
412   return insertNetwork(info);
413 }
414
415 QListWidgetItem *NetworksSettingsPage::insertNetwork(const NetworkInfo &info) {
416   QListWidgetItem *item = 0;
417   QList<QListWidgetItem *> items = ui.networkList->findItems(info.networkName, Qt::MatchExactly);
418   if(!items.count()) item = new QListWidgetItem(disconnectedIcon, info.networkName, ui.networkList);
419   else {
420     // we overwrite an existing net if it a) has the same name and b) has a negative ID meaning we created it locally before
421     // -> then we can be sure that this is the core-side replacement for the net we created
422     foreach(QListWidgetItem *i, items) {
423       NetworkId id = i->data(Qt::UserRole).value<NetworkId>();
424       if(id < 0) { item = i; break; }
425     }
426     if(!item) item = new QListWidgetItem(disconnectedIcon, info.networkName, ui.networkList);
427   }
428   item->setData(Qt::UserRole, QVariant::fromValue<NetworkId>(info.networkId));
429   setItemState(info.networkId, item);
430   widgetHasChanged();
431   return item;
432 }
433
434 void NetworksSettingsPage::displayNetwork(NetworkId id) {
435   _ignoreWidgetChanges = true;
436   if(id != 0) {
437     NetworkInfo info = networkInfos[id];
438     ui.identityList->setCurrentIndex(ui.identityList->findData(info.identity.toInt()));
439     ui.serverList->clear();
440     foreach(Network::Server server, info.serverList) {
441       QListWidgetItem *item = new QListWidgetItem(QString("%1:%2").arg(server.host).arg(server.port));
442       if(server.useSsl)
443         item->setIcon(SmallIcon("document-encrypt"));
444       ui.serverList->addItem(item);
445     }
446     //setItemState(id);
447     //ui.randomServer->setChecked(info.useRandomServer);
448     ui.performEdit->setPlainText(info.perform.join("\n"));
449     ui.autoIdentify->setChecked(info.useAutoIdentify);
450     ui.autoIdentifyService->setText(info.autoIdentifyService);
451     ui.autoIdentifyPassword->setText(info.autoIdentifyPassword);
452     if(info.codecForEncoding.isEmpty()) {
453       ui.sendEncoding->setCurrentIndex(ui.sendEncoding->findText(Network::defaultCodecForEncoding()));
454       ui.recvEncoding->setCurrentIndex(ui.recvEncoding->findText(Network::defaultCodecForDecoding()));
455       ui.serverEncoding->setCurrentIndex(ui.serverEncoding->findText(Network::defaultCodecForServer()));
456       ui.useCustomEncodings->setChecked(false);
457     } else {
458       ui.sendEncoding->setCurrentIndex(ui.sendEncoding->findText(info.codecForEncoding));
459       ui.recvEncoding->setCurrentIndex(ui.recvEncoding->findText(info.codecForDecoding));
460       ui.serverEncoding->setCurrentIndex(ui.serverEncoding->findText(info.codecForServer));
461       ui.useCustomEncodings->setChecked(true);
462     }
463     ui.autoReconnect->setChecked(info.useAutoReconnect);
464     ui.reconnectInterval->setValue(info.autoReconnectInterval);
465     ui.reconnectRetries->setValue(info.autoReconnectRetries);
466     ui.unlimitedRetries->setChecked(info.unlimitedReconnectRetries);
467     ui.rejoinOnReconnect->setChecked(info.rejoinChannels);
468   } else {
469     // just clear widgets
470     ui.identityList->setCurrentIndex(-1);
471     ui.serverList->clear();
472     ui.performEdit->clear();
473     ui.autoIdentifyService->clear();
474     ui.autoIdentifyPassword->clear();
475     setWidgetStates();
476   }
477   _ignoreWidgetChanges = false;
478   currentId = id;
479 }
480
481 void NetworksSettingsPage::saveToNetworkInfo(NetworkInfo &info) {
482   info.identity = ui.identityList->itemData(ui.identityList->currentIndex()).toInt();
483   //info.useRandomServer = ui.randomServer->isChecked();
484   info.perform = ui.performEdit->toPlainText().split("\n");
485   info.useAutoIdentify = ui.autoIdentify->isChecked();
486   info.autoIdentifyService = ui.autoIdentifyService->text();
487   info.autoIdentifyPassword = ui.autoIdentifyPassword->text();
488   if(!ui.useCustomEncodings->isChecked()) {
489     info.codecForEncoding.clear();
490     info.codecForDecoding.clear();
491     info.codecForServer.clear();
492   } else {
493     info.codecForEncoding = ui.sendEncoding->currentText().toLatin1();
494     info.codecForDecoding = ui.recvEncoding->currentText().toLatin1();
495     info.codecForServer = ui.serverEncoding->currentText().toLatin1();
496   }
497   info.useAutoReconnect = ui.autoReconnect->isChecked();
498   info.autoReconnectInterval = ui.reconnectInterval->value();
499   info.autoReconnectRetries = ui.reconnectRetries->value();
500   info.unlimitedReconnectRetries = ui.unlimitedRetries->isChecked();
501   info.rejoinChannels = ui.rejoinOnReconnect->isChecked();
502 }
503 /*** Network list ***/
504
505 void NetworksSettingsPage::on_networkList_itemSelectionChanged() {
506   if(currentId != 0) {
507     saveToNetworkInfo(networkInfos[currentId]);
508   }
509   if(ui.networkList->selectedItems().count()) {
510     NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
511     currentId = id;
512     displayNetwork(id);
513     ui.serverList->setCurrentRow(0);
514   } else {
515     currentId = 0;
516   }
517   setWidgetStates();
518 }
519
520 void NetworksSettingsPage::on_addNetwork_clicked() {
521   QStringList existing;
522   for(int i = 0; i < ui.networkList->count(); i++) existing << ui.networkList->item(i)->text();
523   NetworkAddDlg dlg(existing, this);
524   if(dlg.exec() == QDialog::Accepted) {
525     NetworkInfo info = dlg.networkInfo();
526     if(info.networkName.isEmpty())
527       return;  // sanity check
528
529     NetworkId id;
530     for(id = 1; id <= networkInfos.count(); id++) {
531       widgetHasChanged();
532       if(!networkInfos.keys().contains(-id.toInt())) break;
533     }
534     id = -id.toInt();
535     info.networkId = id;
536     networkInfos[id] = info;
537     QListWidgetItem *item = insertNetwork(info);
538     ui.networkList->setCurrentItem(item);
539     setWidgetStates();
540   }
541 }
542
543 void NetworksSettingsPage::on_deleteNetwork_clicked() {
544   if(ui.networkList->selectedItems().count()) {
545     NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
546     int ret = QMessageBox::question(this, tr("Delete Network?"),
547                                     tr("Do you really want to delete the network \"%1\" and all related settings, including the backlog?").arg(networkInfos[netid].networkName),
548                                     QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
549     if(ret == QMessageBox::Yes) {
550       currentId = 0;
551       networkInfos.remove(netid);
552       delete ui.networkList->takeItem(ui.networkList->row(ui.networkList->selectedItems()[0]));
553       ui.networkList->setCurrentRow(qMin(ui.networkList->currentRow()+1, ui.networkList->count()-1));
554       setWidgetStates();
555       widgetHasChanged();
556     }
557   }
558 }
559
560 void NetworksSettingsPage::on_renameNetwork_clicked() {
561   if(!ui.networkList->selectedItems().count()) return;
562   QString old = ui.networkList->selectedItems()[0]->text();
563   QStringList existing;
564   for(int i = 0; i < ui.networkList->count(); i++) existing << ui.networkList->item(i)->text();
565   NetworkEditDlg dlg(old, existing, this);
566   if(dlg.exec() == QDialog::Accepted) {
567     ui.networkList->selectedItems()[0]->setText(dlg.networkName());
568     NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
569     networkInfos[netid].networkName = dlg.networkName();
570     widgetHasChanged();
571   }
572 }
573
574 /*
575 void NetworksSettingsPage::on_connectNow_clicked() {
576   if(!ui.networkList->selectedItems().count()) return;
577   NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
578   const Network *net = Client::network(id);
579   if(!net) return;
580   if(net->connectionState() == Network::Disconnected) net->requestConnect();
581   else net->requestDisconnect();
582 }
583 */
584
585 /*** Server list ***/
586
587 void NetworksSettingsPage::on_serverList_itemSelectionChanged() {
588   setWidgetStates();
589 }
590
591 void NetworksSettingsPage::on_addServer_clicked() {
592   if(currentId == 0) return;
593   ServerEditDlg dlg(Network::Server(), this);
594   if(dlg.exec() == QDialog::Accepted) {
595     networkInfos[currentId].serverList.append(dlg.serverData());
596     displayNetwork(currentId);
597     ui.serverList->setCurrentRow(ui.serverList->count()-1);
598     widgetHasChanged();
599   }
600 }
601
602 void NetworksSettingsPage::on_editServer_clicked() {
603   if(currentId == 0) return;
604   int cur = ui.serverList->currentRow();
605   ServerEditDlg dlg(networkInfos[currentId].serverList[cur], this);
606   if(dlg.exec() == QDialog::Accepted) {
607     networkInfos[currentId].serverList[cur] = dlg.serverData();
608     displayNetwork(currentId);
609     ui.serverList->setCurrentRow(cur);
610     widgetHasChanged();
611   }
612 }
613
614 void NetworksSettingsPage::on_deleteServer_clicked() {
615   if(currentId == 0) return;
616   int cur = ui.serverList->currentRow();
617   networkInfos[currentId].serverList.removeAt(cur);
618   displayNetwork(currentId);
619   ui.serverList->setCurrentRow(qMin(cur, ui.serverList->count()-1));
620   widgetHasChanged();
621 }
622
623 void NetworksSettingsPage::on_upServer_clicked() {
624   int cur = ui.serverList->currentRow();
625   Network::Server server = networkInfos[currentId].serverList.takeAt(cur);
626   networkInfos[currentId].serverList.insert(cur-1, server);
627   displayNetwork(currentId);
628   ui.serverList->setCurrentRow(cur-1);
629   widgetHasChanged();
630 }
631
632 void NetworksSettingsPage::on_downServer_clicked() {
633   int cur = ui.serverList->currentRow();
634   Network::Server server = networkInfos[currentId].serverList.takeAt(cur);
635   networkInfos[currentId].serverList.insert(cur+1, server);
636   displayNetwork(currentId);
637   ui.serverList->setCurrentRow(cur+1);
638   widgetHasChanged();
639 }
640
641 void NetworksSettingsPage::on_editIdentities_clicked() {
642   SettingsPageDlg dlg(new IdentitiesSettingsPage(this), this);
643   dlg.exec();
644 }
645
646 /**************************************************************************
647 * NetworkAddDlg
648 *************************************************************************/
649
650 NetworkAddDlg::NetworkAddDlg(const QStringList &exist, QWidget *parent) : QDialog(parent), existing(exist) {
651   ui.setupUi(this);
652   ui.useSSL->setIcon(SmallIcon("document-encrypt"));
653
654   // read preset networks
655   QStringList networks = Network::presetNetworks();
656   foreach(QString s, existing)
657     networks.removeAll(s);
658   if(networks.count())
659     ui.presetList->addItems(networks);
660   else {
661     ui.useManual->setChecked(true);
662     ui.usePreset->setEnabled(false);
663   }
664   connect(ui.networkName, SIGNAL(textChanged(const QString &)), SLOT(setButtonStates()));
665   connect(ui.serverAddress, SIGNAL(textChanged(const QString &)), SLOT(setButtonStates()));
666   setButtonStates();
667 }
668
669 NetworkInfo NetworkAddDlg::networkInfo() const {
670   if(ui.useManual->isChecked()) {
671     NetworkInfo info;
672     info.networkName = ui.networkName->text().trimmed();
673     info.serverList << Network::Server(ui.serverAddress->text().trimmed(), ui.port->value(), ui.serverPassword->text(), ui.useSSL->isChecked());
674     return info;
675   } else
676     return Network::networkInfoFromPreset(ui.presetList->currentText());
677 }
678
679 void NetworkAddDlg::setButtonStates() {
680   bool ok = false;
681   if(ui.usePreset->isChecked() && ui.presetList->count())
682     ok = true;
683   else if(ui.useManual->isChecked()) {
684     ok = !ui.networkName->text().trimmed().isEmpty() && !existing.contains(ui.networkName->text().trimmed())
685       && !ui.serverAddress->text().isEmpty();
686   }
687   ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(ok);
688 }
689
690 /**************************************************************************
691  * NetworkEditDlg
692  *************************************************************************/
693
694 NetworkEditDlg::NetworkEditDlg(const QString &old, const QStringList &exist, QWidget *parent) : QDialog(parent), existing(exist) {
695   ui.setupUi(this);
696
697   if(old.isEmpty()) {
698     // new network
699     setWindowTitle(tr("Add Network"));
700     on_networkEdit_textChanged(""); // disable ok button
701   } else ui.networkEdit->setText(old);
702 }
703
704 QString NetworkEditDlg::networkName() const {
705   return ui.networkEdit->text().trimmed();
706
707 }
708
709 void NetworkEditDlg::on_networkEdit_textChanged(const QString &text) {
710   ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(text.isEmpty() || existing.contains(text.trimmed()));
711 }
712
713 /**************************************************************************
714  * ServerEditDlg
715  *************************************************************************/
716 ServerEditDlg::ServerEditDlg(const Network::Server &server, QWidget *parent) : QDialog(parent) {
717   ui.setupUi(this);
718   ui.useSSL->setIcon(SmallIcon("document-encrypt"));
719   ui.host->setText(server.host);
720   ui.port->setValue(server.port);
721   ui.password->setText(server.password);
722   ui.useSSL->setChecked(server.useSsl);
723   ui.sslVersion->setCurrentIndex(server.sslVersion);
724   ui.useProxy->setChecked(server.useProxy);
725   ui.proxyType->setCurrentIndex(server.proxyType == QNetworkProxy::Socks5Proxy ? 0 : 1);
726   ui.proxyHost->setText(server.proxyHost);
727   ui.proxyPort->setValue(server.proxyPort);
728   ui.proxyUsername->setText(server.proxyUser);
729   ui.proxyPassword->setText(server.proxyPass);
730   on_host_textChanged();
731 }
732
733 Network::Server ServerEditDlg::serverData() const {
734   Network::Server server(ui.host->text().trimmed(), ui.port->value(), ui.password->text(), ui.useSSL->isChecked());
735   server.sslVersion = ui.sslVersion->currentIndex();
736   server.useProxy = ui.useProxy->isChecked();
737   server.proxyType = ui.proxyType->currentIndex() == 0 ? QNetworkProxy::Socks5Proxy : QNetworkProxy::HttpProxy;
738   server.proxyHost = ui.proxyHost->text();
739   server.proxyPort = ui.proxyPort->value();
740   server.proxyUser = ui.proxyUsername->text();
741   server.proxyPass = ui.proxyPassword->text();
742   return server;
743 }
744
745 void ServerEditDlg::on_host_textChanged() {
746   ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(ui.host->text().trimmed().isEmpty());
747 }
748
749 /**************************************************************************
750  * SaveNetworksDlg
751  *************************************************************************/
752
753 SaveNetworksDlg::SaveNetworksDlg(const QList<NetworkInfo> &toCreate, const QList<NetworkInfo> &toUpdate, const QList<NetworkId> &toRemove, QWidget *parent) : QDialog(parent)
754 {
755   ui.setupUi(this);
756
757   numevents = toCreate.count() + toUpdate.count() + toRemove.count();
758   rcvevents = 0;
759   if(numevents) {
760     ui.progressBar->setMaximum(numevents);
761     ui.progressBar->setValue(0);
762
763     connect(Client::instance(), SIGNAL(networkCreated(NetworkId)), this, SLOT(clientEvent()));
764     connect(Client::instance(), SIGNAL(networkRemoved(NetworkId)), this, SLOT(clientEvent()));
765
766     foreach(NetworkId id, toRemove) {
767       Client::removeNetwork(id);
768     }
769     foreach(NetworkInfo info, toCreate) {
770       Client::createNetwork(info);
771     }
772     foreach(NetworkInfo info, toUpdate) {
773       const Network *net = Client::network(info.networkId);
774       if(!net) {
775         qWarning() << "Invalid client network!";
776         numevents--;
777         continue;
778       }
779       // FIXME this only checks for one changed item rather than all!
780       connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientEvent()));
781       Client::updateNetwork(info);
782     }
783   } else {
784     qWarning() << "Sync dialog called without stuff to change!";
785     accept();
786   }
787 }
788
789 void SaveNetworksDlg::clientEvent() {
790   ui.progressBar->setValue(++rcvevents);
791   if(rcvevents >= numevents) accept();
792 }