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