migrating identities from QSettings to the storage backend
[quassel.git] / src / qtui / settingspages / identitiessettingspage.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 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) any later version.                                   *
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 "identitiessettingspage.h"
22
23 #include <QDesktopServices>
24 #include <QDragEnterEvent>
25 #include <QDropEvent>
26 #include <QFileDialog>
27 #include <QInputDialog>
28 #include <QMessageBox>
29
30 #include "client.h"
31 #include "iconloader.h"
32 #include "signalproxy.h"
33
34 IdentitiesSettingsPage::IdentitiesSettingsPage(QWidget *parent)
35   : SettingsPage(tr("General"), tr("Identities"), parent),
36     _editSsl(false)
37 {
38
39   ui.setupUi(this);
40   ui.renameIdentity->setIcon(BarIcon("edit-rename"));
41   ui.addIdentity->setIcon(BarIcon("list-add-user"));
42   ui.deleteIdentity->setIcon(BarIcon("list-remove-user"));
43   ui.addNick->setIcon(SmallIcon("list-add"));
44   ui.deleteNick->setIcon(SmallIcon("edit-delete"));
45   ui.renameNick->setIcon(SmallIcon("edit-rename"));
46   ui.nickUp->setIcon(SmallIcon("go-up"));
47   ui.nickDown->setIcon(SmallIcon("go-down"));
48
49   coreConnectionStateChanged(Client::isConnected());  // need a core connection!
50   setWidgetStates();
51   connect(Client::instance(), SIGNAL(coreConnectionStateChanged(bool)), this, SLOT(coreConnectionStateChanged(bool)));
52   connect(Client::instance(), SIGNAL(identityCreated(IdentityId)), this, SLOT(clientIdentityCreated(IdentityId)));
53   connect(Client::instance(), SIGNAL(identityRemoved(IdentityId)), this, SLOT(clientIdentityRemoved(IdentityId)));
54
55   currentId = 0;
56
57   // We need to know whenever the state of input widgets changes...
58   //connect(ui.identityList, SIGNAL(editTextChanged(const QString &)), this, SLOT(widgetHasChanged()));
59   connect(ui.realName, SIGNAL(textEdited(const QString &)), this, SLOT(widgetHasChanged()));
60   connect(ui.nicknameList, SIGNAL(itemChanged(QListWidgetItem *)), this, SLOT(widgetHasChanged()));
61   connect(ui.awayNick, SIGNAL(textEdited(const QString &)), this, SLOT(widgetHasChanged()));
62   connect(ui.awayNickEnabled, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
63   connect(ui.awayReason, SIGNAL(textEdited(const QString &)), this, SLOT(widgetHasChanged()));
64   connect(ui.awayReasonEnabled, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
65   connect(ui.autoAwayEnabled, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
66   connect(ui.autoAwayTime, SIGNAL(valueChanged(int)), this, SLOT(widgetHasChanged()));
67   connect(ui.autoAwayReason, SIGNAL(textEdited(const QString &)), this, SLOT(widgetHasChanged()));
68   connect(ui.autoAwayReasonEnabled, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
69   connect(ui.detachAwayEnabled, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
70   connect(ui.detachAwayReason, SIGNAL(textEdited(const QString &)), this, SLOT(widgetHasChanged()));
71   connect(ui.detachAwayReasonEnabled, SIGNAL(clicked(bool)), this, SLOT(widgetHasChanged()));
72   connect(ui.ident, SIGNAL(textEdited(const QString &)), this, SLOT(widgetHasChanged()));
73   connect(ui.kickReason, SIGNAL(textEdited(const QString &)), this, SLOT(widgetHasChanged()));
74   connect(ui.partReason, SIGNAL(textEdited(const QString &)), this, SLOT(widgetHasChanged()));
75   connect(ui.quitReason, SIGNAL(textEdited(const QString &)), this, SLOT(widgetHasChanged()));
76
77   connect(ui.nicknameList, SIGNAL(itemSelectionChanged()), this, SLOT(setWidgetStates()));
78
79   // we would need this if we enabled drag and drop in the nicklist...
80   //connect(ui.nicknameList, SIGNAL(rowsInserted(const QModelIndex &, int, int)), this, SLOT(setWidgetStates()));
81   //connect(ui.nicknameList->model(), SIGNAL(rowsInserted(const QModelIndex &, int, int)), this, SLOT(nicklistHasChanged()));
82
83   ui.sslKeyGroupBox->setAcceptDrops(true);
84   ui.sslKeyGroupBox->installEventFilter(this);
85   ui.sslCertGroupBox->setAcceptDrops(true);
86   ui.sslCertGroupBox->installEventFilter(this);
87 }
88
89 void IdentitiesSettingsPage::setWidgetStates() {
90   if(ui.nicknameList->selectedItems().count()) {
91     ui.renameNick->setEnabled(true);
92     ui.nickUp->setEnabled(ui.nicknameList->row(ui.nicknameList->selectedItems()[0]) > 0);
93     ui.nickDown->setEnabled(ui.nicknameList->row(ui.nicknameList->selectedItems()[0]) < ui.nicknameList->count()-1);
94   } else {
95     ui.renameNick->setDisabled(true);
96     ui.nickUp->setDisabled(true);
97     ui.nickDown->setDisabled(true);
98   }
99   ui.deleteNick->setEnabled(ui.nicknameList->count() > 1);
100 }
101
102 void IdentitiesSettingsPage::coreConnectionStateChanged(bool connected) {
103   setEnabled(connected);
104   if(connected) {
105 #ifdef HAVE_SSL
106     if(Client::signalProxy()->isSecure()) {
107       ui.keyAndCertSettings->setCurrentIndex(2);
108       _editSsl = true;
109     } else {
110       ui.keyAndCertSettings->setCurrentIndex(1);
111       _editSsl = false;
112     }
113 #else
114     ui.keyAndCertSettings->setCurrentIndex(0);
115 #endif
116     load();
117   } else {
118     // reset
119     currentId = 0;
120   }
121 }
122
123 void IdentitiesSettingsPage::save() {
124   setEnabled(false);
125   QList<CertIdentity *> toCreate, toUpdate;
126   // we need to remove our temporarily created identities.
127   // these are going to be re-added after the core has propagated them back...
128   QHash<IdentityId, CertIdentity *>::iterator i = identities.begin();
129   while(i != identities.end()) {
130     if((*i)->id() < 0) {
131       CertIdentity *temp = *i;
132       i = identities.erase(i);
133       toCreate.append(temp);
134       ui.identityList->removeItem(ui.identityList->findData(temp->id().toInt()));
135     } else {
136       if(**i != *Client::identity((*i)->id()) || (*i)->isDirty()) {
137         toUpdate.append(*i);
138       }
139       ++i;
140     }
141   }
142   SaveIdentitiesDlg dlg(toCreate, toUpdate, deletedIdentities, this);
143   int ret = dlg.exec();
144   if(ret == QDialog::Rejected) {
145     // canceled -> reload everything to be safe
146     load();
147   }
148   foreach(Identity *id, toCreate) {
149     id->deleteLater();
150   }
151   changedIdentities.clear();
152   deletedIdentities.clear();
153   setChangedState(false);
154   setEnabled(true);
155 }
156
157 void IdentitiesSettingsPage::load() {
158   currentId = 0;
159   foreach(Identity *identity, identities.values()) {
160     identity->deleteLater();
161   }
162   identities.clear();
163   deletedIdentities.clear();
164   changedIdentities.clear();
165   ui.identityList->clear();
166   foreach(IdentityId id, Client::identityIds()) {
167     clientIdentityCreated(id);
168   }
169   setChangedState(false);
170 }
171
172 void IdentitiesSettingsPage::widgetHasChanged() {
173   bool changed = testHasChanged();
174   if(changed != hasChanged()) setChangedState(changed);
175 }
176
177 bool IdentitiesSettingsPage::testHasChanged() {
178   if(deletedIdentities.count()) return true;
179   if(currentId < 0) {
180     return true; // new identity
181   } else {
182     if(currentId != 0) {
183       changedIdentities.removeAll(currentId);
184       CertIdentity temp(currentId, this);
185       saveToIdentity(&temp);
186       temp.setIdentityName(identities[currentId]->identityName());
187       if(temp != *Client::identity(currentId) || temp.isDirty())
188         changedIdentities.append(currentId);
189     }
190     return changedIdentities.count();
191   }
192 }
193
194 bool IdentitiesSettingsPage::aboutToSave() {
195   saveToIdentity(identities[currentId]);
196   QList<int> errors;
197   foreach(Identity *id, identities.values()) {
198     if(id->identityName().isEmpty()) errors.append(1);
199     if(!id->nicks().count()) errors.append(2);
200     if(id->realName().isEmpty()) errors.append(3);
201     if(id->ident().isEmpty()) errors.append(4);
202   }
203   if(!errors.count()) return true;
204   QString error(tr("<b>The following problems need to be corrected before your changes can be applied:</b><ul>"));
205   if(errors.contains(1)) error += tr("<li>All identities need an identity name set</li>");
206   if(errors.contains(2)) error += tr("<li>Every identity needs at least one nickname defined</li>");
207   if(errors.contains(3)) error += tr("<li>You need to specify a real name for every identity</li>");
208   if(errors.contains(4)) error += tr("<li>You need to specify an ident for every identity</li>");
209   error += tr("</ul>");
210   QMessageBox::warning(this, tr("One or more identities are invalid"), error);
211   return false;
212 }
213
214 void IdentitiesSettingsPage::clientIdentityCreated(IdentityId id) {
215   CertIdentity *identity = new CertIdentity(*Client::identity(id), this);
216   identity->enableEditSsl(_editSsl);
217   insertIdentity(identity);
218   connect(identity, SIGNAL(sslSettingsUpdated()), this, SLOT(clientIdentityUpdated()));
219   connect(Client::identity(id), SIGNAL(updatedRemotely()), this, SLOT(clientIdentityUpdated()));
220 }
221
222 void IdentitiesSettingsPage::clientIdentityUpdated() {
223   const Identity *clientIdentity = qobject_cast<Identity *>(sender());
224   if(!clientIdentity) {
225     qWarning() << "Invalid identity to update!";
226     return;
227   }
228   if(!identities.contains(clientIdentity->id())) {
229     qWarning() << "Unknown identity to update:" << clientIdentity->identityName();
230     return;
231   }
232
233   CertIdentity *identity = identities[clientIdentity->id()];
234
235   if(identity->identityName() != clientIdentity->identityName())
236     renameIdentity(identity->id(), clientIdentity->identityName());
237
238   identity->update(*clientIdentity);
239
240   if(identity->id() == currentId)
241     displayIdentity(identity, true);
242 }
243
244 void IdentitiesSettingsPage::clientIdentityRemoved(IdentityId id) {
245   if(identities.contains(id)) {
246     removeIdentity(identities[id]);
247     changedIdentities.removeAll(id);
248     deletedIdentities.removeAll(id);
249   }
250 }
251
252 void IdentitiesSettingsPage::insertIdentity(CertIdentity *identity) {
253   IdentityId id = identity->id();
254   identities[id] = identity;
255   if(id == 1) {
256     // default identity is always the first one!
257     ui.identityList->insertItem(0, identity->identityName(), id.toInt());
258   } else {
259     QString name = identity->identityName();
260     for(int j = 0; j < ui.identityList->count(); j++) {
261       if((j>0 || ui.identityList->itemData(0).toInt() != 1) && name.localeAwareCompare(ui.identityList->itemText(j)) < 0) {
262         ui.identityList->insertItem(j, name, id.toInt());
263         widgetHasChanged();
264         return;
265       }
266     }
267     // append
268     ui.identityList->insertItem(ui.identityList->count(), name, id.toInt());
269     widgetHasChanged();
270   }
271 }
272
273 void IdentitiesSettingsPage::renameIdentity(IdentityId id, const QString &newName) {
274   Identity *identity = identities[id];
275   ui.identityList->setItemText(ui.identityList->findData(identity->id().toInt()), newName);
276   identity->setIdentityName(newName);
277 }
278
279 void IdentitiesSettingsPage::removeIdentity(Identity *id) {
280   identities.remove(id->id());
281   ui.identityList->removeItem(ui.identityList->findData(id->id().toInt()));
282   changedIdentities.removeAll(id->id());
283   if(currentId == id->id()) currentId = 0;
284   id->deleteLater();
285   widgetHasChanged();
286 }
287
288 void IdentitiesSettingsPage::on_identityList_currentIndexChanged(int index) {
289   if(index < 0) {
290     //ui.identityList->setEditable(false);
291     displayIdentity(0);
292   } else {
293     IdentityId id = ui.identityList->itemData(index).toInt();
294     if(identities.contains(id)) displayIdentity(identities[id]);
295     ui.deleteIdentity->setEnabled(id != 1); // default identity cannot be deleted
296     ui.renameIdentity->setEnabled(id != 1); // ...or renamed
297   }
298 }
299
300 void IdentitiesSettingsPage::displayIdentity(CertIdentity *id, bool dontsave) {
301   if(currentId != 0 && !dontsave && identities.contains(currentId)) {
302     saveToIdentity(identities[currentId]);
303   }
304   if(id) {
305     currentId = id->id();
306     ui.realName->setText(id->realName());
307     ui.nicknameList->clear();
308     ui.nicknameList->addItems(id->nicks());
309     //for(int i = 0; i < ui.nicknameList->count(); i++) {
310     //  ui.nicknameList->item(i)->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEditable|Qt::ItemIsEnabled);
311     //}
312     if(ui.nicknameList->count()) ui.nicknameList->setCurrentRow(0);
313     ui.awayNick->setText(id->awayNick());
314     ui.awayNickEnabled->setChecked(id->awayNickEnabled());
315     ui.awayReason->setText(id->awayReason());
316     ui.awayReasonEnabled->setChecked(id->awayReasonEnabled());
317     ui.autoAwayEnabled->setChecked(id->autoAwayEnabled());
318     ui.autoAwayTime->setValue(id->autoAwayTime());
319     ui.autoAwayReason->setText(id->autoAwayReason());
320     ui.autoAwayReasonEnabled->setChecked(id->autoAwayReasonEnabled());
321     ui.detachAwayEnabled->setChecked(id->detachAwayEnabled());
322     ui.detachAwayReason->setText(id->detachAwayReason());
323     ui.detachAwayReasonEnabled->setChecked(id->detachAwayReasonEnabled());
324     ui.ident->setText(id->ident());
325     ui.kickReason->setText(id->kickReason());
326     ui.partReason->setText(id->partReason());
327     ui.quitReason->setText(id->quitReason());
328     showKeyState(id->sslKey());
329     showCertState(id->sslCert());
330   }
331 }
332
333 void IdentitiesSettingsPage::saveToIdentity(CertIdentity *id) {
334   id->setRealName(ui.realName->text());
335   QStringList nicks;
336   for(int i = 0; i < ui.nicknameList->count(); i++) {
337     nicks << ui.nicknameList->item(i)->text();
338   }
339   id->setNicks(nicks);
340   id->setAwayNick(ui.awayNick->text());
341   id->setAwayNickEnabled(ui.awayNickEnabled->isChecked());
342   id->setAwayReason(ui.awayReason->text());
343   id->setAwayReasonEnabled(ui.awayReasonEnabled->isChecked());
344   id->setAutoAwayEnabled(ui.autoAwayEnabled->isChecked());
345   id->setAutoAwayTime(ui.autoAwayTime->value());
346   id->setAutoAwayReason(ui.autoAwayReason->text());
347   id->setAutoAwayReasonEnabled(ui.autoAwayReasonEnabled->isChecked());
348   id->setDetachAwayEnabled(ui.detachAwayEnabled->isChecked());
349   id->setDetachAwayReason(ui.detachAwayReason->text());
350   id->setDetachAwayReasonEnabled(ui.detachAwayReasonEnabled->isChecked());
351   id->setIdent(ui.ident->text());
352   id->setKickReason(ui.kickReason->text());
353   id->setPartReason(ui.partReason->text());
354   id->setQuitReason(ui.quitReason->text());
355   id->setSslKey(QSslKey(ui.keyTypeLabel->property("sslKey").toByteArray(), (QSsl::KeyAlgorithm)(ui.keyTypeLabel->property("sslKeyType").toInt())));
356   id->setSslCert(QSslCertificate(ui.certOrgLabel->property("sslCert").toByteArray()));
357 }
358
359 void IdentitiesSettingsPage::on_addIdentity_clicked() {
360   CreateIdentityDlg dlg(ui.identityList->model(), this);
361   if(dlg.exec() == QDialog::Accepted) {
362     // find a free (negative) ID
363     IdentityId id;
364     for(id = 1; id <= identities.count(); id++) {
365       if(!identities.keys().contains(-id.toInt())) break;
366     }
367     id = -id.toInt();
368     CertIdentity *newId = new CertIdentity(id, this);
369     newId->enableEditSsl(_editSsl);
370     if(dlg.duplicateId() != 0) {
371       // duplicate
372       newId->update(*identities[dlg.duplicateId()]);
373       newId->setId(id);
374     }
375     newId->setIdentityName(dlg.identityName());
376     identities[id] = newId;
377     insertIdentity(newId);
378     ui.identityList->setCurrentIndex(ui.identityList->findData(id.toInt()));
379     widgetHasChanged();
380   }
381 }
382
383 void IdentitiesSettingsPage::on_deleteIdentity_clicked() {
384   Identity *id = identities[currentId];
385   int ret = QMessageBox::question(this, tr("Delete Identity?"),
386                                   tr("Do you really want to delete identity \"%1\"?").arg(id->identityName()),
387                                   QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
388   if(ret != QMessageBox::Yes) return;
389   if(id->id() > 0) deletedIdentities.append(id->id());
390   currentId = 0;
391   removeIdentity(id);
392 }
393
394 void IdentitiesSettingsPage::on_renameIdentity_clicked() {
395   QString oldName = identities[currentId]->identityName();
396   bool ok = false;
397   QString name = QInputDialog::getText(this, tr("Rename Identity"),
398                                        tr("Please enter a new name for the identity \"%1\"!").arg(oldName),
399                                        QLineEdit::Normal, oldName, &ok);
400   if(ok && !name.isEmpty()) {
401     renameIdentity(currentId, name);
402     widgetHasChanged();
403   }
404 }
405
406 void IdentitiesSettingsPage::on_addNick_clicked() {
407   QStringList existing;
408   for(int i = 0; i < ui.nicknameList->count(); i++) existing << ui.nicknameList->item(i)->text();
409   NickEditDlg dlg(QString(), existing, this);
410   if(dlg.exec() == QDialog::Accepted) {
411     ui.nicknameList->addItem(dlg.nick());
412     ui.nicknameList->setCurrentRow(ui.nicknameList->count()-1);
413     setWidgetStates();
414     widgetHasChanged();
415   }
416 }
417
418 void IdentitiesSettingsPage::on_deleteNick_clicked() {
419   // no confirmation, since a nickname is really nothing hard to recreate
420   if(ui.nicknameList->selectedItems().count()) {
421     delete ui.nicknameList->takeItem(ui.nicknameList->row(ui.nicknameList->selectedItems()[0]));
422     ui.nicknameList->setCurrentRow(qMin(ui.nicknameList->currentRow()+1, ui.nicknameList->count()-1));
423     setWidgetStates();
424     widgetHasChanged();
425   }
426 }
427
428 void IdentitiesSettingsPage::on_renameNick_clicked() {
429   if(!ui.nicknameList->selectedItems().count()) return;
430   QString old = ui.nicknameList->selectedItems()[0]->text();
431   QStringList existing;
432   for(int i = 0; i < ui.nicknameList->count(); i++) existing << ui.nicknameList->item(i)->text();
433   NickEditDlg dlg(old, existing, this);
434   if(dlg.exec() == QDialog::Accepted) {
435     ui.nicknameList->selectedItems()[0]->setText(dlg.nick());
436   }
437
438 }
439
440 void IdentitiesSettingsPage::on_nickUp_clicked() {
441   if(!ui.nicknameList->selectedItems().count()) return;
442   int row = ui.nicknameList->row(ui.nicknameList->selectedItems()[0]);
443   if(row > 0) {
444     ui.nicknameList->insertItem(row-1, ui.nicknameList->takeItem(row));
445     ui.nicknameList->setCurrentRow(row-1);
446     setWidgetStates();
447     widgetHasChanged();
448   }
449 }
450
451 void IdentitiesSettingsPage::on_nickDown_clicked() {
452   if(!ui.nicknameList->selectedItems().count()) return;
453   int row = ui.nicknameList->row(ui.nicknameList->selectedItems()[0]);
454   if(row < ui.nicknameList->count()-1) {
455     ui.nicknameList->insertItem(row+1, ui.nicknameList->takeItem(row));
456     ui.nicknameList->setCurrentRow(row+1);
457     setWidgetStates();
458     widgetHasChanged();
459   }
460 }
461
462 void IdentitiesSettingsPage::on_continueUnsecured_clicked() {
463   _editSsl = true;
464
465   QHash<IdentityId, CertIdentity *>::iterator idIter;
466   for(idIter = identities.begin(); idIter != identities.end(); idIter++) {
467     idIter.value()->enableEditSsl();
468   }
469
470   ui.keyAndCertSettings->setCurrentIndex(2);
471 }
472
473 bool IdentitiesSettingsPage::eventFilter(QObject *watched, QEvent *event) {
474   bool isCert = (watched == ui.sslCertGroupBox);
475   switch(event->type()) {
476   case QEvent::DragEnter:
477     sslDragEnterEvent(static_cast<QDragEnterEvent *>(event));
478     return true;
479   case QEvent::Drop:
480     sslDropEvent(static_cast<QDropEvent *>(event), isCert);
481     return true;
482   default:
483     return false;
484   }
485 }
486
487 void IdentitiesSettingsPage::sslDragEnterEvent(QDragEnterEvent *event) {
488   if(event->mimeData()->hasFormat("text/uri-list") || event->mimeData()->hasFormat("text/uri")) {
489     event->setDropAction(Qt::CopyAction);
490     event->accept();
491   }
492 }
493
494 void IdentitiesSettingsPage::sslDropEvent(QDropEvent *event, bool isCert) {
495   QByteArray rawUris;
496   if(event->mimeData()->hasFormat("text/uri-list"))
497     rawUris = event->mimeData()->data("text/uri-list");
498   else
499     rawUris = event->mimeData()->data("text/uri");
500
501   QTextStream uriStream(rawUris);
502   QString filename = QUrl(uriStream.readLine()).toLocalFile();
503
504   if(isCert) {
505     QSslCertificate cert = certByFilename(filename);
506     if(cert.isValid())
507       showCertState(cert);
508   } else {
509     QSslKey key = keyByFilename(filename);
510     if(!key.isNull())
511       showKeyState(key);
512   }
513   event->accept();
514   widgetHasChanged();
515 }
516
517 void IdentitiesSettingsPage::on_clearOrLoadKeyButton_clicked() {
518   QSslKey key;
519
520   if(ui.keyTypeLabel->property("sslKey").toByteArray().isEmpty())
521     key = keyByFilename(QFileDialog::getOpenFileName(this, tr("Load a Key"), QDesktopServices::storageLocation(QDesktopServices::HomeLocation)));
522
523   showKeyState(key);
524   widgetHasChanged();
525 }
526
527 QSslKey IdentitiesSettingsPage::keyByFilename(const QString &filename) {
528   QSslKey key;
529
530   QFile keyFile(filename);
531   keyFile.open(QIODevice::ReadOnly);
532   QByteArray keyRaw = keyFile.read(2 << 20);
533   keyFile.close();
534
535   for(int i = 0; i < 2; i++) {
536     for(int j = 0; j < 2; j++) {
537       key = QSslKey(keyRaw, (QSsl::KeyAlgorithm)j, (QSsl::EncodingFormat)i);
538       if(!key.isNull())
539         goto returnKey;
540     }
541   }
542  returnKey:
543   return key;
544 }
545
546 void IdentitiesSettingsPage::showKeyState(const QSslKey &key) {
547   if(key.isNull()) {
548     ui.keyTypeLabel->setText(tr("No Key loaded"));
549     ui.clearOrLoadKeyButton->setText(tr("Load"));
550   } else {
551     switch(key.algorithm()) {
552     case QSsl::Rsa:
553       ui.keyTypeLabel->setText(tr("RSA"));
554       break;
555     case QSsl::Dsa:
556       ui.keyTypeLabel->setText(tr("DSA"));
557       break;
558     default:
559       ui.keyTypeLabel->setText(tr("No Key Loaded"));
560     }
561     ui.clearOrLoadKeyButton->setText(tr("Clear"));
562   }
563   ui.keyTypeLabel->setProperty("sslKey", key.toPem());
564   ui.keyTypeLabel->setProperty("sslKeyType", (int)key.algorithm());
565 }
566
567 void IdentitiesSettingsPage::on_clearOrLoadCertButton_clicked() {
568   QSslCertificate cert;
569
570   if(ui.certOrgLabel->property("sslCert").toByteArray().isEmpty())
571     cert = certByFilename(QFileDialog::getOpenFileName(this, tr("Load a Certificate"), QDesktopServices::storageLocation(QDesktopServices::HomeLocation)));
572
573   showCertState(cert);
574   widgetHasChanged();
575 }
576
577 QSslCertificate IdentitiesSettingsPage::certByFilename(const QString &filename) {
578   QSslCertificate cert;
579   QFile certFile(filename);
580   certFile.open(QIODevice::ReadOnly);
581   QByteArray certRaw = certFile.read(2 << 20);
582   certFile.close();
583
584   for(int i = 0; i < 2; i++) {
585     cert = QSslCertificate(certRaw, (QSsl::EncodingFormat)i);
586     if(cert.isValid())
587       break;
588   }
589   return cert;
590 }
591
592 void IdentitiesSettingsPage::showCertState(const QSslCertificate &cert) {
593   if(!cert.isValid()) {
594     ui.certOrgLabel->setText(tr("No Certificate loaded"));
595     ui.certCNameLabel->setText(tr("No Certificate loaded"));
596     ui.clearOrLoadCertButton->setText(tr("Load"));
597   } else {
598     ui.certOrgLabel->setText(cert.subjectInfo(QSslCertificate::Organization));
599     ui.certCNameLabel->setText(cert.subjectInfo(QSslCertificate::CommonName));
600     ui.clearOrLoadCertButton->setText(tr("Clear"));
601   }
602   ui.certOrgLabel->setProperty("sslCert", cert.toPem());
603  }
604
605 /*****************************************************************************************/
606
607 CreateIdentityDlg::CreateIdentityDlg(QAbstractItemModel *model, QWidget *parent)
608   : QDialog(parent)
609 {
610   ui.setupUi(this);
611
612   ui.identityList->setModel(model);  // now we use the identity list of the main page... Trolltech <3
613   on_identityName_textChanged("");   // disable ok button :)
614 }
615
616 QString CreateIdentityDlg::identityName() const {
617   return ui.identityName->text();
618 }
619
620 IdentityId CreateIdentityDlg::duplicateId() const {
621   if(!ui.duplicateIdentity->isChecked()) return 0;
622   if(ui.identityList->currentIndex() >= 0) {
623     return ui.identityList->itemData(ui.identityList->currentIndex()).toInt();
624   }
625   return 0;
626 }
627
628 void CreateIdentityDlg::on_identityName_textChanged(const QString &text) {
629   ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(text.count());
630
631 }
632
633 /*********************************************************************************************/
634
635 SaveIdentitiesDlg::SaveIdentitiesDlg(const QList<CertIdentity *> &toCreate, const QList<CertIdentity *> &toUpdate, const QList<IdentityId> &toRemove, QWidget *parent)
636   : QDialog(parent)
637 {
638   ui.setupUi(this);
639   ui.abort->setIcon(SmallIcon("dialog-cancel"));
640
641   numevents = toCreate.count() + toUpdate.count() + toRemove.count();
642   rcvevents = 0;
643   if(numevents) {
644     ui.progressBar->setMaximum(numevents);
645     ui.progressBar->setValue(0);
646
647     connect(Client::instance(), SIGNAL(identityCreated(IdentityId)), this, SLOT(clientEvent()));
648     connect(Client::instance(), SIGNAL(identityRemoved(IdentityId)), this, SLOT(clientEvent()));
649
650     foreach(CertIdentity *id, toCreate) {
651       Client::createIdentity(*id);
652     }
653     foreach(CertIdentity *id, toUpdate) {
654       const Identity *cid = Client::identity(id->id());
655       if(!cid) {
656         qWarning() << "Invalid client identity!";
657         numevents--;
658         continue;
659       }
660       connect(cid, SIGNAL(updatedRemotely()), this, SLOT(clientEvent()));
661       Client::updateIdentity(id->id(), id->toVariantMap());
662       id->requestUpdateSslSettings();
663     }
664     foreach(IdentityId id, toRemove) {
665       Client::removeIdentity(id);
666     }
667   } else {
668     qWarning() << "Sync dialog called without stuff to change!";
669     accept();
670   }
671 }
672
673 void SaveIdentitiesDlg::clientEvent() {
674   ui.progressBar->setValue(++rcvevents);
675   if(rcvevents >= numevents) accept();
676 }
677
678 /*************************************************************************************************/
679
680 NickEditDlg::NickEditDlg(const QString &old, const QStringList &exist, QWidget *parent)
681   : QDialog(parent), oldNick(old), existing(exist) {
682   ui.setupUi(this);
683
684   // define a regexp for valid nicknames
685   // TODO: add max nicklength according to ISUPPORT
686   QString letter = "A-Za-z";
687   QString special = "\x5b-\x60\x7b-\x7d";
688   QRegExp rx(QString("[%1%2][%1%2\\d-]*").arg(letter, special));
689   ui.nickEdit->setValidator(new QRegExpValidator(rx, ui.nickEdit));
690   if(old.isEmpty()) {
691     // new nick
692     setWindowTitle(tr("Add Nickname"));
693     on_nickEdit_textChanged(""); // disable ok button
694   } else ui.nickEdit->setText(old);
695 }
696
697 QString NickEditDlg::nick() const {
698   return ui.nickEdit->text();
699
700 }
701
702 void NickEditDlg::on_nickEdit_textChanged(const QString &text) {
703   ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(text.isEmpty() || existing.contains(text));
704 }
705
706
707