Added no caching attribute to ImageFetcher and SituareService requests.
[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
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 <QtAlgorithms>
26 #include <QDebug>
27 #include <QString>
28 #include <QStringList>
29 #include <QUrl>
30 #include <QHash>
31 #include <QHashIterator>
32 #include <QRect>
33
34 #include "common.h"
35 #include "frienditemshandler.h"
36 #include "gpslocationitem.h"
37 #include "mapcommon.h"
38 #include "mapfetcher.h"
39 #include "mapscene.h"
40 #include "maptile.h"
41 #include "ownlocationitem.h"
42
43 #include "mapengine.h"
44 #include "network/networkaccessmanager.h"
45
46 MapEngine::MapEngine(QObject *parent)
47     : QObject(parent),
48       m_autoCenteringEnabled(false),
49       m_zoomedIn(false),
50       m_zoomLevel(DEFAULT_ZOOM_LEVEL),
51       m_centerTile(QPoint(UNDEFINED, UNDEFINED)),
52       m_lastManualPosition(QPoint(0, 0)),
53       m_viewSize(QSize(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT))
54 {
55     qDebug() << __PRETTY_FUNCTION__;
56
57     m_mapScene = new MapScene(this);
58
59     m_mapFetcher = new MapFetcher(NetworkAccessManager::instance(), this);
60     connect(this, SIGNAL(fetchImage(int, int, int)),
61             m_mapFetcher, SLOT(enqueueFetchMapImage(int, int, int)));
62     connect(m_mapFetcher, SIGNAL(mapImageReceived(int, int, int, QPixmap)),
63             this, SLOT(mapImageReceived(int, int, int, QPixmap)));
64
65     m_ownLocation = new OwnLocationItem();
66     m_ownLocation->hide(); // hide until first location info is received
67     m_mapScene->addItem(m_ownLocation);
68
69     m_gpsLocationItem = new GPSLocationItem();
70     m_mapScene->addItem(m_gpsLocationItem);
71
72     m_friendItemsHandler = new FriendItemsHandler(m_mapScene, this);
73     connect(this, SIGNAL(zoomLevelChanged(int)),
74             m_friendItemsHandler, SLOT(refactorFriendItems(int)));
75
76     connect(this, SIGNAL(friendsLocationsReady(QList<User*>&)),
77             m_friendItemsHandler, SLOT(friendListUpdated(QList<User*>&)));
78
79     connect(m_friendItemsHandler, SIGNAL(locationItemClicked(QList<QString>)),
80             this, SIGNAL(locationItemClicked(QList<QString>)));
81 }
82
83 MapEngine::~MapEngine()
84 {
85     qDebug() << __PRETTY_FUNCTION__;
86
87     QSettings settings(DIRECTORY_NAME, FILE_NAME);
88     settings.setValue(MAP_LAST_POSITION,
89                       convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate));
90     settings.setValue(MAP_LAST_ZOOMLEVEL, m_zoomLevel);
91 }
92
93 QRect MapEngine::calculateTileGrid(QPoint sceneCoordinate)
94 {
95     qDebug() << __PRETTY_FUNCTION__;
96
97     QPoint tileCoordinate = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
98     int gridWidth = (m_viewSize.width() / TILE_SIZE_X + 1) + (GRID_PADDING * 2);
99     int gridHeight = (m_viewSize.height() / TILE_SIZE_Y + 1) + (GRID_PADDING * 2);
100     int topLeftX = tileCoordinate.x() - (gridWidth / 2);
101     int topLeftY = tileCoordinate.y() - (gridHeight / 2);
102
103     m_mapFetcher->setDownloadQueueSize(gridWidth * gridHeight);
104
105     return QRect(topLeftX, topLeftY, gridWidth, gridHeight);
106 }
107
108 QPointF MapEngine::centerGeoCoordinate()
109 {
110     qDebug() << __PRETTY_FUNCTION__;
111
112     return convertSceneCoordinateToLatLon(m_zoomLevel, m_sceneCoordinate);
113 }
114
115 QPoint MapEngine::convertLatLonToSceneCoordinate(QPointF latLonCoordinate)
116 {
117     qDebug() << __PRETTY_FUNCTION__;
118
119     qreal longitude = latLonCoordinate.x();
120     qreal latitude = latLonCoordinate.y();
121
122     if ((longitude > MAX_LONGITUDE) || (longitude < MIN_LONGITUDE))
123         return QPoint(UNDEFINED, UNDEFINED);
124     if ((latitude > MAX_LATITUDE) || (latitude < MIN_LATITUDE))
125         return QPoint(UNDEFINED, UNDEFINED);
126
127     qreal z = static_cast<qreal>(1 << MAX_MAP_ZOOM_LEVEL);
128
129     qreal x = static_cast<qreal>((longitude + 180.0) / 360.0);
130     qreal y = static_cast<qreal>((1.0 - log(tan(latitude * M_PI / 180.0) + 1.0
131                                 / cos(latitude * M_PI / 180.0)) / M_PI) / 2.0);
132
133     return QPointF(x * z * TILE_SIZE_X, y * z * TILE_SIZE_Y).toPoint();
134 }
135
136 QPointF MapEngine::convertSceneCoordinateToLatLon(int zoomLevel, QPoint sceneCoordinate)
137 {
138     qDebug() << __PRETTY_FUNCTION__;
139
140     double tileFactor = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
141     double xFactor = (sceneCoordinate.x() / (TILE_SIZE_X*tileFactor));
142     double yFactor = (sceneCoordinate.y() / (TILE_SIZE_Y*tileFactor));
143
144     tileFactor = 1 << zoomLevel;
145     double longitude = xFactor / tileFactor * 360.0 - 180;
146
147     double n = M_PI - 2.0 * M_PI * yFactor / tileFactor;
148     double latitude = 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n)));
149
150     return QPointF(longitude, latitude);
151 }
152
153 QPoint MapEngine::convertSceneCoordinateToTileNumber(int zoomLevel, QPoint sceneCoordinate)
154 {
155     qDebug() << __PRETTY_FUNCTION__;
156
157     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
158     int x = static_cast<int>(sceneCoordinate.x() / (TILE_SIZE_X * pow));
159     int y = static_cast<int>(sceneCoordinate.y() / (TILE_SIZE_Y * pow));
160
161     return QPoint(x, y);
162 }
163
164 QPoint MapEngine::convertTileNumberToSceneCoordinate(int zoomLevel, QPoint tileNumber)
165 {
166     qDebug() << __PRETTY_FUNCTION__;
167
168     int pow = 1 << (MAX_MAP_ZOOM_LEVEL - zoomLevel);
169     int x = tileNumber.x() * TILE_SIZE_X * pow;
170     int y = tileNumber.y() * TILE_SIZE_Y * pow;
171
172     return QPoint(x, y);
173 }
174
175 bool MapEngine::disableAutoCentering(QPoint sceneCoordinate)
176 {
177     if (isAutoCenteringEnabled()) {
178         int zoomFactor = (1 << (MAX_MAP_ZOOM_LEVEL - m_zoomLevel));
179
180         QPoint oldPixelValue = QPoint(m_lastManualPosition.x() / zoomFactor,
181                                       m_lastManualPosition.y() / zoomFactor);
182
183         QPoint newPixelValue = QPoint(sceneCoordinate.x() / zoomFactor,
184                                       sceneCoordinate.y() / zoomFactor);
185
186         if ((abs(oldPixelValue.x() - newPixelValue.x()) > AUTO_CENTERING_DISABLE_DISTANCE) ||
187             (abs(oldPixelValue.y() - newPixelValue.y()) > AUTO_CENTERING_DISABLE_DISTANCE))
188             return true;
189     }
190
191     return false;
192 }
193
194 void MapEngine::getTiles(QPoint sceneCoordinate)
195 {
196     qDebug() << __PRETTY_FUNCTION__;
197
198     m_viewTilesGrid = calculateTileGrid(sceneCoordinate);
199     updateViewTilesSceneRect();
200
201     int topLeftX = m_viewTilesGrid.topLeft().x();
202     int topLeftY = m_viewTilesGrid.topLeft().y();
203     int bottomRightX = m_viewTilesGrid.bottomRight().x();
204     int bottomRightY = m_viewTilesGrid.bottomRight().y();
205
206     int tileMaxVal = tileMaxValue(m_zoomLevel);
207
208     for (int x = topLeftX; x <= bottomRightX; ++x) {
209         for (int y = topLeftY; y <= bottomRightY; ++y) {
210
211             int tileX = x;
212             int tileY = y;
213
214             if (tileX < 0)
215                 tileX += tileMaxVal;
216             else if (tileX > tileMaxVal)
217                 tileX -= tileMaxVal;
218
219             if (tileY < 0)
220                 tileY += tileMaxVal;
221             else if (tileY > tileMaxVal)
222                 tileY -= tileMaxVal;
223
224             if (!m_mapScene->isTileInScene(tilePath(m_zoomLevel, tileX, tileY)))
225                 emit fetchImage(m_zoomLevel, tileX, tileY);
226         }
227     }
228 }
229
230 void MapEngine::gpsPositionUpdate(QPointF position, qreal accuracy)
231 {
232     qDebug() << __PRETTY_FUNCTION__;
233
234     m_gpsLocationItem->updatePosition(convertLatLonToSceneCoordinate(position), accuracy);
235
236     if (m_autoCenteringEnabled)
237         setViewLocation(position);
238 }
239
240 void MapEngine::init()
241 {
242     qDebug() << __PRETTY_FUNCTION__;
243
244     QPointF startLocation;
245     QSettings settings(DIRECTORY_NAME, FILE_NAME);
246
247     if (settings.value(MAP_LAST_POSITION, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString()
248         == ERROR_VALUE_NOT_FOUND_ON_SETTINGS || settings.value(MAP_LAST_ZOOMLEVEL,
249         ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toString() == ERROR_VALUE_NOT_FOUND_ON_SETTINGS) {
250
251         startLocation = QPointF(DEFAULT_LONGITUDE, DEFAULT_LATITUDE);
252         m_zoomLevel = DEFAULT_START_ZOOM_LEVEL;
253     } else {
254         m_zoomLevel = settings.value(MAP_LAST_ZOOMLEVEL, ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toInt();
255         startLocation = settings.value(MAP_LAST_POSITION,
256                                        ERROR_VALUE_NOT_FOUND_ON_SETTINGS).toPointF();
257     }
258
259     emit zoomLevelChanged(m_zoomLevel);
260     setViewLocation(QPointF(startLocation.x(), startLocation.y()));
261 }
262
263 bool MapEngine::isAutoCenteringEnabled()
264 {
265     return m_autoCenteringEnabled;
266 }
267
268 bool MapEngine::isCenterTileChanged(QPoint sceneCoordinate)
269 {
270     qDebug() << __PRETTY_FUNCTION__;
271
272     QPoint centerTile = convertSceneCoordinateToTileNumber(m_zoomLevel, sceneCoordinate);
273     QPoint temp = m_centerTile;
274     m_centerTile = centerTile;
275
276     return (centerTile != temp);
277 }
278
279 void MapEngine::mapImageReceived(int zoomLevel, int x, int y, const QPixmap &image)
280 {
281     qDebug() << __PRETTY_FUNCTION__;
282
283     QString hashKey = tilePath(zoomLevel, x, y);
284     if (!m_mapScene->isTileInScene(hashKey)) {
285
286         MapTile *mapTile = new MapTile();
287         mapTile->setZoomLevel(zoomLevel, m_zoomLevel);
288         mapTile->setTileNumber(QPoint(x, y));
289         mapTile->setPixmap(image);
290
291         m_mapScene->addTile(mapTile, hashKey);
292
293         m_mapScene->enqueueRemoveStackedTiles(mapTile);
294    }
295 }
296
297 void MapEngine::receiveOwnLocation(User *user)
298 {
299     qDebug() << __PRETTY_FUNCTION__;
300
301     if(user) {
302         QPoint newPosition = convertLatLonToSceneCoordinate(user->coordinates());
303         if (m_ownLocation->pos().toPoint() != newPosition) {
304             m_ownLocation->setPos(newPosition);
305         }
306
307         if (!m_ownLocation->isVisible())
308             m_ownLocation->show();
309     }
310     else {
311         m_ownLocation->hide();
312     }
313 }
314
315 QGraphicsScene* MapEngine::scene()
316 {
317     qDebug() << __PRETTY_FUNCTION__;
318
319     return m_mapScene;
320 }
321
322 void MapEngine::setAutoCentering(bool enabled)
323 {
324     m_autoCenteringEnabled = enabled;
325 }
326
327 void MapEngine::setGPSEnabled(bool enabled)
328 {
329     m_gpsLocationItem->setEnabled(enabled);
330 }
331
332 void MapEngine::setLocation(QPoint sceneCoordinate)
333 {
334     qDebug() << __PRETTY_FUNCTION__;
335
336     if (disableAutoCentering(sceneCoordinate))
337         emit mapScrolledManually();
338
339     m_sceneCoordinate = sceneCoordinate;
340     emit locationChanged(m_sceneCoordinate);
341
342     if (isCenterTileChanged(sceneCoordinate)) {
343         getTiles(sceneCoordinate);
344         m_mapScene->removeOutOfViewTiles();
345     }
346 }
347
348 void MapEngine::setZoomLevel(int newZoomLevel)
349 {
350     qDebug() << __PRETTY_FUNCTION__;
351
352     m_zoomLevel = newZoomLevel;
353     emit zoomLevelChanged(m_zoomLevel);
354 }
355
356 void MapEngine::setViewLocation(QPointF latLonCoordinate)
357 {
358     qDebug() << __PRETTY_FUNCTION__;
359
360     QPoint sceneCoordinate = convertLatLonToSceneCoordinate(latLonCoordinate);
361
362     m_lastManualPosition = sceneCoordinate;
363
364     setLocation(sceneCoordinate);
365 }
366
367 int MapEngine::tileMaxValue(int zoomLevel)
368 {
369     qDebug() << __PRETTY_FUNCTION__;
370
371     return (1 << zoomLevel) - 1;
372 }
373
374 QString MapEngine::tilePath(int zoomLevel, int x, int y)
375 {
376     qDebug() << __PRETTY_FUNCTION__;
377
378     QString tilePathString(QString::number(zoomLevel) + "/");
379     tilePathString.append(QString::number(x) + "/");
380     tilePathString.append(QString::number(y));
381
382     return tilePathString;
383 }
384
385 void MapEngine::updateViewTilesSceneRect()
386 {
387     qDebug() << __PRETTY_FUNCTION__;
388
389     const QPoint ONE_TILE = QPoint(1, 1);
390     const QPoint ONE_PIXEL = QPoint(1, 1);
391
392     QPoint topLeft = convertTileNumberToSceneCoordinate(m_zoomLevel, m_viewTilesGrid.topLeft());
393     // one tile - one pixel is added because returned coordinates are pointing to upper left corner
394     // of the last tile.
395     QPoint bottomRight = convertTileNumberToSceneCoordinate(m_zoomLevel,
396                                                             m_viewTilesGrid.bottomRight()
397                                                              + ONE_TILE) - ONE_PIXEL;
398
399     m_mapScene->viewRectUpdated(QRect(topLeft, bottomRight));
400 }
401
402 void MapEngine::viewResized(const QSize &size)
403 {
404     qDebug() << __PRETTY_FUNCTION__;
405
406     m_viewSize = size;
407     emit locationChanged(m_sceneCoordinate);
408     getTiles(m_sceneCoordinate);
409     m_mapScene->removeOutOfViewTiles();
410 }
411
412 void MapEngine::viewZoomFinished()
413 {
414     qDebug() << __PRETTY_FUNCTION__;
415
416     if (m_zoomedIn) {
417         m_zoomedIn = false;
418         m_mapScene->removeOutOfViewTiles();
419     }
420
421     if (m_zoomLevel == MAX_MAP_ZOOM_LEVEL)
422         emit maxZoomLevelReached();
423     else if (m_zoomLevel == MIN_VIEW_ZOOM_LEVEL)
424         emit minZoomLevelReached();
425 }
426
427 void MapEngine::zoomIn()
428 {
429     qDebug() << __PRETTY_FUNCTION__;
430
431     if (m_zoomLevel < MAX_MAP_ZOOM_LEVEL) {
432         m_zoomLevel++;
433         m_zoomedIn = true;
434         emit zoomLevelChanged(m_zoomLevel);
435
436         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
437
438         getTiles(m_sceneCoordinate);
439     }
440 }
441
442 void MapEngine::zoomOut()
443 {
444     qDebug() << __PRETTY_FUNCTION__;
445
446     if (m_zoomLevel > MIN_VIEW_ZOOM_LEVEL) {
447         m_zoomLevel--;
448         emit zoomLevelChanged(m_zoomLevel);
449
450         m_mapScene->setTilesDrawingLevels(m_zoomLevel);
451
452         getTiles(m_sceneCoordinate);
453     }
454 }