Merge branch 'master' of https://vcs.maemo.org/git/gpssportsniffer
[gpssportsniffer] / windowMap.cpp
index 32fcf68..2050c4d 100755 (executable)
@@ -1,3 +1,22 @@
+/****************************************************************************
+**
+**  Copyright (C) 2011  Tito Eritja Real <jtitoo@gmail.com>
+**
+**  This program is free software: you can redistribute it and/or modify
+**  it under the terms of the GNU General Public License as published by
+**  the Free Software Foundation, either version 3 of the License, or
+**  (at your option) any later version.
+**
+**  This program is distributed in the hope that it will be useful,
+**  but WITHOUT ANY WARRANTY; without even the implied warranty of
+**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+**  GNU General Public License for more details.
+**
+**  You should have received a copy of the GNU General Public License
+**  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+**
+****************************************************************************/
+
 #include "windowMap.h"
 
 #include <QAction>
 #include <QMessageBox>
 #include <QProgressBar>
 
-
-
-
-
-#include "satellitedialog.h"
+//#include "satellitedialog.h"
 
 
 
 WindowMap::WindowMap(QWidget *parent, Settings* settings_p, Log *log)
-    : QMainWindow(parent),satelliteInfo(satelliteInfo), satelliteDialog(0),
+    : QMainWindow(parent),
+      //satelliteInfo(satelliteInfo),
+      //satelliteDialog(0),
       log(log),pressed(false),snapped(false), settings(settings_p),track(0),trackToSniff(0),network(false),slippyMap(0),
-      waitingForFix(false),validPositions(0),invalidPositions(0),mode(Mode_NewActivityMode),possitionPaint(true),nSession(0),location(0){
+      //waitingForFix(false),
+      isDisplayInit(false),
+      validPositions(0),invalidPositions(0),mode(Mode_NewActivityMode),possitionPaint(true),nSession(0),location(0){
 
     track = new Track();
     trackToSniff = new Track();
@@ -74,7 +93,7 @@ WindowMap::WindowMap(QWidget *parent, Settings* settings_p, Log *log)
     //log->debug("going to create actions");
 
     loadTrackAction = new QAction(tr("Load track"),this);
-    downloadMapsAction = new QAction(tr("Download maps"),this);
+    downloadMapsTrackAction = new QAction(tr("Download maps from track"),this);
     newActivityAction = new QAction(tr("New activity"),this);
     simulatedActivityAction = new QAction(tr("Activity simulation"),this);
     infoAction = new QAction(tr("Activity info"),this);
@@ -86,14 +105,14 @@ WindowMap::WindowMap(QWidget *parent, Settings* settings_p, Log *log)
     startAction = new QAction(tr("Start"), this);
     startAction->setEnabled(false);
     tracksAction = new QAction(tr("Load track"), this);
-    satelliteAction = new QAction(tr("Satellite info."), this);
+    //satelliteAction = new QAction(tr("Satellite info."), this);
     startNetworkAction = new QAction(tr("Start Networking"),this);
     startNetworkAction->setEnabled(false);
 
     //log->debug("done, connecting");
 
     connect(loadTrackAction, SIGNAL(triggered()),SLOT(loadTrack()));
-    connect(downloadMapsAction, SIGNAL(triggered()),SLOT(downloadMapTrack()));
+    connect(downloadMapsTrackAction, SIGNAL(triggered()),SLOT(downloadMapTrack()));
     connect(newActivityAction, SIGNAL(triggered()),SLOT(newActivityTrack()));
     connect(simulatedActivityAction, SIGNAL(triggered()), SLOT(newSimulation()));
     connect(stopAction, SIGNAL(triggered()), SLOT(stopActivity()));
@@ -102,7 +121,7 @@ WindowMap::WindowMap(QWidget *parent, Settings* settings_p, Log *log)
     connect(lapAction, SIGNAL(triggered()), SLOT(lapActivity()));
     connect(settingsAction, SIGNAL(triggered()), SLOT(configureSettings()));
     connect(tracksAction, SIGNAL(triggered()), SLOT(tracksActivity()));
-    connect(satelliteAction, SIGNAL(triggered()), SLOT(satellite()));
+    //connect(satelliteAction, SIGNAL(triggered()), SLOT(satellite()));
     connect(startNetworkAction,SIGNAL(triggered()), SLOT(networkStart()));
     connect(infoAction, SIGNAL(triggered()), SLOT(info()));
 
@@ -150,7 +169,7 @@ void WindowMap::setMenuLoadTracks(){
 #if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) || defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)
 
     menuBar()->addAction(loadTrackAction);
-    menuBar()->addAction(downloadMapsAction);
+    menuBar()->addAction(downloadMapsTrackAction);
     menuBar()->addAction(newActivityAction);
     menuBar()->addAction(simulatedActivityAction);
     menuBar()->addAction(startNetworkAction);
@@ -162,7 +181,7 @@ void WindowMap::setMenuLoadTracks(){
     QMenu *menu = menuBar()->addMenu("&Options");
     menu->clear();
     menu->addAction(loadTrackAction);
-    menu->addAction(downloadMapsAction);
+    menu->addAction(downloadMapsTrackAction);
     menu->addAction(newActivityAction);
     menu->addAction(simulatedActivityAction);
     menu->addAction(startNetworkAction);
@@ -186,7 +205,7 @@ void WindowMap::setMenuActivity(){
     menuBar()->addAction(quitAction);
 
 
-    menuBar()->addAction(satelliteAction);
+    //menuBar()->addAction(satelliteAction);
 
 #else
     QMenu *menu = menuBar()->addMenu("&Options");
@@ -197,7 +216,7 @@ void WindowMap::setMenuActivity(){
     menu->addAction(startAction);
     menu->addAction(tracksAction);
     menu->addAction(startNetworkAction);
-    menu->addAction(satelliteAction);
+    //menu->addAction(satelliteAction);
     menu->addAction(infoAction);
     menu->addAction(quitAction);
 
@@ -239,6 +258,7 @@ void WindowMap::startServices(){
     startMaps();
 }
 
+/*
 void WindowMap::showSatelliteInfo(){
 
     if(!satelliteInfo)
@@ -265,8 +285,9 @@ void WindowMap::showSatelliteInfo(){
     }
 
 }
+*/
 
-
+/*
 void WindowMap::waitForFix() {
     if (waitingForFix)
         return;
@@ -299,6 +320,8 @@ void WindowMap::waitForFix() {
     waitingForFix = false;
 }
 
+*/
+
 void WindowMap::stopNetworking(){
     network=false;
     if(nSession)
@@ -332,18 +355,24 @@ void WindowMap::startNetworking(){
         }
 
         nSession = new QNetworkSession(cfg, this);
-        nSession->open();
-        nSession->waitForOpened(-1);
-
-
-        connect(nSession, SIGNAL(opened()), this, SLOT(networkSessionOpened()));
         connect(nSession,SIGNAL(error(QNetworkSession::SessionError)),this,SLOT(error(QNetworkSession::SessionError)));
 
+        nSession->open();
+        if(nSession->waitForOpened(-1)){
+            log->info("session connected");
+
+            connect(nSession, SIGNAL(opened()), this, SLOT(networkSessionOpened()));
+            //connect(nSession,SIGNAL(error(QNetworkSession::SessionError)),this,SLOT(error(QNetworkSession::SessionError)));
 
-        network=true;
-        if(slippyMap){
-            slippyMap->setNetwork(true);
+            network=true;
+            if(slippyMap){
+                slippyMap->setNetwork(true);
+            }
+        }else{
+            log->err(nSession->errorString());
+            network=false;
         }
+
     }
 
 }
@@ -356,7 +385,6 @@ void WindowMap::networkSessionOpened(){
         //log->debug("invalidating map");
         slippyMap->setNetwork(true);
         slippyMap->updateTiles();
-
     }
 
 }
@@ -387,11 +415,13 @@ void WindowMap::error(QNetworkSession::SessionError error)
             //log->debug("enabling startNetworking");
             startNetworkAction->setEnabled(true);
             stopNetworking();
-        }else{
-            QTimer::singleShot(60000, nSession, SLOT(open()));
         }
+        //else{
+        //    QTimer::singleShot(60000, nSession, SLOT(open()));
+        //}
         network=false;
-        slippyMap->setNetwork(false);
+        if(slippyMap)
+            slippyMap->setNetwork(false);
     }
 }
 
@@ -421,13 +451,13 @@ void WindowMap::changeMapType(MapType map){
 
 bool WindowMap::checkGPS(){
 
-#if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) || defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)
+//#if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) || defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)
     location = QGeoPositionInfoSource::createDefaultSource(this);
 
-#else
+//#else
     //With maemo simulator doesn't work, I've to change this.
-    location=0;
-#endif
+//    location=0;
+//#endif
 
     if (!location) {
         if(!simulateGPS)
@@ -446,16 +476,86 @@ void WindowMap::startGPS(){
         connect(location,SIGNAL(positionUpdated(QGeoPositionInfo)),this,SLOT(positionUpdated(QGeoPositionInfo)));
         if(!settings->getIsOnline())
             location->setPreferredPositioningMethods(QGeoPositionInfoSource::SatellitePositioningMethods);
-
         location->startUpdates();
-        waitForFix();
+        //waitForFix();
         //log->debug("setting signal updateTimeout...");
-        connect(location, SIGNAL(updateTimeout()), this, SLOT(waitForFix()));
+        //connect(location, SIGNAL(updateTimeout()), this, SLOT(waitForFix()));
         //log->debug("start positioning...");
     }
     startPositioning();
 }
 
+
+void WindowMap::positionUpdated(const QGeoPositionInfo &pos){
+
+    //log->info("ACTIVITYMAP-POSSITIONUPDATED!!!");
+    //setCenter(pos.coordinate().latitude(), pos.coordinate().longitude());
+
+    if(pos.isValid() &&
+            pos.attribute(QGeoPositionInfo::HorizontalAccuracy)<=settings->getHorizontalAccuracy() &&
+            pos.attribute(QGeoPositionInfo::VerticalAccuracy)<=settings->getVerticalAccuracy()){
+
+        GpsPoint* point = new GpsPoint(pos.coordinate().latitude(),pos.coordinate().longitude(),pos.coordinate().altitude(),pos.timestamp(),
+                                       pos.attribute(QGeoPositionInfo::GroundSpeed),pos.attribute(QGeoPositionInfo::Direction),
+                                       pos.attribute(QGeoPositionInfo::MagneticVariation),
+                                       pos.attribute(QGeoPositionInfo::HorizontalAccuracy),
+                                       pos.attribute(QGeoPositionInfo::VerticalAccuracy));
+
+
+       // log->debug(point->toString());
+        //log->debug("going to add point...");
+        track->addPoint(point);
+        emit(infoWindow->updateSummary());
+        validPositions++;
+
+        if(possitionPaint)
+            setCenter(point->getLatitude(),point->getLongitude());
+
+        //if(satelliteDialog)
+        //    satelliteDialog->hide();
+
+
+    }else{
+        log->debug("position not updated:");
+
+        log->debug("Horizontal accuracy (meters):" + QString::number(pos.attribute(QGeoPositionInfo::HorizontalAccuracy)));
+        log->debug("Vertical accuracy (meters):" + QString::number(pos.attribute(QGeoPositionInfo::VerticalAccuracy)));
+        invalidPositions++;
+    }
+
+}
+
+void WindowMap::simulatedPossitionUpdated(){
+    log->info("simulated possition!!!");
+    //log->info(QString("num points to simulate:%1").arg(trackToSimulate.size()));
+    GpsPoint* point= new GpsPoint(0,0,0);
+
+
+    if(trackToSimulate.size()>0){
+
+        point = trackToSimulate.first();
+
+        log->debug(QString("point to simulate:%1").arg(point->toString()));
+        track->addPoint(point);
+        log->debug("going to emit updateSummary!!!");
+        emit(infoWindow->updateSummary());
+        log->debug("point added to track and updated");
+        //log->debug(QString("track num points:%1").arg(track->getNumPoints()));
+
+        trackToSimulate.removeFirst();
+        validPositions++;
+        //log->info(QString("num points to simulate:%1").arg(trackToSimulate.size()));
+
+        //log->debug(QString("Possition paint???????????%1").arg(possitionPaint));
+        if(possitionPaint)
+            setCenter(point->getLatitude(),point->getLongitude());
+    }
+
+
+
+}
+
+
 void WindowMap::setTopLeft(qreal lat, qreal lng){
 
     //log->debug("----setTopLeft----");
@@ -502,6 +602,7 @@ void WindowMap::closeEvent(QCloseEvent *event){
         if (ret == QMessageBox::Cancel){
             event->ignore();
         }else{
+            disconnect(nSession,SIGNAL(error(QNetworkSession::SessionError)),this,SLOT(error(QNetworkSession::SessionError)));
             stopPositioning();
             autosave();
             settings->setIsConfigured(false);
@@ -526,19 +627,21 @@ void WindowMap::closeEvent(QCloseEvent *event){
     }
 }
 
- void WindowMap::showEvent(QShowEvent *){
+void WindowMap::chooseDisplay(){
 
+    if(mode==Mode_NewActivityMode && !settings->getIsConfigured()){
+        checkGPS();
+        setWindowTitle(track->getName());
+        settingsWindow->show();
 
-     if(mode==Mode_NewActivityMode && !settings->getIsConfigured()){
-         checkGPS();
-         settingsWindow->show();
-         //setWindowTitle(settings->getActivity());
-     }else if(mode==Mode_LoadTracksWindow && !settings->getIsConfigured()){
-         setWindowTitle(QString("Load Tracks ->").append(trackToSniff->getName()));
-         loadTracksWindow->show();
-     }else{
-        fixZoomButtons();
-     }
+    }else if(mode==Mode_LoadTracksWindow && !settings->getIsConfigured()){
+        setWindowTitle(QString("Load Tracks ->").append(trackToSniff->getName()));
+        loadTracksWindow->show();
+    }
+}
+
+ void WindowMap::showEvent(QShowEvent *){
+     chooseDisplay();
  }
 
  void WindowMap::networkStart(){
@@ -567,17 +670,17 @@ void WindowMap::closeEvent(QCloseEvent *event){
         qreal lat = slippyMap->getLatitude();
         qreal lng = slippyMap->getLongitude();
         tilesToDownload=0;
-
-        //QPoint pos;
-        //pos.setX((width()-downloadingStatus->width())/2);
-        //pos.setY((height()-downloadingStatus->height())/2);
+        startNetworking();
 
         downloadingStatus->show();
 
         //downloadingStatus->move(pos);
         QProgressBar* pb = downloadingStatus->getProgressBar();
         int numPoints = trackToSniff->getNumPoints();
-        pb->setRange(0,numPoints);
+        int zoomsToDown = (MAX_ZOOM_DOWNL - slippyMap->getZoom());
+        if(zoomsToDown>=0){
+            pb->setRange(0,numPoints*zoomsToDown);
+        }
         pb->setValue(0);
         downloadingStatus->setText(QString(tr("Making map requests")));
 
@@ -609,7 +712,7 @@ void WindowMap::closeEvent(QCloseEvent *event){
      mode=Mode_NewActivityMode;
      settings->setIsConfigured(false);
      setMenuActivity();
-     settingsWindow->show();
+     chooseDisplay();
  }
 
  void WindowMap::newSimulation(){
@@ -617,7 +720,7 @@ void WindowMap::closeEvent(QCloseEvent *event){
      simulateGPS=true;
      settings->setIsConfigured(false);
      setMenuActivity();
-     settingsWindow->show();
+     chooseDisplay();
  }
 
  void WindowMap::info(){
@@ -660,12 +763,15 @@ void WindowMap::tracks(){
 
 }
 */
+
+/*
 void WindowMap::satellite(){
 
 #if defined(Q_OS_SYMBIAN) || defined(Q_OS_WINCE_WM) || defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)
     showSatelliteInfo();
 #endif
 }
+*/
 
 void WindowMap::stopPositioning() {
    if(simulateGPS){
@@ -725,74 +831,6 @@ void WindowMap::updateSummary(){
     emit(infoWindow->updateSummary());
 }
 
-void WindowMap::simulatedPossitionUpdated(){
-    log->info("simulated possition!!!");
-    //log->info(QString("num points to simulate:%1").arg(trackToSimulate.size()));
-    GpsPoint* point= new GpsPoint(0,0,0);
-
-
-    if(trackToSimulate.size()>0){
-
-        point = trackToSimulate.first();
-
-        log->debug(QString("point to simulate:%1").arg(point->toString()));
-        track->addPoint(point);
-        log->debug("going to emit updateSummary!!!");
-        emit(infoWindow->updateSummary());
-        log->debug("point added to track and updated");
-        //log->debug(QString("track num points:%1").arg(track->getNumPoints()));
-
-        trackToSimulate.removeFirst();
-        validPositions++;
-        //log->info(QString("num points to simulate:%1").arg(trackToSimulate.size()));
-
-        //log->debug(QString("Possition paint???????????%1").arg(possitionPaint));
-        if(possitionPaint)
-            setCenter(point->getLatitude(),point->getLongitude());
-    }
-
-
-
-}
-
-void WindowMap::positionUpdated(const QGeoPositionInfo &pos){
-
-    //log->info("ACTIVITYMAP-POSSITIONUPDATED!!!");
-    //setCenter(pos.coordinate().latitude(), pos.coordinate().longitude());
-
-    if(pos.isValid() &&
-            pos.attribute(QGeoPositionInfo::HorizontalAccuracy)<=settings->getHorizontalAccuracy() &&
-            pos.attribute(QGeoPositionInfo::VerticalAccuracy)<=settings->getVerticalAccuracy()){
-
-        GpsPoint* point = new GpsPoint(pos.coordinate().latitude(),pos.coordinate().longitude(),pos.coordinate().altitude(),pos.timestamp(),
-                                       pos.attribute(QGeoPositionInfo::GroundSpeed),pos.attribute(QGeoPositionInfo::Direction),
-                                       pos.attribute(QGeoPositionInfo::MagneticVariation),
-                                       pos.attribute(QGeoPositionInfo::HorizontalAccuracy),
-                                       pos.attribute(QGeoPositionInfo::VerticalAccuracy));
-
-
-       // log->debug(point->toString());
-        //log->debug("going to add point...");
-        track->addPoint(point);
-        emit(infoWindow->updateSummary());
-        validPositions++;
-
-        if(possitionPaint)
-            setCenter(point->getLatitude(),point->getLongitude());
-
-        if(satelliteDialog)
-            satelliteDialog->hide();
-
-
-    }else{
-        log->debug("position not updated:");
-
-        log->debug("Horizontal accuracy (meters):" + QString::number(pos.attribute(QGeoPositionInfo::HorizontalAccuracy)));
-        log->debug("Vertical accuracy (meters):" + QString::number(pos.attribute(QGeoPositionInfo::VerticalAccuracy)));
-        invalidPositions++;
-    }
-
-}
 
 
 void WindowMap::autosave(){
@@ -861,16 +899,18 @@ void WindowMap::showExpanded()
 #endif
 }
 
+
 void WindowMap::paintEvent(QPaintEvent *event) {
 
-    fixZoomButtons();
 
+    fixZoomButtons();
     log->debug("---- paint Event ----!");
 
     QPainter p;
     p.begin(this);
 
     p.setPen(Qt::black);
+
 #if defined(Q_OS_SYMBIAN)
     QFont font = p.font();
     font.setPixelSize(13);
@@ -879,22 +919,25 @@ void WindowMap::paintEvent(QPaintEvent *event) {
 
     if (!slippyMap){
         log->debug("slippyMap not created!");
-        return;
-    }
+        displayInit(&p);
 
-    slippyMap->render(&p, event->rect());
+    }else{
+
+        slippyMap->render(&p, event->rect());
 
-    //log->info("going to draw tracking route...");
-    drawTrack(trackToSniff,&p, settings->getTrackToSniffColor());
+        //log->info("going to draw tracking route...");
+        drawTrack(trackToSniff,&p, settings->getTrackToSniffColor());
 
-    if(mode==Mode_NewActivityMode){
-        //log->info("going to draw actual route...");
-        //log->debug(QString("num points track:%1").arg(track->getNumPoints()));
-        //log->debug("entering to drawTrack");
-        drawTrack(track,&p,settings->getTrackColor(),true);
-        //log->info("done");
+        if(mode==Mode_NewActivityMode){
+            //log->info("going to draw actual route...");
+            //log->debug(QString("num points track:%1").arg(track->getNumPoints()));
+            //log->debug("entering to drawTrack");
+            drawTrack(track,&p,settings->getTrackColor(),true);
+            //log->info("done");
+        }
     }
 
+
     //log->info("done");
     //p.drawText(rect(), Qt::AlignBottom | Qt::TextWordWrap,"OpenStreetMap maps");
     //log->debug("ending Paint event...");
@@ -902,6 +945,34 @@ void WindowMap::paintEvent(QPaintEvent *event) {
     //log->debug("done... and now?");
 
 }
+
+void WindowMap::displayInit(QPainter *p){
+
+    QPixmap emptyTile = QPixmap(tdim,tdim);
+    emptyTile.fill(Qt::lightGray);
+
+    int numWidth = floor(width()/tdim)+1;
+    int numHeight = floor(height()/tdim)+1;
+    qreal tempx = static_cast<qreal>(width())/tdim;
+    qreal tempy = static_cast<qreal>(height())/tdim;
+
+    int width_offset=(tempx-numWidth)*tdim/2;
+    int height_offset=(tempy-numHeight)*tdim/2;
+
+    QPoint topLeft = QPoint(width_offset,height_offset);
+
+    for (int x = 0; x <= numWidth; ++x){
+        for (int y = 0; y <= numHeight; ++y) {
+            QRect box = QRect(topLeft.x()+x*tdim, topLeft.y()+y*tdim, tdim, tdim);
+
+            p->drawPixmap(box,emptyTile);
+        }
+    }
+
+
+
+}
+
 void WindowMap::drawFullTrackMaps(Track* track_p){
 
     QList<GpsPoint*> gpsPoints = track_p->getGpsPoints();
@@ -1091,21 +1162,18 @@ void WindowMap::mouseReleaseEvent(QMouseEvent *) {
 
 void WindowMap::fixZoomButtons(){
 
-    if(settings->getIsConfigured()){
-            int x_in=(width()-zoomInButton->width());
-            int y_in=(height()/2-zoomInButton->height()/2);
-            //log->debug(QString("ZoomIn possition: x=%1,y=%2").arg(x_in).arg(y_in));
-
-            int x_out=0;
-            int y_out=(height()/2-zoomOutButton->height()/2);
-            //log->debug(QString("ZoomOut possition: x=%1,y=%2").arg(x_out).arg(y_out));
+    int x_in=(width()-zoomInButton->width());
+    int y_in=(height()/2-zoomInButton->height()/2);
+    //log->debug(QString("ZoomIn possition: x=%1,y=%2").arg(x_in).arg(y_in));
 
-            zoomInButton->move(x_in,y_in);
-            zoomOutButton->move(x_out,y_out);
-            zoomInButton->show();
-            zoomOutButton->show();
+    int x_out=0;
+    int y_out=(height()/2-zoomOutButton->height()/2);
+    //log->debug(QString("ZoomOut possition: x=%1,y=%2").arg(x_out).arg(y_out));
 
-        }
+    zoomInButton->move(x_in,y_in);
+    zoomOutButton->move(x_out,y_out);
+    zoomInButton->show();
+    zoomOutButton->show();
 }
 
 void WindowMap::resizeEvent(QResizeEvent * /* event */)