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