Exemple #1
0
    def onClose(self):
        print 'wizard finished'
        f = open('offline1.xml','w')
        f.write('<root>\n\t')
        f.write('<catalog>\n\t<name>')
        node1 = self.model.item(0,0)
        f.write(str(node1.text()))
        f.write('</name>\n\t')

        cn = self.getChildNodes(node1)
        for c in cn:
            #if c.hasChilren():

            f.write('<catalog>\n\t<name>')
            f.write( str( c.text() ) )
            f.write('</name>\n')
            f.write('</catalog>\n')

        f.write('\t</catalog>\n')
        f.write('</root>')
        self.mapwin =  MapWindow(self.datalist)
        #FIXME
        self.mdi.addSubWindow(self.mapwin)
        self.mapwin.show()       
        
        self.accept()
        self.done(QDialog.Accepted)
        self.close()
class SashaMainWindow(QMainWindow, Ui_SashaMainWindow):
    def __init__(self, arg):
        QMainWindow.__init__(self)
        self.arg_ = arg
        
        
        self.setupUi(self)
        
        self.setCentralWidget(self.mdiArea)
        #self.setLayout(self.verticalLayout)

#        self.navwin =  NavigationWindow()
#        self.mdiArea.addSubWindow(self.navwin)
#        self.navwin.show()

        #self.prefsWindow_ = PreferencesWindow()
        
        ##self.actionT_LonLat.triggered.connect(self.showNavWindow)

        self.actionM_Navigation.triggered.connect(self.showNavWindow)
        self.actionM_Query.triggered.connect(self.showQueryWindow)
        self.actionM_GPS.triggered.connect(self.showGpsWindow)
        self.actionM_Data.triggered.connect(self.showDataWindow)
        self.actionM_Import.triggered.connect(self.showImportWindow)
        self.actionM_Preferences.triggered.connect(self.showPrefsWindow)
        self.actionM_Map.triggered.connect(self.showMapWindow)
        self.actionM_Ossim.triggered.connect(self.showOssimWindow)

        #self.connect(self.actionLonLat, SIGNAL("triggered()"),           self.LonLatunceckbuttons)                 
#        connection

        self.navwin = None
        self.joy = logJ()

        #self.hw = HWS()
        self.gpsx = GpsT()
        #self.gt = gt(self.setcmd)
        #
        #self.lineEdit2 = QLineEdit(self.tab_6)
        #self.lineEdit2.setObjectName(_fromUtf8("lineEdit2"))
        #self.compassLayout.addWidget(self.lineEdit2)

        self.initWidgets()
        
        self.connectSignals()

        #

        #self.mainTabWidget.setCurrentIndex(0)    


    def showNavWindow(self):
        self.navwin =  NavigationWindow()
        self.mdiArea.addSubWindow(self.navwin)
        self.navwin.show()
        

    def showQueryWindow(self):
        self.querywin =  QueryWindow()
        self.mdiArea.addSubWindow(self.querywin)
        self.querywin.show()
        
    def showGpsWindow(self):
        self.gpswin =  GpsWindow()
        self.mdiArea.addSubWindow(self.gpswin)
        self.gpswin.show()

    def showDataWindow(self):
        if Utils.haveGRASS_:
            self.datawin =  DataWindow()
            self.mdiArea.addSubWindow(self.datawin)
            self.datawin.show()
        else:
            print "I can't do it. You don't have pygrass"
            from gui.datawindow import DataWindow
            self.datawin =  DataWindow()
            self.mdiArea.addSubWindow(self.datawin)
            self.datawin.show()

    def showImportWindow(self):
        self.impwin =  ImportWindow(self.mdiArea)
        #self.impwin.setAttribute(Qt.WA_DeleteOnClose, True)
        self.mdiArea.addSubWindow(self.impwin)
        #self.mdiArea.resize(752,497)
        self.impwin.show()
         
    def showPrefsWindow(self):
        self.prefwin =  PreferencesWindow()
        self.mdiArea.addSubWindow(self.prefwin)
        self.prefwin.show()

    def showMapWindow(self):
        self.mapwin =  MapWindow()
        self.mdiArea.addSubWindow(self.mapwin)
        self.mapwin.show()
        
    def showOssimWindow(self):
        self.osmwin =  OssimWindow()
        self.mdiArea.addSubWindow(self.osmwin)
        self.osmwin.show()
        
#    def showExportWindow(self):
#        self.expwin =  KmlWindow()
#        self.mdiArea.addSubWindow(self.expwin)
#        self.expwin.show()            
                 
                 
    def initWidgets(self):           
                     
        if Utils.haveGRASS_ == 0:
            #self.mainTabWidget.removeTab(1)
            self.actionT_Grass.setEnabled(False)
            self.actionT_Data.setEnabled(False)
            self.actionT_Grass.setVisible(False)
            self.actionT_Data.setVisible(False)
            self.actionT_Grassshell.setEnabled(False)
            self.actionT_Grassshell.setVisible(False)
        else:
            self.grasswin = GrassWindow()
            self.datawin  = DataWindow()
            

###FIXME REVIEW                         
###            self.vectors = VectorList()
###            self.rasters = RasterList()
###            vect = len(self.vectors)
###            rast = len(self.rasters)
###            numrow = max(vect,rast)
###            self.layerTable.setColumnCount(2)
###            self.layerTable.setRowCount(numrow)
###            self.layerTable.setEditTriggers(QTableWidget.NoEditTriggers)
###            for i in range(rast):
###                item = QTableWidgetItem(self.rasters[i])
###                item.setTextAlignment(Qt.AlignCenter)
###                item.setCheckState(Qt.Unchecked)
###                self.layerTable.setItem(i, 0, item)
###            for i in range(vect):
###                item = QTableWidgetItem(self.vectors[i])
###                item.setTextAlignment(Qt.AlignCenter)
###                item.setCheckState(Qt.Unchecked)
###                self.layerTable.setItem(i, 1, item)
            self.gcmd.setEditable(1)
            self.gcmd.setAutoCompletion(1)
            commandlist = self.commandlist()
            self.gcmd.addItems(commandlist)
            self.gcmd.setEditable(1)
            self.gcmd.setAutoCompletion(1)
            self.gt = gt(self.setcmd)
           
                        



        
        #
        ##FME 
        """
        self.grassvectoroption.hide()
        # Hide/Show Slider
        self.actionHideSlider.setChecked(True)
        self.actionHideSpinbox.setChecked(True)
        self.actionHideStepTool.setChecked(True)
        self.actionHide_place_position.setChecked(True)
        """



        # spyderlib
        if self.arg_ == '-d':
            from spyderlib.widgets import internalshell
            dock = QDockWidget("Python Shell")
            self.pythonshell = internalshell.InternalShell(dock, namespace=globals(),commands=[], multithreaded=False)
            dock.setWidget(self.pythonshell)
            self.addDockWidget(Qt.BottomDockWidgetArea, dock)

        #self.show()        
        
        


    def connectSignals(self):
        # Hide Panel
        self.connect(self.actionHideSlider, SIGNAL("triggered()"), self.hidetool)

        #self.connectZoomSignals()
        #self.connectPlaceSignals()
        self.connectActionSignals()


        # Epsg search-tool
        #self.connect(self.actionEpsg, SIGNAL("triggered()"), self.SEpsg)
        
        # Geonames sqlite DB


        # Vector GeoTransform
        ##self.connect(self.actionVectorOp, SIGNAL("triggered()"), self.Geom) 
        # Exit QApp
        #self.connect(self.actionExit, SIGNAL("triggered()"), qApp, SLOT("quit()"))
        ##print 'here'
        self.connect(self.actionT_Exit, SIGNAL("triggered()"), self.quitAll)
        
        
        
        
        ##MV to grass window
        """
        self.connect(self.getlisttoquery, SIGNAL("clicked()"),self.getrasterstate)
        self.connect(self.getlisttoquery, SIGNAL("clicked()"),self.getvectorstate)
        self.connect(self.gcmdexec, SIGNAL("clicked()"),self.commandlist)

        self.connect(self.gcmd, SIGNAL("currentIndexChanged(int)"), self.selectcmd)
        self.connect(self.gcmdexec, SIGNAL("clicked()"), self.startstopGt)
        self.connect(self.gcmdexec, SIGNAL("clicked()"), self.stopstartGt)

#        self.connect(self.update, SIGNAL("clicked()"),self.aggiorna)
#        self.connect(self.getlisttoquery, SIGNAL("clicked()"),self.getrasterstate)
#        self.connect(self.getlisttoquery, SIGNAL("clicked()"),self.getvectorstate)
#        self.connect(self.gcmdexec, SIGNAL("clicked()"),self.commandlist) 
        """

    def connectPlaceSignals(self):
        # Place Model (send position to save kml model)
        #xprint "here"
        self.connect(self.Lon, SIGNAL("textChanged(QString)"), 
                     self.placemodel.setLonValue)
        self.connect(self.Lat, SIGNAL("textChanged(QString)"), 
                     self.placemodel.setLatValue)
        self.connect(self.RollSpinBox, SIGNAL("valueChanged(double)"), 
                     self.placemodel.setChangeRoll)
        self.connect(self.PitchSpinBox, SIGNAL("valueChanged(double)"), 
                     self.placemodel.setChangePitch)
        self.connect(self.HandlingSpinBox, SIGNAL("valueChanged(double)"), 
                     self.placemodel.setChangeHead)
        self.connect(self.ZoomSpinBox, SIGNAL("valueChanged(double)"), 
                     self.placemodel.setChangeZoom)
        self.connect(self.RangeSpinBox, SIGNAL("valueChanged(double)"), 
                     self.placemodel.setChangeRange)
        self.connect(self.actionModel, SIGNAL("triggered()"), 
                     self.modeldialog)

#FIXME
#        # 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)                     


        # ACTIONS
        # GPS
    def connectActionSignals(self):
        self.connectGpsActions()
        #self.connectLonLatActions()
        #FME self.connectJoystickActions()
        self.connectHwActions()
        ###self.connectPositonActions()

        self.connect(self.actionT_Broadcast, SIGNAL("triggered()"),     self.onTActionBroadCast)
        self.connect(self.actionT_LonLat, SIGNAL("triggered()"),        self.onTActionLonLat) 
        ##actionT_Prefs actionT_GVrt
        self.connect(self.actionT_Prefs, SIGNAL("triggered()"),         self.showPreferences)                   
        


                        

    def connectGpsActions(self):    
        #FME self.connect(self.actionT_GPS, SIGNAL("triggered()"),                      self.startstopgpsx)	
        self.connect(self.actionT_GPS, SIGNAL("triggered()"), 
                     self.GPSunceckbuttons)
        #FME self.connect(self.actionT_GPS, SIGNAL("triggered()"),                      self.stopstartgpsx)
                     
                     
                     
        #self.connect(self.actionNMEA, SIGNAL("triggered()"),
        #             self.GpsHandling)
        #self.connect(self.actionGPS, SIGNAL("triggered()"),
        #             self.GpsHandling)
        

        
    def connectJoystickActions(self):         
        # Joistick
        self.connect(self.actionJoystick, SIGNAL("triggered()"),
                     self.Joyunceckbuttons)
        self.connect(self.actionJoystick, SIGNAL("triggered()"), 
                     self.startstopjoy)	
        self.connect(self.actionJoystick, SIGNAL("triggered()"), 
                     self.stopstartjoy)
                     

    def connectHwActions(self):        
        # HW
        self.connect(self.actionT_HW, SIGNAL("triggered()"),
                     self.Serialunceckbuttons2)
        self.connect(self.actionT_HW, SIGNAL("triggered()"), 
                     self.stopstartHW)
        self.connect(self.actionT_HW, SIGNAL("triggered()"),
                     self.startstopHW)
        self.connect(self.actionDB_setting, SIGNAL("triggered()"),
                     self.pgsetting)


        self.connect(self.actionDataexp, SIGNAL("triggered()"),
                     self.processdata)
        #FME 
        """
        self.connect(self.actionData, SIGNAL("triggered()"),
                     self.processdata)
        self.connect(self.renderoptions, SIGNAL("clicked()"), self.getRenderOptions)
        self.connect(self.renderoptions, SIGNAL("clicked()"), self.showrenderoptions)
        """
    #moving to nav
    """
    def connectPositonActions(self):
        # Send Position
        self.connect(self.SendPosition, SIGNAL("clicked()"),
                     self.SetLonLat)
        self.connect(self.SendPosition, SIGNAL("clicked()"),
                     self.SetJoyCoords)
        self.connect(self.SendPosition, SIGNAL("clicked()"),
                     self.ResetPosition)
        self.connect(self.RollSpinBox, SIGNAL("valueChanged(double)"), 
                     self.kmlview.setChangeRoll)
        self.connect(self.PitchSpinBox, SIGNAL("valueChanged(double)"), 
                     self.kmlview.setChangePitch)
        self.connect(self.HandlingSpinBox, SIGNAL("valueChanged(double)"), 
                     self.kmlview.setChangeHead)
        self.connect(self.ZoomSpinBox, SIGNAL("valueChanged(double)"), 
                     self.kmlview.setChangeZoom)
        self.connect(self.RangeSpinBox, SIGNAL("valueChanged(double)"), 
                     self.kmlview.setChangeRange)
        self.connect(self.actionSavekml, SIGNAL("triggered()"), 
                     self.kmldialog)
    """
    
    def showPreferences(self):
        self.prefsWindow_.show()
        

    def processdata(self):
        self.datawin.show()
    
    
    def dataprocess(self):
        self.DataW.show()
        #self.compass.show()
    
    
    def GrassShell(self):
        if Utils.haveGRASS_ != 0:
            self.Gshell.show()
    
        
    def kmldialog(self):
        self.kmlview.show()
     
    def SEpsg(self):
        #self.searchepsg = SearchEpsg()
        self.epsgWindow.show()
    
    
    def Geom(self):
        self.vectoroperation.show()
            
    def pgsetting(self):
        self.pgconn = PgConn()
        self.pgconn.show()

    def worningmessage(self,text):
        self.worn = WarnMsgWindow()
        self.worn.label.setText(text)
        self.worn.show()
                                     
#    def showPreference(self):
#        self.preferencesetting = PreferencesWindow()
#        
        
    def selectcmd(self,index):
        #global setcmd
        self.setcmd = self.w.gcmd.itemText(index)
        return self.setcmd

    def addLayer(self):
        count = self.layerTable.rowCount()
        self.rasterCombo.clear()
        for j in xrange(1):
            for i in xrange(count):
                cell = self.layerTable.item(i,j)
                if cell and cell.checkState() == 2:
                
                    self.rasterCombo.addItem(cell.text())
        # cell = self.layerTable.item(i, 0)
#            if cell.checkState() == 2:
 #               while 1:
  #                  try:
   #                     s = read_command('r.what', input=cell.text(), east_north=lonlat)
    def addRasterLayer(self):
        try:
            pp = str(parseOutputconf()['pport'])
            dp = str(parseOutputconf()['dport'])
            host = str(parseOutputconf()['host']).split()
            #print host, dp, pp
            for item in self.layerTable.selectedItems():
                lname = item.text()
                #print host
                for i in host :
                    #print i
                    try:
                        run_command('./grass_script/r.planet.py', 
                                    flags = 'a', 
                                    map = lname, 
                                    host = str(i), 
                                    dport = dp, pport = pp )
                    except IOError:
                        time.sleep(0.1)

        except IOError:
            time.sleep(0.1)
        print 'add', lname
    
        
    def removeraster(self):
        while 1:
            try:
                run_command('r.planet.py', flags = 'r', map = inputR, host = str(parseOutputconf()['host']), dport = parseOutputconf()['dport'], pport = parseOutputconf()['pport'])
                break
            except IOError:
                time.sleep(0.1)
        print 'removed', inputR
    
        
    def addvector(self):
        database_name = parseOutputconf()['spatialitedb']
        print database_name
        while 1:
            try:
                print inputV
                mapset = getEnv()['MAPSET']
                #instruction = "v.planet.py -a map='%s'@'%s' brush=111,111,111 pen=111,111,111 size=1,1 fill=0 "  % (inputV, mapset)
                #print instruction
                #os.system(instruction)
                #PointSize = str(parseOutputconf()['PointSize'])
                #LineWidth = str(parseOutputconf()['LineWidth'])
                #PenColor = str(parseOutputconf()['PenColor'])
                #BrushColor = str(parseOutputconf()['BrushColor'])
                Thickness = parseOutputconf()['Thickness']
                Fill = parseOutputconf()['Fill']
                PointSize = self.w.PointSize.text()
                LineWidth = self.w.LineWidth.value()
                PenColor = self.w.PenColor.text()
                BrushColor = self.w.BrushColor.text()
                
                run_command('v.planet.py', flags = 'a', map = str(inputV)+'@'+str(mapset), host = str(parseOutputconf()['host']), dport = parseOutputconf()['dport'], pport = parseOutputconf()['pport'], brush = BrushColor, pen = PenColor, size = PointSize, fill = Fill)
                break
            except IOError:
                time.sleep(0.2)
        print 'add', inputV
    
        
    def removevector(self):
        while 1:
            try:
                #mapsets = read_command('g.mapsets', flags ='l')
                #mapsets.replace('\n','').split()
                #for i in mapsets :
                #    print inputV+str(i)
                #    run_command('v.planet.py', flags = 'r', map = inputV+'@'+str(i), dport = 8000, pport = 7000)
                mapset = getEnv()['MAPSET']
                run_command('v.planet.py', flags = 'r', map = str(inputV)+'@'+str(mapset), host = str(parseOutputconf()['host']), dport = parseOutputconf()['dport'], pport = parseOutputconf()['pport'])
                time.sleep(0.1)
                break
            except IOError:
                time.sleep(0.1)
        print 'removed', inputV

    def selectraster(self,index):

        inputR = self.rasterCombo.itemText(index)
        return inputR
        
    def selectvector(self,index):
        global inputV
        inputV = self.w.GrassVLayer.itemText(index)
        return inputV
    def refreshlayer(self):
        vector = VectorList()
        raster = RasterList()
        self.GrassRLayer.clear()
        self.GrassVLayer.clear()
        self.GrassRLayer.addItems(raster)
        self.GrassVLayer.addItems(vector)
        
    def showrenderoptions(self):
        if self.renderoptions.isChecked():
            self.grassvectoroption.show()
        else :
            self.grassvectoroption.hide()

    def getRenderOptions(self):
        PointSize = self.w.PointSize.text()
        LineWidth = self.w.LineWidth.value()
        PenColor = self.w.PenColor.text()
        BrushColor = self.w.BrushColor.text()
        #Tikchness = self.w.Tikchness.text()
        print PointSize, LineWidth, PenColor, BrushColor
       

    def commandlist(self):
        grassCmd = []
        grassCmd = GetGRASSCmds()
        #grassCmd.append(grassCmds)
        #grassCmds = self.GetGRASSCmds(bin = False)
        #grassCmd.append(grassCmds)
        return grassCmd
                
# Refresh SQLite
        

    

    
        
    def setplacezonecoords(self,index):
        Placename = self.placezone.itemText(index)
        st = unicode(Placename)
        st = st.split(' ')
        try :
            lat = st[-2]
            lon = st[-1]
            self.Lon.setText(lon)
            self.Lat.setText(lat)
        except :
            pass
    
        
    def gettablelist(self):
        #database_name = sqlitedb
        database_name = parseOutputconf()['spatialitedb']
        #xprint database_name
        db_connection = None
        try :
            db_connection = sqlite3.connect(database_name)
        except :
            self.worningmessage('spatialitedb not found')
        if db_connection is not None:
            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
    
    def SEpsg(self):
        self.searchepsg = SearchEpsg()
        self.searchepsg.show()

# Quit Application
        
    def quitAll(self):
        print "Good Bye, PlanetSasha"
        qApp.quit()
    
    
    def Geom(self):
        self.vectoroperation.show()
    

    def aggiorna(self):
        newlon = str(self.Lon.text())
        newlat = str(self.Lat.text())
        #'''
        try :
            if self.ViewType == 'LookAt':
                newlon = str(self.lookatLon.text())
                newlat = str(self.lookatLat.text())
                #xprint 'query mode set to LookAt'
        except :
            print 'query mode set to eye' #xprint
        #'''
        self.longitude.setText(newlon)
        self.latitude.setText(newlat)

    def getrasterstate(self):
        raster = RasterList()
        rast = len(raster)
        rastertoquery = []
        valori = []
        newlon = str(self.longitude.text())
        newlat = str(self.latitude.text())
        lonlat = str(newlon)+' '+str(newlat)
        f = tempfile.NamedTemporaryFile(delete=False)
        coordsfile = f.name
        f.write(lonlat)
        f.flush()
        f.close
        while 1:
            try:
                c = read_command('m.proj', input=coordsfile, flags='i')
                break
            except IOError:
                time.sleep(0.1) 
        os.unlink(f.name)
        lonlat = parse_key_val(c,'\t')
        lonlat = str(lonlat)
        lonlat = lonlat.replace('{','')
        lonlat = lonlat.replace('}','')
        lonlat = lonlat.replace("'",'')
        lonlat = lonlat.replace(':','')
        lonlat = lonlat.replace('|',' ')
        lonlat = lonlat.split(' ')
        lonlat = str(lonlat[0])+','+str(lonlat[1])
        htmlquery = []
        html = """<TABLE cellpadding="4" style="border: 1px solid \
        000000; border-collapse: collapse;" border="1"><TR><TD>Layer</TD>\
        <TD>Values</TD>"""
        htmlquery.append(html)
        for i in range(rast):
            cell = self.layerTable.item(i, 0)
            if cell.checkState() == 2:
                while 1:
                    try:
                        s = read_command('r.what', input=cell.text(), east_north=lonlat) 
                        break
                    except IOError:
                        time.sleep(0.1)
                attr = str(s)
                attr = attr.replace("|",' ')
                attr = attr.replace('\n',' ')
                attr = attr.split(':')
                attr = str(attr)
                attr = attr.replace("'",'')
                attr = attr.replace('"','')
                attr = attr.replace('[','')
                attr = attr.replace(']','')
                results = str(cell.text())+'  : '+attr
                htmlvalue = '<TR><TD>%s</TD><TD>%s</TD>' % (cell.text() ,attr)
                htmlquery.append(htmlvalue)
                rastertoquery.append(results)
        htmlend = """</TR></TABLE>"""
        htmlquery.append(htmlend)
        rastertoquery = str(rastertoquery)
        rastertoquery = rastertoquery.replace("'",'')
        rastertoquery = rastertoquery.split(',')
        rastertoquery = str(rastertoquery)
        rastertoquery = rastertoquery.replace('[','')
        rastertoquery = rastertoquery.replace(']','')
        htmlquery = str(htmlquery)
        htmlquery = htmlquery.replace("', u'",'')
        htmlquery = htmlquery.replace("']",'')
        htmlquery = htmlquery.replace("['",'')
        htmlquery = htmlquery.replace("', '",'')
        self.QueryResultsRaster.setText(htmlquery)
        #xprint rastertoquery

    def getvectorstate(self):
        vector = VectorList()
        vect = len(vector)
        vectortoquery = []
        newlon = str(self.longitude.text())
        newlat = str(self.latitude.text())
        lonlat = str(newlon)+' '+str(newlat)
        f = tempfile.NamedTemporaryFile(delete=False)
        coordsfile = f.name
        f.write(lonlat)
        f.flush()
        f.close
        while 1:
            try:
                c = read_command('m.proj', input=coordsfile, flags='i') 
                break
            except IOError:
                time.sleep(0.1)
        os.unlink(f.name)
        lonlat = parse_key_val(c,'\t')
        lonlat = str(lonlat)
        lonlat = lonlat.replace('{','')
        lonlat = lonlat.replace('}','')
        lonlat = lonlat.replace("'",'')
        lonlat = lonlat.replace(':','')
        lonlat = lonlat.replace('|',' ')
        lonlat = lonlat.split(' ')
        lonlat = str(lonlat[0])+','+str(lonlat[1])
        htmlquery = []
        html = """<TABLE cellpadding="4" style="border: 1px solid \
        000000; border-collapse: collapse;" border="1"><TR>\
        <TD>Layer</TD><TD>Values</TD>"""
        htmlquery.append(html)
        for i in range(vect):
            cell = self.layerTable.item(i, 1)
            if cell.checkState() == 2:
                while 1:
                    try:
                        s = read_command('v.what', map=cell.text(), east_north=lonlat)
                        break
                    except IOError:
                        time.sleep(0.1)
                attr = parse_key_val(s,':')
                attr = str(attr)
                attr = attr.replace('{','')
                attr = attr.replace('}','')
                attr = attr.replace("'",'')
                attr = attr.replace(': None','')
                htmlvalue = '<TR><TD>%s</TD><TD>%s</TD>' % (cell.text() ,attr)
                htmlquery.append(htmlvalue)
                #xprint attr
        htmlend = """</TR></TABLE>"""
        htmlquery.append(htmlend)
        htmlquery = str(htmlquery)
        htmlquery = htmlquery.replace("', u'",'')
        htmlquery = htmlquery.replace("']",'')
        htmlquery = htmlquery.replace("['",'')
        htmlquery = htmlquery.replace("', '",'')
        htmlquery = htmlquery.replace(",",'<BR>')
        self.QueryResultsVector.setText(str(htmlquery))
    
# Set Toolbar Action
    
    def GPSunceckbuttons(self):
        Utils.preferences().setSettings('actionGPS',self.actionT_GPS.isChecked())
        self.actionT_LonLat.setChecked(False)
        if Utils.haveGRASS_ != 0:
            self.actionT_Grass.setChecked(False)
        #TBD
        """
        if self.actionJoystick.isChecked():
            self.joy.stop()
            self.actionJoystick.setChecked(False)
        """    
        if self.actionT_HW.isChecked():
            self.hw.stop()
            self.actionT_HW.setChecked(False)
        #if self.actionSerial.isChecked():
    
    #renamed from LonLatunceckbuttons
    def onTActionLonLat(self):

        checked = not self.actionT_LonLat.isChecked()
        self.actionT_Broadcast.setChecked(checked)
        Utils.preferences().setSettings('actionLonLat', checked )
        
        if self.actionT_GPS.isChecked():
            self.gpsx.stop()
            self.actionT_GPS.setChecked(False)
        if Utils.haveGRASS_ != 0:
            self.actionT_Grass.setChecked(False)
        #if self.actionJoystick.isChecked():
        #    self.joy.stop()
        #    self.actionJoystick.setChecked(False)
        if self.actionT_HW.isChecked():
            self.hw.stop()
            self.actionT_HW.setChecked(False)

    #renamed from serialunceckbuttons
    def onTActionBroadCast(self):
        checked = self.actionT_Broadcast.isChecked()
        print checked
        self.actionT_Broadcast.setChecked(checked)
        Utils.preferences().setSettings('actionBroadcast', checked )
        self.actionT_GPS.setChecked(False)
        self.actionT_LonLat.setChecked(False)
        if Utils.haveGRASS_ != 0:
            self.actionT_Grass.setChecked(False)
        #self.actionJoystick.setChecked(False)
        self.actionT_HW.setChecked(False) 
        if self.navwin:
            self.navwin.toogleBroadCast(self.actionT_Broadcast.isChecked())
        else:
            print 'nav win not created'       
    
    
    def Grassunceckbuttons(self):
        if self.actionGPS.isChecked():
            self.gpsx.stop()
            self.actionGPS.setChecked(False)
        self.actionLonLat.setChecked(False)
        if self.actionJoystick.isChecked():
            self.joy.stop()
            self.actionJoystick.setChecked(False)
        if self.actionHW.isChecked():
            self.hw.stop()
            self.actionHW.setChecked(False)
    
    
    def Joyunceckbuttons(self):
        self.actionGPS.setChecked(False)
        self.actionLonLat.setChecked(False)
        if Utils.haveGRASS_ != 0:
            self.actionGrass.setChecked(False)
        self.actionHW.setChecked(False)
    



    def Serialunceckbuttons2(self):
        self.actionGPS.setChecked(False)
        self.actionLonLat.setChecked(False)
        if Utils.haveGRASS_ != 0:
            self.actionGrass.setChecked(False)

    def startstopjoy(self):
        if self.actionJoystick.isChecked():
            self.joy = logJ()
            self.joy.start()
            #xprint 'i am self jcords', self.Jcoords()
            self.joy.toggle(self.Jcoords()[0],self.Jcoords()[1])
            self.connect(self.Lon, SIGNAL("textChanged(QString)"), self.joy.setValueLonJ)
            self.connect(self.Lat, SIGNAL("textChanged(QString)"), self.joy.setValueLatJ)
            self.SetJoyCoords()
            self.Lon.setText(self.Lon.text())
            self.Lat.setText(self.Lat.text())
            #xprint self.Lon.text(), self.Lat.text()
        else :
            self.joy.stop()
            
    
    
    def stopstartjoy(self):
        if not self.actionJoystick.isChecked():
            self.joy = logJ()
            self.joy.stop()
            self.joy.toggle(0,0)
            
    


    def startstopHW(self):
        if self.actionHW.isChecked():
            self.hw = HWS()
            self.hw.start()
            self.hw.ValUpdated.connect(self.textHW.setText)
            self.hw.toggle()
        else :
            #self.hw = HWS()
            self.hw.stop()

    def stopstartHW(self):
        if not self.actionHW.isChecked():
            self.hw = HWS()
            self.hw.stop()
            self.hw.toggle()
    
    """
    MV moved to navwindow
    def startstoplog(self):
        if self.actionBroadcast.isChecked():
            self.log = logS()
            self.log.start()
            self.log.LonUpdated.connect(self.Lon.setText)
            self.log.LatUpdated.connect(self.Lat.setText)
            self.log.RollUpdated.connect(self.RollSpinBox.setValue)
            self.log.PitchUpdated.connect(self.PitchSpinBox.setValue)
            self.log.GainUpdated.connect(self.HandlingSpinBox.setValue)
            self.log.AltUpdated2.connect(self.Alt.setText)
            self.log.AltUpdated.connect(self.ZoomSpinBox.setValue)
            self.log.LookAtLonUpdated.connect(self.lookatLon.setText)
            self.log.LookAtLatUpdated.connect(self.lookatLat.setText)
            self.log.LookAtAltitudeUpdated.connect(self.lookatAlt.setText)
            self.log.LookAtRangeUpdated.connect(self.RangeSpinBox.setValue)
            
            self.log.toggle()
        else :
            self.log.stop()
    
    
    def stopstartlog(self):
        if not self.actionBroadcast.isChecked():
            self.log = logS()
            self.log.stop()
            self.log.toggle()
    
    """
    
    def startstopGt(self):
        if self.gcmdexec.isChecked():
            self.gt = gt(self.setcmd)
            self.gt.start()
            self.gt.toggle()
        else :
            self.gt.stop()
            
    def stopstartGt(self):
        if not self.gcmdexec.isChecked():
            self.gt = gt(self.setcmd)
            self.gt.stop()
            self.gt.toggle()
    


    def startstopgpsx(self):
        if self.actionGPS.isChecked():
            #self.gpsx = GpsT()
            self.gpsx.start()
            self.gpsx.GPSlatitude.connect(self.GPSlat.setText)
            self.gpsx.GPSlongitude.connect(self.GPSlon.setText)
            self.gpsx.GPStime.connect(self.GPSTime.setText)
            self.gpsx.GPSutctime.connect(self.GPSUtctime.setText)
            self.gpsx.GPSaltitude.connect(self.GPSAltitude.setText)
            self.gpsx.GPSspeed.connect(self.GPSSpeed.setText)
            self.gpsx.GPStrack.connect(self.GPSTrack.setText)
            self.gpsx.GPSclimb.connect(self.GPSClimb.setText)
            self.gpsx.GPSeph.connect(self.GPSEph.setText)
            self.gpsx.GPSept.connect(self.GPSEpt.setText)
            self.gpsx.GPSepv.connect(self.GPSEpv.setText)
            self.gpsx.GPSepd.connect(self.GPSEpd.setText)
            self.gpsx.GPSepc.connect(self.GPSEpc.setText)
            self.gpsx.GPSeps.connect(self.GPSEps.setText)
            self.gpsx.GPSpdop.connect(self.GPSPdop.setText)
            self.gpsx.GPShdop.connect(self.GPSHdop.setText)
            self.gpsx.GPSvdop.connect(self.GPSVdop.setText)
            self.gpsx.GPStdop.connect(self.GPSTdop.setText)
            self.gpsx.GPSgdop.connect(self.GPSGdop.setText)
            self.gpsx.GPSsat.connect(self.Satellite.setText)
            #xprint self.GPSlat.text()
            #print 'qualcosa'
            #if head == str('Manual'):
            #    heads = self.HandlingSlider.value()
            #if head == str('Auto'):
            #    heads = self.GPSTrack
            #print heads
            head = 'Manual'
            self.gpsx.toggle()
        else :
            self.gpsx.stop()
    
    
    def stopstartgpsx(self):
        if not self.actionGPS.isChecked():
            self.gpsx = GpsT()
            #self.gpsx.wait()
            self.gpsx.stop()
            self.gpsx.toggle()
    
    

    def modeldialog(self):
        self.placemodel.show()
    
# Hide/Show widget
    

    def hidetool(self):
        if self.actionHideSlider.isChecked():
            self.tabWidget.show()
        else :
            self.tabWidget.hide()    
    
            

    def SetJoyCoords(self):
        if self.actionJoystick.isChecked():
            a = self.Lon.text()
            b = self.Lat.text()
            aa = float(a) + 1
            bb = float(b) + 1
            self.Lon.setText(str(aa))
            self.Lat.setText(str(bb))
            self.Lon.setText(str(a))
            self.Lat.setText(str(b))
 def showMapWindow(self):
     self.mapwin =  MapWindow()
     self.mdiArea.addSubWindow(self.mapwin)
     self.mapwin.show()
Exemple #4
0
class ImportWindow(QWizard, Ui_ImportWindow):
    GN = 'GeoNetwork'
    GP = 'GeoPortal'
    TH = 'Thredds'
    def __init__(self, mdi):
        QWidget.__init__(self)
        self.setupUi(self)

        self.resize(752,497)

        self.mdi = mdi

        self.xmlMap = dict()

        self.debug = 1
        self.url_prefix = '/thredds/'
        
        self.datalist = []
        
        #self.datac= [][]
   	    #imgQ = ImageQt.ImageQt(img)
        pixMap = QPixmap.fromImage(QImage("gui/images/qgis_world.png"))
        self.dslist = []
        scene = QGraphicsScene()
        self.graphicsView.setScene(scene)
        pixMap = pixMap.scaled(QSize(400,200))
        scene.addPixmap(pixMap)               
        self.graphicsView.repaint()
        self.graphicsView.show()

        self.treeView.setEditTriggers(QTreeView.NoEditTriggers)

        self.treeView.setSelectionMode(  QAbstractItemView.ExtendedSelection  )
        
        self.bboxWidget.setLayout(self.bboxLayout)
        #self.treeView.setSelectionMode(QAbstractItemView.MultiSelection)

        self.btAddTo.clicked.connect(self.onAddToList)
        
        self.button(QWizard.NextButton).clicked.connect(self.onNextPage)
        self.button(QWizard.FinishButton).clicked.connect(self.onClose)
        self.cmbService.currentIndexChanged.connect(self.onToggleBBox)
        self.treeView.doubleClicked.connect(self.onSelect)

    def getDatasetBaseFromTree(self, item):
        a = item
        b = []

        b.append("/")
        while a.parent():
            b.append(str(a.text()))
            b.append("/")
            a = a.parent()
            
        cc = ""
        ##print b
        ##print "here"
        
        i  = len(b) - 1
        ww = 0
        while i > -1:
            if ww == 1:
                qq = b[i]
                cc = cc + qq.lower()
            else:
                cc = cc + b[i]
            i = i - 1
            ww = ww + 1
        ##print cc
        #cc = cc[:-1]
        #print cc
        return cc[:-1]
        
        #return b

    def onAddToList(self):
        for index in self.treeView.selectedIndexes():
            item = self.model.itemFromIndex(index)
            self.urlbase = "http://www.smast.umassd.edu:8080/thredds/"
            self.catalogbase = "dodsC/models/"
            ##self.datasetbase = 
            #http://www.smast.umassd.edu:8080/thredds/fileServer/models/
            if not item.hasChildren() and item.text() != '--Fetch--':
                itemtext = self.urlbase + self.catalogbase + self.getDatasetBaseFromTree(item)
                ##print itemtext
                self.lmodel.appendRow(QStandardItem(itemtext))
                dataset = Dataset(itemtext, self.bbox)
                self.datalist.append(dataset)
                #print self.datalist

           
    def onSelect(self, index):
        item = self.model.itemFromIndex(index)
        
        if item.text() == '--Fetch--': #PSasha.FETCH_TEXT
            item.setText('Fetching data..')
            pindex = self.model.parent(index)
            pitem = self.model.itemFromIndex(pindex)
            
            ptext  = str(pitem.text())
            urlN = str(self.xmlMap[ptext])
            
            #if not urlN.startswith('/thredds'):
            #    urlN =  self.url_prefix + urlN
            #print urlN
            #print ptext
            
            self.fetchTHData(urlN, pitem)

            #pparent = self.model.itemFromIndex(pindex.parent())
            #if pparent:
            #    print pparent.text() + 'xxxxxxy'
            #    print ptext + 'yyzzz'




            #prefix = urlN.rsplit('/',1)[0]
            ##print prefix
            #if not prefix.endswith('.xml'):
            #    self.url_prefix = prefix + '/'
            #
            #print self.url_prefix
 
            #remove fetching data text...


    def fetchTHData(self, urlnext ='thredds/catalog.xml', rootItem = None):

        #if urlnext.startswith('/thredds'):
        #    url = urlparse.urljoin(self.url_base, urlnext)
        #else:    
        #    url = urlparse.urljoin(self.url_base, '/thredds/' + urlnext)
        if urlnext == 'thredds/catalog.xml':
            url = urlparse.urljoin(self.url_base, urlnext)
        else:    
            url = urlnext
        #print url

        xml = ''
        try:
            xml= urllib2.urlopen(url)
        except:
            print 'error:' + url
            if rootItem is not None:
                rootItem.child(0).setText('?? error ??')
                #TODO show the error on a error window in ui
                return

        tree = et.parse(xml)
        root = tree.getroot()
        
        #print 'Fetching data from ' + url
        for dataset in root.iter('{http://www.unidata.ucar.edu/namespaces/thredds/InvCatalog/v1.0}dataset'):
            
            dsname = dataset.get('name')
            #dataset.get('ID')
            urlPath = dataset.get('urlPath')
            if urlPath is not None:
                item = QStandardItem(dsname)
                item.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)  
                if rootItem is None:
                   self.model.appendRow(item)
                else:
                    rootItem.appendRow(item)
         
                        
        for catalogref in root.iter('{http://www.unidata.ucar.edu/namespaces/thredds/InvCatalog/v1.0}catalogRef'):
            href = catalogref.get('{http://www.w3.org/1999/xlink}href')
            title = catalogref.get('{http://www.w3.org/1999/xlink}title')
            
            if href is None:
                return  #FIXME needs testing and may need to change to continue or break
            
            url_key = ''
            if rootItem:
                prev = self.xmlMap[str(rootItem.text())]
                
                prev = prev.rsplit('/',1)[0]
                if href.startswith('/thredds'):
                    url_key = prev + '/' + href[8:]
                else:
                    url_key = prev + '/' + href   
            else:
                if not href.startswith('/thredds'):
                    url_key = self.url_base + '/thredds/' + href
                else:
                    url_key = self.url_base + href

            #print url_key
            self.xmlMap[title] = url_key
            #if self.debug == 2:
            #print title + "::" + self.xmlMap[title]
               
            item = QStandardItem(title)
            item.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)  
            item.appendRow(QStandardItem('--Fetch--'))
            loadIcon = QIcon()
            loadIcon.addPixmap(QPixmap(":/icons/icons/loading.gif"), QIcon.Normal, QIcon.Off)
            item.setIcon(loadIcon)

            if rootItem is None:
                self.model.appendRow(item)
            else:
                rootItem.appendRow(item)
        
        if rootItem is not None:
            rootItem.removeRow(0)

        return
       
    def onToggleBBox(self):
    
        if self.cmbService.currentIndex() == 1:
            self.bboxWidget.hide()
        else:
            self.bboxWidget.show()

    def validate(self):

        return 0
        
        
    def onNextPage(self):
        
        url_i = self.cmbUrl.currentIndex()
        type_i = self.cmbType.currentIndex()
        service_i = self.cmbService.currentIndex()
        if url_i < 1 or type_i < 1 or service_i < 1:
            print 'select url, type, service.'
            #return None
            
        self.url_s = str(self.cmbUrl.currentText())
        self.type_s = self.cmbType.currentText()
        self.service_s = self.cmbService.currentText()
        E = self.txtE.text()
        S = self.txtS.text()
        N = self.txtN.text()
        W = self.txtW.text()
        self.bbox = []
        self.bbox.append(str(E))
        self.bbox.append(str(S))
        self.bbox.append(str(N))
        self.bbox.append(str(W))
        self.keywords = None
        self.maxrec = None
        self.row = 0
        self.col = 0
        
        self.model = QStandardItemModel(self)
        self.treeView.setModel(self.model)
 
        self.lmodel = QStandardItemModel(self)
        self.listView.setModel(self.lmodel)
        
        self.type_s = ImportWindow.TH #D code
        #self.url_s = 'http://www.smast.umassd.edu:8080/thredds'
        urlinfotext = 'Catalog Home: ' + self.url_s
        self.lblInfo.setText(urlinfotext)
        
        
        self.url_base = self.url_s.rsplit('/',1)[0]
        if self.type_s == ImportWindow.GN:
            self.fetchGNData()
        elif self.type_s == ImportWindow.GP:
            self.fetchGCData()
        if self.type_s == ImportWindow.TH:
            xmlfile = 'offline.xml'
            try:
                with open(xmlfile) as xfile:
                    self.readTHData(xfile)
            except IOError:
                print 'No cache exists. Fetching from:' + self.url_s
                self.fetchTHData()

    def readTHData(self, xfile):
        x = 1

    def getResource(self, endpoint = 'http://www.nodc.noaa.gov/geoportal/csw', bbox=None, keywords=None, maxrecords=1, service_type='opendap', verbose=None):
        if service_type == 'opendap':
            service_string='urn:x-esri:specification:ServiceType:OPeNDAP'
        if service_type == 'wms':
            service_string='urn:x-esri:specification:ServiceType:WMS'
        csw = CatalogueServiceWeb(endpoint,timeout=30)
        if keywords is not None:
            csw.getrecords(keywords=keywords, bbox=bbox, maxrecords=maxrecords)
        else :
            csw.getrecords(bbox=bbox, maxrecords=maxrecords)
        csw.records.keys()
        result = {}
        for i in csw.records.keys():
            records=csw.records[i]
            resource = {}
            for key,rec in csw.records.iteritems():
                url = next((d['url'] for d in rec.references if d['scheme'] == service_string), None)
                print rec.references[0]['url']
                if url is not None:
                    resource[rec.title] = url
            result[i] = resource
        if verbose is not None:
            print 'endpoint: ', endpoint, '\n' , 'bbox: ', bbox, '\n' , 'keywords: ', keywords, '\n', 'maxrecords: ', maxrecords , '\n', 'service_type: ' , service_type
        return result

    #endpoint = 'http://www.smast.umassd.edu:8080/thredds/catalog.xml'
    #bbox = [-71.5, 39.5, -63.0, 46]
    #keywords = ['temperature']
    #maxrecords = 20
    #service_type = 'opendap'
    #res = getResource(endpoint=endpoint, bbox=bbox, keywords=keywords, maxrecords=maxrecords)
    #print res.keys()[0]

    #csw = CatalogueServiceWeb(endpoint)




            
        
    def fetchGNData(self):
    
        xml = self.url_s + "/thredds.xml"
        
    def fetchGPData(self):
    
        xml = self.url_s + "/thredds.xml"     
        
    def onClose(self):
        print 'wizard finished'
        f = open('offline1.xml','w')
        f.write('<root>\n\t')
        f.write('<catalog>\n\t<name>')
        node1 = self.model.item(0,0)
        f.write(str(node1.text()))
        f.write('</name>\n\t')

        cn = self.getChildNodes(node1)
        for c in cn:
            #if c.hasChilren():

            f.write('<catalog>\n\t<name>')
            f.write( str( c.text() ) )
            f.write('</name>\n')
            f.write('</catalog>\n')

        f.write('\t</catalog>\n')
        f.write('</root>')
        self.mapwin =  MapWindow(self.datalist)
        #FIXME
        self.mdi.addSubWindow(self.mapwin)
        self.mapwin.show()       
        
        self.accept()
        self.done(QDialog.Accepted)
        self.close()

       


    def writenode(self, cn):

        #for r in xrange(self.model.rowCount()):
        #    item = self.model.item(r,0)
        #    self.getChildNodes(item)
#            while item.hasChildren():
#                txt =str(item.text())
#                print txt
#                f.write('<cref>' + txt  + '</cref>')
#                item = item.child(0)
#
        f.close()
        self.close()
         
    def getChildNodes(self, pnode):
        cnodes = []
        #print pnode.rowCount()
        for r in xrange(pnode.rowCount()):    
            cnodes.append( pnode.child(r) )
        return cnodes