git Merge branch 'search_item'
[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
194 void MainWindow::buildInformationBox(const QString &message, bool modal)
195 {
196     qDebug() << __PRETTY_FUNCTION__;
197
198     QString errorMessage = message;
199
200 #ifdef Q_WS_MAEMO_5
201
202     QMaemo5InformationBox *msgBox = new QMaemo5InformationBox(this);
203
204     if(modal) {
205         msgBox->setTimeout(QMaemo5InformationBox::NoTimeout);
206         // extra line changes are needed to make error notes broader
207         errorMessage.prepend("\n");
208         errorMessage.append("\n");
209     } else {
210         msgBox->setTimeout(QMaemo5InformationBox::DefaultTimeout);
211     }
212     QLabel *label = new QLabel(msgBox);
213     label->setAlignment(Qt::AlignCenter);
214     label->setText(errorMessage);
215     msgBox->setWidget(label);
216 #else
217     QMessageBox *msgBox = new QMessageBox(this);
218     msgBox->button(QMessageBox::Ok);
219     msgBox->setText(errorMessage);
220     msgBox->setModal(modal);
221 #endif
222
223     queueDialog(msgBox);
224 }
225
226 void MainWindow::buildManualLocationCrosshair()
227 {
228     qDebug() << __PRETTY_FUNCTION__;
229
230     m_ownLocationCrosshair = new QLabel(this);
231     QPixmap crosshairImage(":/res/images/sight.png");
232     m_ownLocationCrosshair->setPixmap(crosshairImage);
233     m_ownLocationCrosshair->setFixedSize(crosshairImage.size());
234     m_ownLocationCrosshair->hide();
235     m_ownLocationCrosshair->setAttribute(Qt::WA_TransparentForMouseEvents, true);
236
237     connect(m_mapView, SIGNAL(viewResized(QSize)),
238             this, SLOT(drawOwnLocationCrosshair(QSize)));
239 }
240
241 void MainWindow::buildMap()
242 {
243     qDebug() << __PRETTY_FUNCTION__;
244
245     m_mapView = new MapView(this);
246
247     buildZoomButtonPanel();
248     buildOsmLicense();
249     buildManualLocationCrosshair();
250     buildFullScreenButton();
251     buildIndicatorButton();
252     buildMapScale();
253
254     connect(m_mapView, SIGNAL(viewScrolled(SceneCoordinate)),
255             this, SIGNAL(mapViewScrolled(SceneCoordinate)));
256
257     connect(this, SIGNAL(centerToSceneCoordinates(SceneCoordinate)),
258             m_mapView, SLOT(centerToSceneCoordinates(SceneCoordinate)));
259
260     connect(m_mapView, SIGNAL(viewResized(QSize)),
261             this, SIGNAL(mapViewResized(QSize)));
262
263     connect(m_mapView, SIGNAL(viewResized(QSize)),
264             this, SLOT(drawFullScreenButton(QSize)));
265
266     connect(m_mapView, SIGNAL(viewResized(QSize)),
267             this, SLOT(drawMapScale(QSize)));
268
269     connect(m_mapView, SIGNAL(viewResized(QSize)),
270              this, SLOT(setViewPortSize(QSize)));
271
272     connect(this, SIGNAL(zoomLevelChanged(int)),
273             m_mapView, SLOT(setZoomLevel(int)));
274
275     connect(m_mapView, SIGNAL(viewZoomFinished()),
276             this, SIGNAL(viewZoomFinished()));
277
278     connect(m_mapView, SIGNAL(zoomIn()),
279             this, SIGNAL(zoomIn()));
280 }
281
282 void MainWindow::buildMapScale()
283 {
284     m_mapScale = new MapScale(this);
285     connect(this, SIGNAL(newMapResolution(qreal)),
286             m_mapScale, SLOT(updateMapResolution(qreal)));
287 }
288
289 void MainWindow::buildOsmLicense()
290 {
291     qDebug() << __PRETTY_FUNCTION__;
292
293     m_osmLicense = new QLabel(this);
294     m_osmLicense->setAttribute(Qt::WA_TranslucentBackground, true);
295     m_osmLicense->setAttribute(Qt::WA_TransparentForMouseEvents, true);
296     m_osmLicense->setText("<font color='black'>" + OSM_LICENSE + "</font>");
297     m_osmLicense->setFont(QFont("Nokia Sans", 9));
298     m_osmLicense->resize(m_osmLicense->fontMetrics().width(OSM_LICENSE),
299                          m_osmLicense->fontMetrics().height());
300
301     connect(m_mapView, SIGNAL(viewResized(QSize)),
302             this, SLOT(drawOsmLicense(QSize)));
303 }
304
305 void MainWindow::buildUserInfoPanel()
306 {
307     qDebug() << __PRETTY_FUNCTION__;
308
309     m_userPanel = new UserInfoPanel(this);
310
311     m_userPanelSidebar = new PanelSideBar(this, LEFT);
312
313     m_userPanelSidebar->stackUnder(m_friendsListPanel);
314     m_userPanel->stackUnder(m_userPanelSidebar);
315
316     connect(this, SIGNAL(userLocationReady(User*)),
317             m_userPanel, SLOT(userDataReceived(User*)));
318
319     connect(this, SIGNAL(reverseGeoReady(QString)),
320             m_userPanel, SIGNAL(reverseGeoReady(QString)));
321
322     connect(this, SIGNAL(clearUpdateLocationDialogData()),
323             m_userPanel, SIGNAL(clearUpdateLocationDialogData()));
324
325     connect(m_mapView, SIGNAL(viewResized(QSize)),
326             m_userPanel, SLOT(resizePanel(QSize)));
327
328     connect(m_mapView, SIGNAL(viewResized(QSize)),
329             m_userPanelSidebar, SLOT(resizeSideBar(QSize)));
330
331     connect(m_userPanel, SIGNAL(findUser(GeoCoordinate)),
332             this, SIGNAL(findUser(GeoCoordinate)));
333
334     connect(m_userPanel, SIGNAL(requestReverseGeo()),
335             this, SIGNAL(requestReverseGeo()));
336
337     connect(m_userPanel, SIGNAL(statusUpdate(QString,bool)),
338             this, SIGNAL(statusUpdate(QString,bool)));
339
340     connect(m_userPanel, SIGNAL(refreshUserData()),
341             this, SIGNAL(refreshUserData()));
342
343     connect(m_userPanel, SIGNAL(notificateUpdateFailing(QString, bool)),
344             this, SLOT(buildInformationBox(QString, bool)));
345 }
346
347 void MainWindow::buildWebView()
348 {
349     qDebug() << __PRETTY_FUNCTION__;
350
351     if(!m_webView) {
352         m_webView = new QWebView;
353
354         if(!m_cookieJar)
355             m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
356
357         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
358
359         connect(m_webView->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
360                 this, SLOT(webViewRequestFinished(QNetworkReply*)));
361         connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
362                 this, SIGNAL(updateCredentials(QUrl)));
363         connect(m_webView, SIGNAL(loadFinished(bool)),
364                 this, SLOT(loadDone(bool)));
365
366         m_webView->hide();
367     }
368 }
369
370 void MainWindow::buildZoomButtonPanel()
371 {
372     qDebug() << __PRETTY_FUNCTION__;
373
374     m_zoomButtonPanel = new ZoomButtonPanel(this);
375
376     connect(m_zoomButtonPanel->zoomInButton(), SIGNAL(clicked()),
377             this, SIGNAL(zoomIn()));
378
379     connect(m_zoomButtonPanel->zoomOutButton(), SIGNAL(clicked()),
380             this, SIGNAL(zoomOut()));
381
382     connect(this, SIGNAL(zoomLevelChanged(int)),
383             m_zoomButtonPanel, SLOT(resetButtons()));
384
385     connect(this, SIGNAL(maxZoomLevelReached()),
386             m_zoomButtonPanel, SLOT(disableZoomInButton()));
387
388     connect(this, SIGNAL(minZoomLevelReached()),
389             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
390
391     connect(m_mapView, SIGNAL(viewResized(QSize)),
392             m_zoomButtonPanel, SLOT(screenResized(QSize)));
393
394 }
395
396 void MainWindow::clearCookieJar()
397 {
398     qDebug() << __PRETTY_FUNCTION__;
399
400     buildWebView();
401
402     m_webView->stop();
403
404     if(!m_cookieJar) {
405         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
406     }
407     QList<QNetworkCookie> emptyList;
408     emptyList.clear();
409
410     m_cookieJar->setAllCookies(emptyList);
411     m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
412 }
413
414 void MainWindow::createMenus()
415 {
416     qDebug() << __PRETTY_FUNCTION__;
417
418     // login/logout
419     m_loginAct = new QAction(tr("Login"), this);
420     connect(m_loginAct, SIGNAL(triggered()),
421             this, SIGNAL(loginActionPressed()));
422
423     // settings
424     m_toSettingsAct = new QAction(tr("Settings"), this);
425     connect(m_toSettingsAct, SIGNAL(triggered()),
426         this, SLOT(openSettingsDialog()));
427
428     // GPS
429     m_gpsToggleAct = new QAction(tr("GPS"), this);
430     m_gpsToggleAct->setCheckable(true);
431
432     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
433             this, SIGNAL(gpsTriggered(bool)));
434
435     /// @todo remove when not needed!
436     m_searchLocationAct = new QAction(tr("Location search"), this);
437     connect(m_searchLocationAct, SIGNAL(triggered()),
438             this, SLOT(startLocationSearch()));
439
440     // build the actual menu
441     m_viewMenu = menuBar()->addMenu(tr("Main"));
442     m_viewMenu->addAction(m_loginAct);
443     m_viewMenu->addAction(m_toSettingsAct);
444     m_viewMenu->addAction(m_gpsToggleAct);
445     m_viewMenu->addAction(m_searchLocationAct); /// @todo remove when not needed!
446     m_viewMenu->setObjectName(tr("Menu"));
447 }
448
449 void MainWindow::dialogFinished(int status)
450 {
451     qDebug() << __PRETTY_FUNCTION__;
452
453     QDialog *dialog = m_queue.takeFirst();
454     LoginDialog *loginDialog = qobject_cast<LoginDialog *>(dialog);
455     SearchDialog *searchDialog = qobject_cast<SearchDialog *>(dialog);
456     if(loginDialog) {
457         if(status != 0) {
458             buildWebView();
459             loginDialog->userInput(m_email, m_password);
460
461             QStringList urlParts;
462             urlParts.append(FACEBOOK_LOGINBASE);
463             urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
464             urlParts.append(INTERVAL1);
465             urlParts.append(SITUARE_LOGIN_SUCCESS);
466             urlParts.append(INTERVAL2);
467             urlParts.append(SITUARE_LOGIN_FAILURE);
468             urlParts.append(FACEBOOK_LOGIN_ENDING);
469
470             emit saveUsername(m_email);
471             m_refresh = true;
472             m_webView->load(QUrl(urlParts.join(EMPTY)));
473             toggleProgressIndicator(true);
474         } else {
475             emit cancelLoginProcess();
476         }
477     } else if(searchDialog) {
478         if(status != 0) {
479             emit searchForLocation(searchDialog->input());
480         }
481     }
482
483     dialog->deleteLater();
484
485     if(!m_error_queue.isEmpty() && m_errorShown == false) {
486         showErrorInformationBox();
487     } else {
488         if(!m_queue.isEmpty()) {
489             showInformationBox();
490         }
491     }
492 }
493
494 void MainWindow::drawFullScreenButton(const QSize &size)
495 {
496     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
497
498     if(m_fullScreenButton) {
499         if(m_loggedIn) {
500             m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width()
501                                      - PANEL_PEEK_AMOUNT,
502                                      size.height() - m_fullScreenButton->size().height());
503         } else {
504             m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width(),
505                                      size.height() - m_fullScreenButton->size().height());
506         }
507     }
508 }
509
510 void MainWindow::drawMapScale(const QSize &size)
511 {
512     qDebug() << __PRETTY_FUNCTION__;
513
514     const int LEFT_SCALE_MARGIN = 10;
515     const int BOTTOM_SCALE_MARGIN = 2;
516     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
517
518     m_mapScale->move(PANEL_PEEK_AMOUNT + LEFT_SCALE_MARGIN,
519                      size.height() - m_mapScale->size().height() - BOTTOM_SCALE_MARGIN);
520 }
521
522 void MainWindow::drawOsmLicense(const QSize &size)
523 {
524     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
525
526     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
527                        - PANEL_PEEK_AMOUNT,
528                        size.height() - m_osmLicense->fontMetrics().height());
529 }
530
531 void MainWindow::drawOwnLocationCrosshair(const QSize &size)
532 {
533     qDebug() << __PRETTY_FUNCTION__;
534
535     if (m_drawOwnLocationCrosshair && m_ownLocationCrosshair != 0) {
536         m_ownLocationCrosshair->move(size.width()/2 - m_ownLocationCrosshair->pixmap()->width()/2,
537                             size.height()/2 - m_ownLocationCrosshair->pixmap()->height()/2);
538     }
539 }
540
541 void MainWindow::errorDialogFinished(int status)
542 {
543     qDebug() << __PRETTY_FUNCTION__;
544
545     qDebug() << status;
546     QDialog *dialog = m_error_queue.takeFirst();
547
548     dialog->deleteLater();
549     m_errorShown = false;
550
551     if(!m_error_queue.isEmpty())
552         showErrorInformationBox();
553     else if(!m_queue.isEmpty())
554         showInformationBox();
555 }
556
557 void MainWindow::gpsTimeout()
558 {
559     qDebug() << __PRETTY_FUNCTION__;
560
561     buildInformationBox(tr("GPS timeout"));
562 }
563
564 void MainWindow::grabZoomKeys(bool grab)
565 {
566     qDebug() << __PRETTY_FUNCTION__;
567
568 #ifdef Q_WS_MAEMO_5
569     // Can't grab keys unless we have a window id
570     if (!winId())
571         return;
572
573     unsigned long val = (grab) ? 1 : 0;
574     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
575     if (!atom)
576         return;
577
578     XChangeProperty (QX11Info::display(),
579                      winId(),
580                      atom,
581                      XA_INTEGER,
582                      32,
583                      PropModeReplace,
584                      reinterpret_cast<unsigned char *>(&val),
585                      1);
586 #else
587     Q_UNUSED(grab);
588 #endif // Q_WS_MAEMO_5
589 }
590
591 void MainWindow::keyPressEvent(QKeyEvent* event)
592 {
593     qDebug() << __PRETTY_FUNCTION__;
594
595     switch (event->key()) {
596     case Qt::Key_F7:
597         event->accept();
598         emit zoomIn();
599         break;
600
601     case Qt::Key_F8:
602         event->accept();
603         emit zoomOut();
604         break;
605     }
606     QWidget::keyPressEvent(event);
607 }
608
609 void MainWindow::loadCookies()
610 {
611     qDebug() << __PRETTY_FUNCTION__;
612
613     QSettings settings(DIRECTORY_NAME, FILE_NAME);
614
615     QStringList list = settings.value(COOKIES, EMPTY).toStringList();
616
617     if(!list.isEmpty()) {
618         QList<QNetworkCookie> cookieList;
619         for(int i=0;i<list.count();i++) {
620             cookieList.append(QNetworkCookie::parseCookies(list.at(i).toAscii()));
621         }
622
623         if(!m_cookieJar)
624                m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
625
626         m_cookieJar->setAllCookies(cookieList);
627         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
628     }
629 }
630
631 void MainWindow::loadDone(bool done)
632 {
633     qDebug() << __PRETTY_FUNCTION__;
634
635     // for the first time the login page is opened, we need to refresh it to get cookies working
636     if(m_refresh) {
637         m_webView->reload();
638         m_refresh = false;
639     }
640
641     if (done)
642     {
643         QWebFrame* frame = m_webView->page()->currentFrame();
644         if (frame!=NULL)
645         {
646             // set email box
647             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
648
649             foreach (QWebElement element, emailCollection) {
650                 element.setAttribute("value", m_email.toAscii());
651             }
652             // set password box
653             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
654             foreach (QWebElement element, passwordCollection) {
655                 element.setAttribute("value", m_password.toAscii());
656             }
657             // find connect button
658             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
659             foreach (QWebElement element, buttonCollection)
660             {
661                 QPoint pos(element.geometry().center());
662
663                 // send a mouse click event to the web page
664                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
665                                    Qt::NoModifier);
666                 QApplication::sendEvent(m_webView->page(), &event0);
667                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
668                                    Qt::NoModifier);
669                 QApplication::sendEvent(m_webView->page(), &event1);
670             }
671         }
672     }
673 }
674
675 void MainWindow::loggedIn(bool logged)
676 {
677     qDebug() << __PRETTY_FUNCTION__;
678
679     m_loggedIn = logged;
680
681     if(logged) {
682         m_loginAct->setText(tr("Logout"));
683     } else {
684         clearCookieJar();
685         m_email.clear();
686         m_password.clear();
687
688         m_loginAct->setText(tr("Login"));
689     }
690     updateItemVisibility();
691 }
692
693 void MainWindow::loginFailed()
694 {
695     qDebug() << __PRETTY_FUNCTION__;
696
697     clearCookieJar();
698     startLoginProcess();
699 }
700
701 bool MainWindow::loginState()
702 {
703     qDebug() << __PRETTY_FUNCTION__;
704
705     return m_loggedIn;
706 }
707
708 void MainWindow::loginUsingCookies()
709 {
710     qDebug() << __PRETTY_FUNCTION__;
711
712     toggleProgressIndicator(true);
713
714     buildWebView();
715     loadCookies();
716
717     QStringList urlParts;
718     urlParts.append(FACEBOOK_LOGINBASE);
719     urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
720     urlParts.append(INTERVAL1);
721     urlParts.append(SITUARE_LOGIN_SUCCESS);
722     urlParts.append(INTERVAL2);
723     urlParts.append(SITUARE_LOGIN_FAILURE);
724     urlParts.append(FACEBOOK_LOGIN_ENDING);
725
726     m_webView->load(QUrl(urlParts.join(EMPTY)));
727
728 }
729
730 void MainWindow::openSettingsDialog()
731 {
732     qDebug() << __PRETTY_FUNCTION__;
733
734     SettingsDialog *settingsDialog = new SettingsDialog(this);
735     settingsDialog->enableSituareSettings((m_loggedIn && m_gpsToggleAct->isChecked()));
736     connect(settingsDialog, SIGNAL(accepted()), this, SLOT(settingsDialogAccepted()));
737
738     settingsDialog->show();
739 }
740
741 void MainWindow::readAutomaticLocationUpdateSettings()
742 {
743     qDebug() << __PRETTY_FUNCTION__;
744
745     QSettings settings(DIRECTORY_NAME, FILE_NAME);
746     bool automaticUpdateEnabled = settings.value(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false).toBool();
747     QTime automaticUpdateInterval = settings.value(SETTINGS_AUTOMATIC_UPDATE_INTERVAL, QTime())
748                                       .toTime();
749
750     if (automaticUpdateEnabled && automaticUpdateInterval.isValid()) {
751         QTime time;
752         emit enableAutomaticLocationUpdate(true, time.msecsTo(automaticUpdateInterval));
753     } else {
754         emit enableAutomaticLocationUpdate(false);
755     }
756 }
757
758 void MainWindow::queueDialog(QDialog *dialog)
759 {
760     qDebug() << __PRETTY_FUNCTION__;
761
762     // check is dialog is modal, for now all modal dialogs have hihger priority i.e. errors
763     if(dialog->isModal()) {
764         m_error_queue.append(dialog);
765     } else {
766         m_queue.append(dialog);
767     }
768
769     // show error dialog if there is only one error dialog in the queue and no error dialog is shown
770     if(m_error_queue.count() == 1 && m_errorShown == false)
771         showErrorInformationBox();
772     else if(m_queue.count() == 1 && m_errorShown == false)
773         showInformationBox();
774 }
775
776 void MainWindow::saveCookies()
777 {
778     qDebug() << __PRETTY_FUNCTION__;
779
780     if(!m_cookieJar)
781         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
782
783     QList<QNetworkCookie> cookieList = m_cookieJar->allCookies();
784     QStringList list;
785
786     for(int i=0;i<cookieList.count();i++) {
787         QNetworkCookie cookie = cookieList.at(i);
788         QByteArray byteArray = cookie.toRawForm(QNetworkCookie::Full);
789         list.append(QString(byteArray));
790     }
791     list.removeDuplicates();
792
793     QSettings settings(DIRECTORY_NAME, FILE_NAME);
794     settings.setValue(COOKIES, list);
795 }
796
797 void MainWindow::setGPSButtonEnabled(bool enabled)
798 {
799     qDebug() << __PRETTY_FUNCTION__;
800
801     m_gpsToggleAct->setChecked(enabled);
802
803     setOwnLocationCrosshairVisibility(!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 && m_loggedIn) {
826         m_ownLocationCrosshair->show();
827         m_drawOwnLocationCrosshair = true;
828         drawOwnLocationCrosshair(m_viewPortSize);
829     } else {
830         m_ownLocationCrosshair->hide();
831         m_drawOwnLocationCrosshair = false;
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
974         if(!m_gpsToggleAct->isChecked())
975             setOwnLocationCrosshairVisibility(true);
976     } else {
977         m_friendsListPanel->closePanel();
978         m_friendsListPanel->hide();
979         m_friendsListPanelSidebar->hide();
980         m_userPanel->closePanel();
981         m_userPanel->hide();
982         m_userPanelSidebar->hide();
983         setOwnLocationCrosshairVisibility(false);
984     }
985 }
986
987 const QString MainWindow::username()
988 {
989     qDebug() << __PRETTY_FUNCTION__;
990
991     return m_email;
992 }
993
994 void MainWindow::webViewRequestFinished(QNetworkReply *reply)
995 {
996     qDebug() << __PRETTY_FUNCTION__;
997
998     // omit QNetworkReply::OperationCanceledError due to it's nature to be called when ever
999     // qwebview starts to load a new page while the current page loading is not finished
1000     if(reply->error() != QNetworkReply::OperationCanceledError &&
1001        reply->error() != QNetworkReply::NoError) {
1002         emit error(ErrorContext::NETWORK, reply->error());
1003     }
1004 }