Final implementation of logout
[situare] / src / ui / mainwindow.cpp
1 /*
2    Situare - A location system for Facebook
3    Copyright (C) 2010  Ixonos Plc. Authors:
4
5       Henri Lampela - henri.lampela@ixonos.com
6       Kaj Wallin - kaj.wallin@ixonos.com
7       Jussi Laitinen jussi.laitinen@ixonos.com
8       Sami Rämö - sami.ramo@ixonos.com
9
10    Situare is free software; you can redistribute it and/or
11    modify it under the terms of the GNU General Public License
12    version 2 as published by the Free Software Foundation.
13
14    Situare is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with Situare; if not, write to the Free Software
21    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
22    USA.
23 */
24
25 #include <QtGui>
26 #include <QtWebKit>
27
28 #ifdef Q_WS_MAEMO_5
29 #include <QtMaemo5/QMaemo5InformationBox>
30 #endif // Q_WS_MAEMO_5
31
32 #include "common.h"
33 #include "facebookservice/facebookauthentication.h"
34 #include "friendlistpanel.h"
35 #include "logindialog.h"
36 #include "map/mapview.h"
37 #include "settingsdialog.h"
38 #include "userinfopanel.h"
39 #include "zoombuttonpanel.h"
40
41 #include "mainwindow.h"
42
43 #include <QtGui/QX11Info>
44 #include <X11/Xlib.h>
45 #include <X11/Xatom.h>
46
47 // values for setting screen size in desktop matching N900 screen size
48 const int N900_APP_WIDTH = 800;
49 const int N900_APP_HEIGHT = 449;
50
51 MainWindow::MainWindow(QWidget *parent)
52     : QMainWindow(parent),
53     m_drawOwnLocationCrosshair(false),
54     m_loggedIn(false),
55     m_refresh(false),
56     m_email(),    
57     m_password(),
58     m_loginUrl(),
59     m_webView(0)
60 {
61     qDebug() << __PRETTY_FUNCTION__;
62
63     buildMap();
64
65     // build main layout
66     QHBoxLayout *layout = new QHBoxLayout;
67     layout->addWidget(m_mapView);
68     layout->setMargin(0);
69     setCentralWidget(new QWidget());
70     centralWidget()->setLayout(layout);
71
72     buildFriendListPanel();
73     buildUserInfoPanel();
74
75     createMenus();
76     setWindowTitle(tr("Situare"));
77
78     // set stacking order of widgets
79     m_zoomButtonPanel->stackUnder(m_userPanel);
80     m_osmLicense->stackUnder(m_zoomButtonPanel);
81     m_ownLocationCrosshair->stackUnder(m_osmLicense);
82     m_mapView->stackUnder(m_ownLocationCrosshair);
83
84     this->toggleProgressIndicator(true);
85
86     grabZoomKeys(true);
87
88     // set screen size in desktop matching N900 screen size
89     resize(N900_APP_WIDTH, N900_APP_HEIGHT);
90 }
91
92 MainWindow::~MainWindow()
93 {
94     qDebug() << __PRETTY_FUNCTION__;
95
96     grabZoomKeys(false);
97
98     if(m_webView)
99         delete m_webView;
100 }
101
102 void MainWindow::buildFriendListPanel()
103 {
104     qDebug() << __PRETTY_FUNCTION__;
105
106     m_friendsListPanel = new FriendListPanel(this);
107     m_friendsListPanelSidebar = new PanelSideBar(this, RIGHT);
108
109     m_friendsListPanel->stackUnder(m_friendsListPanelSidebar);
110
111     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
112             m_friendsListPanel, SLOT(friendInfoReceived(QList<User*>&)));
113
114     connect(m_friendsListPanel, SIGNAL(findFriend(QPointF)),
115             this, SIGNAL(findFriend(QPointF)));
116
117     connect(m_mapView, SIGNAL(viewResized(QSize)),
118             m_friendsListPanel, SLOT(screenResized(QSize)));
119
120     connect(m_mapView, SIGNAL(viewResizedNewSize(int, int)),
121             m_friendsListPanelSidebar, SLOT(reDrawSidebar(int, int)));
122 }
123
124 void MainWindow::buildManualLocationCrosshair()
125 {
126     qDebug() << __PRETTY_FUNCTION__;
127
128     m_ownLocationCrosshair = new QLabel(this);
129     QPixmap crosshairImage(":/res/images/sight.png");
130     m_ownLocationCrosshair->setPixmap(crosshairImage);
131     m_ownLocationCrosshair->setFixedSize(crosshairImage.size());
132     m_ownLocationCrosshair->hide();
133     m_ownLocationCrosshair->setAttribute(Qt::WA_TransparentForMouseEvents, true);
134
135     connect(m_mapView, SIGNAL(viewResizedNewSize(int, int)),
136             this, SLOT(drawOwnLocationCrosshair(int, int)));
137 }
138
139 void MainWindow::buildMap()
140 {
141     qDebug() << __PRETTY_FUNCTION__;
142
143     m_mapView = new MapView(this);
144
145     buildZoomButtonPanel();
146
147     m_ownLocationCrosshair = 0;
148     buildOsmLicense();
149     buildManualLocationCrosshair();
150
151     connect(m_mapView, SIGNAL(viewScrolled(QPoint)),
152             this, SIGNAL(mapViewScrolled(QPoint)));
153
154     connect(this, SIGNAL(centerToSceneCoordinates(QPoint)),
155             m_mapView, SLOT(centerToSceneCoordinates(QPoint)));
156
157     connect(m_mapView, SIGNAL(viewResized(QSize)),
158             this, SIGNAL(mapViewResized(QSize)));
159
160     connect(m_mapView, SIGNAL(viewResizedNewSize(int, int)),
161              this, SLOT(setViewPortSize(int, int)));
162
163     connect(this, SIGNAL(zoomLevelChanged(int)),
164             m_mapView, SLOT(setZoomLevel(int)));
165
166     connect(m_mapView, SIGNAL(viewZoomFinished()),
167             this, SIGNAL(viewZoomFinished()));
168 }
169
170 void MainWindow::buildOsmLicense()
171 {
172     qWarning() << __PRETTY_FUNCTION__;
173
174     m_osmLicense = new QLabel(this);
175     m_osmLicense->setAttribute(Qt::WA_TranslucentBackground, true);
176     m_osmLicense->setAttribute(Qt::WA_TransparentForMouseEvents, true);
177     m_osmLicense->setText("<font color='black'>" + OSM_LICENSE + "</font>");
178     m_osmLicense->setFont(QFont("Nokia Sans", 9));
179     m_osmLicense->resize(m_osmLicense->fontMetrics().width(OSM_LICENSE),
180                          m_osmLicense->fontMetrics().height());
181
182     connect(m_mapView, SIGNAL(viewResized(QSize)),
183             this, SLOT(drawOsmLicense(QSize)));
184 }
185
186 void MainWindow::buildUserInfoPanel()
187 {
188     qDebug() << __PRETTY_FUNCTION__;
189
190     m_userPanel = new UserInfoPanel(this);
191     m_userPanelSidebar = new PanelSideBar(this, LEFT);
192
193     m_userPanelSidebar->stackUnder(m_friendsListPanel);
194     m_userPanel->stackUnder(m_userPanelSidebar);
195
196     connect(this, SIGNAL(userLocationReady(User*)),
197             m_userPanel, SLOT(userDataReceived(User*)));
198
199     connect(m_userPanel, SIGNAL(requestReverseGeo()),
200             this, SIGNAL(requestReverseGeo()));
201
202     connect(this, SIGNAL(reverseGeoReady(QString)),
203             m_userPanel, SIGNAL(reverseGeoReady(QString)));
204
205     connect(m_userPanel, SIGNAL(statusUpdate(QString,bool)),
206             this, SIGNAL(statusUpdate(QString,bool)));
207
208     connect(m_userPanel, SIGNAL(refreshUserData()),
209             this, SIGNAL(refreshUserData()));
210
211     connect(m_mapView, SIGNAL(viewResized(QSize)),
212             m_userPanel, SLOT(screenResized(QSize)));
213 }
214
215 void MainWindow::buildZoomButtonPanel()
216 {
217     qDebug() << __PRETTY_FUNCTION__;
218
219     m_zoomButtonPanel = new ZoomButtonPanel(this, ZOOM_BUTTON_PANEL_POSITION_X,
220                                             ZOOM_BUTTON_PANEL_POSITION_Y);
221
222     connect(m_zoomButtonPanel->m_zoomInButton, SIGNAL(clicked()),
223             this, SIGNAL(zoomIn()));
224
225     connect(m_zoomButtonPanel->m_zoomOutButton, SIGNAL(clicked()),
226             this, SIGNAL(zoomOut()));
227
228     connect(this, SIGNAL(zoomLevelChanged(int)),
229             m_zoomButtonPanel, SLOT(resetButtons()));
230
231     connect(this, SIGNAL(maxZoomLevelReached()),
232             m_zoomButtonPanel, SLOT(disableZoomInButton()));
233
234     connect(this, SIGNAL(minZoomLevelReached()),
235             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
236 }
237
238 void MainWindow::createMenus()
239 {
240     qDebug() << __PRETTY_FUNCTION__;
241
242     // login/logout
243     m_loginAct = new QAction(tr("Login"), this);
244     connect(m_loginAct, SIGNAL(triggered()),
245             this, SIGNAL(loginPressed()));
246
247     // settings
248     m_toSettingsAct = new QAction(tr("Settings"), this);
249     connect(m_toSettingsAct, SIGNAL(triggered()),
250         this, SLOT(openSettingsDialog()));
251
252     // GPS
253     m_gpsToggleAct = new QAction(tr("GPS"), this);
254     m_gpsToggleAct->setCheckable(true);
255
256     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
257             this, SIGNAL(gpsTriggered(bool)));
258
259     // automatic centering
260     m_autoCenteringAct = new QAction(tr("Auto centering"), this);
261     m_autoCenteringAct->setCheckable(true);
262     connect(m_autoCenteringAct, SIGNAL(triggered(bool)),
263         this, SIGNAL(autoCenteringTriggered(bool)));
264
265     // build the actual menu
266     m_viewMenu = menuBar()->addMenu(tr("Main"));
267     m_viewMenu->addAction(m_loginAct);
268     m_viewMenu->addAction(m_toSettingsAct);
269     m_viewMenu->addAction(m_gpsToggleAct);
270     m_viewMenu->addAction(m_autoCenteringAct);
271     m_viewMenu->setObjectName(tr("Menu"));
272 }
273
274 void MainWindow::drawOsmLicense(const QSize &size)
275 {
276     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
277
278     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE) - PANEL_PEEK_AMOUNT,
279                         size.height() - m_osmLicense->fontMetrics().height());
280
281 }
282
283 void MainWindow::drawOwnLocationCrosshair(int width, int height)
284 {
285     qDebug() << __PRETTY_FUNCTION__;
286
287     if (m_drawOwnLocationCrosshair && m_ownLocationCrosshair != 0) {
288         m_ownLocationCrosshair->move(width/2 - m_ownLocationCrosshair->pixmap()->width()/2,
289                             height/2 - m_ownLocationCrosshair->pixmap()->height()/2);
290     }
291 }
292
293 void MainWindow::gpsError(const QString &message)
294 {
295     qDebug() << __PRETTY_FUNCTION__;
296
297     showMaemoInformationBox(message);
298 }
299
300 void MainWindow::gpsTimeout()
301 {
302     qDebug() << __PRETTY_FUNCTION__;
303
304     showMaemoInformationBox(tr("GPS timeout"));
305 }
306
307 void MainWindow::grabZoomKeys(bool grab)
308 {
309     qDebug() << __PRETTY_FUNCTION__;
310
311 #ifdef Q_WS_MAEMO_5
312     // Can't grab keys unless we have a window id
313     if (!winId())
314         return;
315
316     unsigned long val = (grab) ? 1 : 0;
317     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
318     if (!atom)
319         return;
320
321     XChangeProperty (QX11Info::display(),
322                      winId(),
323                      atom,
324                      XA_INTEGER,
325                      32,
326                      PropModeReplace,
327                      reinterpret_cast<unsigned char *>(&val),
328                      1);
329 #else
330     Q_UNUSED(grab);
331 #endif // Q_WS_MAEMO_5
332 }
333
334 void MainWindow::keyPressEvent(QKeyEvent* event)
335 {
336     qDebug() << __PRETTY_FUNCTION__;
337
338     switch (event->key()) {
339     case Qt::Key_F7:
340         event->accept();
341         emit zoomIn();
342         break;
343
344     case Qt::Key_F8:
345         event->accept();
346         emit zoomOut();
347         break;
348     }
349     QWidget::keyPressEvent(event);
350 }
351
352 void MainWindow::loadDone(bool done)
353 {
354     qDebug() << __PRETTY_FUNCTION__;
355
356     // for the first time the login page is opened, we need to refresh it to get cookies working
357     if(m_refresh) {
358         m_webView->reload();
359         m_refresh = false;
360     }
361
362     if (done)
363     {
364         QWebFrame* frame = m_webView->page()->currentFrame();
365         if (frame!=NULL)
366         {
367             // set email box
368             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
369
370             foreach (QWebElement element, emailCollection) {
371                 element.setAttribute("value", m_email.toAscii());
372             }
373             // set password box
374             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
375             foreach (QWebElement element, passwordCollection) {
376                 element.setAttribute("value", m_password.toAscii());
377             }
378             // find connect button
379             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
380             foreach (QWebElement element, buttonCollection)
381             {
382                 QPoint pos(element.geometry().center());
383
384                 // send a mouse click event to the web page
385                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
386                                    Qt::NoModifier);
387                 QApplication::sendEvent(m_webView->page(), &event0);
388                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
389                                    Qt::NoModifier);
390                 QApplication::sendEvent(m_webView->page(), &event1);
391             }
392         }
393     }
394 }
395
396 void MainWindow::loggedIn(bool logged)
397 {
398     qDebug() << __PRETTY_FUNCTION__;
399
400     m_loggedIn = logged;
401
402     if(logged) {
403         m_loginAct->setText(tr("Logout"));
404     }
405     else {
406         m_loginAct->setText(tr("Login"));
407     }
408     showPanels(m_loggedIn);
409 }
410
411 void MainWindow::loginDialogDone(const QString &email, const QString &password)
412 {
413     qDebug() << __PRETTY_FUNCTION__;
414
415     m_email = email;
416     m_password = password;
417 }
418
419 void MainWindow::loginFailed()
420 {
421     qDebug() << __PRETTY_FUNCTION__;
422
423     m_email.clear();
424     m_password.clear();
425
426     toggleProgressIndicator(false);
427
428 #ifdef Q_WS_MAEMO_5
429     QMaemo5InformationBox::information(this, tr("Invalid E-mail address or password"),
430                                        QMaemo5InformationBox::NoTimeout);
431
432 #endif // Q_WS_MAEMO_5
433
434     if(!m_email.isEmpty()) {
435         m_loginDialog->setEmailField(m_email);
436     }
437
438     if(m_loginDialog->exec() != QDialog::Accepted) {
439         // if login dialog was canceled we need to stop processing webview
440         // stop and disconnect m_webView;
441         m_webView->stop();
442         disconnect(m_webView, SIGNAL(loadFinished(bool)),
443                    this, SLOT(loadDone(bool)));
444         disconnect(m_webView, SIGNAL(urlChanged(const QUrl &)),
445                    this, SLOT(updateCredentials(const QUrl &)));
446
447         emit cancelLoginProcess();
448     }
449     else {
450         // re-load login page for webview
451         toggleProgressIndicator(true);
452         m_webView->load(m_loginUrl);
453     }
454 }
455
456 void MainWindow::openSettingsDialog()
457 {
458     qDebug() << __PRETTY_FUNCTION__;
459
460     SettingsDialog *dialog = new SettingsDialog(this);
461     if(!m_loggedIn) {
462         dialog->disableSituareSettings();
463     }
464     dialog->show();
465 }
466
467 void MainWindow::setAutoCenteringButtonEnabled(bool enabled)
468 {
469     qDebug() << __PRETTY_FUNCTION__;
470
471     m_autoCenteringAct->setChecked(enabled);
472 }
473
474 void MainWindow::setGPSButtonEnabled(bool enabled)
475 {
476     qDebug() << __PRETTY_FUNCTION__;
477
478     m_gpsToggleAct->setChecked(enabled);
479     setOwnLocationCrosshairVisibility(!enabled);
480     m_autoCenteringAct->setVisible(enabled);
481 }
482
483 void MainWindow::setMapViewScene(QGraphicsScene *scene)
484 {
485     qDebug() << __PRETTY_FUNCTION__;
486
487     m_mapView->setScene(scene);
488 }
489
490 void MainWindow::setOwnLocationCrosshairVisibility(bool visibility)
491 {
492     qDebug() << __PRETTY_FUNCTION__;
493
494     if (visibility) {
495         m_ownLocationCrosshair->show();
496         m_drawOwnLocationCrosshair = true;
497         drawOwnLocationCrosshair(m_viewPortWidth, m_viewPortHeight);
498     }
499     else {
500         m_ownLocationCrosshair->hide();
501         m_drawOwnLocationCrosshair = false;
502     }
503 }
504
505 void MainWindow::setUsername(const QString &username)
506 {
507     qDebug() << __PRETTY_FUNCTION__;
508     m_email = username;
509 }
510
511 void MainWindow::setViewPortSize(int width, int height)
512 {
513     qDebug() << __PRETTY_FUNCTION__;
514
515     m_viewPortWidth = width;
516     m_viewPortHeight = height;
517 }
518
519 void MainWindow::showMaemoInformationBox(const QString &message)
520 {
521     qDebug() << __PRETTY_FUNCTION__;
522
523 #ifdef Q_WS_MAEMO_5
524     QMaemo5InformationBox::information(this, message, QMaemo5InformationBox::DefaultTimeout);
525 #else
526     Q_UNUSED(message);
527 #endif
528 }
529
530 void MainWindow::showPanels(bool show)
531 {
532     qDebug() << __PRETTY_FUNCTION__;
533     if(show) {
534         m_friendsListPanel->show();
535         m_friendsListPanelSidebar->show();
536         m_userPanel->show();
537         m_userPanelSidebar->show();
538     }
539     else {
540         m_friendsListPanel->closePanel();
541         m_friendsListPanel->hide();
542         m_friendsListPanelSidebar->hide();
543         m_userPanel->closePanel();
544         m_userPanel->hide();
545         m_userPanelSidebar->hide();
546     }
547 }
548
549 void MainWindow::startLoginProcess(const QUrl &url)
550 {
551     qDebug() << __PRETTY_FUNCTION__;
552
553     m_loginUrl = url;
554     m_webView = new QWebView;
555     m_loginDialog = new LoginDialog(this);
556
557     connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
558             this, SIGNAL(updateCredentials(QUrl)));
559     connect(m_webView, SIGNAL(loadFinished(bool)),
560             this, SLOT(loadDone(bool)));
561
562     connect(m_loginDialog, SIGNAL(loginDialogDone(QString,QString)),
563             this, SLOT(loginDialogDone(QString,QString)));
564
565     m_webView->hide();
566
567     emit fetchUsernameFromSettings();
568
569     if(!m_email.isEmpty()) {
570         m_loginDialog->setEmailField(m_email);
571     }
572
573     if(m_loginDialog->exec() != QDialog::Accepted) {
574         // if login dialog was canceled we need to stop processing webview
575         // stop and disconnect m_webView;
576         m_webView->stop();
577         disconnect(m_webView, SIGNAL(loadFinished(bool)),
578                    this, SLOT(loadDone(bool)));
579         disconnect(m_webView, SIGNAL(urlChanged(const QUrl &)),
580                    this, SLOT(updateCredentials(const QUrl &)));
581
582         emit cancelLoginProcess();
583     }
584     else {
585         m_webView->load(m_loginUrl);
586         toggleProgressIndicator(true);
587         m_refresh = true;
588     }
589 }
590
591 void MainWindow::toggleProgressIndicator(bool value)
592 {
593     qDebug() << __PRETTY_FUNCTION__;
594
595 #ifdef Q_WS_MAEMO_5
596     setAttribute(Qt::WA_Maemo5ShowProgressIndicator, value);
597 #else
598     Q_UNUSED(value);
599 #endif // Q_WS_MAEMO_5
600 }
601
602 const QString MainWindow::username()
603 {
604     qDebug() << __PRETTY_FUNCTION__;
605     return m_email;
606 }