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