Fix ALL the license headers!
[quassel.git] / src / qtui / settingspages / identitiessettingspage.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-2012 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             ui.identityEditor->saveToIdentity(&temp);
179             temp.setIdentityName(identities[currentId]->identityName());
180             if (temp != *Client::identity(currentId) || temp.isDirty())
181                 changedIdentities.append(currentId);
182         }
183         return changedIdentities.count();
184     }
185 }
186
187
188 bool IdentitiesSettingsPage::aboutToSave()
189 {
190     ui.identityEditor->saveToIdentity(identities[currentId]);
191     QList<int> errors;
192     foreach(Identity *id, identities.values()) {
193         if (id->identityName().isEmpty()) errors.append(1);
194         if (!id->nicks().count()) errors.append(2);
195         if (id->realName().isEmpty()) errors.append(3);
196         if (id->ident().isEmpty()) errors.append(4);
197     }
198     if (!errors.count()) return true;
199     QString error(tr("<b>The following problems need to be corrected before your changes can be applied:</b><ul>"));
200     if (errors.contains(1)) error += tr("<li>All identities need an identity name set</li>");
201     if (errors.contains(2)) error += tr("<li>Every identity needs at least one nickname defined</li>");
202     if (errors.contains(3)) error += tr("<li>You need to specify a real name for every identity</li>");
203     if (errors.contains(4)) error += tr("<li>You need to specify an ident for every identity</li>");
204     error += tr("</ul>");
205     QMessageBox::warning(this, tr("One or more identities are invalid"), error);
206     return false;
207 }
208
209
210 void IdentitiesSettingsPage::clientIdentityCreated(IdentityId id)
211 {
212     CertIdentity *identity = new CertIdentity(*Client::identity(id), this);
213 #ifdef HAVE_SSL
214     identity->enableEditSsl(_editSsl);
215 #endif
216     insertIdentity(identity);
217 #ifdef HAVE_SSL
218     connect(identity, SIGNAL(sslSettingsUpdated()), this, SLOT(clientIdentityUpdated()));
219 #endif
220     connect(Client::identity(id), SIGNAL(updatedRemotely()), this, SLOT(clientIdentityUpdated()));
221 }
222
223
224 void IdentitiesSettingsPage::clientIdentityUpdated()
225 {
226     const Identity *clientIdentity = qobject_cast<Identity *>(sender());
227     if (!clientIdentity) {
228         qWarning() << "Invalid identity to update!";
229         return;
230     }
231     if (!identities.contains(clientIdentity->id())) {
232         qWarning() << "Unknown identity to update:" << clientIdentity->identityName();
233         return;
234     }
235
236     CertIdentity *identity = identities[clientIdentity->id()];
237
238     if (identity->identityName() != clientIdentity->identityName())
239         renameIdentity(identity->id(), clientIdentity->identityName());
240
241     identity->copyFrom(*clientIdentity);
242
243     if (identity->id() == currentId)
244         ui.identityEditor->displayIdentity(identity);
245 }
246
247
248 void IdentitiesSettingsPage::clientIdentityRemoved(IdentityId id)
249 {
250     if (identities.contains(id)) {
251         removeIdentity(identities[id]);
252         changedIdentities.removeAll(id);
253         deletedIdentities.removeAll(id);
254     }
255 }
256
257
258 void IdentitiesSettingsPage::insertIdentity(CertIdentity *identity)
259 {
260     IdentityId id = identity->id();
261     identities[id] = identity;
262
263     QString name = identity->identityName();
264     for (int j = 0; j < ui.identityList->count(); j++) {
265         if ((j > 0 || ui.identityList->itemData(0).toInt() != 1) && name.localeAwareCompare(ui.identityList->itemText(j)) < 0) {
266             ui.identityList->insertItem(j, name, id.toInt());
267             widgetHasChanged();
268             return;
269         }
270     }
271     // append
272     ui.identityList->insertItem(ui.identityList->count(), name, id.toInt());
273     setWidgetStates();
274     widgetHasChanged();
275 }
276
277
278 void IdentitiesSettingsPage::renameIdentity(IdentityId id, const QString &newName)
279 {
280     Identity *identity = identities[id];
281     ui.identityList->setItemText(ui.identityList->findData(identity->id().toInt()), newName);
282     identity->setIdentityName(newName);
283 }
284
285
286 void IdentitiesSettingsPage::removeIdentity(Identity *id)
287 {
288     identities.remove(id->id());
289     ui.identityList->removeItem(ui.identityList->findData(id->id().toInt()));
290     changedIdentities.removeAll(id->id());
291     if (currentId == id->id()) currentId = 0;
292     id->deleteLater();
293     setWidgetStates();
294     widgetHasChanged();
295 }
296
297
298 void IdentitiesSettingsPage::on_identityList_currentIndexChanged(int index)
299 {
300     CertIdentity *previousIdentity = 0;
301     if (currentId != 0 && identities.contains(currentId))
302         previousIdentity = identities[currentId];
303
304     if (index < 0) {
305         //ui.identityList->setEditable(false);
306         ui.identityEditor->displayIdentity(0, previousIdentity);
307         currentId = 0;
308     }
309     else {
310         IdentityId id = ui.identityList->itemData(index).toInt();
311         if (identities.contains(id)) {
312             ui.identityEditor->displayIdentity(identities[id], previousIdentity);
313             currentId = id;
314         }
315     }
316 }
317
318
319 void IdentitiesSettingsPage::on_addIdentity_clicked()
320 {
321     CreateIdentityDlg dlg(ui.identityList->model(), this);
322     if (dlg.exec() == QDialog::Accepted) {
323         // find a free (negative) ID
324         IdentityId id;
325         for (id = 1; id <= identities.count(); id++) {
326             if (!identities.keys().contains(-id.toInt())) break;
327         }
328         id = -id.toInt();
329         CertIdentity *newId = new CertIdentity(id, this);
330 #ifdef HAVE_SSL
331         newId->enableEditSsl(_editSsl);
332 #endif
333         if (dlg.duplicateId() != 0) {
334             // duplicate
335             newId->copyFrom(*identities[dlg.duplicateId()]);
336             newId->setId(id);
337         }
338         newId->setIdentityName(dlg.identityName());
339         identities[id] = newId;
340         insertIdentity(newId);
341         ui.identityList->setCurrentIndex(ui.identityList->findData(id.toInt()));
342         widgetHasChanged();
343     }
344 }
345
346
347 void IdentitiesSettingsPage::on_deleteIdentity_clicked()
348 {
349     Identity *id = identities[currentId];
350     int ret = QMessageBox::question(this, tr("Delete Identity?"),
351         tr("Do you really want to delete identity \"%1\"?").arg(id->identityName()),
352         QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
353     if (ret != QMessageBox::Yes) return;
354     if (id->id() > 0) deletedIdentities.append(id->id());
355     currentId = 0;
356     removeIdentity(id);
357 }
358
359
360 void IdentitiesSettingsPage::on_renameIdentity_clicked()
361 {
362     QString oldName = identities[currentId]->identityName();
363     bool ok = false;
364     QString name = QInputDialog::getText(this, tr("Rename Identity"),
365         tr("Please enter a new name for the identity \"%1\"!").arg(oldName),
366         QLineEdit::Normal, oldName, &ok);
367     if (ok && !name.isEmpty()) {
368         renameIdentity(currentId, name);
369         widgetHasChanged();
370     }
371 }
372
373
374 /*****************************************************************************************/
375
376 CreateIdentityDlg::CreateIdentityDlg(QAbstractItemModel *model, QWidget *parent)
377     : QDialog(parent)
378 {
379     ui.setupUi(this);
380
381     ui.identityList->setModel(model); // now we use the identity list of the main page... Trolltech <3
382     on_identityName_textChanged(""); // disable ok button :)
383 }
384
385
386 QString CreateIdentityDlg::identityName() const
387 {
388     return ui.identityName->text();
389 }
390
391
392 IdentityId CreateIdentityDlg::duplicateId() const
393 {
394     if (!ui.duplicateIdentity->isChecked()) return 0;
395     if (ui.identityList->currentIndex() >= 0) {
396         return ui.identityList->itemData(ui.identityList->currentIndex()).toInt();
397     }
398     return 0;
399 }
400
401
402 void CreateIdentityDlg::on_identityName_textChanged(const QString &text)
403 {
404     ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(text.count());
405 }
406
407
408 /*********************************************************************************************/
409
410 SaveIdentitiesDlg::SaveIdentitiesDlg(const QList<CertIdentity *> &toCreate, const QList<CertIdentity *> &toUpdate, const QList<IdentityId> &toRemove, QWidget *parent)
411     : QDialog(parent)
412 {
413     ui.setupUi(this);
414     ui.abort->setIcon(SmallIcon("dialog-cancel"));
415
416     numevents = toCreate.count() + toUpdate.count() + toRemove.count();
417     rcvevents = 0;
418     if (numevents) {
419         ui.progressBar->setMaximum(numevents);
420         ui.progressBar->setValue(0);
421
422         connect(Client::instance(), SIGNAL(identityCreated(IdentityId)), this, SLOT(clientEvent()));
423         connect(Client::instance(), SIGNAL(identityRemoved(IdentityId)), this, SLOT(clientEvent()));
424
425         foreach(CertIdentity *id, toCreate) {
426             Client::createIdentity(*id);
427         }
428         foreach(CertIdentity *id, toUpdate) {
429             const Identity *cid = Client::identity(id->id());
430             if (!cid) {
431                 qWarning() << "Invalid client identity!";
432                 numevents--;
433                 continue;
434             }
435             connect(cid, SIGNAL(updatedRemotely()), this, SLOT(clientEvent()));
436             Client::updateIdentity(id->id(), id->toVariantMap());
437 #ifdef HAVE_SSL
438             id->requestUpdateSslSettings();
439 #endif
440         }
441         foreach(IdentityId id, toRemove) {
442             Client::removeIdentity(id);
443         }
444     }
445     else {
446         qWarning() << "Sync dialog called without stuff to change!";
447         accept();
448     }
449 }
450
451
452 void SaveIdentitiesDlg::clientEvent()
453 {
454     ui.progressBar->setValue(++rcvevents);
455     if (rcvevents >= numevents) accept();
456 }
457
458
459 /*************************************************************************************************/
460
461 NickEditDlg::NickEditDlg(const QString &old, const QStringList &exist, QWidget *parent)
462     : QDialog(parent), oldNick(old), existing(exist)
463 {
464     ui.setupUi(this);
465
466     // define a regexp for valid nicknames
467     // TODO: add max nicklength according to ISUPPORT
468     QString letter = "A-Za-z";
469     QString special = "\x5b-\x60\x7b-\x7d";
470     QRegExp rx(QString("[%1%2][%1%2\\d-]*").arg(letter, special));
471     ui.nickEdit->setValidator(new QRegExpValidator(rx, ui.nickEdit));
472     if (old.isEmpty()) {
473         // new nick
474         setWindowTitle(tr("Add Nickname"));
475         on_nickEdit_textChanged(""); // disable ok button
476     }
477     else ui.nickEdit->setText(old);
478 }
479
480
481 QString NickEditDlg::nick() const
482 {
483     return ui.nickEdit->text();
484 }
485
486
487 void NickEditDlg::on_nickEdit_textChanged(const QString &text)
488 {
489     ui.buttonBox->button(QDialogButtonBox::Ok)->setDisabled(text.isEmpty() || existing.contains(text));
490 }