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