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