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