Added fibration feedback feature.
[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(m_indicatorButton, SIGNAL(draggingModeTriggered()),
193             this, SIGNAL(draggingModeTriggered()));
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     connect(m_zoomButtonPanel, SIGNAL(draggingModeTriggered()),
397             this, SIGNAL(draggingModeTriggered()));
398 }
399
400 void MainWindow::clearCookieJar()
401 {
402     qDebug() << __PRETTY_FUNCTION__;
403
404     buildWebView();
405
406     m_webView->stop();
407
408     if(!m_cookieJar) {
409         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
410     }
411     QList<QNetworkCookie> emptyList;
412     emptyList.clear();
413
414     m_cookieJar->setAllCookies(emptyList);
415     m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
416 }
417
418 void MainWindow::createMenus()
419 {
420     qDebug() << __PRETTY_FUNCTION__;
421
422     // login/logout
423     m_loginAct = new QAction(tr("Login"), this);
424     connect(m_loginAct, SIGNAL(triggered()),
425             this, SIGNAL(loginActionPressed()));
426
427     // settings
428     m_toSettingsAct = new QAction(tr("Settings"), this);
429     connect(m_toSettingsAct, SIGNAL(triggered()),
430         this, SLOT(openSettingsDialog()));
431
432     // GPS
433     m_gpsToggleAct = new QAction(tr("GPS"), this);
434     m_gpsToggleAct->setCheckable(true);
435
436     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
437             this, SIGNAL(gpsTriggered(bool)));
438
439     /// @todo remove when not needed!
440     m_searchLocationAct = new QAction(tr("Location search"), this);
441     connect(m_searchLocationAct, SIGNAL(triggered()),
442             this, SLOT(startLocationSearch()));
443
444     // build the actual menu
445     m_viewMenu = menuBar()->addMenu(tr("Main"));
446     m_viewMenu->addAction(m_loginAct);
447     m_viewMenu->addAction(m_toSettingsAct);
448     m_viewMenu->addAction(m_gpsToggleAct);
449     m_viewMenu->addAction(m_searchLocationAct); /// @todo remove when not needed!
450     m_viewMenu->setObjectName(tr("Menu"));
451 }
452
453 void MainWindow::dialogFinished(int status)
454 {
455     qDebug() << __PRETTY_FUNCTION__;
456
457     QDialog *dialog = m_queue.takeFirst();
458     LoginDialog *loginDialog = qobject_cast<LoginDialog *>(dialog);
459     SearchDialog *searchDialog = qobject_cast<SearchDialog *>(dialog);
460     if(loginDialog) {
461         if(status != 0) {
462             buildWebView();
463             loginDialog->userInput(m_email, m_password);
464
465             QStringList urlParts;
466             urlParts.append(FACEBOOK_LOGINBASE);
467             urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
468             urlParts.append(INTERVAL1);
469             urlParts.append(SITUARE_LOGIN_SUCCESS);
470             urlParts.append(INTERVAL2);
471             urlParts.append(SITUARE_LOGIN_FAILURE);
472             urlParts.append(FACEBOOK_LOGIN_ENDING);
473
474             emit saveUsername(m_email);
475             m_refresh = true;
476             m_webView->load(QUrl(urlParts.join(EMPTY)));
477             toggleProgressIndicator(true);
478         } else {
479             emit cancelLoginProcess();
480         }
481     } else if(searchDialog) {
482         if(status != 0) {
483             emit searchForLocation(searchDialog->input());
484         }
485     }
486
487     dialog->deleteLater();
488
489     if(!m_error_queue.isEmpty() && m_errorShown == false) {
490         showErrorInformationBox();
491     } else {
492         if(!m_queue.isEmpty()) {
493             showInformationBox();
494         }
495     }
496 }
497
498 void MainWindow::drawFullScreenButton(const QSize &size)
499 {
500     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
501
502     if(m_fullScreenButton) {
503         if(m_loggedIn) {
504             m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width()
505                                      - PANEL_PEEK_AMOUNT,
506                                      size.height() - m_fullScreenButton->size().height());
507         } else {
508             m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width(),
509                                      size.height() - m_fullScreenButton->size().height());
510         }
511     }
512 }
513
514 void MainWindow::drawMapScale(const QSize &size)
515 {
516     qDebug() << __PRETTY_FUNCTION__;
517
518     const int LEFT_SCALE_MARGIN = 10;
519     const int BOTTOM_SCALE_MARGIN = 2;
520     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
521
522     m_mapScale->move(PANEL_PEEK_AMOUNT + LEFT_SCALE_MARGIN,
523                      size.height() - m_mapScale->size().height() - BOTTOM_SCALE_MARGIN);
524 }
525
526 void MainWindow::drawOsmLicense(const QSize &size)
527 {
528     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
529
530     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
531                        - PANEL_PEEK_AMOUNT,
532                        size.height() - m_osmLicense->fontMetrics().height());
533 }
534
535 void MainWindow::drawOwnLocationCrosshair(const QSize &size)
536 {
537     qDebug() << __PRETTY_FUNCTION__;
538
539     if (m_ownLocationCrosshair != 0) {
540         m_ownLocationCrosshair->move(size.width()/2 - m_ownLocationCrosshair->pixmap()->width()/2,
541                             size.height()/2 - m_ownLocationCrosshair->pixmap()->height()/2);
542     }
543 }
544
545 void MainWindow::errorDialogFinished(int status)
546 {
547     qDebug() << __PRETTY_FUNCTION__;
548
549     qDebug() << status;
550     QDialog *dialog = m_error_queue.takeFirst();
551
552     dialog->deleteLater();
553     m_errorShown = false;
554
555     if(!m_error_queue.isEmpty())
556         showErrorInformationBox();
557     else if(!m_queue.isEmpty())
558         showInformationBox();
559 }
560
561 void MainWindow::gpsTimeout()
562 {
563     qDebug() << __PRETTY_FUNCTION__;
564
565     buildInformationBox(tr("GPS timeout"));
566 }
567
568 void MainWindow::grabZoomKeys(bool grab)
569 {
570     qDebug() << __PRETTY_FUNCTION__;
571
572 #ifdef Q_WS_MAEMO_5
573     // Can't grab keys unless we have a window id
574     if (!winId())
575         return;
576
577     unsigned long val = (grab) ? 1 : 0;
578     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
579     if (!atom)
580         return;
581
582     XChangeProperty (QX11Info::display(),
583                      winId(),
584                      atom,
585                      XA_INTEGER,
586                      32,
587                      PropModeReplace,
588                      reinterpret_cast<unsigned char *>(&val),
589                      1);
590 #else
591     Q_UNUSED(grab);
592 #endif // Q_WS_MAEMO_5
593 }
594
595 void MainWindow::keyPressEvent(QKeyEvent* event)
596 {
597     qDebug() << __PRETTY_FUNCTION__;
598
599     switch (event->key()) {
600     case Qt::Key_F7:
601         event->accept();
602         emit zoomIn();
603         break;
604
605     case Qt::Key_F8:
606         event->accept();
607         emit zoomOut();
608         break;
609     }
610     QWidget::keyPressEvent(event);
611 }
612
613 void MainWindow::loadCookies()
614 {
615     qDebug() << __PRETTY_FUNCTION__;
616
617     QSettings settings(DIRECTORY_NAME, FILE_NAME);
618
619     QStringList list = settings.value(COOKIES, EMPTY).toStringList();
620
621     if(!list.isEmpty()) {
622         QList<QNetworkCookie> cookieList;
623         for(int i=0;i<list.count();i++) {
624             cookieList.append(QNetworkCookie::parseCookies(list.at(i).toAscii()));
625         }
626
627         if(!m_cookieJar)
628                m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
629
630         m_cookieJar->setAllCookies(cookieList);
631         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
632     }
633 }
634
635 void MainWindow::loadDone(bool done)
636 {
637     qDebug() << __PRETTY_FUNCTION__;
638
639     // for the first time the login page is opened, we need to refresh it to get cookies working
640     if(m_refresh) {
641         m_webView->reload();
642         m_refresh = false;
643     }
644
645     if (done)
646     {
647         QWebFrame* frame = m_webView->page()->currentFrame();
648         if (frame!=NULL)
649         {
650             // set email box
651             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
652
653             foreach (QWebElement element, emailCollection) {
654                 element.setAttribute("value", m_email.toAscii());
655             }
656             // set password box
657             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
658             foreach (QWebElement element, passwordCollection) {
659                 element.setAttribute("value", m_password.toAscii());
660             }
661             // find connect button
662             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
663             foreach (QWebElement element, buttonCollection)
664             {
665                 QPoint pos(element.geometry().center());
666
667                 // send a mouse click event to the web page
668                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
669                                    Qt::NoModifier);
670                 QApplication::sendEvent(m_webView->page(), &event0);
671                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
672                                    Qt::NoModifier);
673                 QApplication::sendEvent(m_webView->page(), &event1);
674             }
675         }
676     }
677 }
678
679 void MainWindow::loggedIn(bool logged)
680 {
681     qDebug() << __PRETTY_FUNCTION__;
682
683     m_loggedIn = logged;
684
685     if(logged) {
686         m_loginAct->setText(tr("Logout"));
687     } else {
688         clearCookieJar();
689         m_email.clear();
690         m_password.clear();
691
692         m_loginAct->setText(tr("Login"));
693     }
694     updateItemVisibility();
695 }
696
697 void MainWindow::loginFailed()
698 {
699     qDebug() << __PRETTY_FUNCTION__;
700
701     clearCookieJar();
702     startLoginProcess();
703 }
704
705 bool MainWindow::loginState()
706 {
707     qDebug() << __PRETTY_FUNCTION__;
708
709     return m_loggedIn;
710 }
711
712 void MainWindow::loginUsingCookies()
713 {
714     qDebug() << __PRETTY_FUNCTION__;
715
716     toggleProgressIndicator(true);
717
718     buildWebView();
719     loadCookies();
720
721     QStringList urlParts;
722     urlParts.append(FACEBOOK_LOGINBASE);
723     urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
724     urlParts.append(INTERVAL1);
725     urlParts.append(SITUARE_LOGIN_SUCCESS);
726     urlParts.append(INTERVAL2);
727     urlParts.append(SITUARE_LOGIN_FAILURE);
728     urlParts.append(FACEBOOK_LOGIN_ENDING);
729
730     m_webView->load(QUrl(urlParts.join(EMPTY)));
731
732 }
733
734 void MainWindow::openSettingsDialog()
735 {
736     qDebug() << __PRETTY_FUNCTION__;
737
738     SettingsDialog *settingsDialog = new SettingsDialog(this);
739     settingsDialog->enableSituareSettings((m_loggedIn && m_gpsToggleAct->isChecked()));
740     connect(settingsDialog, SIGNAL(accepted()), this, SLOT(settingsDialogAccepted()));
741
742     settingsDialog->show();
743 }
744
745 void MainWindow::readAutomaticLocationUpdateSettings()
746 {
747     qDebug() << __PRETTY_FUNCTION__;
748
749     QSettings settings(DIRECTORY_NAME, FILE_NAME);
750     bool automaticUpdateEnabled = settings.value(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false).toBool();
751     QTime automaticUpdateInterval = settings.value(SETTINGS_AUTOMATIC_UPDATE_INTERVAL, QTime())
752                                       .toTime();
753
754     if (automaticUpdateEnabled && automaticUpdateInterval.isValid()) {
755         QTime time;
756         emit enableAutomaticLocationUpdate(true, time.msecsTo(automaticUpdateInterval));
757     } else {
758         emit enableAutomaticLocationUpdate(false);
759     }
760 }
761
762 void MainWindow::queueDialog(QDialog *dialog)
763 {
764     qDebug() << __PRETTY_FUNCTION__;
765
766     // check is dialog is modal, for now all modal dialogs have hihger priority i.e. errors
767     if(dialog->isModal()) {
768         m_error_queue.append(dialog);
769     } else {
770         m_queue.append(dialog);
771     }
772
773     // show error dialog if there is only one error dialog in the queue and no error dialog is shown
774     if(m_error_queue.count() == 1 && m_errorShown == false)
775         showErrorInformationBox();
776     else if(m_queue.count() == 1 && m_errorShown == false)
777         showInformationBox();
778 }
779
780 void MainWindow::saveCookies()
781 {
782     qDebug() << __PRETTY_FUNCTION__;
783
784     if(!m_cookieJar)
785         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
786
787     QList<QNetworkCookie> cookieList = m_cookieJar->allCookies();
788     QStringList list;
789
790     for(int i=0;i<cookieList.count();i++) {
791         QNetworkCookie cookie = cookieList.at(i);
792         QByteArray byteArray = cookie.toRawForm(QNetworkCookie::Full);
793         list.append(QString(byteArray));
794     }
795     list.removeDuplicates();
796
797     QSettings settings(DIRECTORY_NAME, FILE_NAME);
798     settings.setValue(COOKIES, list);
799 }
800
801 void MainWindow::setGPSButtonEnabled(bool enabled)
802 {
803     qDebug() << __PRETTY_FUNCTION__;
804
805     m_gpsToggleAct->setChecked(enabled);
806 }
807
808 void MainWindow::setIndicatorButtonEnabled(bool enabled)
809 {
810     qDebug() << __PRETTY_FUNCTION__;
811
812     m_indicatorButton->setChecked(enabled);
813
814 }
815
816 void MainWindow::setMapViewScene(QGraphicsScene *scene)
817 {
818     qDebug() << __PRETTY_FUNCTION__;
819
820     m_mapView->setScene(scene);
821 }
822
823 void MainWindow::setOwnLocationCrosshairVisibility(bool visibility)
824 {
825     qDebug() << __PRETTY_FUNCTION__;
826
827     if (visibility) {
828         m_ownLocationCrosshair->show();
829         drawOwnLocationCrosshair(m_viewPortSize);
830     } else {
831         m_ownLocationCrosshair->hide();
832     }
833 }
834
835 void MainWindow::settingsDialogAccepted()
836 {
837     qDebug() << __PRETTY_FUNCTION__;
838
839     readAutomaticLocationUpdateSettings();
840 }
841
842 void MainWindow::setUsername(const QString &username)
843 {
844     qDebug() << __PRETTY_FUNCTION__;
845
846     m_email = username;
847 }
848
849 void MainWindow::setViewPortSize(const QSize &size)
850 {
851     qDebug() << __PRETTY_FUNCTION__;
852
853     m_viewPortSize = size;
854 }
855
856 void MainWindow::showEnableAutomaticUpdateLocationDialog(const QString &text)
857 {
858     qDebug() << __PRETTY_FUNCTION__;
859
860     m_automaticUpdateLocationDialog = new QMessageBox(QMessageBox::Question,
861                                                       tr("Automatic location update"), text,
862                                                       QMessageBox::Yes | QMessageBox::No |
863                                                       QMessageBox::Cancel, this);
864     connect(m_automaticUpdateLocationDialog, SIGNAL(finished(int)),
865             this, SLOT(automaticUpdateDialogFinished(int)));
866
867     m_automaticUpdateLocationDialog->show();
868 }
869
870 void MainWindow::toggleFullScreen()
871 {
872     qDebug() << __PRETTY_FUNCTION__;
873
874     if(windowState() == Qt::WindowNoState)
875         showFullScreen();
876     else
877         showNormal();
878 }
879
880 void MainWindow::showErrorInformationBox()
881 {
882     qDebug() << __PRETTY_FUNCTION__;
883
884     if(m_error_queue.count()) {
885         m_errorShown = true;
886         QDialog *dialog = m_error_queue.first();
887         connect(dialog, SIGNAL(finished(int)),
888                 this, SLOT(errorDialogFinished(int)));
889         dialog->show();
890     }
891 }
892
893 void MainWindow::showInformationBox()
894 {
895     qDebug() << __PRETTY_FUNCTION__;
896
897     if(m_queue.count()) {
898         QDialog *dialog = m_queue.first();
899         connect(dialog, SIGNAL(finished(int)),
900                 this, SLOT(dialogFinished(int)));
901         dialog->show();
902     }
903 }
904
905 void MainWindow::showPanels()
906 {
907     qDebug() << __PRETTY_FUNCTION__;
908
909     drawFullScreenButton(m_viewPortSize);
910
911     if(m_loggedIn) {
912         if(!m_friendsListPanel->isVisible()) {
913             m_friendsListPanel->show();
914             m_friendsListPanelSidebar->show();
915         }
916
917         if(!m_userPanel->isVisible()) {
918             m_userPanel->show();
919             m_userPanelSidebar->show();
920         }
921     }
922 }
923
924 void MainWindow::startLocationSearch()
925 {
926     qDebug() << __PRETTY_FUNCTION__;
927
928     SearchDialog *searchDialog = new SearchDialog();
929     queueDialog(searchDialog);
930 }
931
932 void MainWindow::startLoginProcess()
933 {
934     qDebug() << __PRETTY_FUNCTION__;
935
936     LoginDialog *loginDialog = new LoginDialog();
937
938     emit fetchUsernameFromSettings();
939
940     loginDialog->clearTextFields();
941
942     if(!m_email.isEmpty())
943         loginDialog->setEmailField(m_email);
944
945     queueDialog(loginDialog);
946 }
947
948 void MainWindow::toggleProgressIndicator(bool value)
949 {
950     qDebug() << __PRETTY_FUNCTION__;
951
952 #ifdef Q_WS_MAEMO_5
953     if(value) {
954         m_progressIndicatorCount++;
955         setAttribute(Qt::WA_Maemo5ShowProgressIndicator, true);
956     } else {
957         if(m_progressIndicatorCount > 0)
958             m_progressIndicatorCount--;
959
960         if(m_progressIndicatorCount == 0)
961             setAttribute(Qt::WA_Maemo5ShowProgressIndicator, false);
962     }
963 #else
964     Q_UNUSED(value);
965 #endif // Q_WS_MAEMO_5
966 }
967
968 void MainWindow::updateItemVisibility()
969 {
970     qDebug() << __PRETTY_FUNCTION__;
971
972     if(!m_loggedIn) {
973         m_friendsListPanel->closePanel();
974         m_friendsListPanel->hide();
975         m_friendsListPanelSidebar->hide();
976         m_userPanel->closePanel();
977         m_userPanel->hide();
978         m_userPanelSidebar->hide();
979     }
980 }
981
982 const QString MainWindow::username()
983 {
984     qDebug() << __PRETTY_FUNCTION__;
985
986     return m_email;
987 }
988
989 void MainWindow::webViewRequestFinished(QNetworkReply *reply)
990 {
991     qDebug() << __PRETTY_FUNCTION__;
992
993     // omit QNetworkReply::OperationCanceledError due to it's nature to be called when ever
994     // qwebview starts to load a new page while the current page loading is not finished
995     if(reply->error() != QNetworkReply::OperationCanceledError &&
996        reply->error() != QNetworkReply::NoError) {
997         emit error(ErrorContext::NETWORK, reply->error());
998     }
999 }