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