Fixed following things: Crosshair is now visible when GPS is not in use on
[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     m_automaticUpdateLocationDialog = new QMessageBox(QMessageBox::Question,
87                                                       tr("Automatic location update"), "",
88                                                       QMessageBox::Yes | QMessageBox::No |
89                                                       QMessageBox::Cancel, this);
90     connect(m_automaticUpdateLocationDialog, SIGNAL(finished(int)),
91             this, SLOT(automaticUpdateDialogFinished(int)));
92
93     createMenus();
94     setWindowTitle(tr("Situare"));
95
96     // set stacking order of widgets
97     m_zoomButtonPanel->stackUnder(m_userPanel);
98     if(m_fullScreenButton) {
99         m_fullScreenButton->stackUnder(m_zoomButtonPanel);
100         m_osmLicense->stackUnder(m_fullScreenButton);
101     } else {
102         m_osmLicense->stackUnder(m_zoomButtonPanel);
103     }
104     m_ownLocationCrosshair->stackUnder(m_osmLicense);
105     m_mapScale->stackUnder(m_ownLocationCrosshair);
106     m_mapView->stackUnder(m_mapScale);
107
108     this->toggleProgressIndicator(true);
109
110     grabZoomKeys(true);
111
112     // set screen size in desktop matching N900 screen size
113     resize(N900_APP_WIDTH, N900_APP_HEIGHT);
114 #ifdef Q_WS_MAEMO_5
115     setAttribute(Qt::WA_Maemo5StackedWindow);
116 #endif
117 }
118
119 MainWindow::~MainWindow()
120 {
121     qDebug() << __PRETTY_FUNCTION__;
122
123     grabZoomKeys(false);
124
125     if(m_webView)
126         delete m_webView;
127
128     qDeleteAll(m_queue.begin(), m_queue.end());
129     m_queue.clear();
130
131     qDeleteAll(m_error_queue.begin(), m_error_queue.end());
132     m_error_queue.clear();
133 }
134
135 void MainWindow::automaticUpdateDialogFinished(int result)
136 {
137     qDebug() << __PRETTY_FUNCTION__;
138
139     if (result == QMessageBox::Yes) {
140         m_settingsDialog->setAutomaticLocationUpdateSettings(true);
141         m_settingsDialog->emitAutomaticLocationUpdateSettings();
142     }
143     else {
144         m_settingsDialog->setAutomaticLocationUpdateSettings(false);
145         m_settingsDialog->emitAutomaticLocationUpdateSettings();
146     }
147 }
148
149 void MainWindow::buildFullScreenButton()
150 {
151     qDebug() << __PRETTY_FUNCTION__;
152 #ifdef Q_WS_MAEMO_5
153     m_fullScreenButton = new QToolButton(this);
154     m_fullScreenButton->setIcon(QIcon::fromTheme(QLatin1String("general_fullsize")));
155     m_fullScreenButton->setFixedSize(m_fullScreenButton->sizeHint());
156     connect(m_fullScreenButton, SIGNAL(clicked()),
157             this, SLOT(toggleFullScreen()));
158 #endif // Q_WS_MAEMO_5
159
160 }
161
162 void MainWindow::buildFriendListPanel()
163 {
164     qDebug() << __PRETTY_FUNCTION__;
165
166     m_friendsListPanel = new FriendListPanel(this);
167     m_friendsListPanelSidebar = new PanelSideBar(this, RIGHT);
168
169     m_friendsListPanel->stackUnder(m_friendsListPanelSidebar);
170
171     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
172             m_friendsListPanel, SLOT(friendInfoReceived(QList<User*>&)));
173
174     connect(m_friendsListPanel, SIGNAL(findFriend(QPointF)),
175             this, SIGNAL(findFriend(QPointF)));
176
177     connect(m_mapView, SIGNAL(viewResized(QSize)),
178             m_friendsListPanel, SLOT(screenResized(QSize)));
179
180     connect(this, SIGNAL(locationItemClicked(QList<QString>)),
181             m_friendsListPanel, SLOT(showFriendsInList(QList<QString>)));
182
183     connect(m_mapView, SIGNAL(viewResized(QSize)),
184             m_friendsListPanelSidebar, SLOT(reDrawSidebar(QSize)));
185 }
186
187 void MainWindow::buildInformationBox(const QString &message, bool modal)
188 {
189     qDebug() << __PRETTY_FUNCTION__;
190
191     QString errorMessage = message;
192
193 #ifdef Q_WS_MAEMO_5
194
195     QMaemo5InformationBox *msgBox = new QMaemo5InformationBox(this);
196
197     if(modal) {
198         msgBox->setTimeout(QMaemo5InformationBox::NoTimeout);
199         // extra line changes are needed to make error notes broader
200         errorMessage.prepend("\n");
201         errorMessage.append("\n");
202     } else {
203         msgBox->setTimeout(QMaemo5InformationBox::DefaultTimeout);
204     }
205     QLabel *label = new QLabel(msgBox);
206     label->setAlignment(Qt::AlignCenter);
207     label->setText(errorMessage);
208     msgBox->setWidget(label);
209 #else
210     QMessageBox *msgBox = new QMessageBox(this);
211     msgBox->button(QMessageBox::Ok);
212     msgBox->setText(errorMessage);
213     msgBox->setModal(modal);
214 #endif
215
216     queueDialog(msgBox);
217 }
218
219 void MainWindow::buildManualLocationCrosshair()
220 {
221     qDebug() << __PRETTY_FUNCTION__;
222
223     m_ownLocationCrosshair = new QLabel(this);
224     QPixmap crosshairImage(":/res/images/sight.png");
225     m_ownLocationCrosshair->setPixmap(crosshairImage);
226     m_ownLocationCrosshair->setFixedSize(crosshairImage.size());
227     m_ownLocationCrosshair->hide();
228     m_ownLocationCrosshair->setAttribute(Qt::WA_TransparentForMouseEvents, true);
229
230     connect(m_mapView, SIGNAL(viewResized(QSize)),
231             this, SLOT(drawOwnLocationCrosshair(QSize)));
232 }
233
234 void MainWindow::buildMap()
235 {
236     qDebug() << __PRETTY_FUNCTION__;
237
238     m_mapView = new MapView(this);
239
240     buildZoomButtonPanel();
241     buildOsmLicense();
242     buildManualLocationCrosshair();
243     buildFullScreenButton();
244     buildMapScale();
245
246     connect(m_mapView, SIGNAL(viewScrolled(QPoint)),
247             this, SIGNAL(mapViewScrolled(QPoint)));
248
249     connect(this, SIGNAL(centerToSceneCoordinates(QPoint)),
250             m_mapView, SLOT(centerToSceneCoordinates(QPoint)));
251
252     connect(m_mapView, SIGNAL(viewResized(QSize)),
253             this, SIGNAL(mapViewResized(QSize)));
254
255     connect(m_mapView, SIGNAL(viewResized(QSize)),
256             this, SLOT(drawFullScreenButton(QSize)));
257
258     connect(m_mapView, SIGNAL(viewResized(QSize)),
259             this, SLOT(drawMapScale(QSize)));
260
261     connect(m_mapView, SIGNAL(viewResized(QSize)),
262              this, SLOT(setViewPortSize(QSize)));
263
264     connect(this, SIGNAL(zoomLevelChanged(int)),
265             m_mapView, SLOT(setZoomLevel(int)));
266
267     connect(m_mapView, SIGNAL(viewZoomFinished()),
268             this, SIGNAL(viewZoomFinished()));
269 }
270
271 void MainWindow::buildMapScale()
272 {
273     m_mapScale = new MapScale(this);
274     connect(this, SIGNAL(newMapResolution(qreal)),
275             m_mapScale, SLOT(updateMapResolution(qreal)));
276 }
277
278 void MainWindow::buildOsmLicense()
279 {
280     qDebug() << __PRETTY_FUNCTION__;
281
282     m_osmLicense = new QLabel(this);
283     m_osmLicense->setAttribute(Qt::WA_TranslucentBackground, true);
284     m_osmLicense->setAttribute(Qt::WA_TransparentForMouseEvents, true);
285     m_osmLicense->setText("<font color='black'>" + OSM_LICENSE + "</font>");
286     m_osmLicense->setFont(QFont("Nokia Sans", 9));
287     m_osmLicense->resize(m_osmLicense->fontMetrics().width(OSM_LICENSE),
288                          m_osmLicense->fontMetrics().height());
289
290     connect(m_mapView, SIGNAL(viewResized(QSize)),
291             this, SLOT(drawOsmLicense(QSize)));
292 }
293
294 void MainWindow::buildUserInfoPanel()
295 {
296     qDebug() << __PRETTY_FUNCTION__;
297
298     m_userPanel = new UserInfoPanel(this);
299     m_userPanelSidebar = new PanelSideBar(this, LEFT);
300
301     m_userPanelSidebar->stackUnder(m_friendsListPanel);
302     m_userPanel->stackUnder(m_userPanelSidebar);
303
304     connect(m_userPanel, SIGNAL(findUser(QPointF)),
305             this, SIGNAL(findUser(QPointF)));
306
307     connect(this, SIGNAL(userLocationReady(User*)),
308             m_userPanel, SLOT(userDataReceived(User*)));
309
310     connect(m_userPanel, SIGNAL(requestReverseGeo()),
311             this, SIGNAL(requestReverseGeo()));
312
313     connect(this, SIGNAL(reverseGeoReady(QString)),
314             m_userPanel, SIGNAL(reverseGeoReady(QString)));
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_mapView, SIGNAL(viewResized(QSize)),
323             m_userPanel, SLOT(screenResized(QSize)));
324
325     connect(this, SIGNAL(clearUpdateLocationDialogData()),
326             m_userPanel, SIGNAL(clearUpdateLocationDialogData()));
327
328     connect(this, SIGNAL(messageSendingFailed(int)),
329             m_userPanel, SIGNAL(messageSendingFailed(int)));
330
331     connect(m_userPanel, SIGNAL(notificateUpdateFailing(QString, bool)),
332             this, SLOT(buildInformationBox(QString, bool)));
333 }
334
335 void MainWindow::buildWebView()
336 {
337     qDebug() << __PRETTY_FUNCTION__;
338
339     if(!m_webView) {
340         m_webView = new QWebView;
341
342         if(!m_cookieJar)
343             m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
344
345         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
346
347         connect(m_webView->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
348                 this, SLOT(webViewRequestFinished(QNetworkReply*)));
349         connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
350                 this, SIGNAL(updateCredentials(QUrl)));
351         connect(m_webView, SIGNAL(loadFinished(bool)),
352                 this, SLOT(loadDone(bool)));
353
354         m_webView->hide();
355     }
356 }
357
358 void MainWindow::buildZoomButtonPanel()
359 {
360     qDebug() << __PRETTY_FUNCTION__;
361
362     m_zoomButtonPanel = new ZoomButtonPanel(this);
363
364     connect(m_zoomButtonPanel->zoomInButton(), SIGNAL(clicked()),
365             this, SIGNAL(zoomIn()));
366
367     connect(m_zoomButtonPanel->zoomOutButton(), SIGNAL(clicked()),
368             this, SIGNAL(zoomOut()));
369
370     connect(this, SIGNAL(zoomLevelChanged(int)),
371             m_zoomButtonPanel, SLOT(resetButtons()));
372
373     connect(this, SIGNAL(maxZoomLevelReached()),
374             m_zoomButtonPanel, SLOT(disableZoomInButton()));
375
376     connect(this, SIGNAL(minZoomLevelReached()),
377             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
378
379     connect(m_mapView, SIGNAL(viewResized(QSize)),
380             m_zoomButtonPanel, SLOT(screenResized(QSize)));
381 }
382
383 void MainWindow::clearCookieJar()
384 {
385     qDebug() << __PRETTY_FUNCTION__;
386
387     buildWebView();
388
389     if(!m_cookieJar) {
390         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
391     }
392     QList<QNetworkCookie> emptyList;
393     emptyList.clear();
394
395     m_cookieJar->setAllCookies(emptyList);
396     m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
397 }
398
399 void MainWindow::createMenus()
400 {
401     qDebug() << __PRETTY_FUNCTION__;
402
403     // login/logout
404     m_loginAct = new QAction(tr("Login"), this);
405     connect(m_loginAct, SIGNAL(triggered()),
406             this, SIGNAL(loginActionPressed()));
407
408     // settings
409     m_toSettingsAct = new QAction(tr("Settings"), this);
410     connect(m_toSettingsAct, SIGNAL(triggered()),
411         this, SLOT(openSettingsDialog()));
412
413     // GPS
414     m_gpsToggleAct = new QAction(tr("GPS"), this);
415     m_gpsToggleAct->setCheckable(true);
416
417     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
418             this, SIGNAL(gpsTriggered(bool)));
419
420     // automatic centering
421     m_autoCenteringAct = new QAction(tr("Auto centering"), this);
422     m_autoCenteringAct->setCheckable(true);
423     connect(m_autoCenteringAct, SIGNAL(triggered(bool)),
424         this, SIGNAL(autoCenteringTriggered(bool)));
425
426     // build the actual menu
427     m_viewMenu = menuBar()->addMenu(tr("Main"));
428     m_viewMenu->addAction(m_loginAct);
429     m_viewMenu->addAction(m_toSettingsAct);
430     m_viewMenu->addAction(m_gpsToggleAct);
431     m_viewMenu->addAction(m_autoCenteringAct);
432     m_viewMenu->setObjectName(tr("Menu"));
433 }
434
435 void MainWindow::dialogFinished(int status)
436 {
437     qDebug() << __PRETTY_FUNCTION__;
438
439     QDialog *dialog = m_queue.takeFirst();
440     LoginDialog *loginDialog = qobject_cast<LoginDialog *>(dialog);
441     if(loginDialog) {
442         if(status != 0) {
443             buildWebView();
444             loginDialog->userInput(m_email, m_password);
445
446             QStringList urlParts;
447             urlParts.append(FACEBOOK_LOGINBASE);
448             urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
449             urlParts.append(INTERVAL1);
450             urlParts.append(SITUARE_LOGIN_SUCCESS);
451             urlParts.append(INTERVAL2);
452             urlParts.append(SITUARE_LOGIN_FAILURE);
453             urlParts.append(FACEBOOK_LOGIN_ENDING);
454
455             emit saveUsername(m_email);
456             m_refresh = true;
457             m_webView->load(QUrl(urlParts.join(EMPTY)));
458             toggleProgressIndicator(true);
459         } else {
460             emit cancelLoginProcess();
461         }
462     }
463
464     dialog->deleteLater();
465
466     if(!m_error_queue.isEmpty() && m_errorShown == false) {
467         showErrorInformationBox();
468     } else {
469         if(!m_queue.isEmpty()) {
470             showInformationBox();
471         }
472     }
473 }
474
475 void MainWindow::drawFullScreenButton(const QSize &size)
476 {
477     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
478
479     if(m_fullScreenButton) {
480         m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width()
481                                  - PANEL_PEEK_AMOUNT,
482                                  size.height() - m_fullScreenButton->size().height());
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(m_loggedIn);
666 }
667
668 void MainWindow::loginFailed()
669 {
670     qDebug() << __PRETTY_FUNCTION__;
671
672     clearCookieJar();
673
674     toggleProgressIndicator(false);
675
676     startLoginProcess();
677 }
678
679 void MainWindow::loginUsingCookies()
680 {
681     qDebug() << __PRETTY_FUNCTION__;
682
683     buildWebView();
684     loadCookies();
685     
686     QStringList urlParts;
687     urlParts.append(FACEBOOK_LOGINBASE);
688     urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
689     urlParts.append(INTERVAL1);
690     urlParts.append(SITUARE_LOGIN_SUCCESS);
691     urlParts.append(INTERVAL2);
692     urlParts.append(SITUARE_LOGIN_FAILURE);
693     urlParts.append(FACEBOOK_LOGIN_ENDING);
694
695     m_webView->load(QUrl(urlParts.join(EMPTY)));
696
697 }
698
699 void MainWindow::openSettingsDialog()
700 {
701     qDebug() << __PRETTY_FUNCTION__;
702
703     m_settingsDialog->enableSituareSettings(m_gpsToggleAct->isChecked() && m_loggedIn);
704     m_settingsDialog->readSettings();
705     m_settingsDialog->show();
706 }
707
708 void MainWindow::requestAutomaticLocationUpdateSettings()
709 {
710     qDebug() << __PRETTY_FUNCTION__;
711
712     m_settingsDialog->readSettings();
713     m_settingsDialog->emitAutomaticLocationUpdateSettings();
714 }
715
716 void MainWindow::queueDialog(QDialog *dialog)
717 {
718     qDebug() << __PRETTY_FUNCTION__;
719
720     // check is dialog is modal, for now all modal dialogs have hihger priority i.e. errors
721     if(dialog->isModal()) {
722         m_error_queue.append(dialog);
723     } else {
724         m_queue.append(dialog);
725     }
726
727     // show error dialog if there is only one error dialog in the queue and no error dialog is shown
728     if(m_error_queue.count() == 1 && m_errorShown == false)
729         showErrorInformationBox();
730     else if(m_queue.count() == 1 && m_errorShown == false)
731         showInformationBox();
732 }
733
734 void MainWindow::saveCookies()
735 {
736     qDebug() << __PRETTY_FUNCTION__;
737
738     if(!m_cookieJar)
739         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
740
741     QList<QNetworkCookie> cookieList = m_cookieJar->allCookies();
742     QStringList list;
743
744     for(int i=0;i<cookieList.count();i++) {
745         QNetworkCookie cookie = cookieList.at(i);
746         QByteArray byteArray = cookie.toRawForm(QNetworkCookie::Full);
747         list.append(QString(byteArray));
748     }
749     list.removeDuplicates();
750
751     QSettings settings(DIRECTORY_NAME, FILE_NAME);
752     settings.setValue(COOKIES, list);
753 }
754
755 void MainWindow::setAutoCenteringButtonEnabled(bool enabled)
756 {
757     qDebug() << __PRETTY_FUNCTION__;
758
759     m_autoCenteringAct->setChecked(enabled);
760 }
761
762 void MainWindow::setGPSButtonEnabled(bool enabled)
763 {
764     qDebug() << __PRETTY_FUNCTION__;
765
766     m_gpsToggleAct->setChecked(enabled);
767
768     setOwnLocationCrosshairVisibility(!enabled);
769
770     m_autoCenteringAct->setVisible(enabled);
771 }
772
773 void MainWindow::setMapViewScene(QGraphicsScene *scene)
774 {
775     qDebug() << __PRETTY_FUNCTION__;
776
777     m_mapView->setScene(scene);
778 }
779
780 void MainWindow::setOwnLocationCrosshairVisibility(bool visibility)
781 {
782     qDebug() << __PRETTY_FUNCTION__;
783
784     if (visibility && m_loggedIn) {
785         m_ownLocationCrosshair->show();
786         m_drawOwnLocationCrosshair = true;
787         drawOwnLocationCrosshair(QSize(m_viewPortWidth, m_viewPortHeight));
788     } else {
789         m_ownLocationCrosshair->hide();
790         m_drawOwnLocationCrosshair = false;
791     }
792 }
793
794 void MainWindow::setUsername(const QString &username)
795 {
796     qDebug() << __PRETTY_FUNCTION__;
797
798     m_email = username;
799 }
800
801 void MainWindow::setViewPortSize(const QSize &size)
802 {
803     qDebug() << __PRETTY_FUNCTION__;
804
805     m_viewPortWidth = size.width();
806     m_viewPortHeight = size.height();
807 }
808
809 void MainWindow::showEnableAutomaticUpdateLocationDialog(const QString &text)
810 {
811     qDebug() << __PRETTY_FUNCTION__;
812
813     m_automaticUpdateLocationDialog->setText(text);
814     m_automaticUpdateLocationDialog->show();
815 }
816
817 void MainWindow::toggleFullScreen()
818 {
819     qDebug() << __PRETTY_FUNCTION__;
820
821     if(windowState() == Qt::WindowNoState)
822         showFullScreen();
823     else
824         showNormal();
825 }
826
827 void MainWindow::showErrorInformationBox()
828 {
829     qDebug() << __PRETTY_FUNCTION__;
830
831     if(m_error_queue.count()) {
832         m_errorShown = true;
833         QDialog *dialog = m_error_queue.first();
834         connect(dialog, SIGNAL(finished(int)),
835                 this, SLOT(errorDialogFinished(int)));
836         dialog->show();
837     }
838 }
839
840 void MainWindow::showInformationBox()
841 {
842     qDebug() << __PRETTY_FUNCTION__;
843
844     if(m_queue.count()) {
845         QDialog *dialog = m_queue.first();
846         connect(dialog, SIGNAL(finished(int)),
847                 this, SLOT(dialogFinished(int)));
848         dialog->show();
849     }
850 }
851
852 void MainWindow::startLoginProcess()
853 {
854     qDebug() << __PRETTY_FUNCTION__;
855
856     LoginDialog *loginDialog = new LoginDialog();
857
858     emit fetchUsernameFromSettings();
859
860     loginDialog->clearTextFields();
861
862     if(!m_email.isEmpty())
863         loginDialog->setEmailField(m_email);
864
865     queueDialog(loginDialog);
866 }
867
868 void MainWindow::toggleProgressIndicator(bool value)
869 {
870     qDebug() << __PRETTY_FUNCTION__;
871
872 #ifdef Q_WS_MAEMO_5
873     setAttribute(Qt::WA_Maemo5ShowProgressIndicator, value);
874 #else
875     Q_UNUSED(value);
876 #endif // Q_WS_MAEMO_5
877 }
878
879 void MainWindow::updateItemVisibility(bool show)
880 {
881     qDebug() << __PRETTY_FUNCTION__;
882     
883     if(show) {
884         m_friendsListPanel->show();
885         m_friendsListPanelSidebar->show();
886         m_userPanel->show();
887         m_userPanelSidebar->show();
888         if(!m_gpsToggleAct->isChecked())
889             setOwnLocationCrosshairVisibility(show);
890
891     } else {
892         m_friendsListPanel->closePanel();
893         m_friendsListPanel->hide();
894         m_friendsListPanelSidebar->hide();
895         m_userPanel->closePanel();
896         m_userPanel->hide();
897         m_userPanelSidebar->hide();
898         setOwnLocationCrosshairVisibility(false);
899     }
900 }
901
902 const QString MainWindow::username()
903 {
904     qDebug() << __PRETTY_FUNCTION__;
905     
906     return m_email;
907 }
908
909 void MainWindow::webViewRequestFinished(QNetworkReply *reply)
910 {
911     qDebug() << __PRETTY_FUNCTION__;
912
913     if(reply->error()) {
914         emit error(reply->error());
915         toggleProgressIndicator(false);
916     }
917 }
918