Fixed login bug when trying to login with expired cookies
[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       Ville Tiensuu - ville.tiensuu@ixonos.com
10
11    Situare is free software; you can redistribute it and/or
12    modify it under the terms of the GNU General Public License
13    version 2 as published by the Free Software Foundation.
14
15    Situare is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with Situare; if not, write to the Free Software
22    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
23    USA.
24 */
25
26 #include <QtGui>
27 #include <QtWebKit>
28 #include <QtAlgorithms>
29
30 #include "common.h"
31 #include "facebookservice/facebookauthentication.h"
32 #include "friendlistpanel.h"
33 #include "logindialog.h"
34 #include "map/mapview.h"
35 #include "settingsdialog.h"
36 #include "userinfopanel.h"
37 #include "zoombuttonpanel.h"
38 #include "mapscale.h"
39
40 #include "mainwindow.h"
41
42 // These MUST BE HERE, compiling for Maemo fails if moved
43 #ifdef Q_WS_MAEMO_5
44 #include <QtMaemo5/QMaemo5InformationBox>
45 #include <QtGui/QX11Info>
46 #include <X11/Xatom.h>
47 #include <X11/Xlib.h>
48 #endif // Q_WS_MAEMO_5
49
50 // values for setting screen size in desktop matching N900 screen size
51 const int N900_APP_WIDTH = 800;
52 const int N900_APP_HEIGHT = 449;
53
54 MainWindow::MainWindow(QWidget *parent)
55     : QMainWindow(parent),
56     m_drawOwnLocationCrosshair(false),
57     m_errorShown(false),
58     m_loggedIn(false),
59     m_refresh(false),
60     m_ownLocationCrosshair(0),
61     m_email(),    
62     m_password(),
63     m_fullScreenButton(0),
64     m_webView(0),
65     m_mapScale(0),
66     m_cookieJar(0)
67 {
68     qDebug() << __PRETTY_FUNCTION__;
69
70     buildMap();
71
72     // build main layout
73     QHBoxLayout *layout = new QHBoxLayout;
74     layout->addWidget(m_mapView);
75     layout->setMargin(0);
76     setCentralWidget(new QWidget());
77     centralWidget()->setLayout(layout);
78
79     buildFriendListPanel();
80     buildUserInfoPanel();
81
82     m_settingsDialog = new SettingsDialog(this);
83     m_settingsDialog->hide();
84     connect(m_settingsDialog, SIGNAL(enableAutomaticLocationUpdate(bool,int)),
85             this, SIGNAL(enableAutomaticLocationUpdate(bool,int)));
86     m_automaticUpdateLocationDialog = new QMessageBox(QMessageBox::Question,
87                                                       tr("Automatic location update"), "",
88                                                       QMessageBox::Yes | QMessageBox::No |
89                                                       QMessageBox::Cancel, this);
90     connect(m_automaticUpdateLocationDialog, SIGNAL(finished(int)),
91             this, SLOT(automaticUpdateDialogFinished(int)));
92
93     createMenus();
94     setWindowTitle(tr("Situare"));
95
96     // set stacking order of widgets
97     m_zoomButtonPanel->stackUnder(m_userPanel);
98     if(m_fullScreenButton) {
99         m_fullScreenButton->stackUnder(m_zoomButtonPanel);
100         m_osmLicense->stackUnder(m_fullScreenButton);
101     } else {
102         m_osmLicense->stackUnder(m_zoomButtonPanel);
103     }
104     m_ownLocationCrosshair->stackUnder(m_osmLicense);
105     m_mapScale->stackUnder(m_ownLocationCrosshair);
106     m_mapView->stackUnder(m_mapScale);
107
108     this->toggleProgressIndicator(true);
109
110     grabZoomKeys(true);
111
112     // set screen size in desktop matching N900 screen size
113     resize(N900_APP_WIDTH, N900_APP_HEIGHT);
114 #ifdef Q_WS_MAEMO_5
115     setAttribute(Qt::WA_Maemo5StackedWindow);
116 #endif
117 }
118
119 MainWindow::~MainWindow()
120 {
121     qDebug() << __PRETTY_FUNCTION__;
122
123     grabZoomKeys(false);
124
125     if(m_webView)
126         delete m_webView;
127
128     qDeleteAll(m_queue.begin(), m_queue.end());
129     m_queue.clear();
130
131     qDeleteAll(m_error_queue.begin(), m_error_queue.end());
132     m_error_queue.clear();
133 }
134
135 void MainWindow::automaticUpdateDialogFinished(int result)
136 {
137     qDebug() << __PRETTY_FUNCTION__;
138
139     if (result == QMessageBox::Yes) {
140         m_settingsDialog->setAutomaticLocationUpdateSettings(true);
141         m_settingsDialog->emitAutomaticLocationUpdateSettings();
142     }
143     else {
144         m_settingsDialog->setAutomaticLocationUpdateSettings(false);
145         m_settingsDialog->emitAutomaticLocationUpdateSettings();
146     }
147 }
148
149 void MainWindow::buildFullScreenButton()
150 {
151     qDebug() << __PRETTY_FUNCTION__;
152 #ifdef Q_WS_MAEMO_5
153     m_fullScreenButton = new QToolButton(this);
154     m_fullScreenButton->setIcon(QIcon::fromTheme(QLatin1String("general_fullsize")));
155     m_fullScreenButton->setFixedSize(m_fullScreenButton->sizeHint());
156     connect(m_fullScreenButton, SIGNAL(clicked()),
157             this, SLOT(toggleFullScreen()));
158 #endif // Q_WS_MAEMO_5
159
160 }
161
162 void MainWindow::buildFriendListPanel()
163 {
164     qDebug() << __PRETTY_FUNCTION__;
165
166     m_friendsListPanel = new FriendListPanel(this);
167     m_friendsListPanelSidebar = new PanelSideBar(this, RIGHT);
168
169     m_friendsListPanel->stackUnder(m_friendsListPanelSidebar);
170
171     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
172             m_friendsListPanel, SLOT(friendInfoReceived(QList<User*>&)));
173
174     connect(m_friendsListPanel, SIGNAL(findFriend(QPointF)),
175             this, SIGNAL(findFriend(QPointF)));
176
177     connect(m_mapView, SIGNAL(viewResized(QSize)),
178             m_friendsListPanel, SLOT(screenResized(QSize)));
179
180     connect(this, SIGNAL(locationItemClicked(QList<QString>)),
181             m_friendsListPanel, SLOT(showFriendsInList(QList<QString>)));
182
183     connect(m_mapView, SIGNAL(viewResized(QSize)),
184             m_friendsListPanelSidebar, SLOT(reDrawSidebar(QSize)));
185 }
186
187 void MainWindow::buildInformationBox(const QString &message, bool modal)
188 {
189     qDebug() << __PRETTY_FUNCTION__;
190
191     QString errorMessage = message;
192
193 #ifdef Q_WS_MAEMO_5
194
195     QMaemo5InformationBox *msgBox = new QMaemo5InformationBox(this);
196
197     if(modal) {
198         msgBox->setTimeout(QMaemo5InformationBox::NoTimeout);
199         // extra line changes are needed to make error notes broader
200         errorMessage.prepend("\n");
201         errorMessage.append("\n");
202     } else {
203         msgBox->setTimeout(QMaemo5InformationBox::DefaultTimeout);
204     }
205     QLabel *label = new QLabel(msgBox);
206     label->setAlignment(Qt::AlignCenter);
207     label->setText(errorMessage);
208     msgBox->setWidget(label);
209 #else
210     QMessageBox *msgBox = new QMessageBox(this);
211     msgBox->button(QMessageBox::Ok);
212     msgBox->setText(errorMessage);
213     msgBox->setModal(modal);
214 #endif
215
216     queueDialog(msgBox);
217 }
218
219 void MainWindow::buildManualLocationCrosshair()
220 {
221     qDebug() << __PRETTY_FUNCTION__;
222
223     m_ownLocationCrosshair = new QLabel(this);
224     QPixmap crosshairImage(":/res/images/sight.png");
225     m_ownLocationCrosshair->setPixmap(crosshairImage);
226     m_ownLocationCrosshair->setFixedSize(crosshairImage.size());
227     m_ownLocationCrosshair->hide();
228     m_ownLocationCrosshair->setAttribute(Qt::WA_TransparentForMouseEvents, true);
229
230     connect(m_mapView, SIGNAL(viewResized(QSize)),
231             this, SLOT(drawOwnLocationCrosshair(QSize)));
232 }
233
234 void MainWindow::buildMap()
235 {
236     qDebug() << __PRETTY_FUNCTION__;
237
238     m_mapView = new MapView(this);
239
240     buildZoomButtonPanel();
241     buildOsmLicense();
242     buildManualLocationCrosshair();
243     buildFullScreenButton();
244     buildMapScale();
245
246     connect(m_mapView, SIGNAL(viewScrolled(QPoint)),
247             this, SIGNAL(mapViewScrolled(QPoint)));
248
249     connect(this, SIGNAL(centerToSceneCoordinates(QPoint)),
250             m_mapView, SLOT(centerToSceneCoordinates(QPoint)));
251
252     connect(m_mapView, SIGNAL(viewResized(QSize)),
253             this, SIGNAL(mapViewResized(QSize)));
254
255     connect(m_mapView, SIGNAL(viewResized(QSize)),
256             this, SLOT(drawFullScreenButton(QSize)));
257
258     connect(m_mapView, SIGNAL(viewResized(QSize)),
259             this, SLOT(drawMapScale(QSize)));
260
261     connect(m_mapView, SIGNAL(viewResized(QSize)),
262              this, SLOT(setViewPortSize(QSize)));
263
264     connect(this, SIGNAL(zoomLevelChanged(int)),
265             m_mapView, SLOT(setZoomLevel(int)));
266
267     connect(m_mapView, SIGNAL(viewZoomFinished()),
268             this, SIGNAL(viewZoomFinished()));
269 }
270
271 void MainWindow::buildMapScale()
272 {
273     m_mapScale = new MapScale(this);
274     connect(this, SIGNAL(newMapResolution(qreal)),
275             m_mapScale, SLOT(updateMapResolution(qreal)));
276 }
277
278 void MainWindow::buildOsmLicense()
279 {
280     qDebug() << __PRETTY_FUNCTION__;
281
282     m_osmLicense = new QLabel(this);
283     m_osmLicense->setAttribute(Qt::WA_TranslucentBackground, true);
284     m_osmLicense->setAttribute(Qt::WA_TransparentForMouseEvents, true);
285     m_osmLicense->setText("<font color='black'>" + OSM_LICENSE + "</font>");
286     m_osmLicense->setFont(QFont("Nokia Sans", 9));
287     m_osmLicense->resize(m_osmLicense->fontMetrics().width(OSM_LICENSE),
288                          m_osmLicense->fontMetrics().height());
289
290     connect(m_mapView, SIGNAL(viewResized(QSize)),
291             this, SLOT(drawOsmLicense(QSize)));
292 }
293
294 void MainWindow::buildUserInfoPanel()
295 {
296     qDebug() << __PRETTY_FUNCTION__;
297
298     m_userPanel = new UserInfoPanel(this);
299     m_userPanelSidebar = new PanelSideBar(this, LEFT);
300
301     m_userPanelSidebar->stackUnder(m_friendsListPanel);
302     m_userPanel->stackUnder(m_userPanelSidebar);
303
304     connect(m_userPanel, SIGNAL(findUser(QPointF)),
305             this, SIGNAL(findUser(QPointF)));
306
307     connect(this, SIGNAL(userLocationReady(User*)),
308             m_userPanel, SLOT(userDataReceived(User*)));
309
310     connect(m_userPanel, SIGNAL(requestReverseGeo()),
311             this, SIGNAL(requestReverseGeo()));
312
313     connect(this, SIGNAL(reverseGeoReady(QString)),
314             m_userPanel, SIGNAL(reverseGeoReady(QString)));
315
316     connect(m_userPanel, SIGNAL(statusUpdate(QString,bool)),
317             this, SIGNAL(statusUpdate(QString,bool)));
318
319     connect(m_userPanel, SIGNAL(refreshUserData()),
320             this, SIGNAL(refreshUserData()));
321
322     connect(m_mapView, SIGNAL(viewResized(QSize)),
323             m_userPanel, SLOT(screenResized(QSize)));
324
325     connect(this, SIGNAL(clearUpdateLocationDialogData()),
326             m_userPanel, SIGNAL(clearUpdateLocationDialogData()));
327
328     connect(this, SIGNAL(messageSendingFailed(int)),
329             m_userPanel, SIGNAL(messageSendingFailed(int)));
330
331     connect(m_userPanel, SIGNAL(notificateUpdateFailing(QString, bool)),
332             this, SLOT(buildInformationBox(QString, bool)));
333 }
334
335 void MainWindow::buildWebView()
336 {
337     qDebug() << __PRETTY_FUNCTION__;
338
339     if(!m_webView) {
340         m_webView = new QWebView;
341
342         if(!m_cookieJar)
343             m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
344
345         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
346
347         connect(m_webView->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
348                 this, SLOT(webViewRequestFinished(QNetworkReply*)));
349         connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
350                 this, SIGNAL(updateCredentials(QUrl)));
351         connect(m_webView, SIGNAL(loadFinished(bool)),
352                 this, SLOT(loadDone(bool)));
353
354         m_webView->hide();
355     }
356 }
357
358 void MainWindow::buildZoomButtonPanel()
359 {
360     qDebug() << __PRETTY_FUNCTION__;
361
362     m_zoomButtonPanel = new ZoomButtonPanel(this);
363
364     connect(m_zoomButtonPanel->zoomInButton(), SIGNAL(clicked()),
365             this, SIGNAL(zoomIn()));
366
367     connect(m_zoomButtonPanel->zoomOutButton(), SIGNAL(clicked()),
368             this, SIGNAL(zoomOut()));
369
370     connect(this, SIGNAL(zoomLevelChanged(int)),
371             m_zoomButtonPanel, SLOT(resetButtons()));
372
373     connect(this, SIGNAL(maxZoomLevelReached()),
374             m_zoomButtonPanel, SLOT(disableZoomInButton()));
375
376     connect(this, SIGNAL(minZoomLevelReached()),
377             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
378
379     connect(m_mapView, SIGNAL(viewResized(QSize)),
380             m_zoomButtonPanel, SLOT(screenResized(QSize)));
381 }
382
383 void MainWindow::clearCookieJar()
384 {
385     qDebug() << __PRETTY_FUNCTION__;
386
387     buildWebView();
388
389     m_webView->stop();
390
391     if(!m_cookieJar) {
392         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
393     }
394     QList<QNetworkCookie> emptyList;
395     emptyList.clear();
396
397     m_cookieJar->setAllCookies(emptyList);
398     m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
399 }
400
401 void MainWindow::createMenus()
402 {
403     qDebug() << __PRETTY_FUNCTION__;
404
405     // login/logout
406     m_loginAct = new QAction(tr("Login"), this);
407     connect(m_loginAct, SIGNAL(triggered()),
408             this, SIGNAL(loginActionPressed()));
409
410     // settings
411     m_toSettingsAct = new QAction(tr("Settings"), this);
412     connect(m_toSettingsAct, SIGNAL(triggered()),
413         this, SLOT(openSettingsDialog()));
414
415     // GPS
416     m_gpsToggleAct = new QAction(tr("GPS"), this);
417     m_gpsToggleAct->setCheckable(true);
418
419     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
420             this, SIGNAL(gpsTriggered(bool)));
421
422     // automatic centering
423     m_autoCenteringAct = new QAction(tr("Auto centering"), this);
424     m_autoCenteringAct->setCheckable(true);
425     connect(m_autoCenteringAct, SIGNAL(triggered(bool)),
426         this, SIGNAL(autoCenteringTriggered(bool)));
427
428     // build the actual menu
429     m_viewMenu = menuBar()->addMenu(tr("Main"));
430     m_viewMenu->addAction(m_loginAct);
431     m_viewMenu->addAction(m_toSettingsAct);
432     m_viewMenu->addAction(m_gpsToggleAct);
433     m_viewMenu->addAction(m_autoCenteringAct);
434     m_viewMenu->setObjectName(tr("Menu"));
435 }
436
437 void MainWindow::dialogFinished(int status)
438 {
439     qDebug() << __PRETTY_FUNCTION__;
440
441     QDialog *dialog = m_queue.takeFirst();
442     LoginDialog *loginDialog = qobject_cast<LoginDialog *>(dialog);
443     if(loginDialog) {
444         if(status != 0) {
445             buildWebView();
446             loginDialog->userInput(m_email, m_password);
447
448             QStringList urlParts;
449             urlParts.append(FACEBOOK_LOGINBASE);
450             urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
451             urlParts.append(INTERVAL1);
452             urlParts.append(SITUARE_LOGIN_SUCCESS);
453             urlParts.append(INTERVAL2);
454             urlParts.append(SITUARE_LOGIN_FAILURE);
455             urlParts.append(FACEBOOK_LOGIN_ENDING);
456
457             emit saveUsername(m_email);
458             m_refresh = true;
459             m_webView->load(QUrl(urlParts.join(EMPTY)));
460             toggleProgressIndicator(true);
461         } else {
462             emit cancelLoginProcess();
463         }
464     }
465
466     dialog->deleteLater();
467
468     if(!m_error_queue.isEmpty() && m_errorShown == false) {
469         showErrorInformationBox();
470     } else {
471         if(!m_queue.isEmpty()) {
472             showInformationBox();
473         }
474     }
475 }
476
477 void MainWindow::drawFullScreenButton(const QSize &size)
478 {
479     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
480
481     if(m_fullScreenButton) {
482         m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width()
483                                  - PANEL_PEEK_AMOUNT,
484                                  size.height() - m_fullScreenButton->size().height());
485     }
486 }
487
488 void MainWindow::drawMapScale(const QSize &size)
489 {
490     const int LEFT_SCALE_MARGIN = 10;
491     const int BOTTOM_SCALE_MARGIN = 2;
492     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
493
494     m_mapScale->move(PANEL_PEEK_AMOUNT + LEFT_SCALE_MARGIN,
495                      size.height() - m_mapScale->size().height() - BOTTOM_SCALE_MARGIN);
496 }
497
498 void MainWindow::drawOsmLicense(const QSize &size)
499 {
500     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
501
502     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
503                        - PANEL_PEEK_AMOUNT,
504                        size.height() - m_osmLicense->fontMetrics().height());
505 }
506
507 void MainWindow::drawOwnLocationCrosshair(const QSize &size)
508 {
509     qDebug() << __PRETTY_FUNCTION__;
510
511     if (m_drawOwnLocationCrosshair && m_ownLocationCrosshair != 0) {
512         m_ownLocationCrosshair->move(size.width()/2 - m_ownLocationCrosshair->pixmap()->width()/2,
513                             size.height()/2 - m_ownLocationCrosshair->pixmap()->height()/2);
514     }
515 }
516
517 void MainWindow::errorDialogFinished(int status)
518 {
519     qDebug() << __PRETTY_FUNCTION__;
520
521     qDebug() << status;
522     QDialog *dialog = m_error_queue.takeFirst();
523
524     dialog->deleteLater();
525     m_errorShown = false;
526
527     if(!m_error_queue.isEmpty())
528         showErrorInformationBox();
529     else if(!m_queue.isEmpty())
530         showInformationBox();
531 }
532
533 void MainWindow::gpsTimeout()
534 {
535     qDebug() << __PRETTY_FUNCTION__;
536
537     buildInformationBox(tr("GPS timeout"));
538 }
539
540 void MainWindow::grabZoomKeys(bool grab)
541 {
542     qDebug() << __PRETTY_FUNCTION__;
543
544 #ifdef Q_WS_MAEMO_5
545     // Can't grab keys unless we have a window id
546     if (!winId())
547         return;
548
549     unsigned long val = (grab) ? 1 : 0;
550     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
551     if (!atom)
552         return;
553
554     XChangeProperty (QX11Info::display(),
555                      winId(),
556                      atom,
557                      XA_INTEGER,
558                      32,
559                      PropModeReplace,
560                      reinterpret_cast<unsigned char *>(&val),
561                      1);
562 #else
563     Q_UNUSED(grab);
564 #endif // Q_WS_MAEMO_5
565 }
566
567 void MainWindow::keyPressEvent(QKeyEvent* event)
568 {
569     qDebug() << __PRETTY_FUNCTION__;
570
571     switch (event->key()) {
572     case Qt::Key_F7:
573         event->accept();
574         emit zoomIn();
575         break;
576
577     case Qt::Key_F8:
578         event->accept();
579         emit zoomOut();
580         break;
581     }
582     QWidget::keyPressEvent(event);
583 }
584
585 void MainWindow::loadCookies()
586 {
587     qDebug() << __PRETTY_FUNCTION__;
588
589     QSettings settings(DIRECTORY_NAME, FILE_NAME);
590
591     QStringList list = settings.value(COOKIES, EMPTY).toStringList();
592
593     if(!list.isEmpty()) {
594         QList<QNetworkCookie> cookieList;
595         for(int i=0;i<list.count();i++) {
596             cookieList.append(QNetworkCookie::parseCookies(list.at(i).toAscii()));
597         }
598
599         if(!m_cookieJar)
600                m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
601
602         m_cookieJar->setAllCookies(cookieList);
603         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
604
605     }
606 }
607
608 void MainWindow::loadDone(bool done)
609 {
610     qDebug() << __PRETTY_FUNCTION__;
611
612     // for the first time the login page is opened, we need to refresh it to get cookies working
613     if(m_refresh) {
614         m_webView->reload();
615         m_refresh = false;
616     }
617
618     if (done)
619     {
620         QWebFrame* frame = m_webView->page()->currentFrame();
621         if (frame!=NULL)
622         {
623             // set email box
624             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
625
626             foreach (QWebElement element, emailCollection) {
627                 element.setAttribute("value", m_email.toAscii());
628             }
629             // set password box
630             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
631             foreach (QWebElement element, passwordCollection) {
632                 element.setAttribute("value", m_password.toAscii());
633             }
634             // find connect button
635             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
636             foreach (QWebElement element, buttonCollection)
637             {
638                 QPoint pos(element.geometry().center());
639
640                 // send a mouse click event to the web page
641                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
642                                    Qt::NoModifier);
643                 QApplication::sendEvent(m_webView->page(), &event0);
644                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
645                                    Qt::NoModifier);
646                 QApplication::sendEvent(m_webView->page(), &event1);
647             }
648         }
649     }
650 }
651
652 void MainWindow::loggedIn(bool logged)
653 {
654     qDebug() << __PRETTY_FUNCTION__;
655
656     m_loggedIn = logged;
657
658     if(logged) {
659         m_loginAct->setText(tr("Logout"));
660     } else {
661         clearCookieJar();
662         m_email.clear();
663         m_password.clear();
664
665         m_loginAct->setText(tr("Login"));
666     }
667     updateItemVisibility(m_loggedIn);
668 }
669
670 void MainWindow::loginFailed()
671 {
672     qDebug() << __PRETTY_FUNCTION__;
673
674     clearCookieJar();
675
676     toggleProgressIndicator(false);
677
678     startLoginProcess();
679 }
680
681 void MainWindow::loginUsingCookies()
682 {
683     qDebug() << __PRETTY_FUNCTION__;
684
685     buildWebView();
686     loadCookies();
687     
688     QStringList urlParts;
689     urlParts.append(FACEBOOK_LOGINBASE);
690     urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
691     urlParts.append(INTERVAL1);
692     urlParts.append(SITUARE_LOGIN_SUCCESS);
693     urlParts.append(INTERVAL2);
694     urlParts.append(SITUARE_LOGIN_FAILURE);
695     urlParts.append(FACEBOOK_LOGIN_ENDING);
696
697     m_webView->load(QUrl(urlParts.join(EMPTY)));
698
699 }
700
701 void MainWindow::openSettingsDialog()
702 {
703     qDebug() << __PRETTY_FUNCTION__;
704
705     m_settingsDialog->enableSituareSettings(m_gpsToggleAct->isChecked() && m_loggedIn);
706     m_settingsDialog->readSettings();
707     m_settingsDialog->show();
708 }
709
710 void MainWindow::requestAutomaticLocationUpdateSettings()
711 {
712     qDebug() << __PRETTY_FUNCTION__;
713
714     m_settingsDialog->readSettings();
715     m_settingsDialog->emitAutomaticLocationUpdateSettings();
716 }
717
718 void MainWindow::queueDialog(QDialog *dialog)
719 {
720     qDebug() << __PRETTY_FUNCTION__;
721
722     // check is dialog is modal, for now all modal dialogs have hihger priority i.e. errors
723     if(dialog->isModal()) {
724         m_error_queue.append(dialog);
725     } else {
726         m_queue.append(dialog);
727     }
728
729     // show error dialog if there is only one error dialog in the queue and no error dialog is shown
730     if(m_error_queue.count() == 1 && m_errorShown == false)
731         showErrorInformationBox();
732     else if(m_queue.count() == 1 && m_errorShown == false)
733         showInformationBox();
734 }
735
736 void MainWindow::saveCookies()
737 {
738     qDebug() << __PRETTY_FUNCTION__;
739
740     if(!m_cookieJar)
741         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
742
743     QList<QNetworkCookie> cookieList = m_cookieJar->allCookies();
744     QStringList list;
745
746     for(int i=0;i<cookieList.count();i++) {
747         QNetworkCookie cookie = cookieList.at(i);
748         QByteArray byteArray = cookie.toRawForm(QNetworkCookie::Full);
749         list.append(QString(byteArray));
750     }
751     list.removeDuplicates();
752
753     QSettings settings(DIRECTORY_NAME, FILE_NAME);
754     settings.setValue(COOKIES, list);
755 }
756
757 void MainWindow::setAutoCenteringButtonEnabled(bool enabled)
758 {
759     qDebug() << __PRETTY_FUNCTION__;
760
761     m_autoCenteringAct->setChecked(enabled);
762 }
763
764 void MainWindow::setGPSButtonEnabled(bool enabled)
765 {
766     qDebug() << __PRETTY_FUNCTION__;
767
768     m_gpsToggleAct->setChecked(enabled);
769
770     setOwnLocationCrosshairVisibility(!enabled);
771
772     m_autoCenteringAct->setVisible(enabled);
773 }
774
775 void MainWindow::setMapViewScene(QGraphicsScene *scene)
776 {
777     qDebug() << __PRETTY_FUNCTION__;
778
779     m_mapView->setScene(scene);
780 }
781
782 void MainWindow::setOwnLocationCrosshairVisibility(bool visibility)
783 {
784     qDebug() << __PRETTY_FUNCTION__;
785
786     if (visibility && m_loggedIn) {
787         m_ownLocationCrosshair->show();
788         m_drawOwnLocationCrosshair = true;
789         drawOwnLocationCrosshair(QSize(m_viewPortWidth, m_viewPortHeight));
790     } else {
791         m_ownLocationCrosshair->hide();
792         m_drawOwnLocationCrosshair = false;
793     }
794 }
795
796 void MainWindow::setUsername(const QString &username)
797 {
798     qDebug() << __PRETTY_FUNCTION__;
799
800     m_email = username;
801 }
802
803 void MainWindow::setViewPortSize(const QSize &size)
804 {
805     qDebug() << __PRETTY_FUNCTION__;
806
807     m_viewPortWidth = size.width();
808     m_viewPortHeight = size.height();
809 }
810
811 void MainWindow::showEnableAutomaticUpdateLocationDialog(const QString &text)
812 {
813     qDebug() << __PRETTY_FUNCTION__;
814
815     m_automaticUpdateLocationDialog->setText(text);
816     m_automaticUpdateLocationDialog->show();
817 }
818
819 void MainWindow::toggleFullScreen()
820 {
821     qDebug() << __PRETTY_FUNCTION__;
822
823     if(windowState() == Qt::WindowNoState)
824         showFullScreen();
825     else
826         showNormal();
827 }
828
829 void MainWindow::showErrorInformationBox()
830 {
831     qDebug() << __PRETTY_FUNCTION__;
832
833     if(m_error_queue.count()) {
834         m_errorShown = true;
835         QDialog *dialog = m_error_queue.first();
836         connect(dialog, SIGNAL(finished(int)),
837                 this, SLOT(errorDialogFinished(int)));
838         dialog->show();
839     }
840 }
841
842 void MainWindow::showInformationBox()
843 {
844     qDebug() << __PRETTY_FUNCTION__;
845
846     if(m_queue.count()) {
847         QDialog *dialog = m_queue.first();
848         connect(dialog, SIGNAL(finished(int)),
849                 this, SLOT(dialogFinished(int)));
850         dialog->show();
851     }
852 }
853
854 void MainWindow::startLoginProcess()
855 {
856     qDebug() << __PRETTY_FUNCTION__;
857
858     LoginDialog *loginDialog = new LoginDialog();
859
860     emit fetchUsernameFromSettings();
861
862     loginDialog->clearTextFields();
863
864     if(!m_email.isEmpty())
865         loginDialog->setEmailField(m_email);
866
867     queueDialog(loginDialog);
868 }
869
870 void MainWindow::toggleProgressIndicator(bool value)
871 {
872     qDebug() << __PRETTY_FUNCTION__;
873
874 #ifdef Q_WS_MAEMO_5
875     setAttribute(Qt::WA_Maemo5ShowProgressIndicator, value);
876 #else
877     Q_UNUSED(value);
878 #endif // Q_WS_MAEMO_5
879 }
880
881 void MainWindow::updateItemVisibility(bool show)
882 {
883     qDebug() << __PRETTY_FUNCTION__;
884     
885     if(show) {
886         m_friendsListPanel->show();
887         m_friendsListPanelSidebar->show();
888         m_userPanel->show();
889         m_userPanelSidebar->show();
890         if(!m_gpsToggleAct->isChecked())
891             setOwnLocationCrosshairVisibility(show);
892
893     } else {
894         m_friendsListPanel->closePanel();
895         m_friendsListPanel->hide();
896         m_friendsListPanelSidebar->hide();
897         m_userPanel->closePanel();
898         m_userPanel->hide();
899         m_userPanelSidebar->hide();
900         setOwnLocationCrosshairVisibility(false);
901     }
902 }
903
904 const QString MainWindow::username()
905 {
906     qDebug() << __PRETTY_FUNCTION__;
907     
908     return m_email;
909 }
910
911 void MainWindow::webViewRequestFinished(QNetworkReply *reply)
912 {
913     qDebug() << __PRETTY_FUNCTION__;
914
915     // omit QNetworkReply::OperationCanceledError due to it's nature to be called when ever
916     // qwebview starts to load a new page while the current page loading is not finished
917     if(reply->error() != QNetworkReply::OperationCanceledError &&
918        reply->error() != QNetworkReply::NoError) {
919         emit error(reply->error());
920         toggleProgressIndicator(false);
921     }
922 }
923