Implemented functionality to show side panels only when they contain data
[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     this->toggleProgressIndicator(true);
99
100     grabZoomKeys(true);
101
102     // Set default screen size
103     resize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT);
104 #ifdef Q_WS_MAEMO_5
105     setAttribute(Qt::WA_Maemo5StackedWindow);
106 #endif
107 }
108
109 MainWindow::~MainWindow()
110 {
111     qDebug() << __PRETTY_FUNCTION__;
112
113     grabZoomKeys(false);
114
115     if(m_webView)
116         delete m_webView;
117
118     qDeleteAll(m_queue.begin(), m_queue.end());
119     m_queue.clear();
120
121     qDeleteAll(m_error_queue.begin(), m_error_queue.end());
122     m_error_queue.clear();
123 }
124
125 void MainWindow::automaticUpdateDialogFinished(int result)
126 {
127     qDebug() << __PRETTY_FUNCTION__;
128
129     if (result == QMessageBox::Yes) {
130         readAutomaticLocationUpdateSettings();
131     } else {
132         QSettings settings(DIRECTORY_NAME, FILE_NAME);
133         settings.setValue(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false);
134         readAutomaticLocationUpdateSettings();
135     }
136
137     m_automaticUpdateLocationDialog->deleteLater();
138 }
139
140 void MainWindow::buildFullScreenButton()
141 {
142     qDebug() << __PRETTY_FUNCTION__;
143 #ifdef Q_WS_MAEMO_5
144     m_fullScreenButton = new FullScreenButton(this);
145     connect(m_fullScreenButton, SIGNAL(clicked()),
146             this, SLOT(toggleFullScreen()));
147 #endif // Q_WS_MAEMO_5
148 }
149
150 void MainWindow::buildFriendListPanel()
151 {
152     qDebug() << __PRETTY_FUNCTION__;
153
154     m_friendsListPanel = new FriendListPanel(this);
155
156     m_friendsListPanelSidebar = new PanelSideBar(this, RIGHT);
157
158     m_friendsListPanel->stackUnder(m_friendsListPanelSidebar);
159
160     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
161             m_friendsListPanel, SLOT(friendInfoReceived(QList<User*>&)));
162
163     connect(this, SIGNAL(locationItemClicked(QList<QString>)),
164             m_friendsListPanel, SLOT(showFriendsInList(QList<QString>)));
165
166     connect(m_mapView, SIGNAL(viewResized(QSize)),
167             m_friendsListPanel, SLOT(resizePanel(QSize)));
168
169     connect(m_mapView, SIGNAL(viewResized(QSize)),
170             m_friendsListPanelSidebar, SLOT(resizeSideBar(QSize)));
171
172     connect(m_friendsListPanel, SIGNAL(findFriend(QPointF)),
173             this, SIGNAL(findFriend(QPointF)));
174 }
175
176 void MainWindow::buildInformationBox(const QString &message, bool modal)
177 {
178     qDebug() << __PRETTY_FUNCTION__;
179
180     QString errorMessage = message;
181
182 #ifdef Q_WS_MAEMO_5
183
184     QMaemo5InformationBox *msgBox = new QMaemo5InformationBox(this);
185
186     if(modal) {
187         msgBox->setTimeout(QMaemo5InformationBox::NoTimeout);
188         // extra line changes are needed to make error notes broader
189         errorMessage.prepend("\n");
190         errorMessage.append("\n");
191     } else {
192         msgBox->setTimeout(QMaemo5InformationBox::DefaultTimeout);
193     }
194     QLabel *label = new QLabel(msgBox);
195     label->setAlignment(Qt::AlignCenter);
196     label->setText(errorMessage);
197     msgBox->setWidget(label);
198 #else
199     QMessageBox *msgBox = new QMessageBox(this);
200     msgBox->button(QMessageBox::Ok);
201     msgBox->setText(errorMessage);
202     msgBox->setModal(modal);
203 #endif
204
205     queueDialog(msgBox);
206 }
207
208 void MainWindow::buildManualLocationCrosshair()
209 {
210     qDebug() << __PRETTY_FUNCTION__;
211
212     m_ownLocationCrosshair = new QLabel(this);
213     QPixmap crosshairImage(":/res/images/sight.png");
214     m_ownLocationCrosshair->setPixmap(crosshairImage);
215     m_ownLocationCrosshair->setFixedSize(crosshairImage.size());
216     m_ownLocationCrosshair->hide();
217     m_ownLocationCrosshair->setAttribute(Qt::WA_TransparentForMouseEvents, true);
218
219     connect(m_mapView, SIGNAL(viewResized(QSize)),
220             this, SLOT(drawOwnLocationCrosshair(QSize)));
221 }
222
223 void MainWindow::buildMap()
224 {
225     qDebug() << __PRETTY_FUNCTION__;
226
227     m_mapView = new MapView(this);
228
229     buildZoomButtonPanel();
230     buildOsmLicense();
231     buildManualLocationCrosshair();
232     buildFullScreenButton();
233     buildMapScale();
234
235     connect(m_mapView, SIGNAL(viewScrolled(QPoint)),
236             this, SIGNAL(mapViewScrolled(QPoint)));
237
238     connect(this, SIGNAL(centerToSceneCoordinates(QPoint)),
239             m_mapView, SLOT(centerToSceneCoordinates(QPoint)));
240
241     connect(m_mapView, SIGNAL(viewResized(QSize)),
242             this, SIGNAL(mapViewResized(QSize)));
243
244     connect(m_mapView, SIGNAL(viewResized(QSize)),
245             this, SLOT(drawFullScreenButton(QSize)));
246
247     connect(m_mapView, SIGNAL(viewResized(QSize)),
248             this, SLOT(drawMapScale(QSize)));
249
250     connect(m_mapView, SIGNAL(viewResized(QSize)),
251              this, SLOT(setViewPortSize(QSize)));
252
253     connect(this, SIGNAL(zoomLevelChanged(int)),
254             m_mapView, SLOT(setZoomLevel(int)));
255
256     connect(m_mapView, SIGNAL(viewZoomFinished()),
257             this, SIGNAL(viewZoomFinished()));
258 }
259
260 void MainWindow::buildMapScale()
261 {
262     m_mapScale = new MapScale(this);
263     connect(this, SIGNAL(newMapResolution(qreal)),
264             m_mapScale, SLOT(updateMapResolution(qreal)));
265 }
266
267 void MainWindow::buildOsmLicense()
268 {
269     qDebug() << __PRETTY_FUNCTION__;
270
271     m_osmLicense = new QLabel(this);
272     m_osmLicense->setAttribute(Qt::WA_TranslucentBackground, true);
273     m_osmLicense->setAttribute(Qt::WA_TransparentForMouseEvents, true);
274     m_osmLicense->setText("<font color='black'>" + OSM_LICENSE + "</font>");
275     m_osmLicense->setFont(QFont("Nokia Sans", 9));
276     m_osmLicense->resize(m_osmLicense->fontMetrics().width(OSM_LICENSE),
277                          m_osmLicense->fontMetrics().height());
278
279     connect(m_mapView, SIGNAL(viewResized(QSize)),
280             this, SLOT(drawOsmLicense(QSize)));
281 }
282
283 void MainWindow::buildUserInfoPanel()
284 {
285     qDebug() << __PRETTY_FUNCTION__;
286
287     m_userPanel = new UserInfoPanel(this);
288
289     m_userPanelSidebar = new PanelSideBar(this, LEFT);
290
291     m_userPanelSidebar->stackUnder(m_friendsListPanel);
292     m_userPanel->stackUnder(m_userPanelSidebar);
293
294     connect(this, SIGNAL(userLocationReady(User*)),
295             m_userPanel, SLOT(userDataReceived(User*)));
296
297     connect(this, SIGNAL(reverseGeoReady(QString)),
298             m_userPanel, SIGNAL(reverseGeoReady(QString)));
299
300     connect(this, SIGNAL(clearUpdateLocationDialogData()),
301             m_userPanel, SIGNAL(clearUpdateLocationDialogData()));
302
303     connect(this, SIGNAL(messageSendingFailed(int)),
304             m_userPanel, SIGNAL(messageSendingFailed(int)));
305
306     connect(m_mapView, SIGNAL(viewResized(QSize)),
307             m_userPanel, SLOT(resizePanel(QSize)));
308
309     connect(m_mapView, SIGNAL(viewResized(QSize)),
310             m_userPanelSidebar, SLOT(resizeSideBar(QSize)));
311
312     connect(m_userPanel, SIGNAL(findUser(QPointF)),
313             this, SIGNAL(findUser(QPointF)));
314
315     connect(m_userPanel, SIGNAL(requestReverseGeo()),
316             this, SIGNAL(requestReverseGeo()));
317
318     connect(m_userPanel, SIGNAL(statusUpdate(QString,bool)),
319             this, SIGNAL(statusUpdate(QString,bool)));
320
321     connect(m_userPanel, SIGNAL(refreshUserData()),
322             this, SIGNAL(refreshUserData()));
323
324     connect(m_userPanel, SIGNAL(notificateUpdateFailing(QString, bool)),
325             this, SLOT(buildInformationBox(QString, bool)));
326 }
327
328 void MainWindow::buildWebView()
329 {
330     qDebug() << __PRETTY_FUNCTION__;
331
332     if(!m_webView) {
333         m_webView = new QWebView;
334
335         if(!m_cookieJar)
336             m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
337
338         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
339
340         connect(m_webView->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
341                 this, SLOT(webViewRequestFinished(QNetworkReply*)));
342         connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
343                 this, SIGNAL(updateCredentials(QUrl)));
344         connect(m_webView, SIGNAL(loadFinished(bool)),
345                 this, SLOT(loadDone(bool)));
346
347         m_webView->hide();
348     }
349 }
350
351 void MainWindow::buildZoomButtonPanel()
352 {
353     qDebug() << __PRETTY_FUNCTION__;
354
355     m_zoomButtonPanel = new ZoomButtonPanel(this);
356
357     connect(m_zoomButtonPanel->zoomInButton(), SIGNAL(clicked()),
358             this, SIGNAL(zoomIn()));
359
360     connect(m_zoomButtonPanel->zoomOutButton(), SIGNAL(clicked()),
361             this, SIGNAL(zoomOut()));
362
363     connect(this, SIGNAL(zoomLevelChanged(int)),
364             m_zoomButtonPanel, SLOT(resetButtons()));
365
366     connect(this, SIGNAL(maxZoomLevelReached()),
367             m_zoomButtonPanel, SLOT(disableZoomInButton()));
368
369     connect(this, SIGNAL(minZoomLevelReached()),
370             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
371
372     connect(m_mapView, SIGNAL(viewResized(QSize)),
373             m_zoomButtonPanel, SLOT(screenResized(QSize)));
374 }
375
376 void MainWindow::clearCookieJar()
377 {
378     qDebug() << __PRETTY_FUNCTION__;
379
380     buildWebView();
381
382     m_webView->stop();
383
384     if(!m_cookieJar) {
385         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
386     }
387     QList<QNetworkCookie> emptyList;
388     emptyList.clear();
389
390     m_cookieJar->setAllCookies(emptyList);
391     m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
392 }
393
394 void MainWindow::createMenus()
395 {
396     qDebug() << __PRETTY_FUNCTION__;
397
398     // login/logout
399     m_loginAct = new QAction(tr("Login"), this);
400     connect(m_loginAct, SIGNAL(triggered()),
401             this, SIGNAL(loginActionPressed()));
402
403     // settings
404     m_toSettingsAct = new QAction(tr("Settings"), this);
405     connect(m_toSettingsAct, SIGNAL(triggered()),
406         this, SLOT(openSettingsDialog()));
407
408     // GPS
409     m_gpsToggleAct = new QAction(tr("GPS"), this);
410     m_gpsToggleAct->setCheckable(true);
411
412     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
413             this, SIGNAL(gpsTriggered(bool)));
414
415     // automatic centering
416     m_autoCenteringAct = new QAction(tr("Auto centering"), this);
417     m_autoCenteringAct->setCheckable(true);
418     connect(m_autoCenteringAct, SIGNAL(triggered(bool)),
419         this, SIGNAL(autoCenteringTriggered(bool)));
420
421     // build the actual menu
422     m_viewMenu = menuBar()->addMenu(tr("Main"));
423     m_viewMenu->addAction(m_loginAct);
424     m_viewMenu->addAction(m_toSettingsAct);
425     m_viewMenu->addAction(m_gpsToggleAct);
426     m_viewMenu->addAction(m_autoCenteringAct);
427     m_viewMenu->setObjectName(tr("Menu"));
428 }
429
430 void MainWindow::dialogFinished(int status)
431 {
432     qDebug() << __PRETTY_FUNCTION__;
433
434     QDialog *dialog = m_queue.takeFirst();
435     LoginDialog *loginDialog = qobject_cast<LoginDialog *>(dialog);
436     if(loginDialog) {
437         if(status != 0) {
438             buildWebView();
439             loginDialog->userInput(m_email, m_password);
440
441             QStringList urlParts;
442             urlParts.append(FACEBOOK_LOGINBASE);
443             urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
444             urlParts.append(INTERVAL1);
445             urlParts.append(SITUARE_LOGIN_SUCCESS);
446             urlParts.append(INTERVAL2);
447             urlParts.append(SITUARE_LOGIN_FAILURE);
448             urlParts.append(FACEBOOK_LOGIN_ENDING);
449
450             emit saveUsername(m_email);
451             m_refresh = true;
452             m_webView->load(QUrl(urlParts.join(EMPTY)));
453             toggleProgressIndicator(true);
454         } else {
455             emit cancelLoginProcess();
456         }
457     }
458
459     dialog->deleteLater();
460
461     if(!m_error_queue.isEmpty() && m_errorShown == false) {
462         showErrorInformationBox();
463     } else {
464         if(!m_queue.isEmpty()) {
465             showInformationBox();
466         }
467     }
468 }
469
470 void MainWindow::drawFullScreenButton(const QSize &size)
471 {
472     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
473
474     if(m_fullScreenButton) {
475         if(m_loggedIn) {
476             m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width()
477                                      - PANEL_PEEK_AMOUNT,
478                                      size.height() - m_fullScreenButton->size().height());
479         } else {
480             m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width(),
481                                      size.height() - m_fullScreenButton->size().height());
482         }
483     }
484 }
485
486 void MainWindow::drawMapScale(const QSize &size)
487 {
488     const int LEFT_SCALE_MARGIN = 10;
489     const int BOTTOM_SCALE_MARGIN = 2;
490     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
491
492     m_mapScale->move(PANEL_PEEK_AMOUNT + LEFT_SCALE_MARGIN,
493                      size.height() - m_mapScale->size().height() - BOTTOM_SCALE_MARGIN);
494 }
495
496 void MainWindow::drawOsmLicense(const QSize &size)
497 {
498     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
499
500     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
501                        - PANEL_PEEK_AMOUNT,
502                        size.height() - m_osmLicense->fontMetrics().height());
503 }
504
505 void MainWindow::drawOwnLocationCrosshair(const QSize &size)
506 {
507     qDebug() << __PRETTY_FUNCTION__;
508
509     if (m_drawOwnLocationCrosshair && m_ownLocationCrosshair != 0) {
510         m_ownLocationCrosshair->move(size.width()/2 - m_ownLocationCrosshair->pixmap()->width()/2,
511                             size.height()/2 - m_ownLocationCrosshair->pixmap()->height()/2);
512     }
513 }
514
515 void MainWindow::errorDialogFinished(int status)
516 {
517     qDebug() << __PRETTY_FUNCTION__;
518
519     qDebug() << status;
520     QDialog *dialog = m_error_queue.takeFirst();
521
522     dialog->deleteLater();
523     m_errorShown = false;
524
525     if(!m_error_queue.isEmpty())
526         showErrorInformationBox();
527     else if(!m_queue.isEmpty())
528         showInformationBox();
529 }
530
531 void MainWindow::gpsTimeout()
532 {
533     qDebug() << __PRETTY_FUNCTION__;
534
535     buildInformationBox(tr("GPS timeout"));
536 }
537
538 void MainWindow::grabZoomKeys(bool grab)
539 {
540     qDebug() << __PRETTY_FUNCTION__;
541
542 #ifdef Q_WS_MAEMO_5
543     // Can't grab keys unless we have a window id
544     if (!winId())
545         return;
546
547     unsigned long val = (grab) ? 1 : 0;
548     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
549     if (!atom)
550         return;
551
552     XChangeProperty (QX11Info::display(),
553                      winId(),
554                      atom,
555                      XA_INTEGER,
556                      32,
557                      PropModeReplace,
558                      reinterpret_cast<unsigned char *>(&val),
559                      1);
560 #else
561     Q_UNUSED(grab);
562 #endif // Q_WS_MAEMO_5
563 }
564
565 void MainWindow::keyPressEvent(QKeyEvent* event)
566 {
567     qDebug() << __PRETTY_FUNCTION__;
568
569     switch (event->key()) {
570     case Qt::Key_F7:
571         event->accept();
572         emit zoomIn();
573         break;
574
575     case Qt::Key_F8:
576         event->accept();
577         emit zoomOut();
578         break;
579     }
580     QWidget::keyPressEvent(event);
581 }
582
583 void MainWindow::loadCookies()
584 {
585     qDebug() << __PRETTY_FUNCTION__;
586
587     QSettings settings(DIRECTORY_NAME, FILE_NAME);
588
589     QStringList list = settings.value(COOKIES, EMPTY).toStringList();
590
591     if(!list.isEmpty()) {
592         QList<QNetworkCookie> cookieList;
593         for(int i=0;i<list.count();i++) {
594             cookieList.append(QNetworkCookie::parseCookies(list.at(i).toAscii()));
595         }
596
597         if(!m_cookieJar)
598                m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
599
600         m_cookieJar->setAllCookies(cookieList);
601         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
602
603     }
604 }
605
606 void MainWindow::loadDone(bool done)
607 {
608     qDebug() << __PRETTY_FUNCTION__;
609
610     // for the first time the login page is opened, we need to refresh it to get cookies working
611     if(m_refresh) {
612         m_webView->reload();
613         m_refresh = false;
614     }
615
616     if (done)
617     {
618         QWebFrame* frame = m_webView->page()->currentFrame();
619         if (frame!=NULL)
620         {
621             // set email box
622             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
623
624             foreach (QWebElement element, emailCollection) {
625                 element.setAttribute("value", m_email.toAscii());
626             }
627             // set password box
628             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
629             foreach (QWebElement element, passwordCollection) {
630                 element.setAttribute("value", m_password.toAscii());
631             }
632             // find connect button
633             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
634             foreach (QWebElement element, buttonCollection)
635             {
636                 QPoint pos(element.geometry().center());
637
638                 // send a mouse click event to the web page
639                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
640                                    Qt::NoModifier);
641                 QApplication::sendEvent(m_webView->page(), &event0);
642                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
643                                    Qt::NoModifier);
644                 QApplication::sendEvent(m_webView->page(), &event1);
645             }
646         }
647     }
648 }
649
650 void MainWindow::loggedIn(bool logged)
651 {
652     qDebug() << __PRETTY_FUNCTION__;
653
654     m_loggedIn = logged;
655
656     if(logged) {
657         m_loginAct->setText(tr("Logout"));
658     } else {
659         clearCookieJar();
660         m_email.clear();
661         m_password.clear();
662
663         m_loginAct->setText(tr("Login"));
664     }
665     updateItemVisibility();
666 }
667
668 void MainWindow::loginFailed()
669 {
670     qDebug() << __PRETTY_FUNCTION__;
671
672     clearCookieJar();
673     startLoginProcess();
674 }
675
676 bool MainWindow::loginState()
677 {
678     qDebug() << __PRETTY_FUNCTION__;
679
680     return m_loggedIn;
681 }
682
683 void MainWindow::loginUsingCookies()
684 {
685     qDebug() << __PRETTY_FUNCTION__;
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     if(m_loggedIn) {
884         if(!m_friendsListPanel->isVisible()) {
885             m_friendsListPanel->show();
886             m_friendsListPanelSidebar->show();
887         }
888
889         if(!m_userPanel->isVisible()) {
890             m_userPanel->show();
891             m_userPanelSidebar->show();
892         }
893     }
894 }
895
896 void MainWindow::startLoginProcess()
897 {
898     qDebug() << __PRETTY_FUNCTION__;
899
900     LoginDialog *loginDialog = new LoginDialog();
901
902     emit fetchUsernameFromSettings();
903
904     loginDialog->clearTextFields();
905
906     if(!m_email.isEmpty())
907         loginDialog->setEmailField(m_email);
908
909     queueDialog(loginDialog);
910 }
911
912 void MainWindow::toggleProgressIndicator(bool value)
913 {
914     qDebug() << __PRETTY_FUNCTION__;
915
916 #ifdef Q_WS_MAEMO_5
917     if(value) {
918         m_progressIndicatorCount++;
919         setAttribute(Qt::WA_Maemo5ShowProgressIndicator, true);
920     } else {
921         if(m_progressIndicatorCount > 0)
922             m_progressIndicatorCount--;
923
924         if(m_progressIndicatorCount == 0)
925             setAttribute(Qt::WA_Maemo5ShowProgressIndicator, false);
926     }
927 #else
928     Q_UNUSED(value);
929 #endif // Q_WS_MAEMO_5
930 }
931
932 void MainWindow::updateItemVisibility()
933 {
934     qDebug() << __PRETTY_FUNCTION__;
935     
936     if(m_loggedIn) {       
937
938         if(!m_gpsToggleAct->isChecked())
939             setOwnLocationCrosshairVisibility(true);
940     } else {
941         m_friendsListPanel->closePanel();
942         m_friendsListPanel->hide();
943         m_friendsListPanelSidebar->hide();
944         m_userPanel->closePanel();
945         m_userPanel->hide();
946         m_userPanelSidebar->hide();
947         setOwnLocationCrosshairVisibility(false);
948     }
949     drawFullScreenButton(m_viewPortSize);
950 }
951
952 const QString MainWindow::username()
953 {
954     qDebug() << __PRETTY_FUNCTION__;
955     
956     return m_email;
957 }
958
959 void MainWindow::webViewRequestFinished(QNetworkReply *reply)
960 {
961     qDebug() << __PRETTY_FUNCTION__;
962
963     // omit QNetworkReply::OperationCanceledError due to it's nature to be called when ever
964     // qwebview starts to load a new page while the current page loading is not finished
965     if(reply->error() != QNetworkReply::OperationCanceledError &&
966        reply->error() != QNetworkReply::NoError) {
967         emit error(reply->error());
968     }
969 }
970