Added missing default values to PanelBar, PanelBase and TabbedPanel constructors
[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_tabbedPanel, SIGNAL(panelOpened()),
311             m_friendsListPanel, SLOT(clearFriendListFilter()));
312
313     connect(m_mapView, SIGNAL(viewResized(QSize)),
314             m_tabbedPanel, SLOT(resizePanel(QSize)));
315 }
316
317 void MainWindow::buildUserInfoPanel()
318 {
319     qDebug() << __PRETTY_FUNCTION__;
320
321     m_userInfoPanel = new UserInfoPanel(this);
322
323     connect(this, SIGNAL(userLocationReady(User*)),
324             m_userInfoPanel, SLOT(userDataReceived(User*)));
325
326     connect(this, SIGNAL(reverseGeoReady(QString)),
327             m_userInfoPanel, SIGNAL(reverseGeoReady(QString)));
328
329     connect(this, SIGNAL(clearUpdateLocationDialogData()),
330             m_userInfoPanel, SIGNAL(clearUpdateLocationDialogData()));
331
332     connect(m_userInfoPanel, SIGNAL(findUser(GeoCoordinate)),
333             this, SIGNAL(findUser(GeoCoordinate)));
334
335     connect(m_userInfoPanel, SIGNAL(requestReverseGeo()),
336             this, SIGNAL(requestReverseGeo()));
337
338     connect(m_userInfoPanel, SIGNAL(statusUpdate(QString,bool)),
339             this, SIGNAL(statusUpdate(QString,bool)));
340
341     connect(m_userInfoPanel, SIGNAL(refreshUserData()),
342             this, SIGNAL(refreshUserData()));
343
344     connect(m_userInfoPanel, SIGNAL(notificateUpdateFailing(QString, bool)),
345             this, SLOT(buildInformationBox(QString, bool)));
346 }
347
348 void MainWindow::buildWebView()
349 {
350     qDebug() << __PRETTY_FUNCTION__;
351
352     if(!m_webView) {
353         m_webView = new QWebView;
354
355         if(!m_cookieJar)
356             m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
357
358         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
359
360         connect(m_webView->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
361                 this, SLOT(webViewRequestFinished(QNetworkReply*)));
362         connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
363                 this, SIGNAL(updateCredentials(QUrl)));
364         connect(m_webView, SIGNAL(loadFinished(bool)),
365                 this, SLOT(loadDone(bool)));
366
367         m_webView->hide();
368     }
369 }
370
371 void MainWindow::buildZoomButtonPanel()
372 {
373     qDebug() << __PRETTY_FUNCTION__;
374
375     m_zoomButtonPanel = new ZoomButtonPanel(this);
376
377     connect(m_zoomButtonPanel->zoomInButton(), SIGNAL(clicked()),
378             this, SIGNAL(zoomIn()));
379
380     connect(m_zoomButtonPanel->zoomOutButton(), SIGNAL(clicked()),
381             this, SIGNAL(zoomOut()));
382
383     connect(this, SIGNAL(zoomLevelChanged(int)),
384             m_zoomButtonPanel, SLOT(resetButtons()));
385
386     connect(this, SIGNAL(maxZoomLevelReached()),
387             m_zoomButtonPanel, SLOT(disableZoomInButton()));
388
389     connect(this, SIGNAL(minZoomLevelReached()),
390             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
391
392     connect(m_mapView, SIGNAL(viewResized(QSize)),
393             m_zoomButtonPanel, SLOT(screenResized(QSize)));
394
395     connect(m_zoomButtonPanel, SIGNAL(draggingModeTriggered()),
396             this, SIGNAL(draggingModeTriggered()));
397 }
398
399 void MainWindow::clearCookieJar()
400 {
401     qDebug() << __PRETTY_FUNCTION__;
402
403     buildWebView();
404
405     m_webView->stop();
406
407     if(!m_cookieJar) {
408         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
409     }
410     QList<QNetworkCookie> emptyList;
411     emptyList.clear();
412
413     m_cookieJar->setAllCookies(emptyList);
414     m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
415 }
416
417 void MainWindow::createMenus()
418 {
419     qDebug() << __PRETTY_FUNCTION__;
420
421     // login/logout
422     m_loginAct = new QAction(tr("Login"), this);
423     connect(m_loginAct, SIGNAL(triggered()),
424             this, SIGNAL(loginActionPressed()));
425
426     // settings
427     m_toSettingsAct = new QAction(tr("Settings"), this);
428     connect(m_toSettingsAct, SIGNAL(triggered()),
429         this, SLOT(openSettingsDialog()));
430
431     // GPS
432     m_gpsToggleAct = new QAction(tr("GPS"), this);
433     m_gpsToggleAct->setCheckable(true);
434
435     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
436             this, SIGNAL(gpsTriggered(bool)));
437
438     /// @todo remove when not needed!
439     m_searchLocationAct = new QAction(tr("Location search"), this);
440     connect(m_searchLocationAct, SIGNAL(triggered()),
441             this, SLOT(startLocationSearch()));
442
443     // build the actual menu
444     m_viewMenu = menuBar()->addMenu(tr("Main"));
445     m_viewMenu->addAction(m_loginAct);
446     m_viewMenu->addAction(m_toSettingsAct);
447     m_viewMenu->addAction(m_gpsToggleAct);
448     m_viewMenu->addAction(m_searchLocationAct); /// @todo remove when not needed!
449     m_viewMenu->setObjectName(tr("Menu"));
450 }
451
452 void MainWindow::dialogFinished(int status)
453 {
454     qDebug() << __PRETTY_FUNCTION__;
455
456     QDialog *dialog = m_queue.takeFirst();
457     LoginDialog *loginDialog = qobject_cast<LoginDialog *>(dialog);
458     SearchDialog *searchDialog = qobject_cast<SearchDialog *>(dialog);
459     if(loginDialog) {
460         if(status != 0) {
461             buildWebView();
462             loginDialog->userInput(m_email, m_password);
463
464             QStringList urlParts;
465             urlParts.append(FACEBOOK_LOGINBASE);
466             urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
467             urlParts.append(INTERVAL1);
468             urlParts.append(SITUARE_LOGIN_SUCCESS);
469             urlParts.append(INTERVAL2);
470             urlParts.append(SITUARE_LOGIN_FAILURE);
471             urlParts.append(FACEBOOK_LOGIN_ENDING);
472
473             emit saveUsername(m_email);
474             m_refresh = true;
475             m_webView->load(QUrl(urlParts.join(EMPTY)));
476             toggleProgressIndicator(true);
477         } else {
478             emit cancelLoginProcess();
479         }
480     } else if(searchDialog) {
481         if(status != 0) {
482             emit searchForLocation(searchDialog->input());
483         }
484     }
485
486     dialog->deleteLater();
487
488     if(!m_error_queue.isEmpty() && m_errorShown == false) {
489         showErrorInformationBox();
490     } else {
491         if(!m_queue.isEmpty()) {
492             showInformationBox();
493         }
494     }
495 }
496
497 void MainWindow::drawFullScreenButton(const QSize &size)
498 {
499     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
500
501     if(m_fullScreenButton)
502         m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width(),
503                                  size.height() - m_fullScreenButton->size().height());
504 }
505
506 void MainWindow::drawMapScale(const QSize &size)
507 {
508     qDebug() << __PRETTY_FUNCTION__;
509
510     const int LEFT_SCALE_MARGIN = 10;
511     const int BOTTOM_SCALE_MARGIN = 2;
512 //    qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
513
514     m_mapScale->move(LEFT_SCALE_MARGIN,
515                      size.height() - m_mapScale->size().height() - BOTTOM_SCALE_MARGIN);
516 }
517
518 void MainWindow::drawOsmLicense(const QSize &size)
519 {
520     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
521
522     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
523                        - PANEL_BAR_WIDTH,
524                        size.height() - m_osmLicense->fontMetrics().height());
525 }
526
527 void MainWindow::drawOwnLocationCrosshair(const QSize &size)
528 {
529     qDebug() << __PRETTY_FUNCTION__;
530
531     if (m_ownLocationCrosshair != 0) {
532         m_ownLocationCrosshair->move(size.width()/2 - m_ownLocationCrosshair->pixmap()->width()/2,
533                             size.height()/2 - m_ownLocationCrosshair->pixmap()->height()/2);
534     }
535 }
536
537 void MainWindow::errorDialogFinished(int status)
538 {
539     qDebug() << __PRETTY_FUNCTION__;
540
541     qDebug() << status;
542     QDialog *dialog = m_error_queue.takeFirst();
543
544     dialog->deleteLater();
545     m_errorShown = false;
546
547     if(!m_error_queue.isEmpty())
548         showErrorInformationBox();
549     else if(!m_queue.isEmpty())
550         showInformationBox();
551 }
552
553 void MainWindow::gpsTimeout()
554 {
555     qDebug() << __PRETTY_FUNCTION__;
556
557     buildInformationBox(tr("GPS timeout"));
558 }
559
560 void MainWindow::grabZoomKeys(bool grab)
561 {
562     qDebug() << __PRETTY_FUNCTION__;
563
564 #ifdef Q_WS_MAEMO_5
565     // Can't grab keys unless we have a window id
566     if (!winId())
567         return;
568
569     unsigned long val = (grab) ? 1 : 0;
570     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
571     if (!atom)
572         return;
573
574     XChangeProperty (QX11Info::display(),
575                      winId(),
576                      atom,
577                      XA_INTEGER,
578                      32,
579                      PropModeReplace,
580                      reinterpret_cast<unsigned char *>(&val),
581                      1);
582 #else
583     Q_UNUSED(grab);
584 #endif // Q_WS_MAEMO_5
585 }
586
587 void MainWindow::keyPressEvent(QKeyEvent* event)
588 {
589     qDebug() << __PRETTY_FUNCTION__;
590
591     switch (event->key()) {
592     case Qt::Key_F7:
593         event->accept();
594         emit zoomIn();
595         break;
596
597     case Qt::Key_F8:
598         event->accept();
599         emit zoomOut();
600         break;
601     }
602     QWidget::keyPressEvent(event);
603 }
604
605 void MainWindow::loadCookies()
606 {
607     qDebug() << __PRETTY_FUNCTION__;
608
609     QSettings settings(DIRECTORY_NAME, FILE_NAME);
610
611     QStringList list = settings.value(COOKIES, EMPTY).toStringList();
612
613     if(!list.isEmpty()) {
614         QList<QNetworkCookie> cookieList;
615         for(int i=0;i<list.count();i++) {
616             cookieList.append(QNetworkCookie::parseCookies(list.at(i).toAscii()));
617         }
618
619         if(!m_cookieJar)
620                m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
621
622         m_cookieJar->setAllCookies(cookieList);
623         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
624     }
625 }
626
627 void MainWindow::loadDone(bool done)
628 {
629     qDebug() << __PRETTY_FUNCTION__;
630
631     // for the first time the login page is opened, we need to refresh it to get cookies working
632     if(m_refresh) {
633         m_webView->reload();
634         m_refresh = false;
635     }
636
637     if (done)
638     {
639         QWebFrame* frame = m_webView->page()->currentFrame();
640         if (frame!=NULL)
641         {
642             // set email box
643             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
644
645             foreach (QWebElement element, emailCollection) {
646                 element.setAttribute("value", m_email.toAscii());
647             }
648             // set password box
649             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
650             foreach (QWebElement element, passwordCollection) {
651                 element.setAttribute("value", m_password.toAscii());
652             }
653             // find connect button
654             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
655             foreach (QWebElement element, buttonCollection)
656             {
657                 QPoint pos(element.geometry().center());
658
659                 // send a mouse click event to the web page
660                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
661                                    Qt::NoModifier);
662                 QApplication::sendEvent(m_webView->page(), &event0);
663                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
664                                    Qt::NoModifier);
665                 QApplication::sendEvent(m_webView->page(), &event1);
666             }
667         }
668     }
669 }
670
671 void MainWindow::loggedIn(bool logged)
672 {
673     qDebug() << __PRETTY_FUNCTION__;
674
675     m_loggedIn = logged;
676
677     if(logged) {
678         m_loginAct->setText(tr("Logout"));
679     } else {
680         clearCookieJar();
681         m_email.clear();
682         m_password.clear();
683
684         m_loginAct->setText(tr("Login"));
685     }
686     updateItemVisibility();
687 }
688
689 void MainWindow::loginFailed()
690 {
691     qDebug() << __PRETTY_FUNCTION__;
692
693     clearCookieJar();
694     startLoginProcess();
695 }
696
697 bool MainWindow::loginState()
698 {
699     qDebug() << __PRETTY_FUNCTION__;
700
701     return m_loggedIn;
702 }
703
704 void MainWindow::loginUsingCookies()
705 {
706     qDebug() << __PRETTY_FUNCTION__;
707
708     toggleProgressIndicator(true);
709
710     buildWebView();
711     loadCookies();
712
713     QStringList urlParts;
714     urlParts.append(FACEBOOK_LOGINBASE);
715     urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
716     urlParts.append(INTERVAL1);
717     urlParts.append(SITUARE_LOGIN_SUCCESS);
718     urlParts.append(INTERVAL2);
719     urlParts.append(SITUARE_LOGIN_FAILURE);
720     urlParts.append(FACEBOOK_LOGIN_ENDING);
721
722     m_webView->load(QUrl(urlParts.join(EMPTY)));
723
724 }
725
726 void MainWindow::openSettingsDialog()
727 {
728     qDebug() << __PRETTY_FUNCTION__;
729
730     SettingsDialog *settingsDialog = new SettingsDialog(this);
731     settingsDialog->enableSituareSettings((m_loggedIn && m_gpsToggleAct->isChecked()));
732     connect(settingsDialog, SIGNAL(accepted()), this, SLOT(settingsDialogAccepted()));
733
734     settingsDialog->show();
735 }
736
737 void MainWindow::readAutomaticLocationUpdateSettings()
738 {
739     qDebug() << __PRETTY_FUNCTION__;
740
741     QSettings settings(DIRECTORY_NAME, FILE_NAME);
742     bool automaticUpdateEnabled = settings.value(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false).toBool();
743     QTime automaticUpdateInterval = settings.value(SETTINGS_AUTOMATIC_UPDATE_INTERVAL, QTime())
744                                       .toTime();
745
746     if (automaticUpdateEnabled && automaticUpdateInterval.isValid()) {
747         QTime time;
748         emit enableAutomaticLocationUpdate(true, time.msecsTo(automaticUpdateInterval));
749     } else {
750         emit enableAutomaticLocationUpdate(false);
751     }
752 }
753
754 void MainWindow::queueDialog(QDialog *dialog)
755 {
756     qDebug() << __PRETTY_FUNCTION__;
757
758     // check is dialog is modal, for now all modal dialogs have hihger priority i.e. errors
759     if(dialog->isModal()) {
760         m_error_queue.append(dialog);
761     } else {
762         m_queue.append(dialog);
763     }
764
765     // show error dialog if there is only one error dialog in the queue and no error dialog is shown
766     if(m_error_queue.count() == 1 && m_errorShown == false)
767         showErrorInformationBox();
768     else if(m_queue.count() == 1 && m_errorShown == false)
769         showInformationBox();
770 }
771
772 void MainWindow::saveCookies()
773 {
774     qDebug() << __PRETTY_FUNCTION__;
775
776     if(!m_cookieJar)
777         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
778
779     QList<QNetworkCookie> cookieList = m_cookieJar->allCookies();
780     QStringList list;
781
782     for(int i=0;i<cookieList.count();i++) {
783         QNetworkCookie cookie = cookieList.at(i);
784         QByteArray byteArray = cookie.toRawForm(QNetworkCookie::Full);
785         list.append(QString(byteArray));
786     }
787     list.removeDuplicates();
788
789     QSettings settings(DIRECTORY_NAME, FILE_NAME);
790     settings.setValue(COOKIES, list);
791 }
792
793 void MainWindow::setGPSButtonEnabled(bool enabled)
794 {
795     qDebug() << __PRETTY_FUNCTION__;
796
797     m_gpsToggleAct->setChecked(enabled);
798 }
799
800 void MainWindow::setIndicatorButtonEnabled(bool enabled)
801 {
802     qDebug() << __PRETTY_FUNCTION__;
803
804     m_indicatorButton->setChecked(enabled);
805
806 }
807
808 void MainWindow::setMapViewScene(QGraphicsScene *scene)
809 {
810     qDebug() << __PRETTY_FUNCTION__;
811
812     m_mapView->setScene(scene);
813 }
814
815 void MainWindow::setOwnLocationCrosshairVisibility(bool visibility)
816 {
817     qDebug() << __PRETTY_FUNCTION__;
818
819     if (visibility) {
820         m_ownLocationCrosshair->show();
821         drawOwnLocationCrosshair(m_viewPortSize);
822     } else {
823         m_ownLocationCrosshair->hide();
824     }
825 }
826
827 void MainWindow::settingsDialogAccepted()
828 {
829     qDebug() << __PRETTY_FUNCTION__;
830
831     readAutomaticLocationUpdateSettings();
832 }
833
834 void MainWindow::setUsername(const QString &username)
835 {
836     qDebug() << __PRETTY_FUNCTION__;
837
838     m_email = username;
839 }
840
841 void MainWindow::setViewPortSize(const QSize &size)
842 {
843     qDebug() << __PRETTY_FUNCTION__;
844
845     m_viewPortSize = size;
846 }
847
848 void MainWindow::showEnableAutomaticUpdateLocationDialog(const QString &text)
849 {
850     qDebug() << __PRETTY_FUNCTION__;
851
852     m_automaticUpdateLocationDialog = new QMessageBox(QMessageBox::Question,
853                                                       tr("Automatic location update"), text,
854                                                       QMessageBox::Yes | QMessageBox::No |
855                                                       QMessageBox::Cancel, this);
856     connect(m_automaticUpdateLocationDialog, SIGNAL(finished(int)),
857             this, SLOT(automaticUpdateDialogFinished(int)));
858
859     m_automaticUpdateLocationDialog->show();
860 }
861
862 void MainWindow::toggleFullScreen()
863 {
864     qDebug() << __PRETTY_FUNCTION__;
865
866     if(windowState() == Qt::WindowNoState)
867         showFullScreen();
868     else
869         showNormal();
870 }
871
872 void MainWindow::showErrorInformationBox()
873 {
874     qDebug() << __PRETTY_FUNCTION__;
875
876     if(m_error_queue.count()) {
877         m_errorShown = true;
878         QDialog *dialog = m_error_queue.first();
879         connect(dialog, SIGNAL(finished(int)),
880                 this, SLOT(errorDialogFinished(int)));
881         dialog->show();
882     }
883 }
884
885 void MainWindow::showInformationBox()
886 {
887     qDebug() << __PRETTY_FUNCTION__;
888
889     if(m_queue.count()) {
890         QDialog *dialog = m_queue.first();
891         connect(dialog, SIGNAL(finished(int)),
892                 this, SLOT(dialogFinished(int)));
893         dialog->show();
894     }
895 }
896
897 void MainWindow::showPanels()
898 {
899     qDebug() << __PRETTY_FUNCTION__;
900
901     drawFullScreenButton(m_viewPortSize);
902
903 //    if(m_loggedIn) {
904 //        if(!m_friendsListPanel->isVisible()) {
905 //            m_friendsListPanel->show();
906 //            m_friendsListPanelSidebar->show();
907 //        }
908
909 //        if(!m_userPanel->isVisible()) {
910 //            m_userPanel->show();
911 //            m_userPanelSidebar->show();
912 //        }
913 //    }
914 }
915
916 void MainWindow::startLocationSearch()
917 {
918     qDebug() << __PRETTY_FUNCTION__;
919
920     SearchDialog *searchDialog = new SearchDialog();
921     queueDialog(searchDialog);
922 }
923
924 void MainWindow::startLoginProcess()
925 {
926     qDebug() << __PRETTY_FUNCTION__;
927
928     LoginDialog *loginDialog = new LoginDialog();
929
930     emit fetchUsernameFromSettings();
931
932     loginDialog->clearTextFields();
933
934     if(!m_email.isEmpty())
935         loginDialog->setEmailField(m_email);
936
937     queueDialog(loginDialog);
938 }
939
940 void MainWindow::toggleProgressIndicator(bool value)
941 {
942     qDebug() << __PRETTY_FUNCTION__;
943
944 #ifdef Q_WS_MAEMO_5
945     if(value) {
946         m_progressIndicatorCount++;
947         setAttribute(Qt::WA_Maemo5ShowProgressIndicator, true);
948     } else {
949         if(m_progressIndicatorCount > 0)
950             m_progressIndicatorCount--;
951
952         if(m_progressIndicatorCount == 0)
953             setAttribute(Qt::WA_Maemo5ShowProgressIndicator, false);
954     }
955 #else
956     Q_UNUSED(value);
957 #endif // Q_WS_MAEMO_5
958 }
959
960 void MainWindow::updateItemVisibility()
961 {
962     qDebug() << __PRETTY_FUNCTION__;
963
964 //    if(!m_loggedIn) {
965 //        m_friendsListPanel->closePanel();
966 //        m_friendsListPanel->hide();
967 //        m_friendsListPanelSidebar->hide();
968
969 //        m_userPanel->closePanel();
970 //        m_userPanel->hide();
971 //        m_userPanelSidebar->hide();
972 //    }
973 }
974
975 const QString MainWindow::username()
976 {
977     qDebug() << __PRETTY_FUNCTION__;
978
979     return m_email;
980 }
981
982 void MainWindow::webViewRequestFinished(QNetworkReply *reply)
983 {
984     qDebug() << __PRETTY_FUNCTION__;
985
986     // omit QNetworkReply::OperationCanceledError due to it's nature to be called when ever
987     // qwebview starts to load a new page while the current page loading is not finished
988     if(reply->error() != QNetworkReply::OperationCanceledError &&
989        reply->error() != QNetworkReply::NoError) {
990         emit error(ErrorContext::NETWORK, reply->error());
991     }
992 }