Added automatic location update timer to Engine. Modified settings in
[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
11    Situare is free software; you can redistribute it and/or
12    modify it under the terms of the GNU General Public License
13    version 2 as published by the Free Software Foundation.
14
15    Situare is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with Situare; if not, write to the Free Software
22    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
23    USA.
24 */
25
26 #include <QtGui>
27 #include <QtWebKit>
28
29 #ifdef Q_WS_MAEMO_5
30 #include <QtMaemo5/QMaemo5InformationBox>
31 #endif // Q_WS_MAEMO_5
32
33 #include "common.h"
34 #include "facebookservice/facebookauthentication.h"
35 #include "friendlistpanel.h"
36 #include "logindialog.h"
37 #include "map/mapview.h"
38 #include "settingsdialog.h"
39 #include "userinfopanel.h"
40 #include "zoombuttonpanel.h"
41
42 #include "mainwindow.h"
43
44 #include <QtGui/QX11Info>
45 #include <X11/Xlib.h>
46 #include <X11/Xatom.h>
47
48 // values for setting screen size in desktop matching N900 screen size
49 const int N900_APP_WIDTH = 800;
50 const int N900_APP_HEIGHT = 449;
51
52 MainWindow::MainWindow(QWidget *parent)
53     : QMainWindow(parent),
54     m_drawOwnLocationCrosshair(false),
55     m_loggedIn(false),
56     m_refresh(false),
57     m_email(),    
58     m_password(),
59     m_loginUrl(),
60     m_webView(0)
61 {
62     qDebug() << __PRETTY_FUNCTION__;
63
64     buildMap();
65
66     // build main layout
67     QHBoxLayout *layout = new QHBoxLayout;
68     layout->addWidget(m_mapView);
69     layout->setMargin(0);
70     setCentralWidget(new QWidget());
71     centralWidget()->setLayout(layout);
72
73     buildFriendListPanel();
74     buildUserInfoPanel();
75
76     m_settingsDialog = new SettingsDialog(this);
77     m_settingsDialog->hide();
78     connect(m_settingsDialog, SIGNAL(automaticLocationUpdateIntervalSet(int)),
79             this, SIGNAL(automaticLocationUpdateIntervalSet(int)));
80
81     createMenus();
82     setWindowTitle(tr("Situare"));
83
84     // set stacking order of widgets
85     m_zoomButtonPanel->stackUnder(m_userPanel);
86     m_osmLicense->stackUnder(m_zoomButtonPanel);
87     m_ownLocationCrosshair->stackUnder(m_osmLicense);
88     m_mapView->stackUnder(m_ownLocationCrosshair);
89
90     this->toggleProgressIndicator(true);
91
92     grabZoomKeys(true);
93
94     // set screen size in desktop matching N900 screen size
95     resize(N900_APP_WIDTH, N900_APP_HEIGHT);
96 }
97
98 MainWindow::~MainWindow()
99 {
100     qDebug() << __PRETTY_FUNCTION__;
101
102     grabZoomKeys(false);
103
104     if(m_webView)
105         delete m_webView;
106 }
107
108 void MainWindow::buildFriendListPanel()
109 {
110     qDebug() << __PRETTY_FUNCTION__;
111
112     m_friendsListPanel = new FriendListPanel(this);
113     m_friendsListPanelSidebar = new PanelSideBar(this, RIGHT);
114
115     m_friendsListPanel->stackUnder(m_friendsListPanelSidebar);
116
117     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
118             m_friendsListPanel, SLOT(friendInfoReceived(QList<User*>&)));
119
120     connect(m_friendsListPanel, SIGNAL(findFriend(QPointF)),
121             this, SIGNAL(findFriend(QPointF)));
122
123     connect(m_mapView, SIGNAL(viewResized(QSize)),
124             m_friendsListPanel, SLOT(screenResized(QSize)));
125
126     connect(this, SIGNAL(locationItemClicked(QList<QString>)),
127             m_friendsListPanel, SLOT(showFriendsInList(QList<QString>)));
128
129     connect(m_mapView, SIGNAL(viewResizedNewSize(int, int)),
130             m_friendsListPanelSidebar, SLOT(reDrawSidebar(int, int)));
131 }
132
133 void MainWindow::buildManualLocationCrosshair()
134 {
135     qDebug() << __PRETTY_FUNCTION__;
136
137     m_ownLocationCrosshair = new QLabel(this);
138     QPixmap crosshairImage(":/res/images/sight.png");
139     m_ownLocationCrosshair->setPixmap(crosshairImage);
140     m_ownLocationCrosshair->setFixedSize(crosshairImage.size());
141     m_ownLocationCrosshair->hide();
142     m_ownLocationCrosshair->setAttribute(Qt::WA_TransparentForMouseEvents, true);
143
144     connect(m_mapView, SIGNAL(viewResizedNewSize(int, int)),
145             this, SLOT(drawOwnLocationCrosshair(int, int)));
146 }
147
148 void MainWindow::buildMap()
149 {
150     qDebug() << __PRETTY_FUNCTION__;
151
152     m_mapView = new MapView(this);
153
154     buildZoomButtonPanel();
155
156     m_ownLocationCrosshair = 0;
157     buildOsmLicense();
158     buildManualLocationCrosshair();
159
160     connect(m_mapView, SIGNAL(viewScrolled(QPoint)),
161             this, SIGNAL(mapViewScrolled(QPoint)));
162
163     connect(this, SIGNAL(centerToSceneCoordinates(QPoint)),
164             m_mapView, SLOT(centerToSceneCoordinates(QPoint)));
165
166     connect(m_mapView, SIGNAL(viewResized(QSize)),
167             this, SIGNAL(mapViewResized(QSize)));
168
169     connect(m_mapView, SIGNAL(viewResizedNewSize(int, int)),
170              this, SLOT(setViewPortSize(int, int)));
171
172     connect(this, SIGNAL(zoomLevelChanged(int)),
173             m_mapView, SLOT(setZoomLevel(int)));
174
175     connect(m_mapView, SIGNAL(viewZoomFinished()),
176             this, SIGNAL(viewZoomFinished()));
177 }
178
179 void MainWindow::buildOsmLicense()
180 {
181     qWarning() << __PRETTY_FUNCTION__;
182
183     m_osmLicense = new QLabel(this);
184     m_osmLicense->setAttribute(Qt::WA_TranslucentBackground, true);
185     m_osmLicense->setAttribute(Qt::WA_TransparentForMouseEvents, true);
186     m_osmLicense->setText("<font color='black'>" + OSM_LICENSE + "</font>");
187     m_osmLicense->setFont(QFont("Nokia Sans", 9));
188     m_osmLicense->resize(m_osmLicense->fontMetrics().width(OSM_LICENSE),
189                          m_osmLicense->fontMetrics().height());
190
191     connect(m_mapView, SIGNAL(viewResized(QSize)),
192             this, SLOT(drawOsmLicense(QSize)));
193 }
194
195 void MainWindow::buildUserInfoPanel()
196 {
197     qDebug() << __PRETTY_FUNCTION__;
198
199     m_userPanel = new UserInfoPanel(this);
200     m_userPanelSidebar = new PanelSideBar(this, LEFT);
201
202     m_userPanelSidebar->stackUnder(m_friendsListPanel);
203     m_userPanel->stackUnder(m_userPanelSidebar);
204
205     connect(this, SIGNAL(userLocationReady(User*)),
206             m_userPanel, SLOT(userDataReceived(User*)));
207
208     connect(m_userPanel, SIGNAL(requestReverseGeo()),
209             this, SIGNAL(requestReverseGeo()));
210
211     connect(this, SIGNAL(reverseGeoReady(QString)),
212             m_userPanel, SIGNAL(reverseGeoReady(QString)));
213
214     connect(m_userPanel, SIGNAL(statusUpdate(QString,bool)),
215             this, SIGNAL(statusUpdate(QString,bool)));
216
217     connect(m_userPanel, SIGNAL(refreshUserData()),
218             this, SIGNAL(refreshUserData()));
219
220     connect(m_mapView, SIGNAL(viewResized(QSize)),
221             m_userPanel, SLOT(screenResized(QSize)));
222 }
223
224 void MainWindow::buildZoomButtonPanel()
225 {
226     qDebug() << __PRETTY_FUNCTION__;
227
228     m_zoomButtonPanel = new ZoomButtonPanel(this, ZOOM_BUTTON_PANEL_POSITION_X,
229                                             ZOOM_BUTTON_PANEL_POSITION_Y);
230
231     connect(m_zoomButtonPanel->m_zoomInButton, SIGNAL(clicked()),
232             this, SIGNAL(zoomIn()));
233
234     connect(m_zoomButtonPanel->m_zoomOutButton, SIGNAL(clicked()),
235             this, SIGNAL(zoomOut()));
236
237     connect(this, SIGNAL(zoomLevelChanged(int)),
238             m_zoomButtonPanel, SLOT(resetButtons()));
239
240     connect(this, SIGNAL(maxZoomLevelReached()),
241             m_zoomButtonPanel, SLOT(disableZoomInButton()));
242
243     connect(this, SIGNAL(minZoomLevelReached()),
244             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
245 }
246
247 void MainWindow::createMenus()
248 {
249     qDebug() << __PRETTY_FUNCTION__;
250
251     // login/logout
252     m_loginAct = new QAction(tr("Login"), this);
253     connect(m_loginAct, SIGNAL(triggered()),
254             this, SIGNAL(loginActionPressed()));
255
256     // settings
257     m_toSettingsAct = new QAction(tr("Settings"), this);
258     connect(m_toSettingsAct, SIGNAL(triggered()),
259         this, SLOT(openSettingsDialog()));
260
261     // GPS
262     m_gpsToggleAct = new QAction(tr("GPS"), this);
263     m_gpsToggleAct->setCheckable(true);
264
265     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
266             this, SIGNAL(gpsTriggered(bool)));
267
268     // automatic centering
269     m_autoCenteringAct = new QAction(tr("Auto centering"), this);
270     m_autoCenteringAct->setCheckable(true);
271     connect(m_autoCenteringAct, SIGNAL(triggered(bool)),
272         this, SIGNAL(autoCenteringTriggered(bool)));
273
274     // build the actual menu
275     m_viewMenu = menuBar()->addMenu(tr("Main"));
276     m_viewMenu->addAction(m_loginAct);
277     m_viewMenu->addAction(m_toSettingsAct);
278     m_viewMenu->addAction(m_gpsToggleAct);
279     m_viewMenu->addAction(m_autoCenteringAct);
280     m_viewMenu->setObjectName(tr("Menu"));
281 }
282
283 void MainWindow::drawOsmLicense(const QSize &size)
284 {
285     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
286
287     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE) - PANEL_PEEK_AMOUNT,
288                         size.height() - m_osmLicense->fontMetrics().height());
289
290 }
291
292 void MainWindow::drawOwnLocationCrosshair(int width, int height)
293 {
294     qDebug() << __PRETTY_FUNCTION__;
295
296     if (m_drawOwnLocationCrosshair && m_ownLocationCrosshair != 0) {
297         m_ownLocationCrosshair->move(width/2 - m_ownLocationCrosshair->pixmap()->width()/2,
298                             height/2 - m_ownLocationCrosshair->pixmap()->height()/2);
299     }
300 }
301
302 void MainWindow::gpsError(const QString &message)
303 {
304     qDebug() << __PRETTY_FUNCTION__;
305
306     showMaemoInformationBox(message);
307 }
308
309 void MainWindow::gpsTimeout()
310 {
311     qDebug() << __PRETTY_FUNCTION__;
312
313     showMaemoInformationBox(tr("GPS timeout"));
314 }
315
316 void MainWindow::grabZoomKeys(bool grab)
317 {
318     qDebug() << __PRETTY_FUNCTION__;
319
320 #ifdef Q_WS_MAEMO_5
321     // Can't grab keys unless we have a window id
322     if (!winId())
323         return;
324
325     unsigned long val = (grab) ? 1 : 0;
326     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
327     if (!atom)
328         return;
329
330     XChangeProperty (QX11Info::display(),
331                      winId(),
332                      atom,
333                      XA_INTEGER,
334                      32,
335                      PropModeReplace,
336                      reinterpret_cast<unsigned char *>(&val),
337                      1);
338 #else
339     Q_UNUSED(grab);
340 #endif // Q_WS_MAEMO_5
341 }
342
343 void MainWindow::keyPressEvent(QKeyEvent* event)
344 {
345     qDebug() << __PRETTY_FUNCTION__;
346
347     switch (event->key()) {
348     case Qt::Key_F7:
349         event->accept();
350         emit zoomIn();
351         break;
352
353     case Qt::Key_F8:
354         event->accept();
355         emit zoomOut();
356         break;
357     }
358     QWidget::keyPressEvent(event);
359 }
360
361 void MainWindow::loadDone(bool done)
362 {
363     qDebug() << __PRETTY_FUNCTION__;
364
365     // for the first time the login page is opened, we need to refresh it to get cookies working
366     if(m_refresh) {
367         m_webView->reload();
368         m_refresh = false;
369     }
370
371     if (done)
372     {
373         QWebFrame* frame = m_webView->page()->currentFrame();
374         if (frame!=NULL)
375         {
376             // set email box
377             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
378
379             foreach (QWebElement element, emailCollection) {
380                 element.setAttribute("value", m_email.toAscii());
381             }
382             // set password box
383             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
384             foreach (QWebElement element, passwordCollection) {
385                 element.setAttribute("value", m_password.toAscii());
386             }
387             // find connect button
388             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
389             foreach (QWebElement element, buttonCollection)
390             {
391                 QPoint pos(element.geometry().center());
392
393                 // send a mouse click event to the web page
394                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
395                                    Qt::NoModifier);
396                 QApplication::sendEvent(m_webView->page(), &event0);
397                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
398                                    Qt::NoModifier);
399                 QApplication::sendEvent(m_webView->page(), &event1);
400             }
401         }
402     }
403 }
404
405 void MainWindow::loggedIn(bool logged)
406 {
407     qDebug() << __PRETTY_FUNCTION__;
408
409     m_loggedIn = logged;
410
411     if(logged) {
412         m_loginAct->setText(tr("Logout"));
413     }
414     else {
415         m_loginAct->setText(tr("Login"));
416     }
417     showPanels(m_loggedIn);
418 }
419
420 void MainWindow::loginDialogDone(const QString &email, const QString &password)
421 {
422     qDebug() << __PRETTY_FUNCTION__;
423
424     m_email = email;
425     m_password = password;
426 }
427
428 void MainWindow::loginFailed()
429 {
430     qDebug() << __PRETTY_FUNCTION__;
431
432     m_email.clear();
433     m_password.clear();
434
435     toggleProgressIndicator(false);
436
437 #ifdef Q_WS_MAEMO_5
438     QMaemo5InformationBox::information(this, tr("Invalid E-mail address or password"),
439                                        QMaemo5InformationBox::NoTimeout);
440
441 #endif // Q_WS_MAEMO_5
442
443     if(!m_email.isEmpty()) {
444         m_loginDialog->setEmailField(m_email);
445     }
446
447     if(m_loginDialog->exec() != QDialog::Accepted) {
448         // if login dialog was canceled we need to stop processing webview
449         // stop and disconnect m_webView;
450         m_webView->stop();
451         disconnect(m_webView, SIGNAL(loadFinished(bool)),
452                    this, SLOT(loadDone(bool)));
453         disconnect(m_webView, SIGNAL(urlChanged(const QUrl &)),
454                    this, SLOT(updateCredentials(const QUrl &)));
455
456         emit cancelLoginProcess();
457     }
458     else {
459         // re-load login page for webview
460         toggleProgressIndicator(true);
461         m_webView->load(m_loginUrl);
462     }
463 }
464
465 void MainWindow::openSettingsDialog()
466 {
467     qDebug() << __PRETTY_FUNCTION__;
468
469     m_settingsDialog->enableSituareSettings(m_gpsToggleAct->isChecked() && m_loggedIn);
470
471     m_settingsDialog->show();
472 }
473
474 void MainWindow::setAutoCenteringButtonEnabled(bool enabled)
475 {
476     qDebug() << __PRETTY_FUNCTION__;
477
478     m_autoCenteringAct->setChecked(enabled);
479 }
480
481 void MainWindow::setGPSButtonEnabled(bool enabled)
482 {
483     qDebug() << __PRETTY_FUNCTION__;
484
485     m_gpsToggleAct->setChecked(enabled);
486     setOwnLocationCrosshairVisibility(!enabled);
487     m_autoCenteringAct->setVisible(enabled);
488 }
489
490 void MainWindow::setMapViewScene(QGraphicsScene *scene)
491 {
492     qDebug() << __PRETTY_FUNCTION__;
493
494     m_mapView->setScene(scene);
495 }
496
497 void MainWindow::setOwnLocationCrosshairVisibility(bool visibility)
498 {
499     qDebug() << __PRETTY_FUNCTION__;
500
501     if (visibility) {
502         m_ownLocationCrosshair->show();
503         m_drawOwnLocationCrosshair = true;
504         drawOwnLocationCrosshair(m_viewPortWidth, m_viewPortHeight);
505     }
506     else {
507         m_ownLocationCrosshair->hide();
508         m_drawOwnLocationCrosshair = false;
509     }
510 }
511
512 void MainWindow::setUsername(const QString &username)
513 {
514     qDebug() << __PRETTY_FUNCTION__;
515     m_email = username;
516 }
517
518 void MainWindow::setViewPortSize(int width, int height)
519 {
520     qDebug() << __PRETTY_FUNCTION__;
521
522     m_viewPortWidth = width;
523     m_viewPortHeight = height;
524 }
525
526 void MainWindow::showMaemoInformationBox(const QString &message)
527 {
528     qDebug() << __PRETTY_FUNCTION__;
529
530 #ifdef Q_WS_MAEMO_5
531     QMaemo5InformationBox::information(this, message, QMaemo5InformationBox::DefaultTimeout);
532 #else
533     Q_UNUSED(message);
534 #endif
535 }
536
537 void MainWindow::showPanels(bool show)
538 {
539     qDebug() << __PRETTY_FUNCTION__;
540     if(show) {
541         m_friendsListPanel->show();
542         m_friendsListPanelSidebar->show();
543         m_userPanel->show();
544         m_userPanelSidebar->show();
545     }
546     else {
547         m_friendsListPanel->closePanel();
548         m_friendsListPanel->hide();
549         m_friendsListPanelSidebar->hide();
550         m_userPanel->closePanel();
551         m_userPanel->hide();
552         m_userPanelSidebar->hide();
553     }
554 }
555
556 void MainWindow::startLoginProcess(const QUrl &url)
557 {
558     qDebug() << __PRETTY_FUNCTION__;
559
560     m_loginUrl = url;
561     m_webView = new QWebView;
562     m_loginDialog = new LoginDialog(this);
563
564     connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
565             this, SIGNAL(updateCredentials(QUrl)));
566     connect(m_webView, SIGNAL(loadFinished(bool)),
567             this, SLOT(loadDone(bool)));
568
569     connect(m_loginDialog, SIGNAL(loginDialogDone(QString,QString)),
570             this, SLOT(loginDialogDone(QString,QString)));
571
572     m_webView->hide();
573
574     emit fetchUsernameFromSettings();
575
576     if(!m_email.isEmpty()) {
577         m_loginDialog->setEmailField(m_email);
578     }
579
580     if(m_loginDialog->exec() != QDialog::Accepted) {
581         // if login dialog was canceled we need to stop processing webview
582         // stop and disconnect m_webView;
583         m_webView->stop();
584         disconnect(m_webView, SIGNAL(loadFinished(bool)),
585                    this, SLOT(loadDone(bool)));
586         disconnect(m_webView, SIGNAL(urlChanged(const QUrl &)),
587                    this, SLOT(updateCredentials(const QUrl &)));
588
589         emit cancelLoginProcess();
590     }
591     else {
592         m_webView->load(m_loginUrl);
593         toggleProgressIndicator(true);
594         m_refresh = true;
595     }
596 }
597
598 void MainWindow::toggleProgressIndicator(bool value)
599 {
600     qDebug() << __PRETTY_FUNCTION__;
601
602 #ifdef Q_WS_MAEMO_5
603     setAttribute(Qt::WA_Maemo5ShowProgressIndicator, value);
604 #else
605     Q_UNUSED(value);
606 #endif // Q_WS_MAEMO_5
607 }
608
609 const QString MainWindow::username()
610 {
611     qDebug() << __PRETTY_FUNCTION__;
612     return m_email;
613 }