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