The first "kind of" working version of the new panels
[situare] / src / ui / mainwindow.cpp
1 /*
2    Situare - A location system for Facebook
3    Copyright (C) 2010  Ixonos Plc. Authors:
4
5       Henri Lampela - henri.lampela@ixonos.com
6       Kaj Wallin - kaj.wallin@ixonos.com
7       Jussi Laitinen jussi.laitinen@ixonos.com
8       Sami Rämö - sami.ramo@ixonos.com
9       Ville Tiensuu - ville.tiensuu@ixonos.com
10
11    Situare is free software; you can redistribute it and/or
12    modify it under the terms of the GNU General Public License
13    version 2 as published by the Free Software Foundation.
14
15    Situare is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with Situare; if not, write to the Free Software
22    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
23    USA.
24 */
25
26 #include <QtGui>
27 #include <QtWebKit>
28 #include <QtAlgorithms>
29
30 #include "facebookservice/facebookauthentication.h"
31 #include "map/mapcommon.h"
32 #include "map/mapview.h"
33 #include "common.h"
34 #include "error.h"
35 #include "friendlistpanel.h"
36 #include "fullscreenbutton.h"
37 #include "indicatorbutton.h"
38 #include "logindialog.h"
39 #include "mapscale.h"
40 #include "panelcommon.h"
41 #include "tabbedpanel.h"
42 #include "searchdialog.h"
43 #include "settingsdialog.h"
44 #include "userinfopanel.h"
45 #include "zoombuttonpanel.h"
46
47 #include "mainwindow.h"
48
49 // These MUST BE HERE, compiling for Maemo fails if moved
50 #ifdef Q_WS_MAEMO_5
51 #include <QtMaemo5/QMaemo5InformationBox>
52 #include <QtGui/QX11Info>
53 #include <X11/Xatom.h>
54 #include <X11/Xlib.h>
55 #endif // Q_WS_MAEMO_5
56
57 MainWindow::MainWindow(QWidget *parent)
58     : QMainWindow(parent),
59       m_errorShown(false),
60       m_loggedIn(false),
61       m_refresh(false),
62       m_progressIndicatorCount(0),
63       m_ownLocationCrosshair(0),
64       m_email(),
65       m_password(),
66       m_webView(0),
67       m_fullScreenButton(0),
68       m_indicatorButton(0),
69       m_mapScale(0),
70       m_cookieJar(0)
71 {
72     qDebug() << __PRETTY_FUNCTION__;
73
74     buildMap();
75
76     // build main layout
77     QHBoxLayout *layout = new QHBoxLayout;
78     layout->addWidget(m_mapView);
79     layout->setMargin(0);
80     layout->setSpacing(0);
81
82     setCentralWidget(new QWidget());
83     centralWidget()->setLayout(layout);
84
85 //    buildFriendListPanel();
86     buildUserInfoPanel();
87
88     createMenus();
89     setWindowTitle(tr("Situare"));
90
91     // set stacking order of widgets
92 //    m_zoomButtonPanel->stackUnder(m_userInfoPanel);
93     m_zoomButtonPanel->stackUnder(m_tabbedPanel);
94     if(m_fullScreenButton) {
95         m_fullScreenButton->stackUnder(m_zoomButtonPanel);
96         m_osmLicense->stackUnder(m_fullScreenButton);
97     } else {
98         m_osmLicense->stackUnder(m_zoomButtonPanel);
99     }
100     m_ownLocationCrosshair->stackUnder(m_osmLicense);
101     m_indicatorButton->stackUnder(m_ownLocationCrosshair);
102     m_mapScale->stackUnder(m_indicatorButton);
103     m_mapView->stackUnder(m_mapScale);
104
105     grabZoomKeys(true);
106
107     // Set default screen size
108     resize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT);
109 #ifdef Q_WS_MAEMO_5
110     setAttribute(Qt::WA_Maemo5StackedWindow);
111 #endif
112 }
113
114 MainWindow::~MainWindow()
115 {
116     qDebug() << __PRETTY_FUNCTION__;
117
118     grabZoomKeys(false);
119
120     if(m_webView)
121         delete m_webView;
122
123     qDeleteAll(m_queue.begin(), m_queue.end());
124     m_queue.clear();
125
126     qDeleteAll(m_error_queue.begin(), m_error_queue.end());
127     m_error_queue.clear();
128 }
129
130 void MainWindow::automaticUpdateDialogFinished(int result)
131 {
132     qDebug() << __PRETTY_FUNCTION__;
133
134     if (result == QMessageBox::Yes) {
135         readAutomaticLocationUpdateSettings();
136     } else {
137         QSettings settings(DIRECTORY_NAME, FILE_NAME);
138         settings.setValue(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false);
139         readAutomaticLocationUpdateSettings();
140     }
141
142     m_automaticUpdateLocationDialog->deleteLater();
143 }
144
145 void MainWindow::buildFullScreenButton()
146 {
147     qDebug() << __PRETTY_FUNCTION__;
148 #ifdef Q_WS_MAEMO_5
149     m_fullScreenButton = new FullScreenButton(this);
150     connect(m_fullScreenButton, SIGNAL(clicked()),
151             this, SLOT(toggleFullScreen()));
152 #endif // Q_WS_MAEMO_5
153 }
154
155 void MainWindow::buildFriendListPanel()
156 {
157     qDebug() << __PRETTY_FUNCTION__;
158
159     m_friendsListPanel = new FriendListPanel(this);
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_friendsListPanel, SIGNAL(findFriend(GeoCoordinate)),
171             this, SIGNAL(findFriend(GeoCoordinate)));
172
173     connect(this, SIGNAL(friendImageReady(User*)),
174             m_friendsListPanel, SLOT(friendImageReady(User*)));
175 }
176
177 void MainWindow::buildIndicatorButton()
178 {
179     qDebug() << __PRETTY_FUNCTION__;
180
181     m_indicatorButton = new IndicatorButton(this);
182
183     connect(m_indicatorButton, SIGNAL(autoCenteringTriggered(bool)),
184         this, SIGNAL(autoCenteringTriggered(bool)));
185
186     connect(m_mapView, SIGNAL(viewResized(QSize)),
187             m_indicatorButton, SLOT(screenResized(QSize)));
188
189     connect(m_indicatorButton, SIGNAL(draggingModeTriggered()),
190             this, SIGNAL(draggingModeTriggered()));
191 }
192
193 void MainWindow::buildInformationBox(const QString &message, bool modal)
194 {
195     qDebug() << __PRETTY_FUNCTION__;
196
197     QString errorMessage = message;
198
199 #ifdef Q_WS_MAEMO_5
200
201     QMaemo5InformationBox *msgBox = new QMaemo5InformationBox(this);
202
203     if(modal) {
204         msgBox->setTimeout(QMaemo5InformationBox::NoTimeout);
205         // extra line changes are needed to make error notes broader
206         errorMessage.prepend("\n");
207         errorMessage.append("\n");
208     } else {
209         msgBox->setTimeout(QMaemo5InformationBox::DefaultTimeout);
210     }
211     QLabel *label = new QLabel(msgBox);
212     label->setAlignment(Qt::AlignCenter);
213     label->setText(errorMessage);
214     msgBox->setWidget(label);
215 #else
216     QMessageBox *msgBox = new QMessageBox(this);
217     msgBox->button(QMessageBox::Ok);
218     msgBox->setText(errorMessage);
219     msgBox->setModal(modal);
220 #endif
221
222     queueDialog(msgBox);
223 }
224
225 void MainWindow::buildManualLocationCrosshair()
226 {
227     qDebug() << __PRETTY_FUNCTION__;
228
229     m_ownLocationCrosshair = new QLabel(this);
230     QPixmap crosshairImage(":/res/images/sight.png");
231     m_ownLocationCrosshair->setPixmap(crosshairImage);
232     m_ownLocationCrosshair->setFixedSize(crosshairImage.size());
233     m_ownLocationCrosshair->hide();
234     m_ownLocationCrosshair->setAttribute(Qt::WA_TransparentForMouseEvents, true);
235
236     connect(m_mapView, SIGNAL(viewResized(QSize)),
237             this, SLOT(drawOwnLocationCrosshair(QSize)));
238 }
239
240 void MainWindow::buildMap()
241 {
242     qDebug() << __PRETTY_FUNCTION__;
243
244     m_mapView = new MapView(this);
245
246     buildZoomButtonPanel();
247     buildOsmLicense();
248     buildManualLocationCrosshair();
249     buildFullScreenButton();
250     buildIndicatorButton();
251     buildMapScale();
252
253     connect(m_mapView, SIGNAL(viewScrolled(SceneCoordinate)),
254             this, SIGNAL(mapViewScrolled(SceneCoordinate)));
255
256     connect(this, SIGNAL(centerToSceneCoordinates(SceneCoordinate)),
257             m_mapView, SLOT(centerToSceneCoordinates(SceneCoordinate)));
258
259     connect(m_mapView, SIGNAL(viewResized(QSize)),
260             this, SIGNAL(mapViewResized(QSize)));
261
262     connect(m_mapView, SIGNAL(viewResized(QSize)),
263             this, SLOT(drawFullScreenButton(QSize)));
264
265     connect(m_mapView, SIGNAL(viewResized(QSize)),
266             this, SLOT(drawMapScale(QSize)));
267
268     connect(m_mapView, SIGNAL(viewResized(QSize)),
269              this, SLOT(setViewPortSize(QSize)));
270
271     connect(this, SIGNAL(zoomLevelChanged(int)),
272             m_mapView, SLOT(setZoomLevel(int)));
273
274     connect(m_mapView, SIGNAL(viewZoomFinished()),
275             this, SIGNAL(viewZoomFinished()));
276
277     connect(m_mapView, SIGNAL(zoomIn()),
278             this, SIGNAL(zoomIn()));
279 }
280
281 void MainWindow::buildMapScale()
282 {
283     m_mapScale = new MapScale(this);
284     connect(this, SIGNAL(newMapResolution(qreal)),
285             m_mapScale, SLOT(updateMapResolution(qreal)));
286 }
287
288 void MainWindow::buildOsmLicense()
289 {
290     qDebug() << __PRETTY_FUNCTION__;
291
292     m_osmLicense = new QLabel(this);
293     m_osmLicense->setAttribute(Qt::WA_TranslucentBackground, true);
294     m_osmLicense->setAttribute(Qt::WA_TransparentForMouseEvents, true);
295     m_osmLicense->setText("<font color='black'>" + OSM_LICENSE + "</font>");
296     m_osmLicense->setFont(QFont("Nokia Sans", 9));
297     m_osmLicense->resize(m_osmLicense->fontMetrics().width(OSM_LICENSE),
298                          m_osmLicense->fontMetrics().height());
299
300     connect(m_mapView, SIGNAL(viewResized(QSize)),
301             this, SLOT(drawOsmLicense(QSize)));
302 }
303
304 void MainWindow::buildUserInfoPanel()
305 {
306     qDebug() << __PRETTY_FUNCTION__;
307
308     m_userInfoPanel = new UserInfoPanel(this);
309
310     connect(this, SIGNAL(userLocationReady(User*)),
311             m_userInfoPanel, SLOT(userDataReceived(User*)));
312
313     connect(this, SIGNAL(reverseGeoReady(QString)),
314             m_userInfoPanel, SIGNAL(reverseGeoReady(QString)));
315
316     connect(this, SIGNAL(clearUpdateLocationDialogData()),
317             m_userInfoPanel, SIGNAL(clearUpdateLocationDialogData()));
318
319     connect(m_userInfoPanel, SIGNAL(findUser(GeoCoordinate)),
320             this, SIGNAL(findUser(GeoCoordinate)));
321
322     connect(m_userInfoPanel, SIGNAL(requestReverseGeo()),
323             this, SIGNAL(requestReverseGeo()));
324
325     connect(m_userInfoPanel, SIGNAL(statusUpdate(QString,bool)),
326             this, SIGNAL(statusUpdate(QString,bool)));
327
328     connect(m_userInfoPanel, SIGNAL(refreshUserData()),
329             this, SIGNAL(refreshUserData()));
330
331     connect(m_userInfoPanel, SIGNAL(notificateUpdateFailing(QString, bool)),
332             this, SLOT(buildInformationBox(QString, bool)));
333
334     m_tabbedPanel = new TabbedPanel(this);
335     m_tabbedPanel->addTab(m_userInfoPanel, QIcon(":/res/images/user_info.png"));
336
337     // This is just testing
338     m_tabbedPanel->addTab(new QPushButton("Friend List"), QIcon(":/res/images/friend_list.png"));
339
340     // Another test
341     m_tabbedPanel->addTab(new QPushButton("Routing"), QIcon(":/res/images/routing.png"));
342
343     connect(m_mapView, SIGNAL(viewResized(QSize)),
344             m_tabbedPanel, SLOT(resizePanel(QSize)));
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     connect(m_zoomButtonPanel, SIGNAL(draggingModeTriggered()),
395             this, SIGNAL(draggingModeTriggered()));
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         m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width(),
502                                  size.height() - m_fullScreenButton->size().height());
503 }
504
505 void MainWindow::drawMapScale(const QSize &size)
506 {
507     qDebug() << __PRETTY_FUNCTION__;
508
509     const int LEFT_SCALE_MARGIN = 10;
510     const int BOTTOM_SCALE_MARGIN = 2;
511 //    qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
512
513     m_mapScale->move(LEFT_SCALE_MARGIN,
514                      size.height() - m_mapScale->size().height() - BOTTOM_SCALE_MARGIN);
515 }
516
517 void MainWindow::drawOsmLicense(const QSize &size)
518 {
519     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
520
521     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
522                        - PANEL_BAR_WIDTH,
523                        size.height() - m_osmLicense->fontMetrics().height());
524 }
525
526 void MainWindow::drawOwnLocationCrosshair(const QSize &size)
527 {
528     qDebug() << __PRETTY_FUNCTION__;
529
530     if (m_ownLocationCrosshair != 0) {
531         m_ownLocationCrosshair->move(size.width()/2 - m_ownLocationCrosshair->pixmap()->width()/2,
532                             size.height()/2 - m_ownLocationCrosshair->pixmap()->height()/2);
533     }
534 }
535
536 void MainWindow::errorDialogFinished(int status)
537 {
538     qDebug() << __PRETTY_FUNCTION__;
539
540     qDebug() << status;
541     QDialog *dialog = m_error_queue.takeFirst();
542
543     dialog->deleteLater();
544     m_errorShown = false;
545
546     if(!m_error_queue.isEmpty())
547         showErrorInformationBox();
548     else if(!m_queue.isEmpty())
549         showInformationBox();
550 }
551
552 void MainWindow::gpsTimeout()
553 {
554     qDebug() << __PRETTY_FUNCTION__;
555
556     buildInformationBox(tr("GPS timeout"));
557 }
558
559 void MainWindow::grabZoomKeys(bool grab)
560 {
561     qDebug() << __PRETTY_FUNCTION__;
562
563 #ifdef Q_WS_MAEMO_5
564     // Can't grab keys unless we have a window id
565     if (!winId())
566         return;
567
568     unsigned long val = (grab) ? 1 : 0;
569     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
570     if (!atom)
571         return;
572
573     XChangeProperty (QX11Info::display(),
574                      winId(),
575                      atom,
576                      XA_INTEGER,
577                      32,
578                      PropModeReplace,
579                      reinterpret_cast<unsigned char *>(&val),
580                      1);
581 #else
582     Q_UNUSED(grab);
583 #endif // Q_WS_MAEMO_5
584 }
585
586 void MainWindow::keyPressEvent(QKeyEvent* event)
587 {
588     qDebug() << __PRETTY_FUNCTION__;
589
590     switch (event->key()) {
591     case Qt::Key_F7:
592         event->accept();
593         emit zoomIn();
594         break;
595
596     case Qt::Key_F8:
597         event->accept();
598         emit zoomOut();
599         break;
600     }
601     QWidget::keyPressEvent(event);
602 }
603
604 void MainWindow::loadCookies()
605 {
606     qDebug() << __PRETTY_FUNCTION__;
607
608     QSettings settings(DIRECTORY_NAME, FILE_NAME);
609
610     QStringList list = settings.value(COOKIES, EMPTY).toStringList();
611
612     if(!list.isEmpty()) {
613         QList<QNetworkCookie> cookieList;
614         for(int i=0;i<list.count();i++) {
615             cookieList.append(QNetworkCookie::parseCookies(list.at(i).toAscii()));
616         }
617
618         if(!m_cookieJar)
619                m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
620
621         m_cookieJar->setAllCookies(cookieList);
622         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
623     }
624 }
625
626 void MainWindow::loadDone(bool done)
627 {
628     qDebug() << __PRETTY_FUNCTION__;
629
630     // for the first time the login page is opened, we need to refresh it to get cookies working
631     if(m_refresh) {
632         m_webView->reload();
633         m_refresh = false;
634     }
635
636     if (done)
637     {
638         QWebFrame* frame = m_webView->page()->currentFrame();
639         if (frame!=NULL)
640         {
641             // set email box
642             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
643
644             foreach (QWebElement element, emailCollection) {
645                 element.setAttribute("value", m_email.toAscii());
646             }
647             // set password box
648             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
649             foreach (QWebElement element, passwordCollection) {
650                 element.setAttribute("value", m_password.toAscii());
651             }
652             // find connect button
653             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
654             foreach (QWebElement element, buttonCollection)
655             {
656                 QPoint pos(element.geometry().center());
657
658                 // send a mouse click event to the web page
659                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
660                                    Qt::NoModifier);
661                 QApplication::sendEvent(m_webView->page(), &event0);
662                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
663                                    Qt::NoModifier);
664                 QApplication::sendEvent(m_webView->page(), &event1);
665             }
666         }
667     }
668 }
669
670 void MainWindow::loggedIn(bool logged)
671 {
672     qDebug() << __PRETTY_FUNCTION__;
673
674     m_loggedIn = logged;
675
676     if(logged) {
677         m_loginAct->setText(tr("Logout"));
678     } else {
679         clearCookieJar();
680         m_email.clear();
681         m_password.clear();
682
683         m_loginAct->setText(tr("Login"));
684     }
685     updateItemVisibility();
686 }
687
688 void MainWindow::loginFailed()
689 {
690     qDebug() << __PRETTY_FUNCTION__;
691
692     clearCookieJar();
693     startLoginProcess();
694 }
695
696 bool MainWindow::loginState()
697 {
698     qDebug() << __PRETTY_FUNCTION__;
699
700     return m_loggedIn;
701 }
702
703 void MainWindow::loginUsingCookies()
704 {
705     qDebug() << __PRETTY_FUNCTION__;
706
707     toggleProgressIndicator(true);
708
709     buildWebView();
710     loadCookies();
711
712     QStringList urlParts;
713     urlParts.append(FACEBOOK_LOGINBASE);
714     urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
715     urlParts.append(INTERVAL1);
716     urlParts.append(SITUARE_LOGIN_SUCCESS);
717     urlParts.append(INTERVAL2);
718     urlParts.append(SITUARE_LOGIN_FAILURE);
719     urlParts.append(FACEBOOK_LOGIN_ENDING);
720
721     m_webView->load(QUrl(urlParts.join(EMPTY)));
722
723 }
724
725 void MainWindow::openSettingsDialog()
726 {
727     qDebug() << __PRETTY_FUNCTION__;
728
729     SettingsDialog *settingsDialog = new SettingsDialog(this);
730     settingsDialog->enableSituareSettings((m_loggedIn && m_gpsToggleAct->isChecked()));
731     connect(settingsDialog, SIGNAL(accepted()), this, SLOT(settingsDialogAccepted()));
732
733     settingsDialog->show();
734 }
735
736 void MainWindow::readAutomaticLocationUpdateSettings()
737 {
738     qDebug() << __PRETTY_FUNCTION__;
739
740     QSettings settings(DIRECTORY_NAME, FILE_NAME);
741     bool automaticUpdateEnabled = settings.value(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false).toBool();
742     QTime automaticUpdateInterval = settings.value(SETTINGS_AUTOMATIC_UPDATE_INTERVAL, QTime())
743                                       .toTime();
744
745     if (automaticUpdateEnabled && automaticUpdateInterval.isValid()) {
746         QTime time;
747         emit enableAutomaticLocationUpdate(true, time.msecsTo(automaticUpdateInterval));
748     } else {
749         emit enableAutomaticLocationUpdate(false);
750     }
751 }
752
753 void MainWindow::queueDialog(QDialog *dialog)
754 {
755     qDebug() << __PRETTY_FUNCTION__;
756
757     // check is dialog is modal, for now all modal dialogs have hihger priority i.e. errors
758     if(dialog->isModal()) {
759         m_error_queue.append(dialog);
760     } else {
761         m_queue.append(dialog);
762     }
763
764     // show error dialog if there is only one error dialog in the queue and no error dialog is shown
765     if(m_error_queue.count() == 1 && m_errorShown == false)
766         showErrorInformationBox();
767     else if(m_queue.count() == 1 && m_errorShown == false)
768         showInformationBox();
769 }
770
771 void MainWindow::saveCookies()
772 {
773     qDebug() << __PRETTY_FUNCTION__;
774
775     if(!m_cookieJar)
776         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
777
778     QList<QNetworkCookie> cookieList = m_cookieJar->allCookies();
779     QStringList list;
780
781     for(int i=0;i<cookieList.count();i++) {
782         QNetworkCookie cookie = cookieList.at(i);
783         QByteArray byteArray = cookie.toRawForm(QNetworkCookie::Full);
784         list.append(QString(byteArray));
785     }
786     list.removeDuplicates();
787
788     QSettings settings(DIRECTORY_NAME, FILE_NAME);
789     settings.setValue(COOKIES, list);
790 }
791
792 void MainWindow::setGPSButtonEnabled(bool enabled)
793 {
794     qDebug() << __PRETTY_FUNCTION__;
795
796     m_gpsToggleAct->setChecked(enabled);
797 }
798
799 void MainWindow::setIndicatorButtonEnabled(bool enabled)
800 {
801     qDebug() << __PRETTY_FUNCTION__;
802
803     m_indicatorButton->setChecked(enabled);
804
805 }
806
807 void MainWindow::setMapViewScene(QGraphicsScene *scene)
808 {
809     qDebug() << __PRETTY_FUNCTION__;
810
811     m_mapView->setScene(scene);
812 }
813
814 void MainWindow::setOwnLocationCrosshairVisibility(bool visibility)
815 {
816     qDebug() << __PRETTY_FUNCTION__;
817
818     if (visibility) {
819         m_ownLocationCrosshair->show();
820         drawOwnLocationCrosshair(m_viewPortSize);
821     } else {
822         m_ownLocationCrosshair->hide();
823     }
824 }
825
826 void MainWindow::settingsDialogAccepted()
827 {
828     qDebug() << __PRETTY_FUNCTION__;
829
830     readAutomaticLocationUpdateSettings();
831 }
832
833 void MainWindow::setUsername(const QString &username)
834 {
835     qDebug() << __PRETTY_FUNCTION__;
836
837     m_email = username;
838 }
839
840 void MainWindow::setViewPortSize(const QSize &size)
841 {
842     qDebug() << __PRETTY_FUNCTION__;
843
844     m_viewPortSize = size;
845 }
846
847 void MainWindow::showEnableAutomaticUpdateLocationDialog(const QString &text)
848 {
849     qDebug() << __PRETTY_FUNCTION__;
850
851     m_automaticUpdateLocationDialog = new QMessageBox(QMessageBox::Question,
852                                                       tr("Automatic location update"), text,
853                                                       QMessageBox::Yes | QMessageBox::No |
854                                                       QMessageBox::Cancel, this);
855     connect(m_automaticUpdateLocationDialog, SIGNAL(finished(int)),
856             this, SLOT(automaticUpdateDialogFinished(int)));
857
858     m_automaticUpdateLocationDialog->show();
859 }
860
861 void MainWindow::toggleFullScreen()
862 {
863     qDebug() << __PRETTY_FUNCTION__;
864
865     if(windowState() == Qt::WindowNoState)
866         showFullScreen();
867     else
868         showNormal();
869 }
870
871 void MainWindow::showErrorInformationBox()
872 {
873     qDebug() << __PRETTY_FUNCTION__;
874
875     if(m_error_queue.count()) {
876         m_errorShown = true;
877         QDialog *dialog = m_error_queue.first();
878         connect(dialog, SIGNAL(finished(int)),
879                 this, SLOT(errorDialogFinished(int)));
880         dialog->show();
881     }
882 }
883
884 void MainWindow::showInformationBox()
885 {
886     qDebug() << __PRETTY_FUNCTION__;
887
888     if(m_queue.count()) {
889         QDialog *dialog = m_queue.first();
890         connect(dialog, SIGNAL(finished(int)),
891                 this, SLOT(dialogFinished(int)));
892         dialog->show();
893     }
894 }
895
896 void MainWindow::showPanels()
897 {
898     qDebug() << __PRETTY_FUNCTION__;
899
900     drawFullScreenButton(m_viewPortSize);
901
902 //    if(m_loggedIn) {
903 //        if(!m_friendsListPanel->isVisible()) {
904 //            m_friendsListPanel->show();
905 //            m_friendsListPanelSidebar->show();
906 //        }
907
908 //        if(!m_userPanel->isVisible()) {
909 //            m_userPanel->show();
910 //            m_userPanelSidebar->show();
911 //        }
912 //    }
913 }
914
915 void MainWindow::startLocationSearch()
916 {
917     qDebug() << __PRETTY_FUNCTION__;
918
919     SearchDialog *searchDialog = new SearchDialog();
920     queueDialog(searchDialog);
921 }
922
923 void MainWindow::startLoginProcess()
924 {
925     qDebug() << __PRETTY_FUNCTION__;
926
927     LoginDialog *loginDialog = new LoginDialog();
928
929     emit fetchUsernameFromSettings();
930
931     loginDialog->clearTextFields();
932
933     if(!m_email.isEmpty())
934         loginDialog->setEmailField(m_email);
935
936     queueDialog(loginDialog);
937 }
938
939 void MainWindow::toggleProgressIndicator(bool value)
940 {
941     qDebug() << __PRETTY_FUNCTION__;
942
943 #ifdef Q_WS_MAEMO_5
944     if(value) {
945         m_progressIndicatorCount++;
946         setAttribute(Qt::WA_Maemo5ShowProgressIndicator, true);
947     } else {
948         if(m_progressIndicatorCount > 0)
949             m_progressIndicatorCount--;
950
951         if(m_progressIndicatorCount == 0)
952             setAttribute(Qt::WA_Maemo5ShowProgressIndicator, false);
953     }
954 #else
955     Q_UNUSED(value);
956 #endif // Q_WS_MAEMO_5
957 }
958
959 void MainWindow::updateItemVisibility()
960 {
961     qDebug() << __PRETTY_FUNCTION__;
962
963 //    if(!m_loggedIn) {
964 //        m_friendsListPanel->closePanel();
965 //        m_friendsListPanel->hide();
966 //        m_friendsListPanelSidebar->hide();
967 //        m_userPanel->closePanel();
968 //        m_userPanel->hide();
969 //        m_userPanelSidebar->hide();
970 //    }
971 }
972
973 const QString MainWindow::username()
974 {
975     qDebug() << __PRETTY_FUNCTION__;
976
977     return m_email;
978 }
979
980 void MainWindow::webViewRequestFinished(QNetworkReply *reply)
981 {
982     qDebug() << __PRETTY_FUNCTION__;
983
984     // omit QNetworkReply::OperationCanceledError due to it's nature to be called when ever
985     // qwebview starts to load a new page while the current page loading is not finished
986     if(reply->error() != QNetworkReply::OperationCanceledError &&
987        reply->error() != QNetworkReply::NoError) {
988         emit error(ErrorContext::NETWORK, reply->error());
989     }
990 }