OK, disabled warnings for the moment :)
[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
24 #include "networkssettingspage.h"
25
26 #include "client.h"
27 #include "global.h"
28 #include "identity.h"
29 #include "network.h"
30
31
32 NetworksSettingsPage::NetworksSettingsPage(QWidget *parent) : SettingsPage(tr("General"), tr("Networks"), parent) {
33   ui.setupUi(this);
34
35   connectedIcon = QIcon(":/22x22/actions/network-connect");
36   disconnectedIcon = QIcon(":/22x22/actions/network-disconnect");
37
38   currentId = 0;
39   setEnabled(false);  // need a core connection!
40   setWidgetStates();
41   connect(Client::instance(), SIGNAL(coreConnectionStateChanged(bool)), this, SLOT(coreConnectionStateChanged(bool)));
42   connect(Client::instance(), SIGNAL(networkCreated(NetworkId)), this, SLOT(clientNetworkAdded(NetworkId)));
43   connect(Client::instance(), SIGNAL(networkRemoved(NetworkId)), this, SLOT(clientNetworkRemoved(NetworkId)));
44   connect(Client::instance(), SIGNAL(identityCreated(IdentityId)), this, SLOT(clientIdentityAdded(IdentityId)));
45   connect(Client::instance(), SIGNAL(identityRemoved(IdentityId)), this, SLOT(clientIdentityRemoved(IdentityId)));
46
47   connect(ui.identityList, SIGNAL(currentIndexChanged(int)), this, SLOT(widgetHasChanged()));
48   //connect(ui., SIGNAL(), this, SLOT(widgetHasChanged()));
49   //connect(ui., SIGNAL(), this, SLOT(widgetHasChanged()));
50
51   foreach(IdentityId id, Client::identityIds()) {
52     clientIdentityAdded(id);
53   }
54 }
55
56 void NetworksSettingsPage::save() {
57   if(currentId != 0) saveToNetworkInfo(networkInfos[currentId]);
58
59   // First, remove the temporarily created networks
60   QList<NetworkInfo> toCreate, toUpdate;
61   QList<NetworkId> toRemove;
62   QHash<NetworkId, NetworkInfo>::iterator i = networkInfos.begin();
63   while(i != networkInfos.end()) {
64     if((*i).networkId < 0) {
65       toCreate.append(*i);
66       i = networkInfos.erase(i);
67     } else {
68       if((*i) != Client::network((*i).networkId)->networkInfo()) {
69         toUpdate.append(*i);
70       }
71       ++i;
72     }
73   }
74   foreach(NetworkId id, Client::networkIds()) {
75     if(!networkInfos.contains(id)) toRemove.append(id);
76   }
77   SaveNetworksDlg dlg(toCreate, toUpdate, toRemove, this);
78   int ret = dlg.exec();
79   if(ret == QDialog::Rejected) {
80     // canceled -> reload everything to be safe
81     load();
82   }
83 }
84
85 void NetworksSettingsPage::load() {
86   reset();
87   foreach(NetworkId netid, Client::networkIds()) {
88     clientNetworkAdded(netid);
89   }
90   ui.networkList->setCurrentRow(0);
91   setChangedState(false);
92 }
93
94 void NetworksSettingsPage::reset() {
95   currentId = 0;
96   ui.networkList->clear();
97   networkInfos.clear();
98
99   /*
100   foreach(Identity *identity, identities.values()) {
101     identity->deleteLater();
102   }
103   identities.clear();
104   deletedIdentities.clear();
105   changedIdentities.clear();
106   ui.identityList->clear();
107   */
108 }
109
110 bool NetworksSettingsPage::aboutToSave() {
111
112   return true; // FIXME
113 }
114
115 void NetworksSettingsPage::widgetHasChanged() {
116   bool changed = testHasChanged();
117   if(changed != hasChanged()) setChangedState(changed);
118 }
119
120 bool NetworksSettingsPage::testHasChanged() {
121   if(currentId != 0) {
122     saveToNetworkInfo(networkInfos[currentId]);
123   }
124   if(Client::networkIds().count() != networkInfos.count()) return true;
125   foreach(NetworkId id, networkInfos.keys()) {
126     if(id < 0) return true;
127     if(Client::network(id)->networkInfo() != networkInfos[id]) return true;
128   }
129   return false;
130 }
131
132 void NetworksSettingsPage::setWidgetStates() {
133   // network list
134   if(ui.networkList->selectedItems().count()) {
135     NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
136     ui.detailsBox->setEnabled(true);
137     ui.renameNetwork->setEnabled(true);
138     ui.deleteNetwork->setEnabled(true);
139     ui.connectNow->setEnabled(true);
140     if(Client::network(id) && Client::network(id)->isConnected()) {
141       ui.connectNow->setIcon(disconnectedIcon);
142       ui.connectNow->setText(tr("Disconnect"));
143     } else {
144       ui.connectNow->setIcon(connectedIcon);
145       ui.connectNow->setText(tr("Connect"));
146     }
147   } else {
148     ui.renameNetwork->setEnabled(false);
149     ui.deleteNetwork->setEnabled(false);
150     ui.connectNow->setEnabled(false);
151     ui.detailsBox->setEnabled(false);
152   }
153   // network details
154   if(ui.serverList->selectedItems().count()) {
155     ui.editServer->setEnabled(true);
156     ui.deleteServer->setEnabled(true);
157     ui.upServer->setEnabled(ui.serverList->currentRow() > 0);
158     ui.downServer->setEnabled(ui.serverList->currentRow() < ui.serverList->count() - 1);
159   } else {
160     ui.editServer->setEnabled(false);
161     ui.deleteServer->setEnabled(false);
162     ui.upServer->setEnabled(false);
163     ui.downServer->setEnabled(false);
164   }
165 }
166
167 void NetworksSettingsPage::coreConnectionStateChanged(bool state) {
168   this->setEnabled(state);
169   if(state) {
170     load();
171   } else {
172     // reset
173     //currentId = 0;
174   }
175 }
176
177 QListWidgetItem *NetworksSettingsPage::networkItem(NetworkId id) const {
178   for(int i = 0; i < ui.networkList->count(); i++) {
179     QListWidgetItem *item = ui.networkList->item(i);
180     if(item->data(Qt::UserRole).value<NetworkId>() == id) return item;
181   }
182   return 0;
183 }
184
185 void NetworksSettingsPage::clientIdentityAdded(IdentityId id) {
186   const Identity * identity = Client::identity(id);
187   connect(identity, SIGNAL(updatedRemotely()), this, SLOT(clientIdentityUpdated()));
188
189   if(id == 1) {
190     // default identity is always the first one!
191     ui.identityList->insertItem(0, identity->identityName(), id.toInt());
192   } else {
193     QString name = identity->identityName();
194     for(int j = 0; j < ui.identityList->count(); j++) {
195       if((j>0 || ui.identityList->itemData(0).toInt() != 1) && name.localeAwareCompare(ui.identityList->itemText(j)) < 0) {
196         ui.identityList->insertItem(j, name, id.toInt());
197         widgetHasChanged();
198         return;
199       }
200     }
201     // append
202     ui.identityList->insertItem(ui.identityList->count(), name, id.toInt());
203     widgetHasChanged();
204   }
205 }
206
207 void NetworksSettingsPage::clientIdentityUpdated() {
208   const Identity *identity = qobject_cast<const Identity *>(sender());
209   if(!identity) {
210     qWarning() << "NetworksSettingsPage: Invalid identity to update!";
211     return;
212   }
213   int row = ui.identityList->findData(identity->id().toInt());
214   if(row < 0) {
215     qWarning() << "NetworksSettingsPage: Invalid identity to update!";
216     return;
217   }
218   if(ui.identityList->itemText(row) != identity->identityName()) {
219     ui.identityList->setItemText(row, identity->identityName());
220   }
221 }
222
223 void NetworksSettingsPage::clientIdentityRemoved(IdentityId id) {
224   ui.identityList->removeItem(ui.identityList->findData(id.toInt()));
225   foreach(NetworkInfo info, networkInfos.values()) {
226     if(info.identity == id) info.identity = 1; // set to default
227   }
228   widgetHasChanged();
229 }
230
231
232 void NetworksSettingsPage::clientNetworkAdded(NetworkId id) {
233   insertNetwork(id);
234   connect(Client::network(id), SIGNAL(updatedRemotely()), this, SLOT(clientNetworkUpdated()));
235 }
236
237 void NetworksSettingsPage::clientNetworkUpdated() {
238   const Network *net = qobject_cast<const Network *>(sender());
239   if(!net) {
240     qWarning() << "Update request for unknown network received!";
241     return;
242   }
243   QListWidgetItem *item = networkItem(net->networkId());
244   if(!item) return;
245   item->setText(net->networkName());
246   if(net->isInitialized()) item->setFlags(item->flags() | Qt::ItemIsEnabled);
247   else item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
248   if(net->isConnected()) {
249     item->setIcon(connectedIcon);
250   } else {
251     item->setIcon(disconnectedIcon);
252   }
253 }
254
255 void NetworksSettingsPage::clientNetworkRemoved(NetworkId) {
256
257 }
258
259 QListWidgetItem *NetworksSettingsPage::insertNetwork(NetworkId id) {
260   NetworkInfo info = Client::network(id)->networkInfo();
261   networkInfos[id] = info;
262   return insertNetwork(info);
263 }
264
265 QListWidgetItem *NetworksSettingsPage::insertNetwork(const NetworkInfo &info) {
266   QListWidgetItem *item = new QListWidgetItem(disconnectedIcon, info.networkName);
267   item->setData(Qt::UserRole, QVariant::fromValue<NetworkId>(info.networkId));
268   ui.networkList->addItem(item);
269   const Network *net = Client::network(info.networkId);
270   if(net->isInitialized()) item->setFlags(item->flags() | Qt::ItemIsEnabled);
271   else item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
272   if(net && net->isConnected()) {
273     item->setIcon(connectedIcon);
274   } else {
275     item->setIcon(disconnectedIcon);
276   }
277   widgetHasChanged();
278   return item;
279 }
280
281 void NetworksSettingsPage::displayNetwork(NetworkId id, bool dontsave) {
282   Q_UNUSED(dontsave);
283   NetworkInfo info = networkInfos[id];
284   ui.identityList->setCurrentIndex(ui.identityList->findData(info.identity.toInt()));
285   ui.serverList->clear();
286   foreach(QVariantMap v, info.serverList) {
287     ui.serverList->addItem(QString("%1:%2").arg(v["Host"].toString()).arg(v["Port"].toUInt()));
288   }
289 }
290
291 void NetworksSettingsPage::saveToNetworkInfo(NetworkInfo &info) {
292   info.identity = ui.identityList->itemData(ui.identityList->currentIndex()).toInt();
293 }
294 /*** Network list ***/
295
296 void NetworksSettingsPage::on_networkList_itemSelectionChanged() {
297   if(currentId != 0) {
298     saveToNetworkInfo(networkInfos[currentId]);
299   }
300   if(ui.networkList->selectedItems().count()) {
301     NetworkId id = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
302     currentId = id;
303     displayNetwork(id);
304     ui.serverList->setCurrentRow(0);
305   } else {
306     currentId = 0;
307   }
308   setWidgetStates();
309 }
310
311 void NetworksSettingsPage::on_addNetwork_clicked() {
312   QStringList existing;
313   for(int i = 0; i < ui.networkList->count(); i++) existing << ui.networkList->item(i)->text();
314   NetworkEditDlgNew dlg(QString(), existing, this);
315   if(dlg.exec() == QDialog::Accepted) {
316     NetworkId id;
317     for(id = 1; id <= networkInfos.count(); id++) {
318       widgetHasChanged();
319       if(!networkInfos.keys().contains(-id.toInt())) break;
320     }
321     id = -id.toInt();
322     NetworkInfo info;
323     info.networkId = id;
324     info.networkName = dlg.networkName();
325     info.identity = 1;
326     networkInfos[id] = info;
327     QListWidgetItem *item = insertNetwork(info);
328     ui.networkList->setCurrentItem(item);
329     setWidgetStates();
330   }
331 }
332
333 void NetworksSettingsPage::on_deleteNetwork_clicked() {
334   if(ui.networkList->selectedItems().count()) {
335     NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
336     int ret = QMessageBox::question(this, tr("Delete Network?"),
337                                     tr("Do you really want to delete the network \"%1\" and all related settings, including the backlog?"
338                                        "<br><br><em>NOTE: Backlog deletion hasn't actually been implemented yet.</em>").arg(networkInfos[netid].networkName),
339                                     QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
340     if(ret == QMessageBox::Yes) {
341       currentId = 0;
342       networkInfos.remove(netid); qDebug() << netid << networkInfos.count();
343       delete ui.networkList->selectedItems()[0];
344       ui.networkList->setCurrentRow(qMin(ui.networkList->currentRow()+1, ui.networkList->count()-1));
345       setWidgetStates();
346       widgetHasChanged();
347     }
348   }
349 }
350
351 void NetworksSettingsPage::on_renameNetwork_clicked() {
352   if(!ui.networkList->selectedItems().count()) return;
353   QString old = ui.networkList->selectedItems()[0]->text();
354   QStringList existing;
355   for(int i = 0; i < ui.networkList->count(); i++) existing << ui.networkList->item(i)->text();
356   NetworkEditDlgNew dlg(old, existing, this);
357   if(dlg.exec() == QDialog::Accepted) {
358     ui.networkList->selectedItems()[0]->setText(dlg.networkName());
359     NetworkId netid = ui.networkList->selectedItems()[0]->data(Qt::UserRole).value<NetworkId>();
360     networkInfos[netid].networkName = dlg.networkName();
361     widgetHasChanged();
362   }
363 }
364
365 /*** Server list ***/
366
367 void NetworksSettingsPage::on_serverList_itemSelectionChanged() {
368   setWidgetStates();
369 }
370
371 void NetworksSettingsPage::on_addServer_clicked() {
372   if(currentId == 0) return;
373   ServerEditDlgNew dlg(QVariantMap(), this);
374   if(dlg.exec() == QDialog::Accepted) {
375     networkInfos[currentId].serverList.append(dlg.serverData());
376     displayNetwork(currentId);
377     ui.serverList->setCurrentRow(ui.serverList->count()-1);
378     widgetHasChanged();
379   }
380
381 }
382
383 void NetworksSettingsPage::on_editServer_clicked() {
384   if(currentId == 0) return;
385   int cur = ui.serverList->currentRow();
386   ServerEditDlgNew dlg(networkInfos[currentId].serverList[cur], this);
387   if(dlg.exec() == QDialog::Accepted) {
388     networkInfos[currentId].serverList[cur] = dlg.serverData();
389     displayNetwork(currentId);
390     ui.serverList->setCurrentRow(cur);
391     widgetHasChanged();
392   }
393 }
394
395 void NetworksSettingsPage::on_deleteServer_clicked() {
396   if(currentId == 0) return;
397   int cur = ui.serverList->currentRow();
398   networkInfos[currentId].serverList.removeAt(cur);
399   displayNetwork(currentId);
400   ui.serverList->setCurrentRow(qMin(cur, ui.serverList->count()-1));
401   widgetHasChanged();
402 }
403
404 void NetworksSettingsPage::on_upServer_clicked() {
405   int cur = ui.serverList->currentRow();
406   QVariantMap foo = networkInfos[currentId].serverList.takeAt(cur);
407   networkInfos[currentId].serverList.insert(cur-1, foo);
408   displayNetwork(currentId);
409   ui.serverList->setCurrentRow(cur-1);
410   widgetHasChanged();
411 }
412
413 void NetworksSettingsPage::on_downServer_clicked() {
414   int cur = ui.serverList->currentRow();
415   QVariantMap foo = networkInfos[currentId].serverList.takeAt(cur);
416   networkInfos[currentId].serverList.insert(cur+1, foo);
417   displayNetwork(currentId);
418   ui.serverList->setCurrentRow(cur+1);
419   widgetHasChanged();
420 }
421
422 /**************************************************************************
423  * NetworkEditDlg
424  *************************************************************************/
425
426 NetworkEditDlgNew::NetworkEditDlgNew(const QString &old, const QStringList &exist, QWidget *parent) : QDialog(parent), existing(exist) {
427   ui.setupUi(this);
428
429   if(old.isEmpty()) {
430     // new network
431     setWindowTitle(tr("Add Network"));
432     on_networkEdit_textChanged(""); // disable ok button
433   } else ui.networkEdit->setText(old);
434 }
435
436 QString NetworkEditDlgNew::networkName() const {
437   return ui.networkEdit->text();
438
439 }
440
441 void NetworkEditDlgNew::on_networkEdit_textChanged(const QString &text) {
442   ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(text.isEmpty() || existing.contains(text));
443 }
444
445
446 /**************************************************************************
447  * ServerEditDlg
448  *************************************************************************/
449
450 ServerEditDlgNew::ServerEditDlgNew(const QVariantMap &serverData, QWidget *parent) : QDialog(parent) {
451   ui.setupUi(this);
452   if(serverData.count()) {
453     ui.host->setText(serverData["Host"].toString());
454     ui.port->setValue(serverData["Port"].toUInt());
455     ui.password->setText(serverData["Password"].toString());
456     ui.useSSL->setChecked(serverData["UseSSL"].toBool());
457   } else {
458     ui.port->setValue(Global::defaultPort);
459   }
460   on_host_textChanged();
461 }
462
463 QVariantMap ServerEditDlgNew::serverData() const {
464   QVariantMap _serverData;
465   _serverData["Host"] = ui.host->text();
466   _serverData["Port"] = ui.port->value();
467   _serverData["Password"] = ui.password->text();
468   _serverData["UseSSL"] = ui.useSSL->isChecked();
469   return _serverData;
470 }
471
472 void ServerEditDlgNew::on_host_textChanged() {
473   ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(ui.host->text().isEmpty());
474 }
475
476 /**************************************************************************
477  * SaveNetworksDlg
478  *************************************************************************/
479
480 SaveNetworksDlg::SaveNetworksDlg(const QList<NetworkInfo> &toCreate, const QList<NetworkInfo> &toUpdate, const QList<NetworkId> &toRemove, QWidget *parent) : QDialog(parent)
481 {
482   ui.setupUi(this);
483
484 }
485