4d2d433cb043dc7d900907f54e11e95333b701ef
[quassel.git] / src / qtui / settingspages / identitiessettingspage.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2013 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  *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
19  ***************************************************************************/
20
21 #include "identitiessettingspage.h"
22
23 #include <QInputDialog>
24 #include <QMessageBox>
25
26 #include "client.h"
27 #include "iconloader.h"
28 #include "signalproxy.h"
29
30 IdentitiesSettingsPage::IdentitiesSettingsPage(QWidget *parent)
31     : SettingsPage(tr("IRC"), tr("Identities"), parent),
32     _editSsl(false)
33 {
34     ui.setupUi(this);
35     ui.renameIdentity->setIcon(BarIcon("edit-rename"));
36     ui.addIdentity->setIcon(BarIcon("list-add-user"));
37     ui.deleteIdentity->setIcon(BarIcon("list-remove-user"));
38
39     coreConnectionStateChanged(Client::isConnected()); // need a core connection!
40     connect(Client::instance(), SIGNAL(coreConnectionStateChanged(bool)), this, SLOT(coreConnectionStateChanged(bool)));
41
42     connect(Client::instance(), SIGNAL(identityCreated(IdentityId)), this, SLOT(clientIdentityCreated(IdentityId)));
43     connect(Client::instance(), SIGNAL(identityRemoved(IdentityId)), this, SLOT(clientIdentityRemoved(IdentityId)));
44
45     connect(ui.identityEditor, SIGNAL(widgetHasChanged()), this, SLOT(widgetHasChanged()));
46 #ifdef HAVE_SSL
47     connect(ui.identityEditor, SIGNAL(requestEditSsl()), this, SLOT(continueUnsecured()));
48 #endif
49
50     currentId = 0;
51
52     //connect(ui.identityList, SIGNAL(editTextChanged(const QString &)), this, SLOT(widgetHasChanged()));
53 }
54
55
56 void IdentitiesSettingsPage::coreConnectionStateChanged(bool connected)
57 {
58     setEnabled(connected);
59     if (connected) {
60 #ifdef HAVE_SSL
61         if (Client::signalProxy()->isSecure()) {
62             ui.identityEditor->setSslState(IdentityEditWidget::AllowSsl);
63             _editSsl = true;
64         }
65         else {
66             ui.identityEditor->setSslState(IdentityEditWidget::UnsecureSsl);
67             _editSsl = false;
68         }
69 #else
70         ui.identityEditor->setSslState(IdentityEditWidget::NoSsl);
71 #endif
72         load();
73     }
74     else {
75         // reset
76         currentId = 0;
77     }
78 }
79
80
81 #ifdef HAVE_SSL
82 void IdentitiesSettingsPage::continueUnsecured()
83 {
84     _editSsl = true;
85
86     QHash<IdentityId, CertIdentity *>::iterator idIter;
87     for (idIter = identities.begin(); idIter != identities.end(); idIter++) {
88         idIter.value()->enableEditSsl();
89     }
90
91     ui.identityEditor->setSslState(IdentityEditWidget::AllowSsl);
92 }
93
94
95 #endif
96
97 void IdentitiesSettingsPage::save()
98 {
99     setEnabled(false);
100     QList<CertIdentity *> toCreate, toUpdate;
101     // we need to remove our temporarily created identities.
102     // these are going to be re-added after the core has propagated them back...
103     QHash<IdentityId, CertIdentity *>::iterator i = identities.begin();
104     while (i != identities.end()) {
105         if ((*i)->id() < 0) {
106             CertIdentity *temp = *i;
107             i = identities.erase(i);
108             toCreate.append(temp);
109             ui.identityList->removeItem(ui.identityList->findData(temp->id().toInt()));
110         }
111         else {
112             if (**i != *Client::identity((*i)->id()) || (*i)->isDirty()) {
113                 toUpdate.append(*i);
114             }
115             ++i;
116         }
117     }
118     SaveIdentitiesDlg dlg(toCreate, toUpdate, deletedIdentities, this);
119     int ret = dlg.exec();
120     if (ret == QDialog::Rejected) {
121         // canceled -> reload everything to be safe
122         load();
123     }
124     foreach(Identity *id, toCreate) {
125         id->deleteLater();
126     }
127     changedIdentities.clear();
128     deletedIdentities.clear();
129     setChangedState(false);
130     setEnabled(true);
131 }
132
133
134 void IdentitiesSettingsPage::load()
135 {
136     currentId = 0;
137     foreach(Identity *identity, identities.values()) {
138         identity->deleteLater();
139     }
140     identities.clear();
141     deletedIdentities.clear();
142     changedIdentities.clear();
143     ui.identityList->clear();
144     setWidgetStates();
145     foreach(IdentityId id, Client::identityIds()) {
146         clientIdentityCreated(id);
147     }
148     setChangedState(false);
149 }
150
151
152 void IdentitiesSettingsPage::widgetHasChanged()
153 {
154     bool changed = testHasChanged();
155     if (changed != hasChanged()) setChangedState(changed);
156 }
157
158
159 void IdentitiesSettingsPage::setWidgetStates()
160 {
161     bool enabled = (ui.identityList->count() > 0);
162     ui.identityEditor->setEnabled(enabled);
163     ui.renameIdentity->setEnabled(enabled);
164     ui.deleteIdentity->setEnabled(ui.identityList->count() > 1);
165 }
166
167
168 bool IdentitiesSettingsPage::testHasChanged()
169 {
170     if (deletedIdentities.count()) return true;
171     if (currentId < 0) {
172         return true; // new identity
173     }
174     else {
175         if (currentId != 0) {
176             changedIdentities.removeAll(currentId);
177             CertIdentity temp(currentId, this);
178             // we need to set the cert and key manually, as they aren't synced
179             CertIdentity *old = identities[currentId];
180             temp.setSslKey(old->sslKey());
181             temp.setSslCert(old->sslCert());
182
183             ui.identityEditor->saveToIdentity(&temp);
184             temp.setIdentityName(identities[currentId]->identityName());
185             if (temp != *Client::identity(currentId) || temp.isDirty())
186                 changedIdentities.append(currentId);
187         }
188         return changedIdentities.count();
189     }
190 }
191
192
193 bool IdentitiesSettingsPage::aboutToSave()
194 {
195     ui.identityEditor->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
215 void IdentitiesSettingsPage::clientIdentityCreated(IdentityId id)
216 {
217     CertIdentity *identity = new CertIdentity(*Client::identity(id), this);
218 #ifdef HAVE_SSL
219     identity->enableEditSsl(_editSsl);
220 #endif
221     insertIdentity(identity);
222 #ifdef HAVE_SSL
223     connect(identity, SIGNAL(sslSettingsUpdated()), this, SLOT(clientIdentityUpdated()));
224 #endif
225     connect(Client::identity(id), SIGNAL(updatedRemotely()), this, SLOT(clientIdentityUpdated()));
226 }
227
228
229 void IdentitiesSettingsPage::clientIdentityUpdated()
230 {
231     const Identity *clientIdentity = qobject_cast<Identity *>(sender());
232     if (!clientIdentity) {
233         qWarning() << "Invalid identity to update!";
234         return;
235     }
236     if (!identities.contains(clientIdentity->id())) {
237         qWarning() << "Unknown identity to update:" << clientIdentity->identityName();
238         return;
239     }
240
241     CertIdentity *identity = identities[clientIdentity->id()];
242
243     if (identity->identityName() != clientIdentity->identityName())
244         renameIdentity(identity->id(), clientIdentity->identityName());
245
246     identity->copyFrom(*clientIdentity);
247
248     if (identity->id() == currentId)
249         ui.identityEditor->displayIdentity(identity);
250 }
251
252
253 void IdentitiesSettingsPage::clientIdentityRemoved(IdentityId id)
254 {
255     if (identities.contains(id)) {
256         removeIdentity(identities[id]);
257         changedIdentities.removeAll(id);
258         deletedIdentities.removeAll(id);
259     }
260 }
261
262
263 void IdentitiesSettingsPage::insertIdentity(CertIdentity *identity)
264 {
265     IdentityId id = identity->id();
266     identities[id] = identity;
267
268     QString name = identity->identityName();
269     for (int j = 0; j < ui.identityList->count(); j++) {
270         if ((j > 0 || ui.identityList->itemData(0).toInt() != 1) && name.localeAwareCompare(ui.identityList->itemText(j)) < 0) {
271             ui.identityList->insertItem(j, name, id.toInt());
272             widgetHasChanged();
273             return;
274         }
275     }
276     // append
277     ui.identityList->insertItem(ui.identityList->count(), name, id.toInt());
278     setWidgetStates();
279     widgetHasChanged();
280 }
281
282
283 void IdentitiesSettingsPage::renameIdentity(IdentityId id, const QString &newName)
284 {
285     Identity *identity = identities[id];
286     ui.identityList->setItemText(ui.identityList->findData(identity->id().toInt()), newName);
287     identity->setIdentityName(newName);
288 }
289
290
291 void IdentitiesSettingsPage::removeIdentity(Identity *id)
292 {
293     identities.remove(id->id());
294     ui.identityList->removeItem(ui.identityList->findData(id->id().toInt()));
295     changedIdentities.removeAll(id->id());
296     if (currentId == id->id()) currentId = 0;
297     id->deleteLater();
298     setWidgetStates();
299     widgetHasChanged();
300 }
301
302
303 void IdentitiesSettingsPage::on_identityList_currentIndexChanged(int index)
304 {
305     CertIdentity *previousIdentity = 0;
306     if (currentId != 0 && identities.contains(currentId))
307         previousIdentity = identities[currentId];
308
309     if (index < 0) {
310         //ui.identityList->setEditable(false);
311         ui.identityEditor->displayIdentity(0, previousIdentity);
312         currentId = 0;
313     }
314     else {
315         IdentityId id = ui.identityList->itemData(index).toInt();
316         if (identities.contains(id)) {
317             ui.identityEditor->displayIdentity(identities[id], previousIdentity);
318             currentId = id;
319         }
320     }
321 }
322
323
324 void IdentitiesSettingsPage::on_addIdentity_clicked()
325 {
326     CreateIdentityDlg dlg(ui.identityList->model(), this);
327     if (dlg.exec() == QDialog::Accepted) {
328         // find a free (negative) ID
329         IdentityId id;
330         for (id = 1; id <= identities.count(); id++) {
331             if (!identities.keys().contains(-id.toInt())) break;
332         }
333         id = -id.toInt();
334         CertIdentity *newId = new CertIdentity(id, this);
335 #ifdef HAVE_SSL
336         newId->enableEditSsl(_editSsl);
337 #endif
338         if (dlg.duplicateId() != 0) {
339             // duplicate
340             newId->copyFrom(*identities[dlg.duplicateId()]);
341             newId->setId(id);
342         }
343         newId->setIdentityName(dlg.identityName());
344         identities[id] = newId;
345         insertIdentity(newId);
346         ui.identityList->setCurrentIndex(ui.identityList->findData(id.toInt()));
347         widgetHasChanged();
348     }
349 }
350
351
352 void IdentitiesSettingsPage::on_deleteIdentity_clicked()
353 {
354     Identity *id = identities[currentId];
355     int ret = QMessageBox::question(this, tr("Delete Identity?"),
356         tr("Do you really want to delete identity \"%1\"?").arg(id->identityName()),
357         QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
358     if (ret != QMessageBox::Yes) return;
359     if (id->id() > 0) deletedIdentities.append(id->id());
360     currentId = 0;
361     removeIdentity(id);
362 }
363
364
365 void IdentitiesSettingsPage::on_renameIdentity_clicked()
366 {
367     QString oldName = identities[currentId]->identityName();
368     bool ok = false;
369     QString name = QInputDialog::getText(this, tr("Rename Identity"),
370         tr("Please enter a new name for the identity \"%1\"!").arg(oldName),
371         QLineEdit::Normal, oldName, &ok);
372     if (ok && !name.isEmpty()) {
373         renameIdentity(currentId, name);
374         widgetHasChanged();
375     }
376 }
377
378
379 /*****************************************************************************************/
380
381 CreateIdentityDlg::CreateIdentityDlg(QAbstractItemModel *model, QWidget *parent)
382     : QDialog(parent)
383 {
384     ui.setupUi(this);
385
386     ui.identityList->setModel(model); // now we use the identity list of the main page... Trolltech <3
387     on_identityName_textChanged(""); // disable ok button :)
388 }
389
390
391 QString CreateIdentityDlg::identityName() const
392 {
393     return ui.identityName->text();
394 }
395
396
397 IdentityId CreateIdentityDlg::duplicateId() const
398 {
399     if (!ui.duplicateIdentity->isChecked()) return 0;
400     if (ui.identityList->currentIndex() >= 0) {
401         return ui.identityList->itemData(ui.identityList->currentIndex()).toInt();
402     }
403     return 0;
404 }
405
406
407 void CreateIdentityDlg::on_identityName_textChanged(const QString &text)
408 {
409     ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(text.count());
410 }
411
412
413 /*********************************************************************************************/
414
415 SaveIdentitiesDlg::SaveIdentitiesDlg(const QList<CertIdentity *> &toCreate, const QList<CertIdentity *> &toUpdate, const QList<IdentityId> &toRemove, QWidget *parent)
416     : QDialog(parent)
417 {
418     ui.setupUi(this);
419     ui.abort->setIcon(SmallIcon("dialog-cancel"));
420
421     numevents = toCreate.count() + toUpdate.count() + toRemove.count();
422     rcvevents = 0;
423     if (numevents) {
424         ui.progressBar->setMaximum(numevents);
425         ui.progressBar->setValue(0);
426
427         connect(Client::instance(), SIGNAL(identityCreated(IdentityId)), this, SLOT(clientEvent()));
428         connect(Client::instance(), SIGNAL(identityRemoved(IdentityId)), this, SLOT(clientEvent()));
429
430         foreach(CertIdentity *id, toCreate) {
431             Client::createIdentity(*id);
432         }
433         foreach(CertIdentity *id, toUpdate) {
434             const Identity *cid = Client::identity(id->id());
435             if (!cid) {
436                 qWarning() << "Invalid client identity!";
437                 numevents--;
438                 continue;
439             }
440             connect(cid, SIGNAL(updatedRemotely()), this, SLOT(clientEvent()));
441             Client::updateIdentity(id->id(), id->toVariantMap());
442 #ifdef HAVE_SSL
443             id->requestUpdateSslSettings();
444 #endif
445         }
446         foreach(IdentityId id, toRemove) {
447             Client::removeIdentity(id);
448         }
449     }
450     else {
451         qWarning() << "Sync dialog called without stuff to change!";
452         accept();
453     }
454 }
455
456
457 void SaveIdentitiesDlg::clientEvent()
458 {
459     ui.progressBar->setValue(++rcvevents);
460     if (rcvevents >= numevents) accept();
461 }
462
463
464 /*************************************************************************************************/
465
466 NickEditDlg::NickEditDlg(const QString &old, const QStringList &exist, QWidget *parent)
467     : QDialog(parent), oldNick(old), existing(exist)
468 {
469     ui.setupUi(this);
470
471     // define a regexp for valid nicknames
472     // TODO: add max nicklength according to ISUPPORT
473     QString letter = "A-Za-z";
474     QString special = "\x5b-\x60\x7b-\x7d";
475     QRegExp rx(QString("[%1%2][%1%2\\d-]*").arg(letter, special));
476     ui.nickEdit->setValidator(new QRegExpValidator(rx, ui.nickEdit));
477     if (old.isEmpty()) {
478         // new nick
479         setWindowTitle(tr("Add Nickname"));
480         on_nickEdit_textChanged(""); // disable ok button
481     }
482     else ui.nickEdit->setText(old);
483 }
484
485
486 QString NickEditDlg::nick() const
487 {
488     return ui.nickEdit->text();
489 }
490
491
492 void NickEditDlg::on_nickEdit_textChanged(const QString &text)
493 {
494     ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(text.isEmpty() || existing.contains(text));
495 }