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