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