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