Bring back icons to NetworkSettingsPage
[quassel.git] / src / qtui / settingspages / networkssettingspage.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel IRC Team                         *
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
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(QVariant v, info.serverList) {
432       ui.serverList->addItem(QString("%1:%2").arg(v.toMap()["Host"].toString()).arg(v.toMap()["Port"].toUInt()));
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   NetworkEditDlg dlg(QString(), 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     NetworkInfo info;
520     info.networkId = id;
521     info.networkName = dlg.networkName();
522     info.identity = 1;
523
524     // defaults
525     info.useRandomServer = false;
526     info.useAutoReconnect = true;
527     info.autoReconnectInterval = 60;
528     info.autoReconnectRetries = 20;
529     info.unlimitedReconnectRetries = false;
530     info.useAutoIdentify = false;
531     info.autoIdentifyService = "NickServ";
532     info.rejoinChannels = true;
533
534     networkInfos[id] = info;
535     QListWidgetItem *item = insertNetwork(info);
536     ui.networkList->setCurrentItem(item);
537     setWidgetStates();
538   }
539 }
540
541 void NetworksSettingsPage::on_deleteNetwork_clicked() {
542   if(ui.networkList->selectedItems().count()) {
543     NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
544     int ret = QMessageBox::question(this, tr("Delete Network?"),
545                                     tr("Do you really want to delete the network \"%1\" and all related settings, including the backlog?").arg(networkInfos[netid].networkName),
546                                     QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
547     if(ret == QMessageBox::Yes) {
548       currentId = 0;
549       networkInfos.remove(netid);
550       delete ui.networkList->takeItem(ui.networkList->row(ui.networkList->selectedItems()[0]));
551       ui.networkList->setCurrentRow(qMin(ui.networkList->currentRow()+1, ui.networkList->count()-1));
552       setWidgetStates();
553       widgetHasChanged();
554     }
555   }
556 }
557
558 void NetworksSettingsPage::on_renameNetwork_clicked() {
559   if(!ui.networkList->selectedItems().count()) return;
560   QString old = ui.networkList->selectedItems()[0]->text();
561   QStringList existing;
562   for(int i = 0; i < ui.networkList->count(); i++) existing << ui.networkList->item(i)->text();
563   NetworkEditDlg dlg(old, existing, this);
564   if(dlg.exec() == QDialog::Accepted) {
565     ui.networkList->selectedItems()[0]->setText(dlg.networkName());
566     NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
567     networkInfos[netid].networkName = dlg.networkName();
568     widgetHasChanged();
569   }
570 }
571
572 void NetworksSettingsPage::on_connectNow_clicked() {
573   if(!ui.networkList->selectedItems().count()) return;
574   NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
575   const Network *net = Client::network(id);
576   if(!net) return;
577   if(net->connectionState() == Network::Disconnected) net->requestConnect();
578   else net->requestDisconnect();
579 }
580
581 /*** Server list ***/
582
583 void NetworksSettingsPage::on_serverList_itemSelectionChanged() {
584   setWidgetStates();
585 }
586
587 void NetworksSettingsPage::on_addServer_clicked() {
588   if(currentId == 0) return;
589   ServerEditDlg dlg(QVariantMap(), this);
590   if(dlg.exec() == QDialog::Accepted) {
591     networkInfos[currentId].serverList.append(dlg.serverData());
592     displayNetwork(currentId);
593     ui.serverList->setCurrentRow(ui.serverList->count()-1);
594     widgetHasChanged();
595   }
596
597 }
598
599 void NetworksSettingsPage::on_editServer_clicked() {
600   if(currentId == 0) return;
601   int cur = ui.serverList->currentRow();
602   ServerEditDlg dlg(networkInfos[currentId].serverList[cur], this);
603   if(dlg.exec() == QDialog::Accepted) {
604     networkInfos[currentId].serverList[cur] = dlg.serverData();
605     displayNetwork(currentId);
606     ui.serverList->setCurrentRow(cur);
607     widgetHasChanged();
608   }
609 }
610
611 void NetworksSettingsPage::on_deleteServer_clicked() {
612   if(currentId == 0) return;
613   int cur = ui.serverList->currentRow();
614   networkInfos[currentId].serverList.removeAt(cur);
615   displayNetwork(currentId);
616   ui.serverList->setCurrentRow(qMin(cur, ui.serverList->count()-1));
617   widgetHasChanged();
618 }
619
620 void NetworksSettingsPage::on_upServer_clicked() {
621   int cur = ui.serverList->currentRow();
622   QVariant foo = networkInfos[currentId].serverList.takeAt(cur);
623   networkInfos[currentId].serverList.insert(cur-1, foo);
624   displayNetwork(currentId);
625   ui.serverList->setCurrentRow(cur-1);
626   widgetHasChanged();
627 }
628
629 void NetworksSettingsPage::on_downServer_clicked() {
630   int cur = ui.serverList->currentRow();
631   QVariant foo = networkInfos[currentId].serverList.takeAt(cur);
632   networkInfos[currentId].serverList.insert(cur+1, foo);
633   displayNetwork(currentId);
634   ui.serverList->setCurrentRow(cur+1);
635   widgetHasChanged();
636 }
637
638 /**************************************************************************
639  * NetworkEditDlg
640  *************************************************************************/
641
642 NetworkEditDlg::NetworkEditDlg(const QString &old, const QStringList &exist, QWidget *parent) : QDialog(parent), existing(exist) {
643   ui.setupUi(this);
644
645   if(old.isEmpty()) {
646     // new network
647     setWindowTitle(tr("Add Network"));
648     on_networkEdit_textChanged(""); // disable ok button
649   } else ui.networkEdit->setText(old);
650 }
651
652 QString NetworkEditDlg::networkName() const {
653   return ui.networkEdit->text();
654
655 }
656
657 void NetworkEditDlg::on_networkEdit_textChanged(const QString &text) {
658   ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(text.isEmpty() || existing.contains(text));
659 }
660
661
662 /**************************************************************************
663  * ServerEditDlg
664  *************************************************************************/
665
666 ServerEditDlg::ServerEditDlg(const QVariant &_serverData, QWidget *parent) : QDialog(parent) {
667   ui.setupUi(this);
668   ui.useSSL->setIcon(SmallIcon("document-encrypt"));
669
670   QVariantMap serverData = _serverData.toMap();
671   if(serverData.count()) {
672     ui.host->setText(serverData["Host"].toString());
673     ui.port->setValue(serverData["Port"].toUInt());
674     ui.password->setText(serverData["Password"].toString());
675     ui.useSSL->setChecked(serverData["UseSSL"].toBool());
676   } else {
677     ui.port->setValue(6667);
678   }
679   on_host_textChanged();
680 }
681
682 QVariant ServerEditDlg::serverData() const {
683   QVariantMap _serverData;
684   _serverData["Host"] = ui.host->text().trimmed();
685   _serverData["Port"] = ui.port->value();
686   _serverData["Password"] = ui.password->text();
687   _serverData["UseSSL"] = ui.useSSL->isChecked();
688   return _serverData;
689 }
690
691 void ServerEditDlg::on_host_textChanged() {
692   ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(ui.host->text().trimmed().isEmpty());
693 }
694
695 /**************************************************************************
696  * SaveNetworksDlg
697  *************************************************************************/
698
699 SaveNetworksDlg::SaveNetworksDlg(const QList<NetworkInfo> &toCreate, const QList<NetworkInfo> &toUpdate, const QList<NetworkId> &toRemove, QWidget *parent) : QDialog(parent)
700 {
701   ui.setupUi(this);
702
703   numevents = toCreate.count() + toUpdate.count() + toRemove.count();
704   rcvevents = 0;
705   if(numevents) {
706     ui.progressBar->setMaximum(numevents);
707     ui.progressBar->setValue(0);
708
709     connect(Client::instance(), SIGNAL(networkCreated(NetworkId)), this, SLOT(clientEvent()));
710     connect(Client::instance(), SIGNAL(networkRemoved(NetworkId)), this, SLOT(clientEvent()));
711
712     foreach(NetworkId id, toRemove) {
713       Client::removeNetwork(id);
714     }
715     foreach(NetworkInfo info, toCreate) {
716       Client::createNetwork(info);
717     }
718     foreach(NetworkInfo info, toUpdate) {
719       const Network *net = Client::network(info.networkId);
720       if(!net) {
721         qWarning() << "Invalid client network!";
722         numevents--;
723         continue;
724       }
725       // FIXME this only checks for one changed item rather than all!
726       connect(net, SIGNAL(updatedRemotely()), this, SLOT(clientEvent()));
727       Client::updateNetwork(info);
728     }
729   } else {
730     qWarning() << "Sync dialog called without stuff to change!";
731     accept();
732   }
733 }
734
735 void SaveNetworksDlg::clientEvent() {
736   ui.progressBar->setValue(++rcvevents);
737   if(rcvevents >= numevents) accept();
738 }