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