570dc67131407ec55b6edf1a78853ded8b7dea36
[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       Katri Kaikkonen - katri.kaikkonen@ixonos.com
11
12    Situare is free software; you can redistribute it and/or
13    modify it under the terms of the GNU General Public License
14    version 2 as published by the Free Software Foundation.
15
16    Situare is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with Situare; if not, write to the Free Software
23    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
24    USA.
25 */
26
27 #include <QtGui>
28 #include <QtWebKit>
29 #include <QtAlgorithms>
30
31 #include "facebookservice/facebookauthentication.h"
32 #include "map/mapcommon.h"
33 #include "map/mapview.h"
34 #include "common.h"
35 #include "error.h"
36 #include "friendlistpanel.h"
37 #include "fullscreenbutton.h"
38 #include "indicatorbuttonpanel.h"
39 #include "logindialog.h"
40 #include "mapscale.h"
41 #include "panelcommon.h"
42 #include "routingpanel.h"
43 #include "tabbedpanel.h"
44 #include "searchdialog.h"
45 #include "settingsdialog.h"
46 #include "userinfopanel.h"
47 #include "zoombuttonpanel.h"
48
49 #include "mainwindow.h"
50
51 // These MUST BE HERE, compiling for Maemo fails if moved
52 #ifdef Q_WS_MAEMO_5
53 #include <QtMaemo5/QMaemo5InformationBox>
54 #include <QtGui/QX11Info>
55 #include <X11/Xatom.h>
56 #include <X11/Xlib.h>
57 #endif // Q_WS_MAEMO_5
58
59 MainWindow::MainWindow(QWidget *parent)
60     : QMainWindow(parent),
61       m_errorShown(false),
62       m_loggedIn(false),
63       m_refresh(false),
64       m_progressIndicatorCount(0),
65       m_ownLocationCrosshair(0),
66       m_email(),
67       m_password(),
68       m_webView(0),
69       m_fullScreenButton(0),
70       m_indicatorButtonPanel(0),
71       m_mapScale(0),
72       m_cookieJar(0)
73 {
74     qDebug() << __PRETTY_FUNCTION__;
75
76     buildMap();
77
78     // build main layout
79     QHBoxLayout *layout = new QHBoxLayout;
80     layout->addWidget(m_mapView);
81     layout->setMargin(0);
82     layout->setSpacing(0);
83
84     setCentralWidget(new QWidget());
85     centralWidget()->setLayout(layout);
86
87     buildPanels();
88
89     createMenus();
90     setWindowTitle(tr("Situare"));
91
92     // set stacking order of widgets
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_indicatorButtonPanel->stackUnder(m_ownLocationCrosshair);
102     m_mapScale->stackUnder(m_indicatorButtonPanel);
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
149 #ifdef Q_WS_MAEMO_5
150     m_fullScreenButton = new FullScreenButton(this);
151
152     if (m_fullScreenButton) {
153         connect(m_fullScreenButton, SIGNAL(clicked()),
154                 this, SLOT(toggleFullScreen()));
155
156         connect(qApp, SIGNAL(showFullScreenButton()),
157                 m_fullScreenButton, SLOT(invoke()));
158     }
159 #endif // Q_WS_MAEMO_5
160 }
161
162 void MainWindow::buildFriendListPanel()
163 {
164     qDebug() << __PRETTY_FUNCTION__;
165
166     m_friendsListPanel = new FriendListPanel(this);
167
168     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
169             m_friendsListPanel, SLOT(friendInfoReceived(QList<User*>&)));
170
171     connect(this, SIGNAL(locationItemClicked(QList<QString>)),
172             m_friendsListPanel, SLOT(showFriendsInList(QList<QString>)));
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::buildIndicatorButtonPanel()
182 {
183     qDebug() << __PRETTY_FUNCTION__;
184
185     m_indicatorButtonPanel = new IndicatorButtonPanel(this);
186
187     connect(m_indicatorButtonPanel, SIGNAL(autoCenteringTriggered(bool)),
188         this, SIGNAL(autoCenteringTriggered(bool)));
189
190     connect(m_mapView, SIGNAL(viewResized(QSize)),
191             m_indicatorButtonPanel, SLOT(screenResized(QSize)));
192
193     connect(this, SIGNAL(directionIndicatorValuesUpdate(qreal, qreal, bool)),
194             m_indicatorButtonPanel, SIGNAL(directionIndicatorValuesUpdate(qreal, qreal, bool)));
195
196     connect(m_indicatorButtonPanel, SIGNAL(draggingModeTriggered()),
197             this, SIGNAL(draggingModeTriggered()));
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     buildIndicatorButtonPanel();
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::buildPanels()
312 {
313     qDebug() << __PRETTY_FUNCTION__;
314
315     buildUserInfoPanel();
316     buildFriendListPanel();
317     buildRoutingPanel();
318
319     m_tabbedPanel = new TabbedPanel(this);
320     m_tabbedPanel->addTab(m_userInfoPanel, QIcon(":/res/images/user_info.png"));
321     m_tabbedPanel->addTab(m_friendsListPanel, QIcon(":/res/images/friend_list.png"));
322     m_tabbedPanel->addTab(m_routingPanel, QIcon(":/res/images/routing.png"));
323
324     connect(m_tabbedPanel, SIGNAL(tabChanged()),
325             m_friendsListPanel, SLOT(clearFriendListFilter()));
326
327     connect(m_mapView, SIGNAL(viewResized(QSize)),
328             m_tabbedPanel, SLOT(resizePanel(QSize)));
329 }
330
331 void MainWindow::buildRoutingPanel()
332 {
333     qDebug() << __PRETTY_FUNCTION__;
334
335     m_routingPanel = new RoutingPanel(this);
336
337     connect(this, SIGNAL(locationDataParsed(const QList<Location>&)),
338             m_routingPanel, SLOT(populateLocationListView(const QList<Location>&)));
339
340     connect(m_routingPanel,
341             SIGNAL(locationItemClicked(const GeoCoordinate&, const GeoCoordinate&)),
342             this,
343             SIGNAL(locationItemClicked(const GeoCoordinate&, const GeoCoordinate&)));
344 }
345
346 void MainWindow::buildUserInfoPanel()
347 {
348     qDebug() << __PRETTY_FUNCTION__;
349
350     m_userInfoPanel = new UserInfoPanel(this);
351
352     connect(this, SIGNAL(userLocationReady(User*)),
353             m_userInfoPanel, SLOT(userDataReceived(User*)));
354
355     connect(this, SIGNAL(reverseGeoReady(QString)),
356             m_userInfoPanel, SIGNAL(reverseGeoReady(QString)));
357
358     connect(this, SIGNAL(clearUpdateLocationDialogData()),
359             m_userInfoPanel, SIGNAL(clearUpdateLocationDialogData()));
360
361     connect(m_userInfoPanel, SIGNAL(findUser(GeoCoordinate)),
362             this, SIGNAL(findUser(GeoCoordinate)));
363
364     connect(m_userInfoPanel, SIGNAL(requestReverseGeo()),
365             this, SIGNAL(requestReverseGeo()));
366
367     connect(m_userInfoPanel, SIGNAL(statusUpdate(QString,bool)),
368             this, SIGNAL(statusUpdate(QString,bool)));
369
370     connect(m_userInfoPanel, SIGNAL(refreshUserData()),
371             this, SIGNAL(refreshUserData()));
372
373     connect(m_userInfoPanel, SIGNAL(notificateUpdateFailing(QString, bool)),
374             this, SLOT(buildInformationBox(QString, bool)));
375 }
376
377 void MainWindow::buildWebView()
378 {
379     qDebug() << __PRETTY_FUNCTION__;
380
381     if(!m_webView) {
382         m_webView = new QWebView;
383
384         if(!m_cookieJar)
385             m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
386
387         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
388
389         connect(m_webView->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
390                 this, SLOT(webViewRequestFinished(QNetworkReply*)));
391         connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
392                 this, SIGNAL(updateCredentials(QUrl)));
393         connect(m_webView, SIGNAL(loadFinished(bool)),
394                 this, SLOT(loadDone(bool)));
395
396         m_webView->hide();
397     }
398 }
399
400 void MainWindow::buildZoomButtonPanel()
401 {
402     qDebug() << __PRETTY_FUNCTION__;
403
404     m_zoomButtonPanel = new ZoomButtonPanel(this);
405
406     connect(m_zoomButtonPanel->zoomInButton(), SIGNAL(clicked()),
407             this, SIGNAL(zoomIn()));
408
409     connect(m_zoomButtonPanel->zoomOutButton(), SIGNAL(clicked()),
410             this, SIGNAL(zoomOut()));
411
412     connect(this, SIGNAL(zoomLevelChanged(int)),
413             m_zoomButtonPanel, SLOT(resetButtons()));
414
415     connect(this, SIGNAL(maxZoomLevelReached()),
416             m_zoomButtonPanel, SLOT(disableZoomInButton()));
417
418     connect(this, SIGNAL(minZoomLevelReached()),
419             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
420
421     connect(m_mapView, SIGNAL(viewResized(QSize)),
422             m_zoomButtonPanel, SLOT(screenResized(QSize)));
423
424     connect(m_zoomButtonPanel, SIGNAL(draggingModeTriggered()),
425             this, SIGNAL(draggingModeTriggered()));
426 }
427
428 void MainWindow::clearCookieJar()
429 {
430     qDebug() << __PRETTY_FUNCTION__;
431
432     buildWebView();
433
434     m_webView->stop();
435
436     if(!m_cookieJar) {
437         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
438     }
439     QList<QNetworkCookie> emptyList;
440     emptyList.clear();
441
442     m_cookieJar->setAllCookies(emptyList);
443     m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
444 }
445
446 void MainWindow::createMenus()
447 {
448     qDebug() << __PRETTY_FUNCTION__;
449
450     // login/logout
451     m_loginAct = new QAction(tr("Login"), this);
452     connect(m_loginAct, SIGNAL(triggered()),
453             this, SIGNAL(loginActionPressed()));
454
455     // settings
456     m_toSettingsAct = new QAction(tr("Settings"), this);
457     connect(m_toSettingsAct, SIGNAL(triggered()),
458         this, SLOT(openSettingsDialog()));
459
460     // GPS
461     m_gpsToggleAct = new QAction(tr("GPS"), this);
462     m_gpsToggleAct->setCheckable(true);
463
464     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
465             this, SIGNAL(gpsTriggered(bool)));
466
467     /// @todo remove when not needed!
468     m_searchLocationAct = new QAction(tr("Location search"), this);
469     connect(m_searchLocationAct, SIGNAL(triggered()),
470             this, SLOT(startLocationSearch()));
471
472     // build the actual menu
473     m_viewMenu = menuBar()->addMenu(tr("Main"));
474     m_viewMenu->addAction(m_loginAct);
475     m_viewMenu->addAction(m_toSettingsAct);
476     m_viewMenu->addAction(m_gpsToggleAct);
477     m_viewMenu->addAction(m_searchLocationAct); /// @todo remove when not needed!
478     m_viewMenu->setObjectName(tr("Menu"));
479 }
480
481 void MainWindow::dialogFinished(int status)
482 {
483     qDebug() << __PRETTY_FUNCTION__;
484
485     QDialog *dialog = m_queue.takeFirst();
486     LoginDialog *loginDialog = qobject_cast<LoginDialog *>(dialog);
487     SearchDialog *searchDialog = qobject_cast<SearchDialog *>(dialog);
488     if(loginDialog) {
489         if(status != 0) {
490             buildWebView();
491             loginDialog->userInput(m_email, m_password);
492
493             QStringList urlParts;
494             urlParts.append(FACEBOOK_LOGINBASE);
495             urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
496             urlParts.append(INTERVAL1);
497             urlParts.append(SITUARE_LOGIN_SUCCESS);
498             urlParts.append(INTERVAL2);
499             urlParts.append(SITUARE_LOGIN_FAILURE);
500             urlParts.append(FACEBOOK_LOGIN_ENDING);
501
502             emit saveUsername(m_email);
503             m_refresh = true;
504             m_webView->load(QUrl(urlParts.join(EMPTY)));
505             toggleProgressIndicator(true);
506         } else {
507             emit cancelLoginProcess();
508         }
509     } else if(searchDialog) {
510         if(status != 0) {
511             emit searchForLocation(searchDialog->input());
512         }
513     }
514
515     dialog->deleteLater();
516
517     if(!m_error_queue.isEmpty() && m_errorShown == false) {
518         showErrorInformationBox();
519     } else {
520         if(!m_queue.isEmpty()) {
521             showInformationBox();
522         }
523     }
524 }
525
526 void MainWindow::drawFullScreenButton(const QSize &size)
527 {
528     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
529
530     if(m_fullScreenButton)
531         m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width(),
532                                  size.height() - m_fullScreenButton->size().height());
533 }
534
535 void MainWindow::drawMapScale(const QSize &size)
536 {
537     qDebug() << __PRETTY_FUNCTION__;
538
539     const int LEFT_SCALE_MARGIN = 10;
540     const int BOTTOM_SCALE_MARGIN = 2;
541 //    qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
542
543     m_mapScale->move(LEFT_SCALE_MARGIN,
544                      size.height() - m_mapScale->size().height() - BOTTOM_SCALE_MARGIN);
545 }
546
547 void MainWindow::drawOsmLicense(const QSize &size)
548 {
549     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
550
551     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
552                        - PANEL_BAR_WIDTH,
553                        size.height() - m_osmLicense->fontMetrics().height());
554 }
555
556 void MainWindow::drawOwnLocationCrosshair(const QSize &size)
557 {
558     qDebug() << __PRETTY_FUNCTION__;
559
560     if (m_ownLocationCrosshair != 0) {
561         m_ownLocationCrosshair->move(size.width()/2 - m_ownLocationCrosshair->pixmap()->width()/2,
562                             size.height()/2 - m_ownLocationCrosshair->pixmap()->height()/2);
563     }
564 }
565
566 void MainWindow::errorDialogFinished(int status)
567 {
568     qDebug() << __PRETTY_FUNCTION__;
569
570     qDebug() << status;
571     QDialog *dialog = m_error_queue.takeFirst();
572
573     dialog->deleteLater();
574     m_errorShown = false;
575
576     if(!m_error_queue.isEmpty())
577         showErrorInformationBox();
578     else if(!m_queue.isEmpty())
579         showInformationBox();
580 }
581
582 void MainWindow::gpsTimeout()
583 {
584     qDebug() << __PRETTY_FUNCTION__;
585
586     buildInformationBox(tr("GPS timeout"));
587 }
588
589 void MainWindow::grabZoomKeys(bool grab)
590 {
591     qDebug() << __PRETTY_FUNCTION__;
592
593 #ifdef Q_WS_MAEMO_5
594     // Can't grab keys unless we have a window id
595     if (!winId())
596         return;
597
598     unsigned long val = (grab) ? 1 : 0;
599     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
600     if (!atom)
601         return;
602
603     XChangeProperty (QX11Info::display(),
604                      winId(),
605                      atom,
606                      XA_INTEGER,
607                      32,
608                      PropModeReplace,
609                      reinterpret_cast<unsigned char *>(&val),
610                      1);
611 #else
612     Q_UNUSED(grab);
613 #endif // Q_WS_MAEMO_5
614 }
615
616 void MainWindow::keyPressEvent(QKeyEvent* event)
617 {
618     qDebug() << __PRETTY_FUNCTION__;
619
620     switch (event->key()) {
621     case Qt::Key_F7:
622         event->accept();
623         emit zoomIn();
624         break;
625
626     case Qt::Key_F8:
627         event->accept();
628         emit zoomOut();
629         break;
630     }
631     QWidget::keyPressEvent(event);
632 }
633
634 void MainWindow::loadCookies()
635 {
636     qDebug() << __PRETTY_FUNCTION__;
637
638     QSettings settings(DIRECTORY_NAME, FILE_NAME);
639
640     QStringList list = settings.value(COOKIES, EMPTY).toStringList();
641
642     if(!list.isEmpty()) {
643         QList<QNetworkCookie> cookieList;
644         for(int i=0;i<list.count();i++) {
645             cookieList.append(QNetworkCookie::parseCookies(list.at(i).toAscii()));
646         }
647
648         if(!m_cookieJar)
649                m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
650
651         m_cookieJar->setAllCookies(cookieList);
652         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
653     }
654 }
655
656 void MainWindow::loadDone(bool done)
657 {
658     qDebug() << __PRETTY_FUNCTION__;
659
660     // for the first time the login page is opened, we need to refresh it to get cookies working
661     if(m_refresh) {
662         m_webView->reload();
663         m_refresh = false;
664     }
665
666     if (done)
667     {
668         QWebFrame* frame = m_webView->page()->currentFrame();
669         if (frame!=NULL)
670         {
671             // set email box
672             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
673
674             foreach (QWebElement element, emailCollection) {
675                 element.setAttribute("value", m_email.toAscii());
676             }
677             // set password box
678             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
679             foreach (QWebElement element, passwordCollection) {
680                 element.setAttribute("value", m_password.toAscii());
681             }
682             // find connect button
683             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
684             foreach (QWebElement element, buttonCollection)
685             {
686                 QPoint pos(element.geometry().center());
687
688                 // send a mouse click event to the web page
689                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
690                                    Qt::NoModifier);
691                 QApplication::sendEvent(m_webView->page(), &event0);
692                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
693                                    Qt::NoModifier);
694                 QApplication::sendEvent(m_webView->page(), &event1);
695             }
696         }
697     }
698 }
699
700 void MainWindow::loggedIn(bool logged)
701 {
702     qDebug() << __PRETTY_FUNCTION__;
703
704     m_loggedIn = logged;
705
706     if(logged) {
707         m_loginAct->setText(tr("Logout"));
708     } else {
709         clearCookieJar();
710         m_email.clear();
711         m_password.clear();
712
713         m_loginAct->setText(tr("Login"));
714     }
715     updateItemVisibility();
716 }
717
718 void MainWindow::loginFailed()
719 {
720     qDebug() << __PRETTY_FUNCTION__;
721
722     clearCookieJar();
723     startLoginProcess();
724 }
725
726 bool MainWindow::loginState()
727 {
728     qDebug() << __PRETTY_FUNCTION__;
729
730     return m_loggedIn;
731 }
732
733 void MainWindow::loginUsingCookies()
734 {
735     qDebug() << __PRETTY_FUNCTION__;
736
737     toggleProgressIndicator(true);
738
739     buildWebView();
740     loadCookies();
741
742     QStringList urlParts;
743     urlParts.append(FACEBOOK_LOGINBASE);
744     urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
745     urlParts.append(INTERVAL1);
746     urlParts.append(SITUARE_LOGIN_SUCCESS);
747     urlParts.append(INTERVAL2);
748     urlParts.append(SITUARE_LOGIN_FAILURE);
749     urlParts.append(FACEBOOK_LOGIN_ENDING);
750
751     m_webView->load(QUrl(urlParts.join(EMPTY)));
752
753 }
754
755 void MainWindow::openSettingsDialog()
756 {
757     qDebug() << __PRETTY_FUNCTION__;
758
759     SettingsDialog *settingsDialog = new SettingsDialog(this);
760     settingsDialog->enableSituareSettings((m_loggedIn && m_gpsToggleAct->isChecked()));
761     connect(settingsDialog, SIGNAL(accepted()), this, SLOT(settingsDialogAccepted()));
762
763     settingsDialog->show();
764 }
765
766 void MainWindow::readAutomaticLocationUpdateSettings()
767 {
768     qDebug() << __PRETTY_FUNCTION__;
769
770     QSettings settings(DIRECTORY_NAME, FILE_NAME);
771     bool automaticUpdateEnabled = settings.value(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false).toBool();
772     QTime automaticUpdateInterval = settings.value(SETTINGS_AUTOMATIC_UPDATE_INTERVAL, QTime())
773                                       .toTime();
774
775     if (automaticUpdateEnabled && automaticUpdateInterval.isValid()) {
776         QTime time;
777         emit enableAutomaticLocationUpdate(true, time.msecsTo(automaticUpdateInterval));
778     } else {
779         emit enableAutomaticLocationUpdate(false);
780     }
781 }
782
783 void MainWindow::queueDialog(QDialog *dialog)
784 {
785     qDebug() << __PRETTY_FUNCTION__;
786
787     // check is dialog is modal, for now all modal dialogs have hihger priority i.e. errors
788     if(dialog->isModal()) {
789         m_error_queue.append(dialog);
790     } else {
791         m_queue.append(dialog);
792     }
793
794     // show error dialog if there is only one error dialog in the queue and no error dialog is shown
795     if(m_error_queue.count() == 1 && m_errorShown == false)
796         showErrorInformationBox();
797     else if(m_queue.count() == 1 && m_errorShown == false)
798         showInformationBox();
799 }
800
801 void MainWindow::saveCookies()
802 {
803     qDebug() << __PRETTY_FUNCTION__;
804
805     if(!m_cookieJar)
806         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
807
808     QList<QNetworkCookie> cookieList = m_cookieJar->allCookies();
809     QStringList list;
810
811     for(int i=0;i<cookieList.count();i++) {
812         QNetworkCookie cookie = cookieList.at(i);
813         QByteArray byteArray = cookie.toRawForm(QNetworkCookie::Full);
814         list.append(QString(byteArray));
815     }
816     list.removeDuplicates();
817
818     QSettings settings(DIRECTORY_NAME, FILE_NAME);
819     settings.setValue(COOKIES, list);
820 }
821
822 void MainWindow::setGPSButtonEnabled(bool enabled)
823 {
824     qDebug() << __PRETTY_FUNCTION__;
825
826     m_gpsToggleAct->setChecked(enabled);
827 }
828
829 void MainWindow::setIndicatorButtonEnabled(bool enabled)
830 {
831     qDebug() << __PRETTY_FUNCTION__;
832
833     m_indicatorButtonPanel->setIndicatorButtonEnabled(enabled);
834 }
835
836 void MainWindow::setMapViewScene(QGraphicsScene *scene)
837 {
838     qDebug() << __PRETTY_FUNCTION__;
839
840     m_mapView->setScene(scene);
841 }
842
843 void MainWindow::setOwnLocationCrosshairVisibility(bool visibility)
844 {
845     qDebug() << __PRETTY_FUNCTION__;
846
847     if (visibility) {
848         m_ownLocationCrosshair->show();
849         drawOwnLocationCrosshair(m_viewPortSize);
850     } else {
851         m_ownLocationCrosshair->hide();
852     }
853 }
854
855 void MainWindow::settingsDialogAccepted()
856 {
857     qDebug() << __PRETTY_FUNCTION__;
858
859     readAutomaticLocationUpdateSettings();
860 }
861
862 void MainWindow::setUsername(const QString &username)
863 {
864     qDebug() << __PRETTY_FUNCTION__;
865
866     m_email = username;
867 }
868
869 void MainWindow::setViewPortSize(const QSize &size)
870 {
871     qDebug() << __PRETTY_FUNCTION__;
872
873     m_viewPortSize = size;
874 }
875
876 void MainWindow::showEnableAutomaticUpdateLocationDialog(const QString &text)
877 {
878     qDebug() << __PRETTY_FUNCTION__;
879
880     m_automaticUpdateLocationDialog = new QMessageBox(QMessageBox::Question,
881                                                       tr("Automatic location update"), text,
882                                                       QMessageBox::Yes | QMessageBox::No |
883                                                       QMessageBox::Cancel, this);
884     connect(m_automaticUpdateLocationDialog, SIGNAL(finished(int)),
885             this, SLOT(automaticUpdateDialogFinished(int)));
886
887     m_automaticUpdateLocationDialog->show();
888 }
889
890 void MainWindow::toggleFullScreen()
891 {
892     qDebug() << __PRETTY_FUNCTION__;
893
894     if(windowState() == Qt::WindowNoState)
895         showFullScreen();
896     else
897         showNormal();
898 }
899
900 void MainWindow::showErrorInformationBox()
901 {
902     qDebug() << __PRETTY_FUNCTION__;
903
904     if(m_error_queue.count()) {
905         m_errorShown = true;
906         QDialog *dialog = m_error_queue.first();
907         connect(dialog, SIGNAL(finished(int)),
908                 this, SLOT(errorDialogFinished(int)));
909         dialog->show();
910     }
911 }
912
913 void MainWindow::showInformationBox()
914 {
915     qDebug() << __PRETTY_FUNCTION__;
916
917     if(m_queue.count()) {
918         QDialog *dialog = m_queue.first();
919         connect(dialog, SIGNAL(finished(int)),
920                 this, SLOT(dialogFinished(int)));
921         dialog->show();
922     }
923 }
924
925 void MainWindow::showPanels()
926 {
927     qDebug() << __PRETTY_FUNCTION__;
928
929     drawFullScreenButton(m_viewPortSize);
930
931 //    if(m_loggedIn) {
932 //        if(!m_friendsListPanel->isVisible()) {
933 //            m_friendsListPanel->show();
934 //            m_friendsListPanelSidebar->show();
935 //        }
936
937 //        if(!m_userPanel->isVisible()) {
938 //            m_userPanel->show();
939 //            m_userPanelSidebar->show();
940 //        }
941 //    }
942 }
943
944 void MainWindow::startLocationSearch()
945 {
946     qDebug() << __PRETTY_FUNCTION__;
947
948     SearchDialog *searchDialog = new SearchDialog();
949     queueDialog(searchDialog);
950 }
951
952 void MainWindow::startLoginProcess()
953 {
954     qDebug() << __PRETTY_FUNCTION__;
955
956     LoginDialog *loginDialog = new LoginDialog();
957
958     emit fetchUsernameFromSettings();
959
960     loginDialog->clearTextFields();
961
962     if(!m_email.isEmpty())
963         loginDialog->setEmailField(m_email);
964
965     queueDialog(loginDialog);
966 }
967
968 void MainWindow::toggleProgressIndicator(bool value)
969 {
970     qDebug() << __PRETTY_FUNCTION__;
971
972 #ifdef Q_WS_MAEMO_5
973     if(value) {
974         m_progressIndicatorCount++;
975         setAttribute(Qt::WA_Maemo5ShowProgressIndicator, true);
976     } else {
977         if(m_progressIndicatorCount > 0)
978             m_progressIndicatorCount--;
979
980         if(m_progressIndicatorCount == 0)
981             setAttribute(Qt::WA_Maemo5ShowProgressIndicator, false);
982     }
983 #else
984     Q_UNUSED(value);
985 #endif // Q_WS_MAEMO_5
986 }
987
988 void MainWindow::updateItemVisibility()
989 {
990     qDebug() << __PRETTY_FUNCTION__;
991
992 //    if(!m_loggedIn) {
993 //        m_friendsListPanel->closePanel();
994 //        m_friendsListPanel->hide();
995 //        m_friendsListPanelSidebar->hide();
996
997 //        m_userPanel->closePanel();
998 //        m_userPanel->hide();
999 //        m_userPanelSidebar->hide();
1000 //    }
1001 }
1002
1003 const QString MainWindow::username()
1004 {
1005     qDebug() << __PRETTY_FUNCTION__;
1006
1007     return m_email;
1008 }
1009
1010 void MainWindow::webViewRequestFinished(QNetworkReply *reply)
1011 {
1012     qDebug() << __PRETTY_FUNCTION__;
1013
1014     // omit QNetworkReply::OperationCanceledError due to it's nature to be called when ever
1015     // qwebview starts to load a new page while the current page loading is not finished
1016     if(reply->error() != QNetworkReply::OperationCanceledError &&
1017        reply->error() != QNetworkReply::NoError) {
1018         emit error(ErrorContext::NETWORK, reply->error());
1019     }
1020 }