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