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