Merge branch 'master' into locationlistview
[situare] / src / map / mapengine.cpp
1 /*
2    Situare - A location system for Facebook
3    Copyright (C) 2010  Ixonos Plc. Authors:
4
5        Sami Rämö - sami.ramo@ixonos.com
6        Jussi Laitinen - jussi.laitinen@ixonos.com
7        Pekka Nissinen - pekka.nissinen@ixonos.com
8        Ville Tiensuu - ville.tiensuu@ixonos.com
9        Henri Lampela - henri.lampela@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 <QtAlgorithms>
27 #include <QDebug>
28 #include <QString>
29 #include <QStringList>
30 #include <QUrl>
31 #include <QHash>
32 #include <QHashIterator>
33 #include <QRect>
34
35 #include "common.h"
36 #include "frienditemshandler.h"
37 #include "gpslocationitem.h"
38 #include "mapcommon.h"
39 #include "mapfetcher.h"
40 #include "maprouteitem.h"
41 #include "mapscene.h"
42 #include "mapscroller.h"
43 #include "maptile.h"
44 #include "network/networkaccessmanager.h"
45 #include "ownlocationitem.h"
46 #include "user/user.h"
47
48 #include "mapengine.h"
49
50 const int SMOOTH_CENTERING_TIME_MS = 1000;
51
52 MapEngine::MapEngine(QObject *parent)
53     : QObject(parent),
54       m_autoCenteringEnabled(false),
55       m_scrollStartedByGps(false),
56       m_smoothScrollRunning(false),
57       m_zoomedIn(false),
58       m_zoomLevel(MAP_DEFAULT_ZOOM_LEVEL),
59       m_centerTile(QPoint(UNDEFINED, UNDEFINED)),
60       m_sceneCoordinate(SceneCoordinate(GeoCoordinate(MAP_DEFAULT_LATITUDE, MAP_DEFAULT_LONGITUDE))),
61       m_tilesGridSize(QSize(0, 0)),
62       m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT)),
63       m_mapRouteItem(0)
64 {
65     qDebug() << __PRETTY_FUNCTION__;
66
67     m_mapScene = new MapScene(this);
68
69     m_mapFetcher = new MapFetcher(new NetworkAccessManager(this), this);
70     connect(this, SIGNAL(fetchImage(int, int, int)),
71             m_mapFetcher, SLOT(enqueueFetchMapImage(int, int, int)));
72     connect(m_mapFetcher, SIGNAL(mapImageReceived(int, int, int, QPixmap)),
73             this, SLOT(mapImageReceived(int, int, int, QPixmap)));
74     connect(m_mapFetcher, SIGNAL(error(int, int)),
75             this, SIGNAL(error(int, int)));
76
77     m_ownLocation = new OwnLocationItem();
78     m_ownLocation->hide(); // hide until first location info is received
79     m_mapScene->addItem(m_ownLocation);
80
81     m_gpsLocationItem = new GPSLocationItem();
82     m_mapScene->addItem(m_gpsLocationItem);
83
84     m_friendItemsHandler = new FriendItemsHandler(m_mapScene, this);
85     connect(this, SIGNAL(zoomLevelChanged(int)),
86             m_friendItemsHandler, SLOT(refactorFriendItems(int)));
87
88     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
89             m_friendItemsHandler, SLOT(friendListUpdated(QList<User*>&)));
90
91     connect(this, SIGNAL(friendImageReady(User*)),
92             m_friendItemsHandler, SLOT(friendImageReady(User*)));
93
94     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
95             this, SLOT(friendsPositionsUpdated()));
96
97     connect(m_friendItemsHandler, SIGNAL(locationItemClicked(QList<QString>)),
98             this, SIGNAL(locationItemClicked(QList<QString>)));
99
100     m_scroller = &MapScroller::getInstance();
101
102     connect(m_scroller, SIGNAL(coordinateUpdated(SceneCoordinate)),
103             this, SLOT(setCenterPosition(SceneCoordinate)));
104
105     connect(m_scroller, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)),
106             this, SLOT(scrollerStateChanged(QAbstractAnimation::State)));
107 }
108
109 MapEngine::~MapEngine()
110 {
111     qDebug() << __PRETTY_FUNCTION__;
112
113     QSettings settings(DIRECTORY_NAME, FILE_NAME);
114
115     settings.setValue(MAP_LAST_POSITION, QVariant::fromValue(centerGeoCoordinate()));
116     settings.setValue(MAP_LAST_ZOOMLEVEL, m_zoomLevel);
117 }
118
119 QRect MapEngine::calculateTileGrid(SceneCoordinate coordinate)
120 {
121     qDebug() << __PRETTY_FUNCTION__;
122
123     QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, coordinate);
124
125     QPoint topLeft;
126     topLeft.setX(tileCoordinate.x() - (m_tilesGridSize.width() / 2));
127     topLeft.setY(tileCoordinate.y() - (m_tilesGridSize.height() / 2));
128
129     return QRect(topLeft, m_tilesGridSize);
130 }
131
132 void MapEngine::centerAndZoomTo(QRect rect, bool useMargins)
133 {
134     qDebug() << __PRETTY_FUNCTION__;
135
136     int marginHorizontal = 50;
137     int marginVertical = 5;
138
139     if (!useMargins) {
140         marginHorizontal = 0;
141         marginVertical = 0;
142     }
143
144     // calculate the usable size of the view
145     int viewUsableHeight = m_viewSize.height() - 2 * marginHorizontal;
146     int viewUsableWidth = m_viewSize.width() - 2 * marginVertical;
147
148     // calculate how many levels must be zoomed out from the closest zoom level to get the rect
149     // fit inside the usable view area
150     int shift = 0;
151     while ((rect.height() > (viewUsableHeight * (1 << shift)))
152            || (rect.width() > (viewUsableWidth * (1 << shift)))) {
153
154         shift++;
155     }
156
157
158     scrollToPosition(SceneCoordinate(double(rect.center().x()), double(rect.center().y())));
159
160     int zoomLevel = qBound(OSM_MIN_ZOOM_LEVEL, OSM_MAX_ZOOM_LEVEL - shift, OSM_MAX_ZOOM_LEVEL);
161     setZoomLevel(zoomLevel);
162 }
163
164 GeoCoordinate MapEngine::centerGeoCoordinate()
165 {
166     qDebug() << __PRETTY_FUNCTION__;
167
168     return GeoCoordinate(m_sceneCoordinate);
169 }
170
171 void MapEngine::centerToCoordinates(GeoCoordinate coordinate)
172 {
173     qDebug() << __PRETTY_FUNCTION__;
174
175     scrollToPosition(SceneCoordinate(coordinate));
176 }
177
178 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, SceneCoordinate coordinate)
179 {
180     qDebug() << __PRETTY_FUNCTION__;
181
182     int pow = 1 << (OSM_MAX_ZOOM_LEVEL - zoomLevel);
183     int x = static_cast<int>(coordinate.x() / (OSM_TILE_SIZE_X * pow));
184     int y = static_cast<int>(coordinate.y() / (OSM_TILE_SIZE_Y * pow));
185
186     return QPoint(x, y);
187 }
188
189 void MapEngine::disableAutoCenteringIfRequired(SceneCoordinate coordinate)
190 {
191     if (isAutoCenteringEnabled()) {
192         int zoomFactor = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
193
194         SceneCoordinate oldPixelValue(m_lastAutomaticPosition.x() / zoomFactor,
195                                       m_lastAutomaticPosition.y() / zoomFactor);
196
197         SceneCoordinate newPixelValue(coordinate.x() / zoomFactor,
198                                       coordinate.y() / zoomFactor);
199
200         if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE)
201             || (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE)) {
202
203             emit mapScrolledManually();
204         }
205     }
206 }
207
208 void MapEngine::friendsPositionsUpdated()
209 {
210     qDebug() << __PRETTY_FUNCTION__;
211
212     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
213 }
214
215 void MapEngine::getTiles(SceneCoordinate coordinate)
216 {
217     qDebug() << __PRETTY_FUNCTION__;
218
219     m_viewTilesGrid = calculateTileGrid(coordinate);
220     updateViewTilesSceneRect();
221     m_mapScene->setTilesGrid(m_viewTilesGrid);
222
223     int topLeftX = m_viewTilesGrid.topLeft().x();
224     int topLeftY = m_viewTilesGrid.topLeft().y();
225     int bottomRightX = m_viewTilesGrid.bottomRight().x();
226     int bottomRightY = m_viewTilesGrid.bottomRight().y();
227
228     int tileMaxVal = MapTile::lastTileIndex(m_zoomLevel);
229
230     for (int x = topLeftX; x <= bottomRightX; ++x) {
231         for (int y = topLeftY; y <= bottomRightY; ++y) {
232
233             // map doesn't span in vertical direction, so y index must be inside the limits
234             if (y >= MAP_TILE_MIN_INDEX && y <= tileMaxVal) {
235                 if (!m_mapScene->tileInScene(MapTile::tilePath(m_zoomLevel, x, y)))
236                     emit fetchImage(m_zoomLevel, normalize(x, MAP_TILE_MIN_INDEX, tileMaxVal), y);
237             }
238         }
239     }
240 }
241
242 void MapEngine::gpsPositionUpdate(GeoCoordinate position, qreal accuracy)
243 {
244     qDebug() << __PRETTY_FUNCTION__;
245
246     // update GPS location item (but only if accuracy is a valid number)
247     if (!isnan(accuracy)) {
248         qreal resolution = MapScene::horizontalResolutionAtLatitude(position.latitude());
249         m_gpsLocationItem->updateItem(SceneCoordinate(position).toPointF(), accuracy, resolution);
250     }
251
252     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
253
254     // do automatic centering (if enabled)
255     if (m_autoCenteringEnabled) {
256         m_lastAutomaticPosition = SceneCoordinate(position);
257         m_scrollStartedByGps = true;
258         scrollToPosition(m_lastAutomaticPosition);
259     }
260 }
261
262 void MapEngine::init()
263 {
264     qDebug() << __PRETTY_FUNCTION__;
265
266     QSettings settings(DIRECTORY_NAME, FILE_NAME);
267
268     // init can be only done if both values exists in the settings
269     if (settings.contains(MAP_LAST_POSITION) && settings.contains(MAP_LAST_ZOOMLEVEL)) {
270         QVariant zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL);
271         QVariant location = settings.value(MAP_LAST_POSITION);
272
273         // also the init can be only done if we are able to convert variants into target data types
274         if (zoomLevel.canConvert<int>() && location.canConvert<GeoCoordinate>()) {
275             m_zoomLevel = zoomLevel.toInt();
276             m_sceneCoordinate = SceneCoordinate(location.value<GeoCoordinate>());
277         }
278     }
279
280     // emit zoom level and center coordinate so that all parts of the map system gets initialized
281     // NOTE: emit is also done even if we weren't able to read initial valuef from the settings
282     //       so that the default values set in the constructor are used
283     emit zoomLevelChanged(m_zoomLevel);
284     scrollToPosition(m_sceneCoordinate);
285 }
286
287 bool MapEngine::isAutoCenteringEnabled()
288 {
289     return m_autoCenteringEnabled;
290 }
291
292 bool MapEngine::isCenterTileChanged(SceneCoordinate coordinate)
293 {
294     qDebug() << __PRETTY_FUNCTION__;
295
296     QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, coordinate);
297     QPoint temp = m_centerTile;
298     m_centerTile = centerTile;
299
300     return (centerTile != temp);
301 }
302
303 void MapEngine::locationItemClicked(GeoCoordinate &swBound, GeoCoordinate &neBound)
304 {
305     qDebug() << __PRETTY_FUNCTION__;
306
307     QRect area;
308     area.setTopRight(SceneCoordinate(neBound).toPointF().toPoint());
309     area.setBottomLeft(SceneCoordinate(swBound).toPointF().toPoint());
310
311     centerAndZoomTo(area, false);
312 }
313
314 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
315 {
316     qDebug() << __PRETTY_FUNCTION__;
317
318     // add normal tile inside the world
319     QPoint tileNumber(x, y);
320     m_mapScene->addTile(zoomLevel, tileNumber, image, m_zoomLevel);
321
322     // note: add 1 so odd width is rounded up and even is rounded down
323     int tilesGridWidthHalf = (m_viewTilesGrid.width() + 1) / 2;
324
325     // duplicate to east side? (don't need to duplicate over padding)
326     if (tileNumber.x() < (tilesGridWidthHalf - MAP_GRID_PADDING)) {
327         QPoint adjustedTileNumber(tileNumber.x() + MapTile::lastTileIndex(zoomLevel) + 1,
328                                   tileNumber.y());
329         m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
330     }
331
332     // duplicate to west side? (don't need to duplicate over padding)
333     if (tileNumber.x() > (MapTile::lastTileIndex(zoomLevel)
334                           - tilesGridWidthHalf
335                           + MAP_GRID_PADDING)) {
336         QPoint adjustedTileNumber(tileNumber.x() - MapTile::lastTileIndex(zoomLevel) - 1,
337                                   tileNumber.y());
338         m_mapScene->addTile(zoomLevel, adjustedTileNumber, image, m_zoomLevel);
339     }
340 }
341
342 int MapEngine::normalize(int value, int min, int max)
343 {
344     qDebug() << __PRETTY_FUNCTION__;
345     Q_ASSERT_X(max >= min, "parameters", "max can't be smaller than min");
346
347     while (value < min)
348         value += max - min + 1;
349
350     while (value > max)
351         value -= max - min + 1;
352
353     return value;
354 }
355
356 void MapEngine::receiveOwnLocation(User *user)
357 {
358     qDebug() << __PRETTY_FUNCTION__;
359
360     if(user) {
361         m_ownLocation->setPos(SceneCoordinate(user->coordinates()).toPointF());
362         if (!m_ownLocation->isVisible())
363             m_ownLocation->show();
364     } else {
365         m_ownLocation->hide();
366     }
367
368     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
369 }
370
371 QGraphicsScene* MapEngine::scene()
372 {
373     qDebug() << __PRETTY_FUNCTION__;
374
375     return m_mapScene;
376 }
377
378 void MapEngine::scrollerStateChanged(QAbstractAnimation::State newState)
379 {
380     qDebug() << __PRETTY_FUNCTION__;
381
382     if (m_smoothScrollRunning
383         && newState != QAbstractAnimation::Running) {
384             m_smoothScrollRunning = false;
385
386             // don't disable auto centering if current animation was stopped by new update from GPS
387             if (!m_scrollStartedByGps)
388                 disableAutoCenteringIfRequired(m_sceneCoordinate);
389     }
390
391     m_scrollStartedByGps = false;
392 }
393
394 void MapEngine::scrollToPosition(SceneCoordinate coordinate)
395 {
396     qDebug() << __PRETTY_FUNCTION__;
397
398     m_scroller->stop();
399     m_scroller->setEasingCurve(QEasingCurve::InOutQuart);
400     m_scroller->setDuration(SMOOTH_CENTERING_TIME_MS);
401     m_scroller->setStartValue(m_sceneCoordinate);
402     m_scroller->setEndValue(coordinate);
403     m_smoothScrollRunning = true;
404     m_scroller->start();
405 }
406
407 void MapEngine::setAutoCentering(bool enabled)
408 {
409     qDebug() << __PRETTY_FUNCTION__;
410
411     m_autoCenteringEnabled = enabled;
412 }
413
414 void MapEngine::setCenterPosition(SceneCoordinate coordinate)
415 {
416     qDebug() << __PRETTY_FUNCTION__;
417
418     // jump to opposite side of the world if world horizontal limit is exceeded
419     coordinate.setX(normalize(coordinate.x(), OSM_MAP_MIN_PIXEL_X, OSM_MAP_MAX_PIXEL_X));
420
421     // don't allow vertical scene coordinates go out of the map
422     coordinate.setY(qBound(double(OSM_MAP_MIN_PIXEL_Y),
423                               coordinate.y(),
424                               double(OSM_MAP_MAX_PIXEL_Y)));
425
426     if (!m_smoothScrollRunning)
427         disableAutoCenteringIfRequired(coordinate);
428
429     m_sceneCoordinate = coordinate;
430     emit locationChanged(m_sceneCoordinate);
431
432     if (isCenterTileChanged(coordinate)) {
433         getTiles(coordinate);
434         m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
435     }
436
437     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
438     emit newMapResolution(viewResolution());
439 }
440
441 void MapEngine::setGPSEnabled(bool enabled)
442 {
443     qDebug() << __PRETTY_FUNCTION__;
444
445     m_gpsLocationItem->setEnabled(enabled);
446 }
447
448 void MapEngine::setRoute(Route &route)
449 {
450     qDebug() << __PRETTY_FUNCTION__;
451
452     m_route = route;
453
454     // delete old route track (if exists)
455     if (m_mapRouteItem) {
456         m_mapScene->removeItem(m_mapRouteItem);
457         delete m_mapRouteItem;
458         m_mapRouteItem = 0;
459     }
460
461     // create new route track
462     m_mapRouteItem = new MapRouteItem(&m_route);
463     m_mapScene->addItem(m_mapRouteItem);
464
465     centerAndZoomTo(m_mapRouteItem->boundingRect().toRect());
466 }
467
468 void MapEngine::setZoomLevel(int newZoomLevel)
469 {
470     qDebug() << __PRETTY_FUNCTION__;
471
472     m_zoomLevel = newZoomLevel;
473     zoomed();
474 }
475
476 void MapEngine::setTilesGridSize(const QSize &viewSize)
477 {
478     qDebug() << __PRETTY_FUNCTION__;
479
480     // there must be scrolling reserve of at least half tile added to tile amount
481     // calculated from view size
482     const qreal SCROLLING_RESERVE = 0.5;
483
484     // converting scene tile to tile number does cause grid centering inaccuracy of one tile
485     const int CENTER_TILE_INACCURACY = 1;
486
487     int gridWidth = ceil(qreal(viewSize.width()) / OSM_TILE_SIZE_X + SCROLLING_RESERVE)
488                     + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
489     int gridHeight = ceil(qreal(viewSize.height()) / OSM_TILE_SIZE_Y + SCROLLING_RESERVE)
490                      + CENTER_TILE_INACCURACY + (MAP_GRID_PADDING * 2);
491
492     m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
493
494     m_tilesGridSize.setHeight(gridHeight);
495     m_tilesGridSize.setWidth(gridWidth);
496 }
497
498 void MapEngine::updateViewTilesSceneRect()
499 {
500     qDebug() << __PRETTY_FUNCTION__;
501
502     const QPoint ONE_TILE = QPoint(1, 1);
503     const double ONE_PIXEL = 1;
504
505     SceneCoordinate topLeft = MapTile::convertTileNumberToSceneCoordinate(m_zoomLevel,
506                                                                         m_viewTilesGrid.topLeft());
507
508     // one tile - one pixel is added because returned coordinates are pointing to upper left corner
509     // of the last tile.
510     SceneCoordinate bottomRight
511             = MapTile::convertTileNumberToSceneCoordinate(m_zoomLevel,
512                                                           m_viewTilesGrid.bottomRight() + ONE_TILE);
513     bottomRight.setX(bottomRight.x() - ONE_PIXEL);
514     bottomRight.setY(bottomRight.y() - ONE_PIXEL);
515
516     m_mapScene->tilesSceneRectUpdated(QRect(topLeft.toPointF().toPoint(),
517                                             bottomRight.toPointF().toPoint()));
518 }
519
520 void MapEngine::viewResized(const QSize &size)
521 {
522     qDebug() << __PRETTY_FUNCTION__;
523
524     m_viewSize = size;
525     setTilesGridSize(m_viewSize);
526
527     emit locationChanged(m_sceneCoordinate);
528     getTiles(m_sceneCoordinate);
529     m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
530     m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
531 }
532
533 qreal MapEngine::viewResolution()
534 {
535     qDebug() << __PRETTY_FUNCTION__;
536
537     qreal scale = (1 << (OSM_MAX_ZOOM_LEVEL - m_zoomLevel));
538
539     return MapScene::horizontalResolutionAtLatitude(centerGeoCoordinate().latitude()) * scale;
540 }
541
542 void MapEngine::viewZoomFinished()
543 {
544     qDebug() << __PRETTY_FUNCTION__;
545
546     if (m_zoomedIn) {
547         m_zoomedIn = false;
548         m_mapScene->removeOutOfViewTiles(m_viewTilesGrid, m_zoomLevel);
549     }
550
551     if (m_zoomLevel == OSM_MAX_ZOOM_LEVEL)
552         emit maxZoomLevelReached();
553     else if (m_zoomLevel == MAP_VIEW_MIN_ZOOM_LEVEL)
554         emit minZoomLevelReached();
555 }
556
557 void MapEngine::zoomed()
558 {
559     emit zoomLevelChanged(m_zoomLevel);
560     m_mapScene->setTilesDrawingLevels(m_zoomLevel);
561     m_mapScene->setZoomLevel(m_zoomLevel);
562     getTiles(m_sceneCoordinate);
563     m_mapScene->setSceneVerticalOverlap(m_viewSize.height(), m_zoomLevel);
564     m_mapScene->spanItems(m_zoomLevel, m_sceneCoordinate, m_viewSize);
565     emit newMapResolution(viewResolution());
566 }
567
568 void MapEngine::zoomIn()
569 {
570     qDebug() << __PRETTY_FUNCTION__;
571
572     if (m_zoomLevel < OSM_MAX_ZOOM_LEVEL) {
573         m_zoomLevel++;
574         m_zoomedIn = true;
575         zoomed();
576     }
577 }
578
579 void MapEngine::zoomOut()
580 {
581     qDebug() << __PRETTY_FUNCTION__;
582
583     if (m_zoomLevel > MAP_VIEW_MIN_ZOOM_LEVEL) {
584         m_zoomLevel--;
585         zoomed();
586     }
587 }