merged with use_last_location
[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 "panelsidebar.h"
39 #include "settingsdialog.h"
40 #include "userinfopanel.h"
41 #include "zoombuttonpanel.h"
42
43 #include "mainwindow.h"
44
45 #include <QtGui/QX11Info>
46 #include <X11/Xlib.h>
47 #include <X11/Xatom.h>
48
49 // values for setting screen size in desktop matching N900 screen size
50 const int N900_APP_WIDTH = 800;
51 const int N900_APP_HEIGHT = 449;
52
53 MainWindow::MainWindow(QWidget *parent)
54     : QMainWindow(parent),
55     m_drawOwnLocationCrosshair(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     PanelSideBar *friendsListPanelSidebar = new PanelSideBar(this, RIGHT);
109
110     m_friendsListPanel->stackUnder(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             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     PanelSideBar *userPanelSidebar = new PanelSideBar(this, LEFT);
196
197     userPanelSidebar->stackUnder(m_friendsListPanel);
198     m_userPanel->stackUnder(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     // settings
247     m_toSettingsAct = new QAction(tr("Settings"), this);
248     m_toSettingsAct->setObjectName(tr("Settings"));
249     connect(m_toSettingsAct, SIGNAL(triggered()),
250         this, SLOT(openSettingsDialog()));
251
252     // GPS
253     m_gpsToggleAct = new QAction(tr("GPS"), this);
254     m_gpsToggleAct->setCheckable(true);
255
256     connect(m_gpsToggleAct, SIGNAL(triggered(bool)),
257             this, SIGNAL(gpsTriggered(bool)));
258
259     // automatic centering
260     m_autoCenteringAct = new QAction(tr("Auto centering"), this);
261     m_autoCenteringAct->setCheckable(true);
262     connect(m_autoCenteringAct, SIGNAL(triggered(bool)),
263         this, SIGNAL(autoCenteringTriggered(bool)));
264
265     // build the actual menu
266     m_viewMenu = menuBar()->addMenu(tr("Main"));
267     m_viewMenu->addAction(m_toSettingsAct);
268     m_viewMenu->addAction(m_gpsToggleAct);
269     m_viewMenu->addAction(m_autoCenteringAct);
270     m_viewMenu->setObjectName(tr("Menu"));
271 }
272
273 void MainWindow::drawOsmLicense(const QSize &size)
274 {
275     qDebug() << __PRETTY_FUNCTION__ << size.width() << "x" << size.height();
276
277     m_osmLicense->move(size.width() - m_osmLicense->fontMetrics().width(OSM_LICENSE) - PANEL_PEEK_AMOUNT,
278                         size.height() - m_osmLicense->fontMetrics().height());
279
280 }
281
282 void MainWindow::drawOwnLocationCrosshair(int width, int height)
283 {
284     qDebug() << __PRETTY_FUNCTION__;
285
286     if (m_drawOwnLocationCrosshair && m_ownLocationCrosshair != 0) {
287         m_ownLocationCrosshair->move(width/2 - m_ownLocationCrosshair->pixmap()->width()/2,
288                             height/2 - m_ownLocationCrosshair->pixmap()->height()/2);
289     }
290 }
291
292 void MainWindow::gpsError(const QString &message)
293 {
294     qDebug() << __PRETTY_FUNCTION__;
295
296     showMaemoInformationBox(message);
297 }
298
299 void MainWindow::gpsTimeout()
300 {
301     qDebug() << __PRETTY_FUNCTION__;
302
303     showMaemoInformationBox(tr("GPS timeout"));
304 }
305
306 void MainWindow::grabZoomKeys(bool grab)
307 {
308     qDebug() << __PRETTY_FUNCTION__;
309
310 #ifdef Q_WS_MAEMO_5
311     // Can't grab keys unless we have a window id
312     if (!winId())
313         return;
314
315     unsigned long val = (grab) ? 1 : 0;
316     Atom atom = XInternAtom(QX11Info::display(), "_HILDON_ZOOM_KEY_ATOM", False);
317     if (!atom)
318         return;
319
320     XChangeProperty (QX11Info::display(),
321                      winId(),
322                      atom,
323                      XA_INTEGER,
324                      32,
325                      PropModeReplace,
326                      reinterpret_cast<unsigned char *>(&val),
327                      1);
328 #else
329     Q_UNUSED(grab);
330 #endif // Q_WS_MAEMO_5
331 }
332
333 void MainWindow::keyPressEvent(QKeyEvent* event)
334 {
335     qDebug() << __PRETTY_FUNCTION__;
336
337     switch (event->key()) {
338     case Qt::Key_F7:
339         event->accept();
340         emit zoomIn();
341         break;
342
343     case Qt::Key_F8:
344         event->accept();
345         emit zoomOut();
346         break;
347     }
348     QWidget::keyPressEvent(event);
349 }
350
351 void MainWindow::loadDone(bool done)
352 {
353     qDebug() << __PRETTY_FUNCTION__;
354
355     // for the first time the login page is opened, we need to refresh it to get cookies working
356     if(m_refresh) {
357         m_webView->reload();
358         m_refresh = false;
359     }
360
361     if (done)
362     {
363         QWebFrame* frame = m_webView->page()->currentFrame();
364         if (frame!=NULL)
365         {
366             // set email box
367             QWebElementCollection emailCollection = frame->findAllElements("input[name=email]");
368
369             foreach (QWebElement element, emailCollection) {
370                 element.setAttribute("value", m_email.toAscii());
371             }
372             // set password box
373             QWebElementCollection passwordCollection = frame->findAllElements("input[name=pass]");
374             foreach (QWebElement element, passwordCollection) {
375                 element.setAttribute("value", m_password.toAscii());
376             }
377             // find connect button
378             QWebElementCollection buttonCollection = frame->findAllElements("input[name=login]");
379             foreach (QWebElement element, buttonCollection)
380             {
381                 QPoint pos(element.geometry().center());
382
383                 // send a mouse click event to the web page
384                 QMouseEvent event0(QEvent::MouseButtonPress, pos, Qt::LeftButton, Qt::LeftButton,
385                                    Qt::NoModifier);
386                 QApplication::sendEvent(m_webView->page(), &event0);
387                 QMouseEvent event1(QEvent::MouseButtonRelease, pos, Qt::LeftButton, Qt::LeftButton,
388                                    Qt::NoModifier);
389                 QApplication::sendEvent(m_webView->page(), &event1);
390             }
391         }
392     }
393 }
394
395 void MainWindow::loginDialogDone(const QString &email, const QString &password)
396 {
397     qDebug() << __PRETTY_FUNCTION__;
398
399     m_email = email;
400     m_password = password;
401 }
402
403 void MainWindow::loginFailed()
404 {
405     qDebug() << __PRETTY_FUNCTION__;
406
407     m_email.clear();
408     m_password.clear();
409
410     toggleProgressIndicator(false);
411
412 #ifdef Q_WS_MAEMO_5
413     QMaemo5InformationBox::information(this, tr("Invalid E-mail address or password"),
414                                        QMaemo5InformationBox::NoTimeout);
415
416 #endif // Q_WS_MAEMO_5
417
418     if(!m_email.isEmpty()) {
419         m_loginDialog->setEmailField(m_email);
420     }
421
422     if(m_loginDialog->exec() != QDialog::Accepted) {
423         // if login dialog was canceled we need to stop processing webview
424         // stop and disconnect m_webView;
425         m_webView->stop();
426         disconnect(m_webView, SIGNAL(loadFinished(bool)),
427                    this, SLOT(loadDone(bool)));
428         disconnect(m_webView, SIGNAL(urlChanged(const QUrl &)),
429                    this, SLOT(updateCredentials(const QUrl &)));
430
431         emit cancelLoginProcess();
432     }
433     else {
434         // re-load login page for webview
435         toggleProgressIndicator(true);
436         m_webView->load(m_loginUrl);
437     }
438 }
439
440 void MainWindow::openSettingsDialog()
441 {
442     qDebug() << __PRETTY_FUNCTION__;
443
444     SettingsDialog *dialog = new SettingsDialog(this);
445     dialog->show();
446 }
447
448 void MainWindow::setAutoCenteringButtonEnabled(bool enabled)
449 {
450     qDebug() << __PRETTY_FUNCTION__;
451
452     m_autoCenteringAct->setChecked(enabled);
453 }
454
455 void MainWindow::setGPSButtonEnabled(bool enabled)
456 {
457     qDebug() << __PRETTY_FUNCTION__;
458
459     m_gpsToggleAct->setChecked(enabled);
460     setOwnLocationCrosshairVisibility(!enabled);
461     m_autoCenteringAct->setVisible(enabled);
462 }
463
464 void MainWindow::setMapViewScene(QGraphicsScene *scene)
465 {
466     qDebug() << __PRETTY_FUNCTION__;
467
468     m_mapView->setScene(scene);
469 }
470
471 void MainWindow::setUsername(const QString &username)
472 {
473     qDebug() << __PRETTY_FUNCTION__;
474     m_email = username;
475 }
476
477 void MainWindow::setOwnLocationCrosshairVisibility(bool visibility)
478 {
479     qDebug() << __PRETTY_FUNCTION__;
480
481     if (visibility) {
482         m_ownLocationCrosshair->show();
483         m_drawOwnLocationCrosshair = true;
484         drawOwnLocationCrosshair(m_viewPortWidth, m_viewPortHeight);
485     }
486     else {
487         m_ownLocationCrosshair->hide();
488         m_drawOwnLocationCrosshair = false;
489     }
490 }
491
492 void MainWindow::setViewPortSize(int width, int height)
493 {
494     qDebug() << __PRETTY_FUNCTION__;
495
496     m_viewPortWidth = width;
497     m_viewPortHeight = height;
498 }
499
500 void MainWindow::showMaemoInformationBox(const QString &message)
501 {
502     qDebug() << __PRETTY_FUNCTION__;
503
504 #ifdef Q_WS_MAEMO_5
505     QMaemo5InformationBox::information(this, message, QMaemo5InformationBox::DefaultTimeout);
506 #else
507     Q_UNUSED(message);
508 #endif
509 }
510
511 void MainWindow::startLoginProcess(const QUrl &url)
512 {
513     qDebug() << __PRETTY_FUNCTION__;
514
515     m_loginUrl = url;
516     m_webView = new QWebView;
517     m_loginDialog = new LoginDialog(this);
518
519     connect(m_webView, SIGNAL(urlChanged(const QUrl &)),
520             this, SIGNAL(updateCredentials(QUrl)));
521     connect(m_webView, SIGNAL(loadFinished(bool)),
522             this, SLOT(loadDone(bool)));
523
524     connect(m_loginDialog, SIGNAL(loginDialogDone(QString,QString)),
525             this, SLOT(loginDialogDone(QString,QString)));
526
527     m_webView->hide();
528
529     emit fetchUsernameFromSettings();
530
531     if(!m_email.isEmpty()) {
532         m_loginDialog->setEmailField(m_email);
533     }
534
535     if(m_loginDialog->exec() != QDialog::Accepted) {
536         // if login dialog was canceled we need to stop processing webview
537         // stop and disconnect m_webView;
538         m_webView->stop();
539         disconnect(m_webView, SIGNAL(loadFinished(bool)),
540                    this, SLOT(loadDone(bool)));
541         disconnect(m_webView, SIGNAL(urlChanged(const QUrl &)),
542                    this, SLOT(updateCredentials(const QUrl &)));
543
544         emit cancelLoginProcess();
545     }
546     else {
547         m_webView->load(m_loginUrl);
548         toggleProgressIndicator(true);
549         m_refresh = true;
550     }
551 }
552
553 void MainWindow::toggleProgressIndicator(bool value)
554 {
555     qDebug() << __PRETTY_FUNCTION__;
556
557 #ifdef Q_WS_MAEMO_5
558     setAttribute(Qt::WA_Maemo5ShowProgressIndicator, value);
559 #else
560     Q_UNUSED(value);
561 #endif // Q_WS_MAEMO_5
562 }
563
564 const QString MainWindow::username()
565 {
566     qDebug() << __PRETTY_FUNCTION__;
567     return m_email;
568 }