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