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