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