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