Fixed crash when joining new channels
[quassel.git] / src / qtui / coreconnectdlg.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-07 by The Quassel 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) 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 <QtGui>
22 #include "coreconnectdlg.h"
23 #include "global.h"
24 #include "client.h"
25 #include "clientsettings.h"
26
27 CoreConnectDlg::CoreConnectDlg(QWidget *parent, bool /*doAutoConnect*/) : QDialog(parent) {
28   ui.setupUi(this); //qDebug() << "new dlg";
29
30   setAttribute(Qt::WA_DeleteOnClose);
31
32   coreState = 0;
33   /* We show ui.internalCore in any case, because we might want to run as monolithic client anyway at another time
34   if(Global::runMode == Global::Monolithic) {
35     connect(ui.internalCore, SIGNAL(toggled(bool)), ui.hostEdit, SLOT(setDisabled(bool)));
36     connect(ui.internalCore, SIGNAL(toggled(bool)), ui.port, SLOT(setDisabled(bool)));
37     ui.internalCore->setChecked(true);
38   } else {
39     //ui.internalCore->hide();
40   }
41   */
42   connect(ui.newAccount, SIGNAL(clicked()), this, SLOT(createAccount()));
43   connect(ui.delAccount, SIGNAL(clicked()), this, SLOT(removeAccount()));
44   connect(ui.buttonBox1, SIGNAL(accepted()), this, SLOT(doConnect()));
45   connect(ui.hostEdit, SIGNAL(textChanged(const QString &)), this, SLOT(checkInputValid()));
46   connect(ui.userEdit, SIGNAL(textChanged(const QString &)), this, SLOT(checkInputValid()));
47   connect(ui.internalCore, SIGNAL(toggled(bool)), this, SLOT(checkInputValid()));
48   connect(ui.internalCore, SIGNAL(toggled(bool)), ui.hostEdit, SLOT(setDisabled(bool)));
49   connect(ui.internalCore, SIGNAL(toggled(bool)), ui.port, SLOT(setDisabled(bool)));
50   connect(ui.accountList, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(accountChanged(const QString &)));
51   connect(ui.autoConnect, SIGNAL(clicked(bool)), this, SLOT(autoConnectToggled(bool)));
52
53   connect(Client::instance(), SIGNAL(coreConnectionMsg(const QString &)), ui.connectionStatus, SLOT(setText(const QString &)));
54   connect(Client::instance(), SIGNAL(coreConnectionProgress(uint, uint)), this, SLOT(updateProgressBar(uint, uint)));
55   connect(Client::instance(), SIGNAL(coreConnectionError(QString)), this, SLOT(coreConnectionError(QString)));
56   connect(Client::instance(), SIGNAL(connected()), this, SLOT(coreConnected()));
57
58   AccountSettings s;
59   ui.accountList->addItems(s.knownAccounts());
60   curacc = s.lastAccount();
61   if(!ui.accountList->count()) {
62     //if(doAutoConnect) reject();
63
64     setAccountEditEnabled(false);
65     QString newacc = QInputDialog::getText(this, tr("Create Account"), tr(
66                                            "In order to connect to a Quassel Core, you need to create an account.<br>"
67                                            "Please enter a name for this account now:"), QLineEdit::Normal, tr("Default"));
68     if(!newacc.isEmpty()) {
69       ui.accountList->addItem(newacc);
70       ui.hostEdit->setText("localhost");
71       ui.port->setValue(DEFAULT_PORT);
72       ui.internalCore->setChecked(false);
73       setAccountEditEnabled(true);
74     }
75     /*
76     // FIXME We create a default account here that just connects to the internal core
77     curacc = "Default";
78     ui.accountList->addItem("Default");
79     ui.internalCore->setChecked(true);
80     ui.userEdit->setText("Default");
81     ui.passwdEdit->setText("password");
82     ui.rememberPasswd->setChecked(true);
83     accountChanged(curacc);
84     ui.passwdEdit->setText("password");
85     ui.accountList->setCurrentIndex(0);
86     ui.autoConnect->setChecked(true);
87     autoConnectToggled(true);
88     */
89   } else {
90     if(!curacc.isEmpty()) {
91       //if(doAutoConnect) { qDebug() << "auto";
92       //  AccountSettings s;
93       //  int idx = ui.accountList->findText(s.autoConnectAccount());
94       //  if(idx < 0) reject();
95       //  else {
96       //    ui.accountList->setCurrentIndex(idx);
97       //    doConnect();
98       //  }
99       //} else {
100         int idx = ui.accountList->findText(curacc);
101         ui.accountList->setCurrentIndex(idx);
102       //}
103     }
104   }
105 }
106
107 CoreConnectDlg::~CoreConnectDlg() {
108   //qDebug() << "destroy";
109 }
110
111 void CoreConnectDlg::setAccountEditEnabled(bool en) {
112   ui.accountList->setEnabled(en);
113   ui.hostEdit->setEnabled(en && !ui.internalCore->isChecked());
114   ui.userEdit->setEnabled(en);
115   ui.passwdEdit->setEnabled(en);
116   ui.port->setEnabled(en && !ui.internalCore->isChecked());
117   ui.editAccount->setEnabled(en);
118   ui.delAccount->setEnabled(en);
119   ui.internalCore->setEnabled(en);
120   ui.rememberPasswd->setEnabled(en);
121   ui.autoConnect->setEnabled(en);
122   ui.buttonBox1->button(QDialogButtonBox::Ok)->setEnabled(en && checkInputValid());
123 }
124
125 void CoreConnectDlg::accountChanged(const QString &text) {
126   AccountSettings s;
127   if(!curacc.isEmpty()) {
128     QVariantMap oldAcc;
129     oldAcc["User"] = ui.userEdit->text();
130     oldAcc["Host"] = ui.hostEdit->text();
131     oldAcc["Port"] = ui.port->value();
132     oldAcc["InternalCore"] = ui.internalCore->isChecked();
133     if(ui.rememberPasswd->isChecked()) oldAcc["Password"] = ui.passwdEdit->text();
134     s.setValue(curacc, "AccountData", oldAcc);
135   }
136   ui.autoConnect->setChecked(false);
137   if(!text.isEmpty()) { // empty text: just save stuff
138     curacc = text;
139     s.setLastAccount(curacc);
140     QVariantMap newAcc = s.value(curacc, "AccountData").toMap();
141     ui.userEdit->setText(newAcc["User"].toString());
142     ui.hostEdit->setText(newAcc["Host"].toString());
143     ui.port->setValue(newAcc["Port"].toInt());
144     ui.internalCore->setChecked(newAcc["InternalCore"].toBool());
145     if(newAcc.contains("Password")) {
146       ui.passwdEdit->setText(newAcc["Password"].toString());
147       ui.rememberPasswd->setChecked(true);
148     } else ui.rememberPasswd->setChecked(false);
149     if(s.autoConnectAccount() == curacc) ui.autoConnect->setChecked(true);
150   }
151 }
152
153 void CoreConnectDlg::autoConnectToggled(bool autoConnect) {
154   AccountSettings s;
155   if(autoConnect) s.setAutoConnectAccount(curacc);
156   else s.setAutoConnectAccount("");
157 }
158
159 bool CoreConnectDlg::checkInputValid() {
160   bool res = (ui.internalCore->isChecked() || ui.hostEdit->text().count()) && ui.userEdit->text().count();
161   ui.buttonBox1->button(QDialogButtonBox::Ok)->setEnabled(res);
162   return res;
163 }
164
165 void CoreConnectDlg::createAccount() {
166   QString accname = QInputDialog::getText(this, tr("Create Account"), tr("Please enter a name for the new account:"));
167   if(accname.isEmpty()) return;
168   if(ui.accountList->findText(accname) >= 0) {
169     QMessageBox::warning(this, tr("Account name already exists!"), tr("An account named '%1' already exists, and account names must be unique!").arg(accname));
170     return;
171   }
172   QVariantMap defdata;
173   ui.accountList->addItem(accname);
174   ui.accountList->setCurrentIndex(ui.accountList->findText(accname));
175   setAccountEditEnabled(true);
176 }
177
178 void CoreConnectDlg::removeAccount() {
179   QString acc = ui.accountList->currentText();
180   int res = QMessageBox::warning(this, tr("Delete account?"), tr("Do you really want to delete the data for the account '%1'?<br>"
181                                                        "Note that this only affects your local account settings and will not remove "
182                                                        "any data from the core.").arg(acc),
183                              QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
184   if(res == QMessageBox::Yes) {
185     AccountSettings s;
186     s.removeAccount(acc);
187     curacc = "";
188     ui.accountList->removeItem(ui.accountList->findText(acc));
189     if(!ui.accountList->count()) setAccountEditEnabled(false);
190   }
191 }
192
193 bool CoreConnectDlg::willDoInternalAutoConnect() {
194   AccountSettings s;
195   if(Global::runMode != Global::Monolithic) return false;
196   if(ui.autoConnect->isChecked() && s.autoConnectAccount() == curacc && ui.internalCore->isChecked()) {
197     return true;
198   }
199   return false;
200 }
201
202 void CoreConnectDlg::doAutoConnect() {
203   AccountSettings s;
204   if(s.autoConnectAccount() == curacc) {
205     doConnect();
206   }
207 }
208
209 void CoreConnectDlg::doConnect() {
210   accountChanged(); // save current account info
211
212   QVariantMap conninfo;
213   ui.stackedWidget->setCurrentIndex(1);
214   if(ui.internalCore->isChecked()) {
215     // FIXME
216     coreConnectionError(tr("Can't connect to internal core at the moment [serious breakage due to switch to dynamic signals]. Please check back later."));
217     return;
218     if(Global::runMode != Global::Monolithic) {
219       coreConnectionError(tr("Can't connect to internal core, since we are running as a standalone GUI!"));
220       return;
221     }
222     ui.connectionGroupBox->setTitle(tr("Connecting to internal core"));
223     ui.connectionProgress->hide();
224   } else {
225     ui.connectionGroupBox->setTitle(tr("Connecting to %1").arg(ui.hostEdit->text()));
226     conninfo["Host"] = ui.hostEdit->text();
227     conninfo["Port"] = ui.port->value();
228   }
229   conninfo["User"] = ui.userEdit->text();
230   conninfo["Password"] = ui.passwdEdit->text();
231   ui.profileLabel->hide(); ui.guiProfile->hide();
232   ui.newGuiProfile->hide(); ui.alwaysUseProfile->hide();
233   ui.connectionProgress->show();
234   try {
235     Client::instance()->connectToCore(conninfo);
236   } catch(Exception e) {
237     QString msg;
238     //if(!e.msg().isEmpty()) msg = tr("<br>%1").arg(e.msg()); // FIXME throw more detailed (vulgo: any) error msg
239     coreConnectionError(tr("Invalid user or password. Pleasy try again.%1").arg(msg));
240     //QMessageBox::warning(this, tr("Unknown account"), tr("Invalid user or password. Pleasy try again.%1").arg(msg));
241     //cancelConnect();
242     return;
243   }
244 }
245
246 void CoreConnectDlg::cancelConnect() {
247   ui.stackedWidget->setCurrentIndex(0);
248 }
249
250 void CoreConnectDlg::setStartState() { /*
251   ui.hostName->show(); ui.hostPort->show(); ui.hostLabel->show(); ui.portLabel->show();
252   ui.statusText->setText(tr("Connect to Quassel Core running on:"));
253   ui.buttonBox->button(QDialogButtonBox::Ok)->show();
254   ui.hostName->setEnabled(true); ui.hostPort->setEnabled(true);
255   ui.hostName->setSelection(0, ui.hostName->text().length()); */
256   ui.stackedWidget->setCurrentIndex(0);
257 }
258
259 void CoreConnectDlg::hostEditChanged(QString /*txt*/) {
260   //ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(txt.length());
261 }
262
263 void CoreConnectDlg::hostSelected() { /*
264   ui.hostName->hide(); ui.hostPort->hide(); ui.hostLabel->hide(); ui.portLabel->hide();
265   ui.statusText->setText(tr("Connecting to %1:%2" ).arg(ui.hostName->text()).arg(ui.hostPort->value()));
266   ui.buttonBox->button(QDialogButtonBox::Ok)->hide();
267   connect(ClientProxy::instance(), SIGNAL(coreConnected()), this, SLOT(coreConnected()));
268   connect(ClientProxy::instance(), SIGNAL(coreConnectionError(QString)), this, SLOT(coreConnectionError(QString)));
269   Client::instance()->connectToCore(ui.hostName->text(), ui.hostPort->value());
270 */
271 }
272
273 void CoreConnectDlg::coreConnected() { /*
274   ui.hostLabel->hide(); ui.hostName->hide(); ui.portLabel->hide(); ui.hostPort->hide();
275   ui.statusText->setText(tr("Synchronizing..."));
276   QSettings s;
277   s.setValue("GUI/CoreHost", ui.hostName->text());
278   s.setValue("GUI/CorePort", ui.hostPort->value());
279   s.setValue("GUI/CoreAutoConnect", ui.autoConnect->isChecked());
280   connect(ClientProxy::instance(), SIGNAL(recvPartialItem(quint32, quint32)), this, SLOT(updateProgressBar(quint32, quint32)));
281   connect(ClientProxy::instance(), SIGNAL(csCoreState(QVariant)), this, SLOT(recvCoreState(QVariant)));
282   ui.progressBar->show();
283   QVariantMap initmsg;
284   initmsg["GUIProtocol"] = GUI_PROTOCOL;
285   // FIXME guiProxy->send(GS_CLIENT_INIT, QVariant(initmsg)); */
286   ui.connectionStatus->setText(tr("Connected to core."));
287   accept();
288 }
289
290 void CoreConnectDlg::coreConnectionError(QString err) {
291   ui.stackedWidget->setCurrentIndex(0);
292   show(); // just in case we started hidden
293   QMessageBox::warning(this, tr("Connection Error"), tr("<b>Could not connect to Quassel Core!</b><br>\n") + err, QMessageBox::Retry);
294   //disconnect(ClientProxy::instance(), 0, this, 0); FIXME?
295   //ui.autoConnect->setChecked(false);
296   setStartState();
297 }
298
299 void CoreConnectDlg::updateProgressBar(uint partial, uint total) {
300   ui.connectionProgress->setMaximum(total);
301   ui.connectionProgress->setValue(partial);
302   //qDebug() << "progress:" << partial << total;
303 }
304
305 void CoreConnectDlg::recvCoreState(QVariant state) {
306   //ui.progressBar->hide();
307   coreState = state;
308   accept();
309 }
310
311 QVariant CoreConnectDlg::getCoreState() {
312   return coreState;
313 }