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