#!/usr/bin/env python

import sys
import os
import subprocess
import string
import socket
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from gui import GuiWidget
from pref import PreferenceSetting
from msgworn import worn
from msgworntcp import worntcp
from Gdata import Data
from GrassShell import GrShell
from datatools import DataWork
from Savekml import KmlView
from model import PlaceModel
#from modelite import PlaceModelite
from epsg import SearchEpsg
from grass.script.core import *
from LatLongUTMconversion import LLtoUTM
from VectorOp import VectorOperation
from episg import *
from pysqlite2 import dbapi2 as sqlite3
from configure import parseOutputconf
import time
from tcp4ossim import parseSignal
import gps
import pygame
from epijoy_joy import startj



# export GRASS environment

grassenv = gisenv()
mapset = grassenv['MAPSET']

#rasterpath = grassenv['GISDBASE']+'/'+grassenv['LOCATION_NAME']+'/'+ \
#           grassenv['MAPSET']+'/cellhd/'
#vectorpath = grassenv['GISDBASE']+'/'+grassenv['LOCATION_NAME']+'/'+ \
#           grassenv['MAPSET']+'/vector/'
apppath = os.path.abspath(os.path.dirname(sys.argv[0]))

splash = '%s/spl.png' % (apppath)
#splash_mask = '%s/splash_mask.png' % (apppath)
configfile = '%s/conf/conf.xml' % (apppath)
coordsfile = apppath+'/lonlatfile'

clon = 0
clat = 0
item = 'LookAt'
head = '0'
ell = 23

class PlanetSasha(QObject):
    def init(self):
        self.Value=0
        self.ValueJ=0
        self.w = GuiWidget()
        self.w.ZoomSpinBox.setValue(0)
        self.w.RangeSpinBox.setValue(100000)
        self.w.ZoomSlider.setValue(0)
        self.w.RangeSlider.setValue(100000)
        self.queryvalue = 0
        self.DataW = DataWork()
        self.Gshell = GrShell()
        self.vectoroperation = VectorOperation()
        self.kmlview = KmlView()
        self.Data = Data()
        self.placemodel = PlaceModel()
        #self.placemodelite = PlaceModelite()
        self.SearchEpsg = SearchEpsg()
        self.slvallon = self.setcenter()[0]
        self.slvallat = self.setcenter()[1]
        self.w.Lon.setText("0")
        self.w.Lat.setText("0")
        self.fxvallon = self.SetPosition()[0]
        self.fxvallat = self.SetPosition()[1]
        self.slstep = 1
        # Hide/Show Slider
        self.w.actionHideSlider.setChecked(True)
        self.w.actionHideSpinbox.setChecked(True)
        self.w.actionHideStepTool.setChecked(True)
        self.w.actionHide_place_position.setChecked(True)
        self.w.RollSlider.hide()
        self.w.PitchSlider.hide()
        self.w.HandlingSlider.hide()
        self.w.ZoomSlider.hide()
        self.w.RangeSlider.hide()
        # Hide Panel
        self.connect(self.w.actionHideSlider, SIGNAL("triggered()"), 
                     self.hidetool)
        # Pan Toolbox
        self.w.north.setAutoRepeat(True)
        self.w.northeast.setAutoRepeat(True)
        self.w.south.setAutoRepeat(True)
        self.w.east.setAutoRepeat(True)
        self.w.west.setAutoRepeat(True)
        self.w.southwest.setAutoRepeat(True)
        self.w.northwest.setAutoRepeat(True)
        self.w.southeast.setAutoRepeat(True)
        self.connect(self.w.center, SIGNAL("clicked()"),
                     self.ResetPosition)
        self.connect(self.w.north, SIGNAL("clicked()"),
                     self.inclat)
        self.connect(self.w.northeast, SIGNAL("clicked()"),
                     self.inclatlon)
        self.connect(self.w.south, SIGNAL("clicked()"),
                     self.declat)
        self.connect(self.w.east, SIGNAL("clicked()"),
                     self.inclon)
        self.connect(self.w.west, SIGNAL("clicked()"),
                     self.declon)
        self.connect(self.w.southwest, SIGNAL("clicked()"),
                     self.declatlon)
        self.connect(self.w.northwest, SIGNAL("clicked()"),
                     self.inclatdeclon)
        self.connect(self.w.southeast, SIGNAL("clicked()"),
                     self.declatinclon)
        self.connect(self.w.center, SIGNAL("clicked()"),
                     self.setcenter)
        # View Slider/SpinBox
        # Zoom
        self.connect(self.w.ZoomSlider, SIGNAL("valueChanged(int)"), 
                     self.setValueZoomSpinBox)
        self.connect(self.w.ZoomSlider, SIGNAL("valueChanged(int)"), 
                     self.sendFunction)
        self.connect(self.w.ZoomSpinBox, SIGNAL("valueChanged(double)"), 
                     self.setValueZoomSlider)
        self.connect(self.w.ZoomSpinBox, SIGNAL("valueChanged(double)"), 
                     self.sendFunction)
        self.connect(self.w.ZoomSlider, SIGNAL("valueChanged()"), 
                     self.setValue)
        self.connect(self.w.ZoomSpinBox, SIGNAL("valueChanged()"), 
                     self.setValue)
        self.connect(self.w.hsZoom, SIGNAL("clicked()"),
                     self.Zoomceckbuttons)
        self.connect(self.w.hsZoom, SIGNAL("clicked()"),
                     self.hideslideZoom)
        # Range
        self.connect(self.w.RangeSlider, SIGNAL("valueChanged(int)"), 
                     self.setValueRangeSpinBox)
        self.connect(self.w.RangeSlider, SIGNAL("valueChanged(int)"), 
                     self.sendFunction)
        self.connect(self.w.RangeSpinBox, SIGNAL("valueChanged(double)"), 
                     self.setValueRangeSlider)
        self.connect(self.w.RangeSpinBox, SIGNAL("valueChanged(double)"), 
                     self.sendFunction)
        self.connect(self.w.RangeSlider, SIGNAL("valueChanged()"), 
                     self.setValue)
        self.connect(self.w.RangeSpinBox, SIGNAL("valueChanged()"), 
                     self.setValue)
        self.connect(self.w.hsRange, SIGNAL("clicked()"),
                     self.Rangececkbuttons)
        self.connect(self.w.hsRange, SIGNAL("clicked()"),
                     self.hideslideRange)
        # Roll
        self.connect(self.w.RollSlider, SIGNAL("valueChanged(int)"), 
                     self.setValueRollSpinBox)
        self.connect(self.w.RollSlider, SIGNAL("valueChanged(int)"), 
                     self.sendFunction)
        self.connect(self.w.RollSpinBox, SIGNAL("valueChanged(double)"), 
                     self.setValueRollSlider)
        self.connect(self.w.RollSpinBox, SIGNAL("valueChanged(double)"), 
                     self.sendFunction)
        self.connect(self.w.RollSlider, SIGNAL("valueChanged()"), 
                     self.setValue)
        self.connect(self.w.RollSpinBox, SIGNAL("valueChanged()"), 
                     self.setValue)
        self.connect(self.w.hsRoll, SIGNAL("clicked()"),
                     self.Rollceckbuttons)
        self.connect(self.w.hsRoll, SIGNAL("clicked()"),
                     self.hideslideRoll)
        # Pitch
        self.connect(self.w.PitchSlider, SIGNAL("valueChanged(int)"), 
                     self.setValuePitchSpinBox)
        self.connect(self.w.PitchSlider, SIGNAL("valueChanged(int)"), 
                     self.sendFunction)
        self.connect(self.w.PitchSpinBox, SIGNAL("valueChanged(double)"), 
                     self.setValuePitchSlider)
        self.connect(self.w.PitchSpinBox, SIGNAL("valueChanged(double)"), 
                     self.sendFunction)
        self.connect(self.w.PitchSlider, SIGNAL("valueChanged()"), 
                     self.setValue)
        self.connect(self.w.PitchSpinBox, SIGNAL("valueChanged()"), 
                     self.setValue)
        self.connect(self.w.hsPitch, SIGNAL("clicked()"),
                     self.Pitchceckbuttons)
        self.connect(self.w.hsPitch, SIGNAL("clicked()"),
                     self.hideslidePitch)
        # Head
        self.connect(self.w.HandlingSlider, SIGNAL("valueChanged(int)"), 
                     self.setValueHandlingSpinBox)
        self.connect(self.w.HandlingSlider, SIGNAL("valueChanged(int)"), 
                     self.sendFunction)
        self.connect(self.w.HandlingSpinBox, SIGNAL("valueChanged(double)"), 
                     self.setValueHandlingSlider)
        self.connect(self.w.HandlingSpinBox, SIGNAL("valueChanged(double)"), 
                     self.sendFunction)
        self.connect(self.w.HandlingSlider, SIGNAL("valueChanged()"), 
                     self.setValue)
        self.connect(self.w.HandlingSpinBox, SIGNAL("valueChanged()"), 
                     self.setValue)
        self.connect(self.w.Head, SIGNAL("currentIndexChanged(int)"),
                     self.GetHead)
        self.connect(self.w.hsHeading, SIGNAL("clicked()"),
                     self.Headingceckbuttons)
        self.connect(self.w.hsHeading, SIGNAL("clicked()"),
                     self.hideslideHead)
        # Speed
        self.connect(self.w.SpeedSpinBox, SIGNAL("valueChanged(double)"), 
                     self.setValueSpeedSpinBox)
        self.connect(self.w.SpeedSpinBox, SIGNAL("valueChanged()"), 
                     self.setValue)
        self.connect(self.w.SpeedMultipler, SIGNAL("valueChanged(double)"), 
                     self.setValueSpeedMultipler)
        self.connect(self.w.SpeedMultipler, SIGNAL("valueChanged()"), 
                     self.setValueM)
        # Zoom/Range Step-Nultipler
        self.connect(self.w.ZoomStepSpinBox, SIGNAL("valueChanged()"), 
                     self.setValueZM)
        self.connect(self.w.RangeStepSpinBox, SIGNAL("valueChanged()"),
                     self.setValueRM)
        self.connect(self.w.ZoomMultipler, SIGNAL("valueChanged(double)"), 
                     self.setValueZoomMultipler)
        self.connect(self.w.ZoomMultipler, SIGNAL("valueChanged()"), 
                     self.setValueZ)
        self.connect(self.w.RangeMultipler, SIGNAL("valueChanged()"), 
                     self.setValueR)
        # ACTIONS
        # GPS
        self.connect(self.w.actionGPS, SIGNAL("triggered()"), 
                     self.startstopgpsx)	
        self.connect(self.w.actionGPS, SIGNAL("triggered()"), 
                     self.GPSunceckbuttons)
        self.connect(self.w.actionGPS, SIGNAL("triggered()"), 
                     self.stopstartgpsx)
        #self.connect(self.w.actionNMEA, SIGNAL("triggered()"),
        #             self.GpsHandling)
        #self.connect(self.w.actionGPS, SIGNAL("triggered()"),
        #             self.GpsHandling)
        # LON LAT
        self.connect(self.w.actionLonLat, SIGNAL("triggered()"),
                     self.LonLatunceckbuttons)
        # GRASS
        self.connect(self.w.actionGrass, SIGNAL("triggered()"),
                     self.Grassunceckbuttons)
        # Joistick
        self.connect(self.w.actionJoystick, SIGNAL("triggered()"),
                     self.Joyunceckbuttons)
        self.connect(self.w.actionJoystick, SIGNAL("triggered()"), 
                     self.startstopjoy)	
        self.connect(self.w.actionJoystick, SIGNAL("triggered()"), 
                     self.stopstartjoy)	
        # Broadcast
        self.connect(self.w.actionBroadcast, SIGNAL("triggered()"), 
                     self.Serialunceckbuttons)
        self.connect(self.w.actionBroadcast, SIGNAL("triggered()"), 
                     self.startstoplog)
        self.connect(self.w.actionBroadcast, SIGNAL("triggered()"), 
                     self.stopstartlog)
        self.connect(self.w.actionDB_setting, SIGNAL("triggered()"),
                     self.pgsetting)
        self.connect(self.w.actionPref, SIGNAL("triggered()"), self.preference)
        self.connect(self.w.actionDataexp, SIGNAL("triggered()"),
                     self.processdata)
        self.connect(self.w.actionData_2, SIGNAL("triggered()"),
                     self.processdata)
        # Coordinate Display UTM
        self.connect(self.w.ellipse, SIGNAL("currentIndexChanged(int)"),
                     self.ellipsesettings)
        # View Type
        self.connect(self.w.View, SIGNAL("currentIndexChanged(int)"),
                     self.GetViewType)
        # Send Position
        self.connect(self.w.SendPosition, SIGNAL("clicked()"),
                     self.SetLonLat)
        self.connect(self.w.SendPosition, SIGNAL("clicked()"),
                     self.SetJoyCoords)
        self.connect(self.w.SendPosition, SIGNAL("clicked()"),
                     self.ResetPosition)
        # DataWork (send position to query grass data)
        self.connect(self.w.Lon, SIGNAL("textChanged(QString)"), 
                     self.DataW.setLonValue)
        self.connect(self.w.Lat, SIGNAL("textChanged(QString)"), 
                     self.DataW.setLatValue)
        self.connect(self.w.actionVrt, SIGNAL("triggered()"), 
                     self.dataprocess)
        self.connect(self.w.actionGVrt, SIGNAL("triggered()"), 
                     self.dataprocess)
        # KmlView (send position to save kml)
        self.connect(self.w.Lon, SIGNAL("textChanged(QString)"), 
                     self.kmlview.setLonValue)
        self.connect(self.w.Lat, SIGNAL("textChanged(QString)"), 
                     self.kmlview.setLatValue)
        self.connect(self.w.RollSpinBox, SIGNAL("valueChanged(double)"), 
                     self.kmlview.setChangeRoll)
        self.connect(self.w.PitchSpinBox, SIGNAL("valueChanged(double)"), 
                     self.kmlview.setChangePitch)
        self.connect(self.w.HandlingSpinBox, SIGNAL("valueChanged(double)"), 
                     self.kmlview.setChangeHead)
        self.connect(self.w.ZoomSpinBox, SIGNAL("valueChanged(double)"), 
                     self.kmlview.setChangeZoom)
        self.connect(self.w.RangeSpinBox, SIGNAL("valueChanged(double)"), 
                     self.kmlview.setChangeRange)
        self.connect(self.w.actionSavekml, SIGNAL("triggered()"), 
                     self.kmldialog)
        # Data ()
        self.connect(self.w.Lon, SIGNAL("textChanged(QString)"), 
                     self.Data.setLonValue)
        self.connect(self.w.Lat, SIGNAL("textChanged(QString)"), 
                     self.Data.setLatValue)
        # Place Model (send position to save kml model)
        self.connect(self.w.Lon, SIGNAL("textChanged(QString)"), 
                     self.placemodel.setLonValue)
        self.connect(self.w.Lat, SIGNAL("textChanged(QString)"), 
                     self.placemodel.setLatValue)
        self.connect(self.w.RollSpinBox, SIGNAL("valueChanged(double)"), 
                     self.placemodel.setChangeRoll)
        self.connect(self.w.PitchSpinBox, SIGNAL("valueChanged(double)"), 
                     self.placemodel.setChangePitch)
        self.connect(self.w.HandlingSpinBox, SIGNAL("valueChanged(double)"), 
                     self.placemodel.setChangeHead)
        self.connect(self.w.ZoomSpinBox, SIGNAL("valueChanged(double)"), 
                     self.placemodel.setChangeZoom)
        self.connect(self.w.RangeSpinBox, SIGNAL("valueChanged(double)"), 
                     self.placemodel.setChangeRange)
        self.connect(self.w.actionModel, SIGNAL("triggered()"), 
                     self.modeldialog)
        # Place Model (send position to save kml model-lite)
        #self.connect(self.w.Lon, SIGNAL("textChanged(QString)"), 
        #             self.placemodelite.setLonValue)
        #self.connect(self.w.Lat, SIGNAL("textChanged(QString)"), 
        #             self.placemodelite.setLatValue)
        #self.connect(self.w.RollSpinBox, SIGNAL("valueChanged(double)"), 
        #             self.placemodelite.setChangeRoll)
        #self.connect(self.w.PitchSpinBox, SIGNAL("valueChanged(double)"), 
        #             self.placemodelite.setChangePitch)
        #self.connect(self.w.HandlingSpinBox, SIGNAL("valueChanged(double)"), 
        #             self.placemodelite.setChangeHead)
        #self.connect(self.w.ZoomSpinBox, SIGNAL("valueChanged(double)"), 
        #             self.placemodelite.setChangeZoom)
        #self.connect(self.w.RangeSpinBox, SIGNAL("valueChanged(double)"), 
        #             self.placemodelite.setChangeRange)
        #
        #self.connect(self.w.RollSpinBox, SIGNAL("valueChanged(double)"), 
        #             self.gps.setChangeRoll)
        #self.connect(self.w.PitchSpinBox, SIGNAL("valueChanged(double)"), 
        #             self.gps.setChangePitch)
        #self.connect(self.w.HandlingSpinBox, SIGNAL("valueChanged(double)"), 
        #             self.gps.setChangeHead)
        #self.connect(self.w.ZoomSpinBox, SIGNAL("valueChanged(double)"), 
        #             self.gps.setChangeZoom)
        #self.connect(self.w.RangeSpinBox, SIGNAL("valueChanged(double)"), 
        #             self.gps.setChangeRange)
        #self.connect(self.w.View, SIGNAL("currentIndexChanged(QString) "), 
        #             self.gps.setChangeVtype)
        # Grass Shell
        self.connect(self.w.actionGrassshell, SIGNAL("triggered()"), 
                     self.GrassShell)
        # Epsg search-tool
        self.connect(self.w.actionEpsg, SIGNAL("triggered()"), self.SEpsg)
        # Geonames sqlite DB       
        self.connect(self.w.Place, SIGNAL("currentIndexChanged(int)"),
                     self.itemlist)
        self.connect(self.w.placezone, SIGNAL("currentIndexChanged(int)"), 
                     self.setplacezonecoords)
        self.connect(self.w.refreshsqlite, SIGNAL("clicked()"), self.refreshsqlitedb)
        # Vector GeoTransform
        self.connect(self.w.actionVectorOp, SIGNAL("triggered()"), self.Geom) 
        # GRASS Data selection
        self.connect(self.w.GrassRLayer, SIGNAL("currentIndexChanged(int)"), self.selectraster)
        self.connect(self.w.GrassVLayer, SIGNAL("currentIndexChanged(int)"), self.selectvector)
        self.connect(self.w.refreshlayerlist, SIGNAL("clicked()"), self.refreshlayer)
        self.connect(self.w.addRlayer, SIGNAL("clicked()"), self.addraster)
        self.connect(self.w.removeRlayer, SIGNAL("clicked()"), self.removeraster)
        self.connect(self.w.addVlayer, SIGNAL("clicked()"), self.addvector)
        self.connect(self.w.removeVlayer, SIGNAL("clicked()"), self.removevector)
        # Exit QApp
        #self.connect(self.w.actionExit, SIGNAL("triggered()"), qApp, SLOT("quit()"))
        self.connect(self.w.actionExit, SIGNAL("triggered()"), self.quitAll)
        self.joy = logJ()
        self.log = logS()
        self.gpsx = GpsT()
        self.w.show()
    
    
# Set Toolbar Action
    
    def GPSunceckbuttons(self):
        self.w.actionLonLat.setChecked(False)
        self.w.actionGrass.setChecked(False)
        if self.w.actionJoystick.isChecked():
            self.joy.stop()
            self.w.actionJoystick.setChecked(False)
        if self.w.actionSerial.isChecked():
            self.log.stop()
            self.w.actionSerial.setChecked(False)
        #if self.w.actionSerial.isChecked():
    
    
    def LonLatunceckbuttons(self):
        if self.w.actionGPS.isChecked():
            self.gpsx.stop()
            self.w.actionGPS.setChecked(False)
        self.w.actionGrass.setChecked(False)
        if self.w.actionJoystick.isChecked():
            self.joy.stop()
            self.w.actionJoystick.setChecked(False)
        if self.w.actionSerial.isChecked():
            self.log.stop()
            self.w.actionSerial.setChecked(False)
    
    
    def Grassunceckbuttons(self):
        if self.w.actionGPS.isChecked():
            self.gpsx.stop()
            self.w.actionGPS.setChecked(False)
        self.w.actionLonLat.setChecked(False)
        if self.w.actionJoystick.isChecked():
            self.joy.stop()
            self.w.actionJoystick.setChecked(False)
        if self.w.actionSerial.isChecked():
            self.log.stop()
            self.w.actionSerial.setChecked(False)
    
    
    def Joyunceckbuttons(self):
        self.w.actionGPS.setChecked(False)
        self.w.actionLonLat.setChecked(False)
        self.w.actionGrass.setChecked(False)
        self.w.actionSerial.setChecked(False)
    
    
    def Serialunceckbuttons(self):
        self.w.actionGPS.setChecked(False)
        self.w.actionLonLat.setChecked(False)
        self.w.actionGrass.setChecked(False)
        #self.w.actionJoystick.setChecked(False)
    
    
    def startstopjoy(self):
        if self.w.actionJoystick.isChecked():
            self.joy = logJ()
            self.joy.start()
            self.joy.toggle()
            self.connect(self.w.Lon, SIGNAL("textChanged(QString)"), self.joy.setValueLonJ)
            self.connect(self.w.Lat, SIGNAL("textChanged(QString)"), self.joy.setValueLatJ)
            self.SetJoyCoords()
            self.w.Lon.setText(self.w.Lon.text())
            self.w.Lat.setText(self.w.Lat.text())
            print self.w.Lon.text(), self.w.Lat.text()
        else :
            self.joy.stop()
    
    
    def stopstartjoy(self):
        if not self.w.actionJoystick.isChecked():
            self.joy = logJ()
            self.joy.stop()
            self.joy.toggle()
    
    
    def startstoplog(self):
        if self.w.actionBroadcast.isChecked():
            self.log = logS()
            self.log.start()
            self.log.LonUpdated.connect(self.w.Lon.setText)
            self.log.LatUpdated.connect(self.w.Lat.setText)
            self.log.RollUpdated.connect(self.w.RollSpinBox.setValue)
            self.log.PitchUpdated.connect(self.w.PitchSpinBox.setValue)
            self.log.GainUpdated.connect(self.w.HandlingSpinBox.setValue)
            self.log.AltUpdated.connect(self.w.ZoomSpinBox.setValue)
            self.log.toggle()
        else :
            self.log.stop()
    
    
    def stopstartlog(self):
        if not self.w.actionBroadcast.isChecked():
            self.log = logS()
            self.log.stop()
            self.log.toggle()
    
    
    def startstopgpsx(self):
        if self.w.actionGPS.isChecked():
            self.gpsx = GpsT()
            self.gpsx.start()
            self.gpsx.GPSlatitude.connect(self.w.GPSlat.setText)
            self.gpsx.GPSlongitude.connect(self.w.GPSlon.setText)
            self.gpsx.GPStime.connect(self.w.GPSTime.setText)
            self.gpsx.GPSutctime.connect(self.w.GPSUtctime.setText)
            self.gpsx.GPSaltitude.connect(self.w.GPSAltitude.setText)
            self.gpsx.GPSspeed.connect(self.w.GPSSpeed.setText)
            self.gpsx.GPStrack.connect(self.w.GPSTrack.setText)
            self.gpsx.GPSclimb.connect(self.w.GPSClimb.setText)
            self.gpsx.GPSeph.connect(self.w.GPSEph.setText)
            self.gpsx.GPSept.connect(self.w.GPSEpt.setText)
            self.gpsx.GPSepv.connect(self.w.GPSEpv.setText)
            self.gpsx.GPSepd.connect(self.w.GPSEpd.setText)
            self.gpsx.GPSepc.connect(self.w.GPSEpc.setText)
            self.gpsx.GPSeps.connect(self.w.GPSEps.setText)
            self.gpsx.GPSpdop.connect(self.w.GPSPdop.setText)
            self.gpsx.GPShdop.connect(self.w.GPSHdop.setText)
            self.gpsx.GPSvdop.connect(self.w.GPSVdop.setText)
            self.gpsx.GPStdop.connect(self.w.GPSTdop.setText)
            self.gpsx.GPSgdop.connect(self.w.GPSGdop.setText)
            self.gpsx.GPSsat.connect(self.w.Satellite.setText)
            print self.w.GPSlat.text()
            #print 'qualcosa'
            #if head == str('Manual'):
            #    heads = self.w.HandlingSlider.value()
            #if head == str('Auto'):
            #    heads = self.w.GPSTrack
            #print heads
            self.gpsx.toggle()
        else :
            self.gpsx.stop()
    
    
    def stopstartgpsx(self):
        if not self.w.actionGPS.isChecked():
            self.gpsx = GpsT()
            #self.gpsx.wait()
            self.gpsx.stop()
            self.gpsx.toggle()
    
    
# Quit Application
        
    def quitAll(self):
        qApp.quit()
    
    
# Hide/Show widget
    
    def Headingceckbuttons(self):
        self.w.hsPitch.setChecked(False)
        self.w.hsRoll.setChecked(False)
    
    
    def Pitchceckbuttons(self):
        self.w.hsHeading.setChecked(False)
        self.w.hsRoll.setChecked(False)
    
    
    def Rollceckbuttons(self):
        self.w.hsHeading.setChecked(False)
        self.w.hsPitch.setChecked(False)
    
        
    def hideslideHead(self):
        if self.w.hsHeading.isChecked():
            self.w.PitchSlider.hide()
            self.w.RollSlider.hide()
            self.w.HandlingSlider.show()
        else :
            self.w.HandlingSlider.hide()
            self.w.PitchSlider.hide()
            self.w.RollSlider.hide()
    
    
    def hideslidePitch(self):
        if self.w.hsPitch.isChecked():
            self.w.HandlingSlider.hide()
            self.w.RollSlider.hide()
            self.w.PitchSlider.show()
        else :
            self.w.HandlingSlider.hide()
            self.w.PitchSlider.hide()
            self.w.RollSlider.hide()
    
    
    def hideslideRoll(self):
        if self.w.hsRoll.isChecked():
            self.w.HandlingSlider.hide()
            self.w.PitchSlider.hide()
            self.w.RollSlider.show()
        else :
            self.w.HandlingSlider.hide()
            self.w.PitchSlider.hide()
            self.w.RollSlider.hide()
    
            
    def Zoomceckbuttons(self):
        self.w.hsRange.setChecked(False)
    
    
    def Rangececkbuttons(self):
        self.w.hsZoom.setChecked(False)
    
        
    def hideslideZoom(self):
        if self.w.hsZoom.isChecked():
            self.w.RangeSlider.hide()
            self.w.ZoomSlider.show()
        else :
            self.w.RangeSlider.hide()
            self.w.ZoomSlider.hide()
    
    
    def hideslideRange(self):
        if self.w.hsRange.isChecked():
            self.w.ZoomSlider.hide()
            self.w.RangeSlider.show()
        else :
            self.w.RangeSlider.hide()
            self.w.ZoomSlider.hide()
    
    
    def hidetool(self):
        if self.w.actionHideSlider.isChecked():
            self.w.tabWidget.show()
        else :
            self.w.tabWidget.hide()    
    
            
# Set Values Slider/SpinBox  
  
    def setValueZoomSpinBox(self, z):
        self.ZoomValue = float(z)
        self.w.ZoomSpinBox.setRange(-10000, 27536977)
        zstep = float(self.w.ZoomStepSpinBox.value())
        zmult = float(self.w.ZoomMultipler.value())
        zstep = zstep * (10 ** zmult)
        self.w.ZoomSpinBox.setSingleStep(zstep)
        self.w.ZoomSpinBox.setValue(self.ZoomValue)
    
    
    def setValueZoomSlider(self, z):
        self.ZoomValue = int(z)
        self.w.ZoomSlider.setMinimum(-10000)
        self.w.ZoomSlider.setMaximum(27536977)
        self.w.ZoomSlider.setValue(self.ZoomValue)
    
    
    def setValueRangeSpinBox(self, r):
        self.RangeValue = float(r)
        self.w.RangeSpinBox.setRange(-10000, 27536977)
        rstep = float(self.w.RangeStepSpinBox.value())
        rmult = float(self.w.RangeMultipler.value())
        rstep = rstep * (10 ** rmult)
        self.w.RangeSpinBox.setSingleStep(rstep)
        self.w.RangeSpinBox.setValue(self.RangeValue)
    
    
    def setValueRangeSlider(self, r):
        self.RangeValue = int(r)
        self.w.RangeSlider.setMinimum(-10000)
        self.w.RangeSlider.setMaximum(27536977)
        self.w.RangeSlider.setValue(self.RangeValue)
    
    
    def setValueRollSpinBox(self, rl):
        self.RollValue = float(rl)
        self.w.RollSpinBox.setRange(-90, 90)
        self.w.RollSpinBox.setSingleStep(1)
        self.w.RollSpinBox.setValue(self.RollValue)
    
    
    def setValueRollSlider(self, rl):
        self.RollValue = int(rl)
        self.w.RollSlider.setMinimum(-90)
        self.w.RollSlider.setMaximum(90)
        self.w.RollSlider.setValue(self.RollValue)
    
    
    def setValuePitchSpinBox(self, p):
        self.PitchValue = float(p)
        self.w.PitchSpinBox.setRange(-90, 90)
        self.w.PitchSpinBox.setSingleStep(1)
        self.w.PitchSpinBox.setValue(self.PitchValue)
    
    
    def setValuePitchSlider(self, p):
        self.PitchValue = int(p)
        self.w.PitchSlider.setMinimum(-90)
        self.w.PitchSlider.setMaximum(90)
        self.w.PitchSlider.setValue(self.PitchValue)
    
    
    def setValueHandlingSpinBox(self, h):
        self.HandlingValue = float(h)
        self.w.HandlingSpinBox.setRange(-360, 360)
        self.w.HandlingSpinBox.setSingleStep(1)
        self.w.HandlingSpinBox.setValue(self.HandlingValue)
    
    
    def setValueHandlingSlider(self, h):
        self.HandlingValue = int(h)
        self.w.HandlingSlider.setMinimum(-360)
        self.w.HandlingSlider.setMaximum(360)
        self.w.HandlingSlider.setValue(self.HandlingValue)
    
    
    def setValueSpeedSpinBox(self, s):
        self.SpeedValue = float(s)
        self.w.SpeedSpinBox.setRange(0.01, 1)
        self.w.SpeedSpinBox.setSingleStep(0.01)
        self.w.SpeedSpinBox.setValue(self.SpeedValue)
    
    
    def setValueSpeedMultipler(self, s):
        self.SpeedM = float(s)
        self.w.SpeedMultipler.setRange(1, 10)
        self.w.SpeedMultipler.setSingleStep(1)
        self.w.SpeedMultipler.setValue(self.SpeedM)
    
    
    def setValueZoomMSpinBox(self, s):
        self.ZoomValue = float(s)
        self.w.ZoomSpinBox.setRange(0.01, 1)
        self.w.ZoomSpinBox.setSingleStep(0.01)
        self.w.ZoomSpinBox.setValue(self.ZoomValue)
    
    
    def setValueZoomMultipler(self, s):
        self.ZoomStepValue = float(s)
        self.w.ZoomMultipler.setRange(1, 10)
        self.w.ZoomMultipler.setSingleStep(1)
        self.w.ZoomMultipler.setValue(self.ZoomStepValue)
    
    
# Set Heading Mode    
    
    def GetHead(self,index):
        global head
        head = self.w.Head.itemText(index)
        if head == 'N':
            head = '0'
        if head == 'NE':
            head = '45' 
        if head == 'E':
            head = '90'
        if head == 'SE':
            head = '135'
        if head == 'S':
            head = '180'
        if head == 'SW':
            head = '-135'
        if head == 'W':
            head = '-90'
        if head == 'NW':
            head = '-45'
        if head == 'Auto':
            head = 'angle'
        if head == 'Manual':
            head = 'Manual'
        return head
    
    
# Set View Type
    
    def GetViewType(self,index):
        ViewT = self.w.View.itemText(index)
        zoomV = self.w.ZoomSlider.value()
        rangeV = self.w.RangeSlider.value()
        if ViewT == 'Camera':
            print 'Camera'
            self.w.RangeSlider.setValue(0)
            self.w.RangeSpinBox.setValue(0)
            self.w.ZoomSpinBox.setValue(rangeV)
            self.w.ZoomSlider.setValue(rangeV)
        if ViewT == 'LookAt':
            print 'LookAt'
            self.w.ZoomSpinBox.setValue(0)
            self.w.ZoomSlider.setValue(0)
            self.w.RangeSlider.setValue(zoomV)
            self.w.RangeSpinBox.setValue(zoomV)
        return ViewT
    
    
    def CeckViewTypeState(self):
        if not self.w.actionLonLat.isChecked():
            self.worningmessage()
    
        
# Set Configuration
              
    def setparamconnection(self):
        try :
            conf = parseOutputconf()
            host = conf['tcpHost']
            nav = conf['tcpPport']
            data = conf['tcpDport']
            return host, nav, data
        except :
            print 'Use preference Panel to set preference'
            self.worningmessagetcp()
    
    
# Set Position Messages    
    
    def makeactiontemplate(self, item, lon, lat, zoom, heads, pitch, roll, range):
        ossimxml = '<Set target=":navigator" vref="wgs84"><%s>\
        <longitude>%s</longitude><latitude>%s</latitude>\
        <altitude>%s</altitude><heading>%s</heading><pitch>%s</pitch>\
        <roll>%s</roll><altitudeMode>absolute</altitudeMode>\
        <range>%s</range></%s></Set>' % (item, lon, lat, zoom, heads, pitch, roll, range, item)
        return ossimxml
    
    
    def sendFunction(self):
        heads = head
        host = self.setparamconnection()[0]
        nav = self.setparamconnection()[1]
        if head == str('Manual'):
            heads = self.w.HandlingSlider.value()
        if self.w.actionLonLat.isChecked():
            (z, e, n) = LLtoUTM(ell, self.fxvallat, self.fxvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.fxvallon), unicode(self.fxvallat), 
                                       self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                       self.w.RollSlider.value(), self.w.RangeSlider.value())
                                
        if self.w.actionGrass.isChecked():
            (z, e, n) = LLtoUTM(ell, self.slvallat, self.slvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.slvallon), unicode(self.slvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
        if self.w.actionGPS.isChecked():
            #f = open(coordsfile, "r")
            #lonlat = f.readline()
            #lonlat = lonlat.split(' ')
            #lon = lonlat[0]
            #lat = lonlat[1]
            lon = self.w.GPSlon.text()
            lat = self.w.GPSlat.text()
            print lon, lat
            ossimxml = self.makeactiontemplate(item, lon, lat, self.w.ZoomSlider.value(), heads, 
                                             self.w.PitchSlider.value(), self.w.RollSlider.value(),
                                             self.w.RangeSlider.value())
        ossim = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ossim.connect((host, int(nav))) 
        try:
            ossim.send(ossimxml)
            ossim.close()
        except:
            if not self.w.actionBroadcast.isChecked():
                self.CeckViewTypeState()
    
    
    def ResetPosition(self):
        heads = head
        host = self.setparamconnection()[0]
        nav = self.setparamconnection()[1]
        if self.w.actionLonLat.isChecked():
            self.fxvallon = self.SetPosition()[0]
            self.fxvallat = self.SetPosition()[1]
            (z, e, n) = LLtoUTM(ell, self.fxvallat, self.fxvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.fxvallon), unicode(self.fxvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.fxvallat))
            self.w.Lon.setText(unicode(self.fxvallon))
        if self.w.actionGrass.isChecked():
            self.slvallon = self.setcenter()[0]
            self.slvallat = self.setcenter()[1]
            (z, e, n) = LLtoUTM(ell, self.slvallat, self.slvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.slvallon), unicode(self.slvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.slvallat))
            self.w.Lon.setText(unicode(self.slvallon))
        if self.w.actionGPS.isChecked():
            #self.CrossClassLon = float(self.CrossClassLon)
            #self.CrossClassLat = float(self.CrossClassLat)
            coordsfile = apppath+'/lonlatfile'
            f = open(coordsfile, "r")
            lonlat = f.readline()
            lonlat = lonlat.split(' ')
            lon = lonlat[0]
            lat = lonlat[1]
            ossimxml = self.makeactiontemplate(item, lon, lat, self.w.ZoomSlider.value(), heads, 
                                             self.w.PitchSlider.value(), self.w.RollSlider.value(),
                                             self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.CrossClassLat))
            self.w.Lon.setText(unicode(self.CrossClassLon))
        ossim = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ossim.connect((host, int(nav)))  
        try:
            ossim.send(ossimxml)
            ossim.close()
        except:
            if not self.w.actionBroadcast.isChecked():
                self.CeckViewTypeState()
    
    
    def inclat(self):
        host = self.setparamconnection()[0]
        nav = self.setparamconnection()[1]
        step = float(self.w.SpeedSpinBox.value())
        mult = float(self.w.SpeedMultipler.value())
        step = step * (10 ** -mult)
        heads = head
        if head == str('Manual'):
            heads = self.w.HandlingSlider.value()
        if self.w.actionLonLat.isChecked():
            self.fxvallat += step
            (z, e, n) = LLtoUTM(ell, self.fxvallat, self.fxvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.fxvallon), unicode(self.fxvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.fxvallat))
            self.w.Lon.setText(unicode(self.fxvallon))
        if self.w.actionGrass.isChecked():
            self.slvallat += step
            (z, e, n) = LLtoUTM(ell, self.slvallat, self.slvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.slvallon), unicode(self.slvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.slvallat))
            self.w.Lon.setText(unicode(self.slvallon))
        if self.w.actionGPS.isChecked():
            self.CrossClassLat = float(self.CrossClassLat)
            self.CrossClassLat += step
            ossimxml = self.makeactiontemplate(item, unicode(self.CrossClassLon), unicode(self.CrossClassLat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.CrossClassLat))
            self.w.Lon.setText(unicode(self.CrossClassLon))
        ossim = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ossim.connect((host, int(nav)))  
        try:
            ossim.send(ossimxml)
            ossim.close()
        except:
            if not self.w.actionBroadcast.isChecked():
                self.CeckViewTypeState()
    
    
    def declat(self):
        host = self.setparamconnection()[0]
        nav = self.setparamconnection()[1]
        step = float(self.w.SpeedSpinBox.value())
        mult = float(self.w.SpeedMultipler.value())
        heads = head
        step = step * (10 ** -mult)
        if head == str('Manual'):
            heads = self.w.HandlingSlider.value()
        if self.w.actionLonLat.isChecked():
            self.fxvallat -= step
            (z, e, n) = LLtoUTM(ell, self.fxvallat, self.fxvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.fxvallon), unicode(self.fxvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.fxvallat))
            self.w.Lon.setText(unicode(self.fxvallon))
        if self.w.actionGrass.isChecked():
            self.slvallat -= step
            (z, e, n) = LLtoUTM(ell, self.slvallat, self.slvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.slvallon), unicode(self.slvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.slvallat))
            self.w.Lon.setText(unicode(self.slvallon))
        if self.w.actionGPS.isChecked():
            self.CrossClassLat = float(self.CrossClassLat)
            self.CrossClassLat -= step
            ossimxml = self.makeactiontemplate(item, unicode(self.CrossClassLon), unicode(self.CrossClassLat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.CrossClassLat))
            self.w.Lon.setText(unicode(self.CrossClassLon))
        ossim = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ossim.connect((host, int(nav)))  
        try:
            ossim.send(ossimxml)
            ossim.close()
        except:
            if not self.w.actionBroadcast.isChecked():
                self.CeckViewTypeState()
    
    
    def inclon(self):
        host = self.setparamconnection()[0]
        nav = self.setparamconnection()[1]
        step = float(self.w.SpeedSpinBox.value())
        mult = float(self.w.SpeedMultipler.value())
        heads = head
        step = step * (10 ** -mult)
        if head == str('Manual'):
            heads = self.w.HandlingSlider.value()
        if self.w.actionLonLat.isChecked():
            self.fxvallon += step
            (z, e, n) = LLtoUTM(ell, self.fxvallat, self.fxvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.fxvallon), unicode(self.fxvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.fxvallat))
            self.w.Lon.setText(unicode(self.fxvallon))
        if self.w.actionGrass.isChecked():
            self.slvallon += step
            (z, e, n) = LLtoUTM(ell, self.slvallat, self.slvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.slvallon), unicode(self.slvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.slvallat))
            self.w.Lon.setText(unicode(self.slvallon))
        if self.w.actionGPS.isChecked():
            self.CrossClassLon = float(self.CrossClassLon)
            self.CrossClassLon += step
            ossimxml = self.makeactiontemplate(item, unicode(self.CrossClassLon), unicode(self.CrossClassLat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.CrossClassLat))
            self.w.Lon.setText(unicode(self.CrossClassLon))
        ossim = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ossim.connect((host, int(nav)))  
        try:
            ossim.send(ossimxml)
            ossim.close()
        except:
            if not self.w.actionBroadcast.isChecked():
                self.CeckViewTypeState()
    
    
    def declon(self):
        host = self.setparamconnection()[0]
        nav = self.setparamconnection()[1]
        step = float(self.w.SpeedSpinBox.value())
        mult = float(self.w.SpeedMultipler.value())
        heads = head
        step = step * (10 ** -mult)
        if head == str('Manual'):
            heads = self.w.HandlingSlider.value()
        if self.w.actionLonLat.isChecked():
            self.fxvallon -= step
            (z, e, n) = LLtoUTM(ell, self.fxvallat, self.fxvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.fxvallon), unicode(self.fxvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.fxvallat))
            self.w.Lon.setText(unicode(self.fxvallon))
        if self.w.actionGrass.isChecked():
            self.slvallon -= step
            (z, e, n) = LLtoUTM(ell, self.slvallat, self.slvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.slvallon), unicode(self.slvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.slvallat))
            self.w.Lon.setText(unicode(self.slvallon))
        if self.w.actionGPS.isChecked():
            self.CrossClassLon = float(self.CrossClassLon)
            self.CrossClassLon -= step
            ossimxml = self.makeactiontemplate(item, unicode(self.CrossClassLon), unicode(self.CrossClassLat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.CrossClassLat))
            self.w.Lon.setText(unicode(self.CrossClassLon))
        ossim = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ossim.connect((host, int(nav)))  
        try:
            ossim.send(ossimxml)
            ossim.close()
        except:
            if not self.w.actionBroadcast.isChecked():
                self.CeckViewTypeState()
    
    
    def inclatlon(self):
        host = self.setparamconnection()[0]
        nav = self.setparamconnection()[1]
        step = float(self.w.SpeedSpinBox.value())
        mult = float(self.w.SpeedMultipler.value())
        heads = head
        step = step * (10 ** -mult)
        if head == str('Manual'):
            heads = self.w.HandlingSlider.value()
        if self.w.actionLonLat.isChecked():
            self.fxvallat += step
            self.fxvallon += step
            (z, e, n) = LLtoUTM(ell, self.fxvallat, self.fxvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.fxvallon), unicode(self.fxvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.fxvallat))
            self.w.Lon.setText(unicode(self.fxvallon))
        if self.w.actionGrass.isChecked():
            self.slvallat += step
            self.slvallon += step
            (z, e, n) = LLtoUTM(ell, self.slvallat, self.slvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.slvallon), unicode(self.slvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.slvallat))
            self.w.Lon.setText(unicode(self.slvallon))
        if self.w.actionGPS.isChecked():
            self.CrossClassLon = float(self.CrossClassLon)
            self.CrossClassLat = float(self.CrossClassLat)
            self.CrossClassLon += step
            self.CrossClassLat += step
            ossimxml = self.makeactiontemplate(item, unicode(self.CrossClassLon), unicode(self.CrossClassLat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.CrossClassLat))
            self.w.Lon.setText(unicode(self.CrossClassLon))
        ossim = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ossim.connect((host, int(nav)))  
        try:
            ossim.send(ossimxml)
            ossim.close()
        except:
            if not self.w.actionBroadcast.isChecked():
                self.CeckViewTypeState()
    
    
    def declatlon(self):
        host = self.setparamconnection()[0]
        nav = self.setparamconnection()[1]
        step = float(self.w.SpeedSpinBox.value())
        mult = float(self.w.SpeedMultipler.value())
        heads = head
        step = step * (10 ** -mult)
        if head == str('Manual'):
            heads = self.w.HandlingSlider.value()
        if self.w.actionLonLat.isChecked():
            self.fxvallat -= step
            self.fxvallon -= step
            (z, e, n) = LLtoUTM(ell, self.fxvallat, self.fxvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.fxvallon), unicode(self.fxvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value() , 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.fxvallat))
            self.w.Lon.setText(unicode(self.fxvallon))
        if self.w.actionGrass.isChecked():
            self.slvallat -= step
            self.slvallon -= step
            (z, e, n) = LLtoUTM(ell, self.slvallat, self.slvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.slvallon), unicode(self.slvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.slvallat))
            self.w.Lon.setText(unicode(self.slvallon))
        if self.w.actionGPS.isChecked():
            self.CrossClassLon = float(self.CrossClassLon)
            self.CrossClassLat = float(self.CrossClassLat)
            self.CrossClassLon -= step
            self.CrossClassLat -= step
            ossimxml = self.makeactiontemplate(item, unicode(self.CrossClassLon), unicode(self.CrossClassLat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.CrossClassLat))
            self.w.Lon.setText(unicode(self.CrossClassLon))
        ossim = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ossim.connect((host, int(nav)))  
        try:
            ossim.send(ossimxml)
            ossim.close()
        except:
            if not self.w.actionBroadcast.isChecked():
                self.CeckViewTypeState()
    
    
    def inclatdeclon(self):
        host = self.setparamconnection()[0]
        nav = self.setparamconnection()[1]
        step = float(self.w.SpeedSpinBox.value())
        mult = float(self.w.SpeedMultipler.value())
        step = step * (10 ** -mult)
        heads = head
        if head == str('Manual'):
            heads = self.w.HandlingSlider.value()
        if self.w.actionLonLat.isChecked():
            self.fxvallat += step
            self.fxvallon -= step
            (z, e, n) = LLtoUTM(ell, self.fxvallat, self.fxvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.fxvallon), unicode(self.fxvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.fxvallat))
            self.w.Lon.setText(unicode(self.fxvallon))
        if self.w.actionGrass.isChecked():
            self.slvallat += step
            self.slvallon -= step
            (z, e, n) = LLtoUTM(ell, self.slvallat, self.slvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.slvallon), unicode(self.slvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value() , 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.slvallat))
            self.w.Lon.setText(unicode(self.slvallon))
        if self.w.actionGPS.isChecked():
            self.CrossClassLon = float(self.CrossClassLon)
            self.CrossClassLat = float(self.CrossClassLat)
            self.CrossClassLon -= step
            self.CrossClassLat += step
            ossimxml = self.makeactiontemplate(item, unicode(self.CrossClassLon), unicode(self.CrossClassLat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.CrossClassLat))
            self.w.Lon.setText(unicode(self.CrossClassLon))
        ossim = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ossim.connect((host, int(nav)))  
        try:
            ossim.send(ossimxml)
            ossim.close()
        except:
            if not self.w.actionBroadcast.isChecked():
                self.CeckViewTypeState()
    
    
    def declatinclon(self):
        host = self.setparamconnection()[0]
        nav = self.setparamconnection()[1]
        step = float(self.w.SpeedSpinBox.value())
        mult = float(self.w.SpeedMultipler.value())
        step = step * (10 ** -mult)
        heads = head
        if head == str('Manual'):
            heads = self.w.HandlingSlider.value()
        if self.w.actionLonLat.isChecked():
            self.fxvallat -= step
            self.fxvallon += step
            (z, e, n) = LLtoUTM(ell, self.fxvallat, self.fxvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.fxvallon), unicode(self.fxvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.fxvallat))
            self.w.Lon.setText(unicode(self.fxvallon))
        if self.w.actionGrass.isChecked():
            self.slvallat -= step
            self.slvallon += step
            (z, e, n) = LLtoUTM(ell, self.slvallat, self.slvallon)
            self.w.Nord.setText(str(n))
            self.w.East.setText(str(e))
            self.w.utmcode.setText(str(z))
            ossimxml = self.makeactiontemplate(item, unicode(self.slvallon), unicode(self.slvallat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.slvallat))
            self.w.Lon.setText(unicode(self.slvallon))
        if self.w.actionGPS.isChecked():
            self.CrossClassLon = float(self.CrossClassLon)
            self.CrossClassLat = float(self.CrossClassLat)
            self.CrossClassLon += step
            self.CrossClassLat -= step
            ossimxml = self.makeactiontemplate(item, unicode(self.CrossClassLon), unicode(self.CrossClassLat), 
                                             self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                             self.w.RollSlider.value(), self.w.RangeSlider.value())
            self.w.Lat.setText(unicode(self.CrossClassLat))
            self.w.Lon.setText(unicode(self.CrossClassLon))
        ossim = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ossim.connect((host, int(nav)))  
        try:
            ossim.send(ossimxml)
            ossim.close()
        except:
            if not self.w.actionBroadcast.isChecked():
                self.CeckViewTypeState()
    
    
    def SetJoyCoords(self):
        if self.w.actionJoystick.isChecked():
            a = self.w.Lon.text()
            b = self.w.Lat.text()
            aa = float(a) + 1
            bb = float(b) + 1
            self.w.Lon.setText(str(aa))
            self.w.Lat.setText(str(bb))
            self.w.Lon.setText(str(a))
            self.w.Lat.setText(str(b))
    
    
    def SetLonLat(self):
        host = self.setparamconnection()[0]
        nav = self.setparamconnection()[1]
        heads = head
        if head == str('Manual'):
            heads = self.w.HandlingSlider.value()
        (z, e, n) = LLtoUTM(ell, float(self.w.Lat.text()), float(self.w.Lon.text()))
        self.w.Nord.setText(str(n))
        self.w.East.setText(str(e))
        self.w.utmcode.setText(str(z))
        ossimxml = self.makeactiontemplate(item, unicode(self.w.Lon.text()), unicode(self.w.Lat.text()), 
                                         self.w.ZoomSlider.value(), heads, self.w.PitchSlider.value(), 
                                         self.w.RollSlider.value(), self.w.RangeSlider.value())
        ossim = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ossim.connect((host, int(nav)))  
        try:
            ossim.send(ossimxml)
            ossim.close()
        except:
            if not self.w.actionBroadcast.isChecked():
                self.CeckViewTypeState()
    
    
# Set Cross Widget Values
    
    def setValue(self, v):
        self.Value = v
    
    
    def setValueM(self, v):
        self.Value = v
    
    
    def setValueZ(self, v):
        self.Value = v
    
    
    def setValueR(self, v):
        self.Value = v
    
    
    def setValueRM(self, v):
        self.Value = v
    
    
    def setValueZM(self, v):
        self.Value = v
    
    
# Set ellipsoid (for UTM display)
    
    def ellipsesettings(self,index):
        global ell
        ell = self.w.ellipse.itemText(index)
        if ell == 'Airy':
            ell = 1
        if ell == 'Australian National':
            ell = 2
        if ell == 'Bessel 1841':
            ell = 3
        if ell == 'Bessel 1841 (Nambia)':
            ell = 4
        if ell == 'Clarke 1866':
            ell = 5
        if ell == 'Clarke 1880':
            ell = 6
        if ell == 'Everest':
            ell = 7
        if ell == 'Fischer 1960 (Mercury)':
            ell = 8
        if ell == 'Fischer 1968':
            ell = 9
        if ell == 'GRS 1967':
            ell = 10
        if ell == 'GRS 1980':
            ell = 11
        if ell == 'Helmert 1906':
            ell = 12
        if ell == 'Hough':
            ell = 13
        if ell == 'International':
            ell = 14
        if ell == 'Krassovsky':
            ell = 15
        if ell == 'Modified Airy':
            ell = 16
        if ell == 'Modified Everest':
            ell = 17
        if ell == 'Modified Fischer 1960':
            ell = 18
        if ell == 'South American 1969':
            ell = 19
        if ell == 'WGS 60':
            ell = 20
        if ell == 'WGS 66':
            ell = 21
        if ell == 'WGS-72':
            ell = 22
        if ell == 'WGS-84':
            ell = 23
        return ell
    
    
#  Set Center on GRASS Location
    
    def setCLL(self):
        while 1:
            try:
                s = read_command("g.region", flags='c')
                break
            except IOError:
                time.sleep(0.1)
        region = parse_key_val(s, ':')
        clon_deg = region['east-west center']
        clat_deg = region['north-south center']
        centro_deg = (clon_deg,clat_deg)
        return centro_deg
    
        
    def setCPRJ(self):
        while 1:
            try:
                s = read_command("g.region", flags='l')
                break
            except IOError:
                time.sleep(0.1)
        region = parse_key_val(s, ':')
        clon_deg = region['center longitude']
        clat_deg = region['center latitude']
        centro_deg = (clon_deg,clat_deg)
        return centro_deg
    
  
    def projinfo(self):
        while 1:
            try :
                units = read_command("g.proj", flags='p')
                break
            except IOError:
                time.sleep(0.1)                
        units = units.replace('-','')
        #units = units.replace('\n','')
        units = parse_key_val(units, ':')
        units_key = units.keys()
        for i in units_key :
            key_value = str(units[i]).strip()
            units[i] =  key_value
        return units
    
       
    def setcenter(self):
        global centro
        clon = 0
        clat = 0
        proj_info = self.projinfo()
        unit = proj_info['units']
        if unit == 'metres'or unit == 'meters':
            clon = self.setCPRJ()[0]
            clat = self.setCPRJ()[1]
        #if unit == 'meters':
        #    clon = self.setCPRJ()[0]
        #    clat = self.setCPRJ()[1]
        if unit == 'degrees' or unit == 'degree':
            clon = self.setCLL()[0]
            clat = self.setCLL()[1]
        #if unit == 'degree':
        #    clon = self.setCLL()[0]
        #    clat = self.setCLL()[1]
        clon = str(clon)
        clat = str(clat)
        clon = clon.replace(':', " ")
        clat = clat.replace(':', " ")
        if clat[-1] == 'N':
            signlat = 1
        if clat[-1] == 'S':
            signlat = -1
        if clon[-1] == 'E':
            signlon = 1
        if clon[-1] == 'W':
            signlon = -1
        clat = clat[:-1] 
        clon = clon[:-1]
        clat = [float(i) for i in clat.split()]
        clon = [float(i) for i in clon.split()]
        if len(clon) > 2 :
            clat = (clat[0] + (clat[1] / 60) + clat[2] / 3600) * float(signlat)
            clon = (clon[0] + (clon[1] / 60) + clon[2] / 3600) * float(signlon)
        else :
            clat = (clat[0] + (clat[1] / 60)) * float(signlat)
            clon = (clon[0] + (clon[1] / 60)) * float(signlon)
        slvallon = clon 
        slvallat = clat
        centro = (clon,clat)
        return centro
    
    
    def SetPosition(self):
        global centro
        lon = float(self.w.Lon.text())
        lat = float(self.w.Lat.text())
        centro = (lon,lat)
        return centro
    
    
    def PrintPosition(self, lon, lat, zoom, roll, pitch, heading, range):
        testo = '''Longitude : %s
        Latitude : %s 
        Altitude : %s
        Heading : %s
        Roll : %s
        Pitch : %s
        Range : %s
        ''' % (lon, lat, zoom, roll, pitch, heading, range)
    
    
# Set GRASS Vector/Raster 
   
    def VectorList(self):
        while 1:
            try:
                v = list_strings('vect')
                break
            except IOError:
                time.sleep(0.1)
        vector = []
        for i in v:
            vname , mname = i.split('@', 2)
            if mname == grassenv['MAPSET']:
                vector.append(vname)
        vector.sort()
        return vector
    
    
    def RasterList(self):
        while 1:
            try:
                r = list_strings('rast')
                break
            except IOError:
                time.sleep(0.1)
        raster = []
        for i in r:
            rname , mname = i.split('@', 2)
            if mname == grassenv['MAPSET']:
                raster.append(rname)
        raster.sort()
        return raster
    
        
    def refreshlayer(self):
        vector = self.VectorList()
        raster = self.RasterList()
        self.w.GrassRLayer.addItems(raster)
        self.w.GrassVLayer.addItems(vector)
    
            
    def selectraster(self,index):
        global inputR
        inputR = self.w.GrassRLayer.itemText(index)
        return inputR
    
        
    def selectvector(self,index):
        global inputV
        inputV = self.w.GrassVLayer.itemText(index)
        return inputV
    
        
    def addraster(self):
        while 1:
            try:
                run_command('r.planet.py', flags = 'a', map = inputR, dport = 8000, pport = 7000)
                break
            except IOError:
                time.sleep(0.1)
        print 'add', inputR
    
        
    def removeraster(self):
        while 1:
            try:
                run_command('r.planet.py', flags = 'r', map = inputR, dport = 8000, pport = 7000)
                break
            except IOError:
                time.sleep(0.1)
        print 'removed', inputR
    
        
    def addvector(self):
        while 1:
            try:
                run_command('v.planet.py', flags = 'a', map = inputV, dport = 8000, pport = 7000, brush = '155,155,155', pen = '055,055,055', size = '1,1', fill = 0)
                break
            except IOError:
                time.sleep(0.1)
        print 'add', inputV
    
        
    def removevector(self):
        while 1:
            try:
                run_command('v.planet.py', flags = 'r', map = inputV, dport = 8000, pport = 7000)
                break
            except IOError:
                time.sleep(0.1)
        print 'removed', inputV
    
            
# Show External Widgets
    
    def pgsetting(self):
        self.pgconn = PgConn()
        self.pgconn.show()
    
    
    def preference(self):
        self.preferencesetting = PreferenceSetting()
        self.preferencesetting.show()
    
    
    def worningmessage(self):
        self.worn = worn()
        self.worn.show()
    
    
    def worningmessagetcp(self):
        self.worntcp = worntcp()
        self.worntcp.show()
    
    
    def processdata(self):
        self.Data.show()
    
    
    def dataprocess(self):
        self.DataW.show()
    
    
    def GrassShell(self):
        self.Gshell.show()
    
        
    def kmldialog(self):
        self.kmlview.show()
    
    
    def modeldialog(self):
        self.placemodel.show()
    
     
    def SEpsg(self):
        self.searchepsg = SearchEpsg()
        self.searchepsg.show()
    
    
    def Geom(self):
        self.vectoroperation.show()
    
    
# code not used :
    
    def modeldialog(self):
        self.placemodelite.show()
    
    
    def setparamconnection2(self):
        try:
            TCP = open(tcpparam, "r")
            K = TCP.read()
            Y = K.rsplit(',')
            host = str(Y[0])
            nav = str(Y[1])
            data = str(Y[2])
            return host, nav, data
        except :
            print 'Use preference Panel to set preference'
            self.worningmessagetcp()
    
		    
    def GpsHandling(self):
        #print item,self.w.ZoomSlider.value(),head,self.w.PitchSlider.value(),
        #self.w.RollSlider.value(),self.w.RangeSlider.value()
        #self.gps = GpsClass(item,self.w.ZoomSlider.value(),head,
        #self.w.PitchSlider.value(),self.w.RollSlider.value(),self.w.RangeSlider.value())
        self.gps.show()
    
    
    def GetType(self,index):
        global Gtype
        Gtype = self.w.GrassType.itemText(index)
        if Gtype == 'region':
            while 1:
                try:
                    rg = list_strings('region')
                    break
                except IOError:
                    time.sleep(0.1)
            region = []
            for i in rg:
                rgname = i.split('@', 2)[0]
                region.append(rgname)
            region.sort()
            self.w.InputType.clear()
            self.w.InputType.addItems(region)
        if Gtype == 'vect':
            while 1:
                try:
                    vc = list_strings('vect')
                    break
                except IOError:
                    time.split(0.1)
            vector = []
            for i in vc:
                vecname = i.split('@', 2)[0]
                vector.append(vecname)
            vector.sort()
            self.w.InputType.clear()
            self.w.InputType.addItems(vector)
        if Gtype == 'rast':
            while 1:
                try:
                    rs = list_strings('rast')
                    break
                except IOError:
                    time.sleep(0.1)
            raster = []
            for i in rs:
                rasname = i.split('@', 2)[0]
                raster.append(rasname)
            raster.sort()
            self.w.InputType.clear()
            self.w.InputType.addItems(raster)
        #return GType
    
        
# Refresh SQLite
        
    def refreshsqlitedb(self):
        print 'refresh sqlite'
        tables = self.gettablelist()
        self.w.Place.clear()
        self.w.Place.addItems(tables)
    
		    
    def itemlist(self,index):
        Zone = self.w.Place.itemText(index)
        database_name = parseOutputconf()['spatialitedb']
        db_connection = sqlite3.connect(database_name)
        db_cursor = db_connection.cursor()
        try :
            listatabelle = db_cursor.execute("SELECT name,latitude,longitude FROM %s ;" % (Zone))
            tabelle = listatabelle.fetchall()
            tablelist = []
            allist = []
            for i in tabelle:
                tablelist.append(i[0])
                allist.append(i[0]+' '+str(i[1])+' '+str(i[2]))
            allist.sort()
            tablelist.sort()
            self.w.placezone.clear()
            self.w.placezone.addItems(allist)
            db_connection.commit()
        except :
            print 'reload sqlite'
    
        
    def setplacezonecoords(self,index):
        Placename = self.w.placezone.itemText(index)
        st = unicode(Placename)
        st = st.split(' ')
        try :
            lat = st[-2]
            lon = st[-1]
            self.w.Lon.setText(lon)
            self.w.Lat.setText(lat)
        except :
            pass
    
        
    def gettablelist(self):
        #database_name = sqlitedb
        database_name = parseOutputconf()['spatialitedb']
        print database_name
        db_connection = sqlite3.connect(database_name)
        db_cursor = db_connection.cursor()
        listatabelle = db_cursor.execute("SELECT name FROM sqlite_master where type = 'table';")
        tabelle = listatabelle.fetchall()
        tablelist = []
        for i in tabelle:
            tablelist.append(i[0])
        db_connection.commit()
        tablelist.sort()
        return tablelist
    
    


    
class GpsT(QThread):
    GPSlatitude = pyqtSignal(str)
    GPSlongitude = pyqtSignal(str)
    GPSsat = pyqtSignal(str)
    GPStime = pyqtSignal(str)
    GPSeph = pyqtSignal(str)
    GPSspeed = pyqtSignal(str)
    GPSaltitude = pyqtSignal(str)
    GPSepv = pyqtSignal(str)
    GPSept = pyqtSignal(str)
    GPSclimb = pyqtSignal(str)
    satellite = pyqtSignal(str)
    GPSutctime = pyqtSignal(str)
    GPStrack = pyqtSignal(str)
    GPSepd = pyqtSignal(str)
    GPSeps = pyqtSignal(str)
    GPSepc = pyqtSignal(str)
    GPSpdop = pyqtSignal(str)
    GPShdop = pyqtSignal(str)
    GPSvdop = pyqtSignal(str)
    GPStdop = pyqtSignal(str)
    GPSgdop = pyqtSignal(str)
    GPSsat = pyqtSignal(str)
    def __init__(self, parent = None):
        QThread.__init__(self, parent)
        self.alive = 1
        self.running = 0
        print "vivo 1"
    
        
    def run(self):
        print "vivo 2"
        #session = gps.gps()
        while self.alive:
            while self.running:
                os.system('clear')
                session.query('admosyq')
                satellitelist=[]
                html = """<TABLE cellpadding="4" style="border: 1px solid \
                #000000; border-collapse: collapse;" border="1"><TR><TD>PRN</TD>\
                <TD>E</TD><TD>Az</TD><TD>Ss</TD><TD>Used</TD></TR>"""
                satellitelist.append(html)
                for i in session.satellites:                    
                    table = """<TR><TD>%s</TD><TD>%s</TD><TD>%s</TD><TD>%s</TD>\
                    <TD>%s</TD>""" % (i.PRN, i.elevation, i.azimuth, i.ss, i.used)
                    satellitelist.append(table)
                htmlend = """</TR></TABLE>"""
                satellitelist.append(htmlend)
                satstringa = str(satellitelist)
                satstringa = satstringa.replace(",","")
                satstringa = satstringa.replace("[","")
                satstringa = satstringa.replace("]","")
                satstringa = satstringa.replace("'","")
                GPSlatitudex = str(session.fix.latitude)
                self.GPSlatitude.emit(str(session.fix.latitude))
                self.GPSlongitude.emit(str(session.fix.longitude))
                self.GPStime.emit(str(session.utc))
                self.GPSutctime.emit(str(session.fix.time))
                self.GPSaltitude.emit(str(session.fix.altitude))
                self.GPSeph.emit(str(session.fix.eph))
                self.GPSepv.emit(str(session.fix.epv))
                self.GPSept.emit(str(session.fix.ept))
                self.GPSspeed.emit(str(session.fix.speed))
                self.GPSclimb.emit(str(session.fix.climb))
                self.GPStrack.emit(str(session.fix.track))
                self.GPSepd.emit(str(session.fix.epd))
                self.GPSeps.emit(str(session.fix.eps))
                self.GPSepc.emit(str(session.fix.epc))
                self.GPSpdop.emit(str(session.pdop))
                self.GPShdop.emit(str(session.hdop))
                self.GPSvdop.emit(str(session.vdop))
                self.GPStdop.emit(str(session.tdop))
                self.GPSgdop.emit(str(session.gdop))
                self.GPSsat.emit(str(satstringa))
                #print satstringa
                self.msleep(1000)
            #self.msleep(1000)
    
    
    def toggle(self):
        print "vivo 3"
        global session
        session = gps.gps()
        if self.running:
            self.running = 0
        else :
            self.running = 1
    
    
    def stop(self):
        print "vivo 4"
        self.alive = 0
        self.running = 0
        self.wait()
    
    

    
class logS(QThread):
    LonUpdated = pyqtSignal(str)
    LatUpdated = pyqtSignal(str)
    RollUpdated = pyqtSignal(float)
    PitchUpdated = pyqtSignal(float)
    GainUpdated = pyqtSignal(float)
    AltUpdated = pyqtSignal(float)
    def __init__(self, parent = None):
        QThread.__init__(self, parent)
        self.alive = 1
        self.running = 0
    
    
    def run(self):
        HOST = 'localhost'
        PORT = 9000
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind((HOST, PORT))
        s.listen(1)
        conn, addr = s.accept()
        print 'Connected by', addr
        while self.alive:
            while self.running:
                data = conn.recv(1024)
                parsed = parseSignal(data)
                self.LonUpdated.emit(str(parsed['lon']))
                self.LatUpdated.emit(str(parsed['lat']))
                self.RollUpdated.emit(float(parsed['roll']))
                self.PitchUpdated.emit(float(parsed['pitch']))
                self.GainUpdated.emit(float(parsed['gain']))
                self.AltUpdated.emit(float(parsed['msl']))
                
                #print parsed
                #navlogger('localhost', 9000)
                #self.msleep(500)
    
    
    def setValueLon(self, valueLon):
        self.valueLon = valueLon
    
    
    def setValueLat(self, valueLat):
        self.valueLat = valueLat
    
    
    def setValueRoll(self, valueRoll):
        self.valueRoll = valueRoll
    
    
    def setValuePitch(self, valuePitch):
        self.valuePitch = valuePitch
    
    
    def setValueGain(self, valueGain):
        self.valueGain = valueGain
    
    
    def setValueAlt(self, valueAlt):
        self.valueAlt = valueAlt
    
    
    def toggle(self):
        if self.running:
            self.running = 0
        else :
            self.running = 1
    
    
    def stop(self):
        self.alive = 0
        self.running = 0
        self.wait()
    
    

    
class logJ(QThread):
    def __init__(self, parent = None):
        QThread.__init__(self, parent)
        self.valuelonJ = ""
        self.valuelatJ = ""
        self.alive = 1
        self.running = 0
    
    
    def run(self):
        while self.alive:
            while self.running:
                try :
                    p = self.aggiorna()
                    time.sleep(1)
                    if p[0] == "":
                        print "zero"
                    else :
                        startj(float(p[0]),float(p[1]))
                except :
                    print 'exit from Joy mode'
    
    
    def toggle(self):
        pygame.init()
        if self.running:
            self.running = 0
        else :
            self.running = 1
    
    
    def stop(self):
        pygame.quit()
        self.alive = 0
        self.running = 0
        self.wait()
    
    
    def setValueLonJ(self, valuelonJ):
        self.valuelonJ = valuelonJ
    
    
    def setValueLatJ(self, valuelatJ):
        self.valuelatJ = valuelatJ
    
    
    def aggiorna(self):
        newvaluelon = str(self.valuelonJ)
        newvaluelat = str(self.valuelatJ)
        position = (newvaluelon,newvaluelat)
        return position
    
    

    
    

if __name__ == "__main__":
    import sys
    import time
    app = QApplication(sys.argv)
    splash_pix = QPixmap(splash)
    splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
    #splash_pix_mask = QPixmap(splash_mask)
    #splash.setMask(splash_pix_mask.mask())
    splash.setMask(splash_pix.mask())
    splash.show()
    time.sleep(1)
    app.processEvents()
    p = PlanetSasha()
    p.init()
    splash.close()
    sys.exit(app.exec_())





