Finished zoom panel drag feature fixes
[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     qDebug() << __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);
224
225     connect(m_zoomButtonPanel->zoomInButton(), SIGNAL(clicked()),
226             this, SIGNAL(zoomIn()));
227
228     connect(m_zoomButtonPanel->zoomOutButton(), SIGNAL(clicked()),
229             this, SIGNAL(zoomOut()));
230
231     connect(this, SIGNAL(zoomLevelChanged(int)),
232             m_zoomButtonPanel, SLOT(resetButtons()));
233
234     connect(this, SIGNAL(maxZoomLevelReached()),
235             m_zoomButtonPanel, SLOT(disableZoomInButton()));
236
237     connect(this, SIGNAL(minZoomLevelReached()),
238             m_zoomButtonPanel, SLOT(disableZoomOutButton()));
239
240     connect(m_mapView, SIGNAL(viewResized(QSize)),
241             m_zoomButtonPanel, SLOT(screenResized(QSize)));
242 }
243
244 void MainWindow::createMenus()
245 {
246     qDebug() << __PRETTY_FUNCTION__;
247
248     // login/logout
249     m_loginAct = new QAction(tr("Login"), this);
250     connect(m_loginAct, SIGNAL(triggered()),
251             this, SIGNAL(loginActionPressed()));
252
253     // settings
254     m_toSettingsAct = new QAction(tr("Settings"), this);
255     connect(m_toSettingsAct, SIGNAL(triggered()),
256         this, SLOT(openSettingsDialog()));
257
258     // GPS
259     m_gpsToggleAct = new QAction(tr("GPS"), this);
260     m_gpsToggleAct->setCheckable(true);
261
262     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
263             this, SIGNAL(gpsTriggered(bool)));
264
265     // automatic centering
266     m_autoCenteringAct = new QAction(tr("Auto centering"), this);
267     m_autoCenteringAct->setCheckable(true);
268     connect(m_autoCenteringAct, SIGNAL(triggered(bool)),
269         this, SIGNAL(autoCenteringTriggered(bool)));
270
271     // build the actual menu
272     m_viewMenu = menuBar()->addMenu(tr("Main"));
273     m_viewMenu->addAction(m_loginAct);
274     m_viewMenu->addAction(m_toSettingsAct);
275     m_viewMenu->addAction(m_gpsToggleAct);
276     m_viewMenu->addAction(m_autoCenteringAct);
277     m_viewMenu->setObjectName(tr("Menu"));
278 }
279
280 void MainWindow::drawOsmLicense(const QSize &size)
281 {
282     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
283
284     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE)
285                        - PANEL_PEEK_AMOUNT,
286                        size.height() - m_osmLicense->fontMetrics().height());
287
288 }
289
290 void MainWindow::drawOwnLocationCrosshair(int width, int height)
291 {
292     qDebug() << __PRETTY_FUNCTION__;
293
294     if (m_drawOwnLocationCrosshair && m_ownLocationCrosshair != 0) {
295         m_ownLocationCrosshair->move(width/2 - m_ownLocationCrosshair->pixmap()->width()/2,
296                             height/2 - m_ownLocationCrosshair->pixmap()->height()/2);
297     }
298 }
299
300 void MainWindow::gpsError(const QString &message)
301 {
302     qDebug() << __PRETTY_FUNCTION__;
303
304     showMaemoInformationBox(message);
305 }
306
307 void MainWindow::gpsTimeout()
308 {
309     qDebug() << __PRETTY_FUNCTION__;
310
311     showMaemoInformationBox(tr("GPS timeout"));
312 }
313
314 void MainWindow::grabZoomKeys(bool grab)
315 {
316     qDebug() << __PRETTY_FUNCTION__;
317
318 #ifdef Q_WS_MAEMO_5
319     // Can't grab keys unless we have a window id
320     if (!winId())
321         return;
322
323     unsigned long val = (grab) ? 1 : 0;
324     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
325     if (!atom)
326         return;
327
328     XChangeProperty (QX11Info::display(),
329                      winId(),
330                      atom,
331                      XA_INTEGER,
332                      32,
333                      PropModeReplace,
334                      reinterpret_cast<unsigned char *>(&val),
335                      1);
336 #else
337     Q_UNUSED(grab);
338 #endif // Q_WS_MAEMO_5
339 }
340
341 void MainWindow::keyPressEvent(QKeyEvent* event)
342 {
343     qDebug() << __PRETTY_FUNCTION__;
344
345     switch (event->key()) {
346     case Qt::Key_F7:
347         event->accept();
348         emit zoomIn();
349         break;
350
351     case Qt::Key_F8:
352         event->accept();
353         emit zoomOut();
354         break;
355     }
356     QWidget::keyPressEvent(event);
357 }
358
359 void MainWindow::loadDone(bool done)
360 {
361     qDebug() << __PRETTY_FUNCTION__;
362
363     // for the first time the login page is opened, we need to refresh it to get cookies working
364     if(m_refresh) {
365         m_webView->reload();
366         m_refresh = false;
367     }
368
369     if (done)
370     {
371         QWebFrame* frame = m_webView->page()->currentFrame();
372         if (frame!=NULL)
373         {
374             // set email box
375             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
376
377             foreach (QWebElement element, emailCollection) {
378                 element.setAttribute("value", m_email.toAscii());
379             }
380             // set password box
381             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
382             foreach (QWebElement element, passwordCollection) {
383                 element.setAttribute("value", m_password.toAscii());
384             }
385             // find connect button
386             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
387             foreach (QWebElement element, buttonCollection)
388             {
389                 QPoint pos(element.geometry().center());
390
391                 // send a mouse click event to the web page
392                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
393                                    Qt::NoModifier);
394                 QApplication::sendEvent(m_webView->page(), &event0);
395                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
396                                    Qt::NoModifier);
397                 QApplication::sendEvent(m_webView->page(), &event1);
398             }
399         }
400     }
401 }
402
403 void MainWindow::loggedIn(bool logged)
404 {
405     qDebug() << __PRETTY_FUNCTION__;
406
407     m_loggedIn = logged;
408
409     if(logged) {
410         m_loginAct->setText(tr("Logout"));
411     }
412     else {
413         m_loginAct->setText(tr("Login"));
414     }
415     showPanels(m_loggedIn);
416 }
417
418 void MainWindow::loginDialogDone(const QString &email, const QString &password)
419 {
420     qDebug() << __PRETTY_FUNCTION__;
421
422     m_email = email;
423     m_password = password;
424 }
425
426 void MainWindow::loginFailed()
427 {
428     qDebug() << __PRETTY_FUNCTION__;
429
430     m_email.clear();
431     m_password.clear();
432
433     toggleProgressIndicator(false);
434
435 #ifdef Q_WS_MAEMO_5
436     QMaemo5InformationBox::information(this, tr("Invalid E-mail address or password"),
437                                        QMaemo5InformationBox::NoTimeout);
438
439 #endif // Q_WS_MAEMO_5
440
441     if(!m_email.isEmpty()) {
442         m_loginDialog->setEmailField(m_email);
443     }
444
445     if(m_loginDialog->exec() != QDialog::Accepted) {
446         // if login dialog was canceled we need to stop processing webview
447         // stop and disconnect m_webView;
448         m_webView->stop();
449         disconnect(m_webView, SIGNAL(loadFinished(bool)),
450                    this, SLOT(loadDone(bool)));
451         disconnect(m_webView, SIGNAL(urlChanged(const QUrl &)),
452                    this, SLOT(updateCredentials(const QUrl &)));
453
454         emit cancelLoginProcess();
455     }
456     else {
457         // re-load login page for webview
458         toggleProgressIndicator(true);
459         m_webView->load(m_loginUrl);
460     }
461 }
462
463 void MainWindow::openSettingsDialog()
464 {
465     qDebug() << __PRETTY_FUNCTION__;
466
467     SettingsDialog *dialog = new SettingsDialog(this);
468     if(!m_loggedIn) {
469         dialog->disableSituareSettings();
470     }
471     dialog->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 }