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