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