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