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