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 <QtAlgorithms>
28 #include <QtWebKit>
29
30 #include <QAction>
31 #include <QApplication>
32 #include <QMenuBar>
33 #include <QMessageBox>
34
35 #include "common.h"
36 #include "error.h"
37 #include "facebookservice/facebookauthentication.h"
38 #include "friendlistpanel.h"
39 #include "fullscreenbutton.h"
40 #include "indicatorbuttonpanel.h"
41 #include "locationsearchpanel.h"
42 #include "logindialog.h"
43 #include "map/mapcommon.h"
44 #include "map/mapview.h"
45 #include "mapscale.h"
46 #include "meetpeoplepanel.h"
47 #include "panelcommon.h"
48 #include "routingpanel.h"
49 #include "searchdialog.h"
50 #include "settingsdialog.h"
51 #include "tabbedpanel.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     connect(this, SIGNAL(searchForLocation(QString)),
283             m_locationSearchPanel, SLOT(prependSearchHistory(QString)));
284
285     connect(m_locationSearchPanel, SIGNAL(searchHistoryItemClicked(QString)),
286             this, SIGNAL(searchHistoryItemClicked(QString)));
287 }
288
289 void MainWindow::buildMap()
290 {
291     qDebug() << __PRETTY_FUNCTION__;
292
293     m_mapView = new MapView(this);
294
295     buildZoomButtonPanel();
296     buildOsmLicense();
297     buildCrosshair();
298     buildFullScreenButton();
299     buildIndicatorButtonPanel();
300     buildMapScale();
301
302     connect(m_mapView, SIGNAL(viewScrolled(SceneCoordinate)),
303             this, SIGNAL(mapViewScrolled(SceneCoordinate)));
304
305     connect(this, SIGNAL(centerToSceneCoordinates(SceneCoordinate)),
306             m_mapView, SLOT(centerToSceneCoordinates(SceneCoordinate)));
307
308     connect(m_mapView, SIGNAL(viewResized(QSize)),
309             this, SIGNAL(mapViewResized(QSize)));
310
311     connect(m_mapView, SIGNAL(viewResized(QSize)),
312             this, SLOT(drawFullScreenButton(QSize)));
313
314     connect(m_mapView, SIGNAL(viewResized(QSize)),
315             this, SLOT(drawMapScale(QSize)));
316
317     connect(m_mapView, SIGNAL(viewResized(QSize)),
318              this, SLOT(moveCrosshair()));
319
320     connect(this, SIGNAL(zoomLevelChanged(int)),
321             m_mapView, SLOT(setZoomLevel(int)));
322
323     connect(m_mapView, SIGNAL(viewZoomFinished()),
324             this, SIGNAL(viewZoomFinished()));
325
326     connect(m_mapView, SIGNAL(zoomIn()),
327             this, SIGNAL(zoomIn()));
328 }
329
330 void MainWindow::buildMapScale()
331 {
332     m_mapScale = new MapScale(this);
333     connect(this, SIGNAL(newMapResolution(qreal)),
334             m_mapScale, SLOT(updateMapResolution(qreal)));
335 }
336
337 void MainWindow::buildMeetPeoplePanel()
338 {
339     m_meetPeoplePanel = new MeetPeoplePanel(this);
340
341     connect(this, SIGNAL(friendImageReady(User*)),
342             m_meetPeoplePanel, SLOT(friendImageReady(User*)));
343
344     connect(this, SIGNAL(interestingPeopleReceived(QList<User*>&)),
345             m_meetPeoplePanel, SLOT(populateInterestingPeopleListView(QList<User*>&)));
346
347     connect(m_meetPeoplePanel, SIGNAL(requestInterestingPeople()),
348             this, SIGNAL(requestInterestingPeople()));
349
350     connect(this, SIGNAL(messagesReceived(QList<Message>&)),
351             m_meetPeoplePanel, SLOT(populateMessageListView(QList<Message>&)));
352 }
353
354 void MainWindow::buildOsmLicense()
355 {
356     qDebug() << __PRETTY_FUNCTION__;
357
358     m_osmLicense = new QLabel(this);
359     m_osmLicense->setAttribute(Qt::WA_TranslucentBackground, true);
360     m_osmLicense->setAttribute(Qt::WA_TransparentForMouseEvents, true);
361     m_osmLicense->setText("<font color='black'>" + OSM_LICENSE + "</font>");
362     m_osmLicense->setFont(QFont("Nokia Sans", 9));
363     m_osmLicense->resize(m_osmLicense->fontMetrics().width(OSM_LICENSE),
364                          m_osmLicense->fontMetrics().height());
365
366     connect(m_mapView, SIGNAL(viewResized(QSize)),
367             this, SLOT(drawOsmLicense(QSize)));
368 }
369
370 void MainWindow::buildPanels()
371 {
372     qDebug() << __PRETTY_FUNCTION__;
373
374     buildUserInfoPanel();
375     buildFriendListPanel();
376     buildLocationSearchPanel();
377     buildRoutingPanel();
378     buildMeetPeoplePanel();
379
380     m_tabbedPanel = new TabbedPanel(this);
381
382     //Save Situare related tab indexes so tabs can be enabled/disabled when logged in/out
383     m_situareTabsIndexes.append(
384             m_tabbedPanel->addTab(m_userInfoPanel, QIcon(":/res/images/user_info.png")));
385     m_situareTabsIndexes.append(
386             m_tabbedPanel->addTab(m_friendsListPanel, QIcon(":/res/images/friend_list.png")));
387
388 //    m_tabbedPanel->addTab(m_locationSearchPanel, QIcon(":/res/images/location_search.png"));
389 //    m_tabbedPanel->addTab(m_routingPanel, QIcon(":/res/images/routing.png"));
390     m_situareTabsIndexes.append(
391             m_tabbedPanel->addTab(m_meetPeoplePanel, QIcon(":/res/images/meet_people.png")));
392
393     connect(m_mapView, SIGNAL(viewResized(QSize)),
394             m_tabbedPanel, SLOT(resizePanel(QSize)));
395
396     connect(m_friendsListPanel, SIGNAL(openPanelRequested(QWidget*)),
397             m_tabbedPanel, SLOT(openPanel(QWidget*)));
398
399     connect(m_routingPanel, SIGNAL(openPanelRequested(QWidget*)),
400             m_tabbedPanel, SLOT(openPanel(QWidget*)));
401
402     connect(m_tabbedPanel, SIGNAL(panelClosed()),
403             m_friendsListPanel, SLOT(anyPanelClosed()));
404
405     connect(m_tabbedPanel, SIGNAL(panelOpened()),
406             m_friendsListPanel, SLOT(anyPanelOpened()));
407
408     connect(m_tabbedPanel, SIGNAL(panelClosed()),
409             m_routingPanel, SLOT(clearListsSelections()));
410
411     connect(m_tabbedPanel, SIGNAL(panelClosed()),
412             m_mapView, SLOT(disableCenterShift()));
413
414     connect(m_tabbedPanel, SIGNAL(panelOpened()),
415             m_mapView, SLOT(enableCenterShift()));
416
417     connect(m_tabbedPanel, SIGNAL(panelClosed()),
418             m_userInfoPanel, SIGNAL(collapse()));
419
420     connect(m_tabbedPanel, SIGNAL(currentChanged(int)),
421             m_userInfoPanel, SIGNAL(collapse()));
422
423     // signals for showing and hiding list item context buttons
424     connect(m_friendsListPanel, SIGNAL(listItemSelectionChanged(bool)),
425             m_tabbedPanel, SIGNAL(listItemSelectionChanged(bool)));
426
427     connect(m_locationSearchPanel, SIGNAL(listItemSelectionChanged(bool)),
428             m_tabbedPanel, SIGNAL(listItemSelectionChanged(bool)));
429
430     connect(m_routingPanel, SIGNAL(listItemSelectionChanged(bool)),
431             m_tabbedPanel, SIGNAL(listItemSelectionChanged(bool)));
432 }
433
434 void MainWindow::buildRoutingPanel()
435 {
436     qDebug() << __PRETTY_FUNCTION__;
437
438     m_routingPanel = new RoutingPanel(this);
439
440     connect(m_routingPanel, SIGNAL(routeToCursor()),
441             this, SIGNAL(routeToCursor()));
442
443     connect(this, SIGNAL(routeParsed(Route&)),
444             m_routingPanel, SLOT(setRoute(Route&)));
445
446     connect(m_routingPanel, SIGNAL(routeWaypointItemClicked(GeoCoordinate)),
447             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
448
449     connect(m_routingPanel, SIGNAL(clearRoute()),
450             this, SIGNAL(clearRoute()));
451 }
452
453 void MainWindow::buildUserInfoPanel()
454 {
455     qDebug() << __PRETTY_FUNCTION__;
456
457     m_userInfoPanel = new UserInfoPanel(this);
458
459     connect(this, SIGNAL(userLocationReady(User*)),
460             m_userInfoPanel, SLOT(userDataReceived(User*)));
461
462     connect(this, SIGNAL(reverseGeoReady(QString)),
463             m_userInfoPanel, SIGNAL(reverseGeoReady(QString)));
464
465     connect(this, SIGNAL(clearUpdateLocationDialogData()),
466             m_userInfoPanel, SIGNAL(clearUpdateLocationDialogData()));
467
468     connect(m_userInfoPanel, SIGNAL(findUser(GeoCoordinate)),
469             this, SIGNAL(centerToCoordinates(GeoCoordinate)));
470
471     connect(m_userInfoPanel, SIGNAL(requestReverseGeo()),
472             this, SIGNAL(requestReverseGeo()));
473
474     connect(m_userInfoPanel, SIGNAL(statusUpdate(QString,bool)),
475             this, SIGNAL(statusUpdate(QString,bool)));
476
477     connect(m_userInfoPanel, SIGNAL(refreshUserData()),
478             this, SIGNAL(refreshUserData()));
479
480     connect(m_userInfoPanel, SIGNAL(notificateUpdateFailing(QString, bool)),
481             this, SLOT(buildInformationBox(QString, bool)));
482 }
483
484 void MainWindow::buildWebView()
485 {
486     qDebug() << __PRETTY_FUNCTION__;
487
488     if(!m_webView) {
489         m_webView = new QWebView;
490
491         if(!m_cookieJar)
492             m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
493
494         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
495
496         connect(m_webView->page()->networkAccessManager(), SIGNAL(finished(QNetworkReply*)),
497                 this, SLOT(webViewRequestFinished(QNetworkReply*)));
498         connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
499                 this, SIGNAL(updateCredentials(QUrl)));
500         connect(m_webView, SIGNAL(loadFinished(bool)),
501                 this, SLOT(loadDone(bool)));
502
503         m_webView->hide();
504     }
505 }
506
507 void MainWindow::buildZoomButtonPanel()
508 {
509     qDebug() << __PRETTY_FUNCTION__;
510
511     m_zoomButtonPanel = new ZoomButtonPanel(this);
512
513     connect(m_zoomButtonPanel->zoomInButton(), SIGNAL(clicked()),
514             this, SIGNAL(zoomIn()));
515
516     connect(m_zoomButtonPanel->zoomOutButton(), SIGNAL(clicked()),
517             this, SIGNAL(zoomOut()));
518
519     connect(this, SIGNAL(zoomLevelChanged(int)),
520             m_zoomButtonPanel, SLOT(resetButtons()));
521
522     connect(this, SIGNAL(maxZoomLevelReached()),
523             m_zoomButtonPanel, SLOT(disableZoomInButton()));
524
525     connect(this, SIGNAL(minZoomLevelReached()),
526             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
527
528     connect(m_mapView, SIGNAL(viewResized(QSize)),
529             m_zoomButtonPanel, SLOT(screenResized(QSize)));
530
531     connect(m_zoomButtonPanel, SIGNAL(draggingModeTriggered()),
532             this, SIGNAL(draggingModeTriggered()));
533 }
534
535 void MainWindow::clearCookieJar()
536 {
537     qDebug() << __PRETTY_FUNCTION__;
538
539     buildWebView();
540
541     m_webView->stop();
542
543     if(!m_cookieJar) {
544         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
545     }
546     QList<QNetworkCookie> emptyList;
547     emptyList.clear();
548
549     m_cookieJar->setAllCookies(emptyList);
550     m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
551 }
552
553 void MainWindow::createMenus()
554 {
555     qDebug() << __PRETTY_FUNCTION__;
556
557     // login/logout
558     m_loginAct = new QAction(tr("Login"), this);
559     connect(m_loginAct, SIGNAL(triggered()),
560             this, SIGNAL(loginActionPressed()));
561
562     // settings
563     m_toSettingsAct = new QAction(tr("Settings"), this);
564     connect(m_toSettingsAct, SIGNAL(triggered()),
565         this, SLOT(openSettingsDialog()));
566
567     // GPS
568     m_gpsToggleAct = new QAction(tr("GPS"), this);
569     m_gpsToggleAct->setCheckable(true);
570
571     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
572             this, SIGNAL(gpsTriggered(bool)));
573
574     // build the actual menu
575     m_viewMenu = menuBar()->addMenu(tr("Main"));
576     m_viewMenu->addAction(m_loginAct);
577     m_viewMenu->addAction(m_toSettingsAct);
578     m_viewMenu->addAction(m_gpsToggleAct);
579     m_viewMenu->setObjectName(tr("Menu"));
580 }
581
582 void MainWindow::dialogFinished(int status)
583 {
584     qDebug() << __PRETTY_FUNCTION__;
585
586     QDialog *dialog = m_queue.takeFirst();
587     LoginDialog *loginDialog = qobject_cast<LoginDialog *>(dialog);
588     SearchDialog *searchDialog = qobject_cast<SearchDialog *>(dialog);
589     if(loginDialog) {
590         if(status != 0) {
591             buildWebView();
592             loginDialog->userInput(m_email, m_password);
593
594             QStringList urlParts;
595             urlParts.append(FACEBOOK_LOGINBASE);
596             urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
597             urlParts.append(INTERVAL1);
598             urlParts.append(SITUARE_LOGIN_SUCCESS);
599             urlParts.append(INTERVAL2);
600             urlParts.append(SITUARE_LOGIN_FAILURE);
601             urlParts.append(FACEBOOK_LOGIN_ENDING);
602
603             emit saveUsername(m_email);
604             m_refresh = true;
605             m_webView->load(QUrl(urlParts.join(EMPTY)));
606             toggleProgressIndicator(true);
607         } else {
608             emit cancelLoginProcess();
609         }
610     } else if(searchDialog) {
611         if(status != 0) {
612             emit searchForLocation(searchDialog->input());
613         }
614     }
615
616     dialog->deleteLater();
617
618     if(!m_error_queue.isEmpty() && m_errorShown == false) {
619         showErrorInformationBox();
620     } else {
621         if(!m_queue.isEmpty()) {
622             showInformationBox();
623         }
624     }
625 }
626
627 void MainWindow::drawFullScreenButton(const QSize &size)
628 {
629     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
630
631     if (m_fullScreenButton) {
632         m_fullScreenButton->move(size.width() - m_fullScreenButton->size().width(),
633                                  size.height() - m_fullScreenButton->size().height());
634     }
635 }
636
637 void MainWindow::drawMapScale(const QSize &size)
638 {
639     qDebug() << __PRETTY_FUNCTION__;
640
641     const int LEFT_SCALE_MARGIN = 10;
642     const int BOTTOM_SCALE_MARGIN = 2;
643
644     m_mapScale->move(LEFT_SCALE_MARGIN,
645                      size.height() - m_mapScale->size().height() - BOTTOM_SCALE_MARGIN);
646 }
647
648 void MainWindow::drawOsmLicense(const QSize &size)
649 {
650     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
651
652     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
653                        - PANEL_BAR_WIDTH,
654                        size.height() - m_osmLicense->fontMetrics().height());
655 }
656
657 void MainWindow::errorDialogFinished(int status)
658 {
659     qDebug() << __PRETTY_FUNCTION__;
660
661     qDebug() << status;
662     QDialog *dialog = m_error_queue.takeFirst();
663
664     dialog->deleteLater();
665     m_errorShown = false;
666
667     if(!m_error_queue.isEmpty())
668         showErrorInformationBox();
669     else if(!m_queue.isEmpty())
670         showInformationBox();
671 }
672
673 void MainWindow::gpsTimeout()
674 {
675     qDebug() << __PRETTY_FUNCTION__;
676
677     buildInformationBox(tr("GPS timeout"));
678 }
679
680 void MainWindow::grabZoomKeys(bool grab)
681 {
682     qDebug() << __PRETTY_FUNCTION__;
683
684 #ifdef Q_WS_MAEMO_5
685     // Can't grab keys unless we have a window id
686     if (!winId())
687         return;
688
689     unsigned long val = (grab) ? 1 : 0;
690     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
691     if (!atom)
692         return;
693
694     XChangeProperty (QX11Info::display(),
695                      winId(),
696                      atom,
697                      XA_INTEGER,
698                      32,
699                      PropModeReplace,
700                      reinterpret_cast<unsigned char *>(&val),
701                      1);
702 #else
703     Q_UNUSED(grab);
704 #endif // Q_WS_MAEMO_5
705 }
706
707 void MainWindow::keyPressEvent(QKeyEvent* event)
708 {
709     qDebug() << __PRETTY_FUNCTION__;
710
711     switch (event->key()) {
712     case Qt::Key_F7:
713         event->accept();
714         emit zoomIn();
715         break;
716
717     case Qt::Key_F8:
718         event->accept();
719         emit zoomOut();
720         break;
721     }
722     QWidget::keyPressEvent(event);
723 }
724
725 void MainWindow::loadCookies()
726 {
727     qDebug() << __PRETTY_FUNCTION__;
728
729     QSettings settings(DIRECTORY_NAME, FILE_NAME);
730
731     QStringList list = settings.value(COOKIES, EMPTY).toStringList();
732
733     if(!list.isEmpty()) {
734         QList<QNetworkCookie> cookieList;
735         for(int i=0;i<list.count();i++) {
736             cookieList.append(QNetworkCookie::parseCookies(list.at(i).toAscii()));
737         }
738
739         if(!m_cookieJar)
740                m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
741
742         m_cookieJar->setAllCookies(cookieList);
743         m_webView->page()->networkAccessManager()->setCookieJar(m_cookieJar);
744     }
745 }
746
747 void MainWindow::loadDone(bool done)
748 {
749     qDebug() << __PRETTY_FUNCTION__;
750
751     // for the first time the login page is opened, we need to refresh it to get cookies working
752     if(m_refresh) {
753         m_webView->reload();
754         m_refresh = false;
755     }
756
757     if (done)
758     {
759         QWebFrame* frame = m_webView->page()->currentFrame();
760         if (frame!=NULL)
761         {
762             // set email box
763             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
764
765             foreach (QWebElement element, emailCollection) {
766                 element.setAttribute("value", m_email.toAscii());
767             }
768             // set password box
769             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
770             foreach (QWebElement element, passwordCollection) {
771                 element.setAttribute("value", m_password.toAscii());
772             }
773             // find connect button
774             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
775             foreach (QWebElement element, buttonCollection)
776             {
777                 QPoint pos(element.geometry().center());
778
779                 // send a mouse click event to the web page
780                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
781                                    Qt::NoModifier);
782                 QApplication::sendEvent(m_webView->page(), &event0);
783                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
784                                    Qt::NoModifier);
785                 QApplication::sendEvent(m_webView->page(), &event1);
786             }
787         }
788     }
789 }
790
791 void MainWindow::loggedIn(bool logged)
792 {
793     qDebug() << __PRETTY_FUNCTION__;
794
795     m_loggedIn = logged;
796
797     if(logged) {
798         m_loginAct->setText(tr("Logout"));
799     } else {
800         clearCookieJar();
801         m_email.clear();
802         m_password.clear();
803
804         m_loginAct->setText(tr("Login"));
805         m_userInfoPanel->showUserInfo(false);
806     }
807     updateItemVisibility();
808 }
809
810 void MainWindow::loginFailed()
811 {
812     qDebug() << __PRETTY_FUNCTION__;
813
814     clearCookieJar();
815     startLoginProcess();
816 }
817
818 bool MainWindow::loginState()
819 {
820     qDebug() << __PRETTY_FUNCTION__;
821
822     return m_loggedIn;
823 }
824
825 void MainWindow::loginUsingCookies()
826 {
827     qDebug() << __PRETTY_FUNCTION__;
828
829     toggleProgressIndicator(true);
830
831     buildWebView();
832     loadCookies();
833
834     QStringList urlParts;
835     urlParts.append(FACEBOOK_LOGINBASE);
836     urlParts.append(SITUARE_PUBLIC_FACEBOOKAPI_KEY);
837     urlParts.append(INTERVAL1);
838     urlParts.append(SITUARE_LOGIN_SUCCESS);
839     urlParts.append(INTERVAL2);
840     urlParts.append(SITUARE_LOGIN_FAILURE);
841     urlParts.append(FACEBOOK_LOGIN_ENDING);
842
843     m_webView->load(QUrl(urlParts.join(EMPTY)));
844
845 }
846
847 void MainWindow::mapCenterHorizontalShiftingChanged(int shifting)
848 {
849     m_mapCenterHorizontalShifting = shifting;
850     moveCrosshair();
851 }
852
853 void MainWindow::moveCrosshair()
854 {
855     qDebug() << __PRETTY_FUNCTION__;
856
857     if (m_crosshair) {
858         int mapHeight = m_mapView->size().height();
859         int mapWidth = m_mapView->size().width();
860         m_crosshair->move(mapWidth / 2 - m_crosshair->pixmap()->width() / 2
861                           - m_mapCenterHorizontalShifting,
862                           mapHeight / 2 - m_crosshair->pixmap()->height() / 2);
863     }
864 }
865
866 void MainWindow::openSettingsDialog()
867 {
868     qDebug() << __PRETTY_FUNCTION__;
869
870     SettingsDialog *settingsDialog = new SettingsDialog(this);
871     settingsDialog->enableSituareSettings((m_loggedIn && m_gpsToggleAct->isChecked()));
872     connect(settingsDialog, SIGNAL(accepted()), this, SLOT(settingsDialogAccepted()));
873
874     settingsDialog->show();
875 }
876
877 void MainWindow::queueDialog(QDialog *dialog)
878 {
879     qDebug() << __PRETTY_FUNCTION__;
880
881     // check is dialog is modal, for now all modal dialogs have hihger priority i.e. errors
882     if(dialog->isModal()) {
883         m_error_queue.append(dialog);
884     } else {
885         m_queue.append(dialog);
886     }
887
888     // show error dialog if there is only one error dialog in the queue and no error dialog is shown
889     if(m_error_queue.count() == 1 && m_errorShown == false)
890         showErrorInformationBox();
891     else if(m_queue.count() == 1 && m_errorShown == false)
892         showInformationBox();
893 }
894
895 void MainWindow::readAutomaticLocationUpdateSettings()
896 {
897     qDebug() << __PRETTY_FUNCTION__;
898
899     QSettings settings(DIRECTORY_NAME, FILE_NAME);
900     bool automaticUpdateEnabled = settings.value(SETTINGS_AUTOMATIC_UPDATE_ENABLED, false).toBool();
901     QTime automaticUpdateInterval = settings.value(SETTINGS_AUTOMATIC_UPDATE_INTERVAL, QTime())
902                                       .toTime();
903
904     if (automaticUpdateEnabled && automaticUpdateInterval.isValid()) {
905         QTime time;
906         emit enableAutomaticLocationUpdate(true, time.msecsTo(automaticUpdateInterval));
907     } else {
908         emit enableAutomaticLocationUpdate(false);
909     }
910 }
911
912 void MainWindow::saveCookies()
913 {
914     qDebug() << __PRETTY_FUNCTION__;
915
916     if(!m_cookieJar)
917         m_cookieJar = new NetworkCookieJar(new QNetworkCookieJar(this));
918
919     QList<QNetworkCookie> cookieList = m_cookieJar->allCookies();
920     QStringList list;
921
922     for(int i=0;i<cookieList.count();i++) {
923         QNetworkCookie cookie = cookieList.at(i);
924         QByteArray byteArray = cookie.toRawForm(QNetworkCookie::Full);
925         list.append(QString(byteArray));
926     }
927     list.removeDuplicates();
928
929     QSettings settings(DIRECTORY_NAME, FILE_NAME);
930     settings.setValue(COOKIES, list);
931 }
932
933 void MainWindow::setCrosshairVisibility(bool visibility)
934 {
935     qDebug() << __PRETTY_FUNCTION__;
936
937     if (visibility) {
938         m_crosshair->show();
939         moveCrosshair();
940     } else {
941         m_crosshair->hide();
942     }
943 }
944
945 void MainWindow::setGPSButtonEnabled(bool enabled)
946 {
947     qDebug() << __PRETTY_FUNCTION__;
948
949     m_gpsToggleAct->setChecked(enabled);
950 }
951
952 void MainWindow::setIndicatorButtonEnabled(bool enabled)
953 {
954     qDebug() << __PRETTY_FUNCTION__;
955
956     m_indicatorButtonPanel->setIndicatorButtonEnabled(enabled);
957 }
958
959 void MainWindow::setMapViewScene(QGraphicsScene *scene)
960 {
961     qDebug() << __PRETTY_FUNCTION__;
962
963     m_mapView->setScene(scene);
964 }
965
966 void MainWindow::settingsDialogAccepted()
967 {
968     qDebug() << __PRETTY_FUNCTION__;
969
970     readAutomaticLocationUpdateSettings();
971 }
972
973 void MainWindow::setUsername(const QString &username)
974 {
975     qDebug() << __PRETTY_FUNCTION__;
976
977     m_email = username;
978 }
979
980 void MainWindow::showContactDialog(const QString &guid)
981 {
982     qDebug() << __PRETTY_FUNCTION__;
983
984 #if defined(Q_WS_MAEMO_5) & defined(ARMEL)
985     OssoABookDialog::showContactDialog(guid);
986 #else
987     Q_UNUSED(guid);
988     buildInformationBox(tr("Contact dialog works only on phone!"), true);
989 #endif
990 }
991
992 void MainWindow::showEnableAutomaticUpdateLocationDialog(const QString &text)
993 {
994     qDebug() << __PRETTY_FUNCTION__;
995
996     m_automaticUpdateLocationDialog = new QMessageBox(QMessageBox::Question,
997                                                       tr("Automatic location update"), text,
998                                                       QMessageBox::Yes | QMessageBox::No |
999                                                       QMessageBox::Cancel, this);
1000     connect(m_automaticUpdateLocationDialog, SIGNAL(finished(int)),
1001             this, SLOT(automaticUpdateDialogFinished(int)));
1002
1003     m_automaticUpdateLocationDialog->show();
1004 }
1005
1006 void MainWindow::showErrorInformationBox()
1007 {
1008     qDebug() << __PRETTY_FUNCTION__;
1009
1010     if(m_error_queue.count()) {
1011         m_errorShown = true;
1012         QDialog *dialog = m_error_queue.first();
1013         connect(dialog, SIGNAL(finished(int)),
1014                 this, SLOT(errorDialogFinished(int)));
1015         dialog->show();
1016     }
1017 }
1018
1019 void MainWindow::showInformationBox()
1020 {
1021     qDebug() << __PRETTY_FUNCTION__;
1022
1023     if(m_queue.count()) {
1024         QDialog *dialog = m_queue.first();
1025         connect(dialog, SIGNAL(finished(int)),
1026                 this, SLOT(dialogFinished(int)));
1027         dialog->show();
1028     }
1029 }
1030
1031 void MainWindow::startLocationSearch()
1032 {
1033     qDebug() << __PRETTY_FUNCTION__;
1034
1035     SearchDialog *searchDialog = new SearchDialog();
1036     queueDialog(searchDialog);
1037 }
1038
1039 void MainWindow::startLoginProcess()
1040 {
1041     qDebug() << __PRETTY_FUNCTION__;
1042
1043     LoginDialog *loginDialog = new LoginDialog();
1044
1045     emit fetchUsernameFromSettings();
1046
1047     loginDialog->clearTextFields();
1048
1049     if(!m_email.isEmpty())
1050         loginDialog->setEmailField(m_email);
1051
1052     queueDialog(loginDialog);
1053 }
1054
1055 void MainWindow::toggleFullScreen()
1056 {
1057     qDebug() << __PRETTY_FUNCTION__;
1058
1059     if(windowState() == Qt::WindowNoState)
1060         showFullScreen();
1061     else
1062         showNormal();
1063 }
1064
1065 void MainWindow::toggleProgressIndicator(bool value)
1066 {
1067     qDebug() << __PRETTY_FUNCTION__;
1068
1069 #ifdef Q_WS_MAEMO_5
1070     if(value) {
1071         m_progressIndicatorCount++;
1072         setAttribute(Qt::WA_Maemo5ShowProgressIndicator, true);
1073     } else {
1074         if(m_progressIndicatorCount > 0)
1075             m_progressIndicatorCount--;
1076
1077         if(m_progressIndicatorCount == 0)
1078             setAttribute(Qt::WA_Maemo5ShowProgressIndicator, false);
1079     }
1080 #else
1081     Q_UNUSED(value);
1082 #endif // Q_WS_MAEMO_5
1083 }
1084
1085 void MainWindow::updateItemVisibility()
1086 {
1087     qDebug() << __PRETTY_FUNCTION__;
1088
1089     m_tabbedPanel->setTabsEnabled(m_situareTabsIndexes, m_loggedIn);
1090 }
1091
1092 const QString MainWindow::username()
1093 {
1094     qDebug() << __PRETTY_FUNCTION__;
1095
1096     return m_email;
1097 }
1098
1099 void MainWindow::webViewRequestFinished(QNetworkReply *reply)
1100 {
1101     qDebug() << __PRETTY_FUNCTION__;
1102
1103     // omit QNetworkReply::OperationCanceledError due to it's nature to be called when ever
1104     // qwebview starts to load a new page while the current page loading is not finished
1105     if(reply->error() != QNetworkReply::OperationCanceledError &&
1106        reply->error() != QNetworkReply::NoError) {
1107         emit error(ErrorContext::NETWORK, reply->error());
1108     }
1109 }