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