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