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