# -*- coding: utf-8 -*-99

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
import sys, locale, math
import helmert2d.tools.utils
from helmert2d.tools.point import Point
from helmert2d.tools.helmert2dbuilder import Helmert2dBuilder
from helmert2d.tools.helmert2dtransformation import Helmert2dTransformation
from helmert2d.tools.doTransformationStatistics import TransformationStatistics
from helmert2d.tools.doExportTransformationParameters import ExportTransformationParameters
from helmert2d.tools.doTransint import Transint


from Ui_helmert2d import Ui_Helmert2dDialog

class Helmert2dDialog(QDialog, Ui_Helmert2dDialog):

    def __init__(self, parent, iface, version):
        QDialog.__init__(self, parent)
        self.setupUi(self)
        
        self.iface = iface
        self.version = version
        
        self.checkedPoints = 0
        self.controlpoints = None
        self.transformationParameters = None            
        self.transformedControlpoints = None
            
        self.settings = QSettings("CatAIS","helmert2d")
        self.outputdir = self.settings.value("outputdir")


    def initGui(self):
        # **** Data (Control points) Tab ****
        vlayers = helmert2d.tools.utils.getLayerNames([0])
        vlayers.sort()
        vlayers.insert(0, "-------------------")
        self.globalLayerCBox.addItems(vlayers)
        self.localLayerCBox.addItems(vlayers)
        
        if len(vlayers) == 1:
            self.identifyBtn.setDisabled (True)
        
        self.sansFont = QFont("Ubuntu", 9)
        self.sansFont.setStyleHint(QFont.SansSerif)
        
        self.tableWidget.clear()
        self.tableWidget.setColumnCount(8)
        self.tableWidget.setColumnWidth(0, 45)
        self.tableWidget.setColumnWidth(1, 85)
        self.tableWidget.setColumnWidth(2, 85)
        self.tableWidget.setColumnWidth(3, 85)        
        self.tableWidget.setColumnWidth(4, 85)
        self.tableWidget.setColumnWidth(5, 85)
        self.tableWidget.setColumnWidth(6, 65)                
        self.tableWidget.setColumnWidth(7, 65) 
        
        item = QTableWidgetItem()
        item.setFont(self.sansFont)
        item.setText("use it")
        self.tableWidget.setHorizontalHeaderItem(0, item)
        
        item = QTableWidgetItem()
        item.setFont(self.sansFont)
        item.setText("Control point")
        self.tableWidget.setHorizontalHeaderItem(1, item)

        item = QTableWidgetItem()
        item.setFont(self.sansFont)
        item.setText("X local")
        self.tableWidget.setHorizontalHeaderItem(2, item)
        
        item = QTableWidgetItem()
        item.setFont(self.sansFont)
        item.setText("Y local")
        self.tableWidget.setHorizontalHeaderItem(3, item)        
        
        item = QTableWidgetItem()
        item.setFont(self.sansFont)
        item.setText("X global")
        self.tableWidget.setHorizontalHeaderItem(4, item)
        
        item = QTableWidgetItem()
        item.setFont(self.sansFont)
        item.setText("Y global")
        self.tableWidget.setHorizontalHeaderItem(5, item)             
        
        item = QTableWidgetItem()
        item.setFont(self.sansFont)
        item.setText("vx")
        self.tableWidget.setHorizontalHeaderItem(6, item)
        
        item = QTableWidgetItem()
        item.setFont(self.sansFont)
        item.setText("vy")
        self.tableWidget.setHorizontalHeaderItem(7, item)             
        
        
        # **** Transformation Tab ****
        # Add the available transformation types.
        self.comboTransformationType.addItem("Helmert (2 - 4 Parameter)",  QVariant(1))
        self.comboTransformationType.addItem("Affin (6 Parameter)",  QVariant(2))


        # **** TransInt Tab ****
        vlayers = helmert2d.tools.utils.getLayerNames([0, 1, 2])
        vlayers.sort()
        vlayers.insert(0, "-------------------")
        self.comboProcessLayer.addItems(vlayers)
        
        if len(vlayers) == 1:
            self.transintBtn.setDisabled (True)
        
        self.comboInterpolationMethod.addItem("Inverse distance",  QVariant(1))
        self.comboInterpolationMethod.addItem("Average",  QVariant(2))
        self.comboInterpolationMethod.addItem("Nearest neighbor",  QVariant(3))
        
        
        # **** Settings Tab ****
        # Set outputdir from settings
        self.lineEditExportData.setText( self.settings.value("outputdir").toString() )         



    def test1(self):
        self.globalLayerCBox.setCurrentIndex(1)
        self.globalIdentifierCBox.setCurrentIndex(1)        
        self.localLayerCBox.setCurrentIndex(2)
        self.localIdentifierCBox.setCurrentIndex(1)     



    @pyqtSignature("on_cBInterpolateLayer_clicked()")      
    def on_cBInterpolateLayer_clicked(self):    
        if self.cBInterpolateLayer.isChecked():
            self.gBInterpolationSettings.setEnabled(True)
        else:
            self.gBInterpolationSettings.setEnabled(False)



    @pyqtSignature("on_comboInterpolationMethod_currentIndexChanged(int)")      
    def on_comboInterpolationMethod_currentIndexChanged(self, idx):    
        self.interpolationMethod = self.comboInterpolationMethod.itemData(idx).toInt()[0]
        
        
        
    @pyqtSignature("on_comboTransformationType_currentIndexChanged(int)")      
    def on_comboTransformationType_currentIndexChanged(self, idx):    
        self.transType = self.comboTransformationType.itemData(idx).toInt()[0]
        if self.transType == 1:
            self.labelParameterE.setEnabled(False)
            self.labelParameterF.setEnabled(False)
            self.lineEditParameterE.setEnabled(False)
            self.lineEditParameterF.setEnabled(False)
            self.cbEstimateScale.setEnabled(True)
            self.cbEstimateRotation.setEnabled(True)
            self.labelEstimateScale.setEnabled(True)
            self.labelEstimateRotation.setEnabled(True)            
            
            self.labelParameterY0.setEnabled(True)
            self.labelParameterX0.setEnabled(True)
            self.labelParameterRotation.setEnabled(True)
            self.labelParameterScale.setEnabled(True)
            self.lineEditParameterY0.setEnabled(True)
            self.lineEditParameterX0.setEnabled(True)
            self.lineEditParameterRotation.setEnabled(True)
            self.lineEditParameterScale.setEnabled(True)
            
        elif self.transType == 2:
            self.labelParameterE.setEnabled(True)
            self.labelParameterF.setEnabled(True)
            self.lineEditParameterE.setEnabled(True)
            self.lineEditParameterF.setEnabled(True)
            self.cbEstimateScale.setEnabled(False)
            self.cbEstimateRotation.setEnabled(False)
            self.labelEstimateScale.setEnabled(False)
            self.labelEstimateRotation.setEnabled(False)

            self.labelParameterY0.setEnabled(False)
            self.labelParameterX0.setEnabled(False)
            self.labelParameterRotation.setEnabled(False)
            self.labelParameterScale.setEnabled(False)
            self.lineEditParameterY0.setEnabled(False)
            self.lineEditParameterX0.setEnabled(False)
            self.lineEditParameterRotation.setEnabled(False)
            self.lineEditParameterScale.setEnabled(False)
            
            
        
    @pyqtSignature("on_globalLayerCBox_currentIndexChanged(QString)")      
    def on_globalLayerCBox_currentIndexChanged(self):    
        vlayer = helmert2d.tools.utils.getVectorLayerByName(self.globalLayerCBox.currentText())

        if vlayer == None:
            self.globalIdentifierCBox.clear()
            self.globalIdentifierCBox.insertItem( 0,  "--------------------" )            
            return
            
        attrList = []
        
        provider = vlayer.dataProvider()
        fields = provider.fields()

        for i in fields:
            fieldType = fields[i].type()
            if fieldType == 6 or fieldType == 2 or fieldType == 10:
                attrList.append(str(fields[i].name()))
                
        self.globalIdentifierCBox.clear()
        self.globalIdentifierCBox.addItems(sorted(attrList))
        self.globalIdentifierCBox.insertItem( 0,  "--------------------" )
        self.globalIdentifierCBox.setCurrentIndex(0)        
        
       
       
    @pyqtSignature("on_localLayerCBox_currentIndexChanged(QString)")      
    def on_localLayerCBox_currentIndexChanged(self):    
        vlayer = helmert2d.tools.utils.getVectorLayerByName(self.localLayerCBox.currentText())

        if vlayer == None:
            self.localIdentifierCBox.clear()
            self.localIdentifierCBox.insertItem( 0,  "--------------------" )            
            return
            
        attrList = []
        
        provider = vlayer.dataProvider()
        fields = provider.fields()

        for i in fields:
            fieldType = fields[i].type()
            if fieldType == 6 or fieldType == 2 or fieldType == 10:
                attrList.append(str(fields[i].name()))
                
        self.localIdentifierCBox.clear()
        self.localIdentifierCBox.addItems(sorted(attrList))
        self.localIdentifierCBox.insertItem( 0,  "--------------------" )
        self.localIdentifierCBox.setCurrentIndex(0)    
        


    @pyqtSignature("on_identifyBtn_clicked()")    
    def on_identifyBtn_clicked(self):
        
        if self.globalLayerCBox.currentIndex() == self.localLayerCBox.currentIndex():
            QMessageBox.warning( None, "Helmert2d", "It's not possible to use the same layer twice.")
            return   

        if self.globalLayerCBox.currentIndex() == 0:
            QMessageBox.warning( None, "Helmert2d", "Please use a global layer.")
            return   

        if self.localLayerCBox.currentIndex() == 0:
            QMessageBox.warning( None, "Helmert2d", "Please use a local layer.")
            return     
      
        if self.globalIdentifierCBox.currentIndex() == 0:
            QMessageBox.warning( None, "Helmert2d", "Please use a global identifier.")
            return           
      
        if self.localIdentifierCBox.currentIndex() == 0:
            QMessageBox.warning( None, "Helmert2d", "Please use a local identifier.")
            return        

        globalLayer = helmert2d.tools.utils.getVectorLayerByName(self.globalLayerCBox.currentText())
        localLayer = helmert2d.tools.utils.getVectorLayerByName(self.localLayerCBox.currentText())
        
        if globalLayer == None or localLayer == None:
            QMessageBox.warning( None, "Helmert2d", "Should not reach here: vector layer is None" )
            return        
        
        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            # Get the controlpoints by comparing the identifier.
            self.controlpoints = helmert2d.tools.utils.getControlPointsFromVectorLayer(globalLayer, localLayer, self.globalIdentifierCBox.currentText(), self.localIdentifierCBox.currentText())
            
            if len(self.controlpoints) == 0:
                QMessageBox.warning( None, "Helmert2d", "No control points found." )
                return        

            # Fill the table with the controlpoints.
            self.updateControlPointsTable(self.controlpoints)

            # Change tab.
#            self.tabWidget.setCurrentWidget(self.tabTransformation) 
      
        except:
            QApplication.restoreOverrideCursor()
        QApplication.restoreOverrideCursor()
    


    @pyqtSignature("on_transformBtn_clicked()")    
    def on_transformBtn_clicked(self):
        self.doEstimateParameters()



    @pyqtSignature("on_transintBtn_clicked()")    
    def on_transintBtn_clicked(self):
        if self.comboProcessLayer.currentIndex() == 0:
            QMessageBox.warning( None, "Helmert2d", "No layer to transform/interpolate selected.")
            return   
            
        # Select at least transform or interpolate layer.
        if self.cBTransformLayer.isChecked() == False and self.cBInterpolateLayer.isChecked() == False:
            QMessageBox.warning( None, "Helmert2d", "No processing method found.")
            return   

        # If we want to transform the dataset, we need to find out the transformation
        # parameters first.
        if self.cBTransformLayer.isChecked() and self.transformationParameters == None:
            QMessageBox.warning( None, "Helmert2d", "No transformation parameters found.")
            return   
            
        # If we only want to interpolate (no transformation), we need at least 
        # the controlpoints.        
        if self.cBTransformLayer.isChecked() == False and self.cBInterpolateLayer.isChecked() == True:
            if self.controlpoints == None:
                QMessageBox.warning( None, "Helmert2d", "No control points found.")
                return   
            if len(self.controlpoints) == 0:
                QMessageBox.warning( None, "Helmert2d", "No control points found.")
                return   

        # Get the layer we want to transform/interpolate.
        vlayer = helmert2d.tools.utils.getVectorLayerByName(self.comboProcessLayer.currentText())
        if vlayer == None:
            QMessageBox.warning( None, "Helmert2d", "Layer not found.")
            return   
            
        d = Transint(self.iface)
        d.setVectorLayer(vlayer)
                
        if self.cBTransformLayer.isChecked():
            d.transform(self.transformationParameters)

        if self.cBInterpolateLayer.isChecked():
            if self.cBTransformLayer.isChecked():
                d.interpolate(self.transformedControlpoints)
            else:
                d.interpolate(self.controlpoints)
            d.setInterpolationMethod(self.interpolationMethod)
            d.setWeightingPower(self.sBWeightingPower.value())
            d.setSearchRadius(self.sBSearchRadius.value())
            d.setMaxPoints(self.sBMaxPoints.value())
            d.setMinPoints(self.sBMinPoints.value())
        
        d.run(self.cBAddProcessedLayer.isChecked())



    @pyqtSignature("on_btnBrowseExportData_clicked()")    
    def on_btnBrowseExportData_clicked(self):
        dir = QFileDialog.getExistingDirectory(self, "Choose output directory", self.outputdir.toString())
        dirInfo = QFileInfo(dir)
        self.lineEditExportData.setText(QString(dirInfo.absoluteFilePath()))
        self.settings.setValue("outputdir",  QVariant( self.lineEditExportData.text() ) )
        
        
        
    def doEstimateParameters(self):
        self.inputGlobalLayerName = self.globalLayerCBox.currentText()
        self.inputLocalLayerName = self.localLayerCBox.currentText()       
        
        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            self.controlpoints = self.readPointsFromTable()
            
            # Check if there are enough points for 
            # the transformation (-> different for helmert and affin...)
            if self.transType == 1:
                if self.checkedPoints < 2:
                    QApplication.restoreOverrideCursor()
                    QMessageBox.warning( None, "Helmert2d", "No enough control points for helmert transformation." )
                    return        
            elif self.transType == 2:
                if self.checkedPoints < 3:
                    QApplication.restoreOverrideCursor()
                    QMessageBox.warning( None, "Helmert2d", "No enough control points for affin transformation." )
                    return       
        
            # Calculate the transformation parameters.
            if self.transType == 1:
                helmert2dbuilder = Helmert2dBuilder(self.controlpoints)
                helmert2dbuilder.estimateScale(self.cbEstimateScale.isChecked())
                helmert2dbuilder.estimateRotation(self.cbEstimateRotation.isChecked())
                self.transformationParameters = helmert2dbuilder.run()
            
            # Transform all the points in the table.
            if self.transformationParameters != None:
                helmert2dtransformation = Helmert2dTransformation(self.transformationParameters)
                self.transformedControlpoints = helmert2dtransformation.transformSimplePoints(self.controlpoints)
                print "Anzahl Passpunkte: " + str(len(self.transformedControlpoints))
            
                # Write the residuals into the table and update/export the parameters.
                self.updateControlPointsTableWithTransformedPoints(self.transformedControlpoints)
                print "1"
                self.updateTransformationParameters(self.transformationParameters, self.transformedControlpoints)
                print "2"
                
                if self.cbExportTransformParameter.isChecked():
                    self.exportTransformationParameters(self.transformationParameters, self.transformedControlpoints, self.inputGlobalLayerName, self.inputLocalLayerName, self.transType, self.cbEstimateScale.isChecked(), self.cbEstimateRotation.isChecked(), self.version)
                    
            else:
                QMessageBox.warning( None, "Helmert2d", "Could not estimate transformation parameters." )
                return        
                
        except:
            QApplication.restoreOverrideCursor()
        QApplication.restoreOverrideCursor()
        
        # Remove/add vector field (result) layer.
        if self.transformedControlpoints != None:
            if self.cbAddVectorField.isChecked() == True:
                if self.cbOverwriteVectorField.isChecked() == True:
                    vlayer = helmert2d.tools.utils.getVectorLayerByName("Control points vector field")
                    if vlayer != None:
                        QgsMapLayerRegistry().instance().removeMapLayer(vlayer.id())
                
                vlayer = helmert2d.tools.utils.createTransformationVectorFieldLayer(self.transformedControlpoints)
                vlayer.setCrs( self.iface.mapCanvas().mapRenderer().destinationCrs() )                        
                
                QgsMapLayerRegistry().instance().addMapLayer(vlayer, True)   
                self.iface.legendInterface().setLayerVisible(vlayer, True)



    def exportTransformationParameters(self, transformationParameters, transformedSimplePoints, inputGlobalLayerName, inputLocalLayerName, transformationType, estimateScale, estimateRotation, version):
        d = ExportTransformationParameters()
        d.run(self.iface, transformationParameters, transformedSimplePoints, inputGlobalLayerName, inputLocalLayerName, transformationType, estimateScale, estimateRotation, version)



    def updateTransformationParameters(self, transformationParameters, transformedSimplePoints):
        a = QString.number(float(transformationParameters[0]), 'f', 8)
        b = QString.number(float(transformationParameters[1]), 'f', 8)
        c = QString.number(float(transformationParameters[2]), 'f', 8)
        d = QString.number(float(transformationParameters[3]), 'f', 8)
        if transformationParameters[4] != None:
            e = QString.number(float(transformationParameters[4]), 'f', 8)
        else:
            e = None
        if transformationParameters[5] != None:
            f = QString.number(float(transformationParameters[5]), 'f', 8)
        else:
            f = None
        
        self.lineEditParameterA.setReadOnly(False)
        self.lineEditParameterB.setReadOnly(False)
        self.lineEditParameterC.setReadOnly(False)
        self.lineEditParameterD.setReadOnly(False)
        self.lineEditParameterE.setReadOnly(False)
        self.lineEditParameterF.setReadOnly(False)
        
        self.lineEditParameterA.setText(str(a))
        self.lineEditParameterB.setText(str(b))
        self.lineEditParameterC.setText(str(c))
        self.lineEditParameterD.setText(str(d))
    
        if e != None:
            self.lineEditParameterE.setText(str(e))
        else:
            self.lineEditParameterE.insert("")

        if f != None:
            self.lineEditParameterF.setText(str(f))
        else:
            self.lineEditParameterF.insert("")

        self.lineEditParameterA.setReadOnly(True)
        self.lineEditParameterB.setReadOnly(True)
        self.lineEditParameterC.setReadOnly(True)
        self.lineEditParameterD.setReadOnly(True)
        self.lineEditParameterE.setReadOnly(True)
        self.lineEditParameterF.setReadOnly(True)

        if e  == None and f == None:
            self.lineEditParameterX0.setReadOnly(False)
            self.lineEditParameterY0.setReadOnly(False)
            self.lineEditParameterRotation.setReadOnly(False)
            self.lineEditParameterScale.setReadOnly(False)
            
            a = transformationParameters[0]
            b = transformationParameters[1] 
            c = transformationParameters[2] 
            d = transformationParameters[3] 
            
            print a
            print b
            print c
            print d
            
            tx = QString.number(float(a), 'f', 4)
            ty = QString.number(float(b), 'f', 4)

            rot = math.degrees(math.atan(float(d)/float(c))) / 0.9
            m = float(c) / math.cos(rot)
            ppm = (1 - m) * 1000000

            print "tx: " + str(a)
            print "ty: " + str(b)
            print "rot: " + str(rot)
            print "ppm: " + str(ppm)
        
            ppmString = QString.number(float(ppm), 'f', 1)
            rotString = QString.number(float(rot), 'f', 4)
        
            self.lineEditParameterX0.setText(tx)
            self.lineEditParameterY0.setText(ty)
            self.lineEditParameterRotation.setText(rotString)
            self.lineEditParameterScale.setText(ppmString)

            self.lineEditParameterX0.setReadOnly(True)
            self.lineEditParameterY0.setReadOnly(True)
            self.lineEditParameterRotation.setReadOnly(True)
            self.lineEditParameterScale.setReadOnly(True)
            
            transformationStatistic = TransformationStatistics(transformedSimplePoints, self.transType, self.cbEstimateScale.isChecked(), self.cbEstimateRotation.isChecked())
            m0 = transformationStatistic.getDeviationOfResidual()
            mpnt = transformationStatistic.getDeviationOfPoint()
            
            print "m0: " + str(m0)
            print "mpoint: " + str(mpnt)
            
            m0String = QString.number(float(m0), 'f', 1)
            mpktString = QString.number(float(mpnt), 'f', 1)
            
            self.lineEditParameterM0.setReadOnly(False)
            self.lineEditParameterMPoint.setReadOnly(False)

            self.lineEditParameterM0.setText(m0String)
            self.lineEditParameterMPoint.setText(mpktString)

            self.lineEditParameterM0.setReadOnly(True)
            self.lineEditParameterMPoint.setReadOnly(True)



    def readPointsFromTable(self):
        controlpoints = []
        self.checkedPoints = 0
        
        for i in range(self.tableWidget.rowCount()):

            checkState = self.tableWidget.cellWidget(i, 0).layout().itemAt(1).widget().checkState ()
            checked = False
            if checkState == Qt.Checked:
                checked = True
                self.checkedPoints += 1

            item = self.tableWidget.item(i, 1)
            id = item.text()
            
            item = self.tableWidget.item(i, 2)            
            xlocal = item.text()

            item = self.tableWidget.item(i, 3)            
            ylocal = item.text()
            
            item = self.tableWidget.item(i, 4)            
            xglobal = item.text()

            item = self.tableWidget.item(i, 5)            
            yglobal = item.text()
            
            gcp = Point(id)
            gcp.setXlocal(xlocal)
            gcp.setYlocal(ylocal)
            gcp.setXglobal(xglobal)
            gcp.setYglobal(yglobal)
            gcp.setChecked(checked)
            
            controlpoints.append(gcp)
        
        return controlpoints
        


    def updateControlPointsTableWithTransformedPoints(self, controlpoints):
        self.tableWidget.clearContents()
        self.tableWidget.setRowCount(len(controlpoints))
        i = 0
        for controlpoint in controlpoints:
            
            self.tableWidget.setRowHeight(i,  20)
            
            cb = QCheckBox()
            if controlpoint.isChecked() == True:
                cb.setCheckState( Qt.Checked ) 
            else:
                cb.setCheckState( Qt.Unchecked ) 
                
            QObject.connect(cb, SIGNAL( "clicked()" ), self.doEstimateParameters )        

            layout1 = QHBoxLayout()
            layout1.addWidget(cb)
            layout1.setMargin(2)
            layout1.insertSpacing(0, 10)
            layout1.setAlignment(Qt.AlignCenter)
            
            frame1 = QFrame()
            frame1.setAutoFillBackground( True )                    
#            frame1.setPalette( QPalette( Qt.blue ) )
            frame1.setLayout(layout1)       

            self.tableWidget.setCellWidget(i, 0,  frame1)                    
            
            item = QTableWidgetItem(str(controlpoint.getIdent()))  
            item.setFont(self.sansFont)        
            if controlpoint.isChecked() == False:
                item.setTextColor(Qt.gray)             
            item.setTextAlignment(Qt.AlignLeft)  
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
            self.tableWidget.setItem(i, 1, item)  

            text = QString.number(float(controlpoint.getXlocal()), 'f', 3);
            item = QTableWidgetItem(text)  
            item.setFont(self.sansFont)      
            if controlpoint.isChecked() == False:
                item.setTextColor(Qt.gray)             
            item.setTextAlignment(Qt.AlignRight)    
            item.setFlags(Qt.ItemIsEnabled)
            self.tableWidget.setItem(i, 2, item)  
            
            text = QString.number(float(controlpoint.getYlocal()), 'f', 3);
            item = QTableWidgetItem(text)  
            item.setFont(self.sansFont)         
            if controlpoint.isChecked() == False:
                item.setTextColor(Qt.gray)             
            item.setTextAlignment(Qt.AlignRight)        
            item.setFlags(Qt.ItemIsEnabled)            
            self.tableWidget.setItem(i, 3, item)              
            
            text = QString.number(float(controlpoint.getXglobal()), 'f', 3);
            item = QTableWidgetItem(text)  
            item.setFont(self.sansFont)            
            if controlpoint.isChecked() == False:
                item.setTextColor(Qt.gray)             
            item.setTextAlignment(Qt.AlignRight)        
            item.setFlags(Qt.ItemIsEnabled)            
            self.tableWidget.setItem(i, 4, item)  
            
            text = QString.number(float(controlpoint.getYglobal()), 'f', 3);
            item = QTableWidgetItem(text)  
            item.setFont(self.sansFont)     
            if controlpoint.isChecked() == False:
                item.setTextColor(Qt.gray)             
            item.setTextAlignment(Qt.AlignRight)   
            item.setFlags(Qt.ItemIsEnabled)            
            self.tableWidget.setItem(i, 5, item)     

            vx = (float(controlpoint.getXtrans()) - float(controlpoint.getXglobal())) * 1000
            text = QString.number(float(vx), 'f', 1);
            item = QTableWidgetItem(text)  
            item.setFont(self.sansFont)           
            if controlpoint.isChecked() == False:
                item.setTextColor(Qt.gray) 
            item.setTextAlignment(Qt.AlignRight)        
            item.setFlags(Qt.ItemIsEnabled)            
            self.tableWidget.setItem(i, 6, item)  
            
            vy = (float(controlpoint.getYtrans()) - float(controlpoint.getYglobal())) * 1000
            text = QString.number(float(vy), 'f', 1);
            item = QTableWidgetItem(text)  
            item.setFont(self.sansFont)    
            if controlpoint.isChecked() == False:
                item.setTextColor(Qt.gray) 
            item.setTextAlignment(Qt.AlignRight)        
            item.setFlags(Qt.ItemIsEnabled)            
            self.tableWidget.setItem(i, 7, item)              
            
            i += 1   
        


    def updateControlPointsTable(self, controlpoints):
        self.tableWidget.clearContents()
        self.tableWidget.setRowCount(len(controlpoints))
        
        i = 0
        for controlpoint in controlpoints:
            
            self.tableWidget.setRowHeight(i,  20)
            
            cb = QCheckBox()
            cb.setCheckState( Qt.Checked ) 
            #self.ctrl.tblWdgtRaw.setCellWidget(j,  0,  cb)
            
            layout1 = QHBoxLayout()
            layout1.addWidget(cb)
            layout1.setMargin(2)
            layout1.insertSpacing(0, 10)
            layout1.setAlignment(Qt.AlignCenter)
            
            frame1 = QFrame()
            frame1.setAutoFillBackground( True )                    
#            frame1.setPalette( QPalette( Qt.blue ) )
            frame1.setLayout(layout1)       

            self.tableWidget.setCellWidget(i, 0,  frame1)                    
            
            item = QTableWidgetItem(str(controlpoint.getIdent()))  
            item.setFont(self.sansFont)            
            item.setTextAlignment(Qt.AlignLeft)  
#            item.setFlags(Qt.ItemIsEnabled)
            self.tableWidget.setItem(i, 1, item)  

            text = QString.number(float(controlpoint.getXlocal()), 'f', 3);
            item = QTableWidgetItem(text)  
            item.setFont(self.sansFont)            
            item.setTextAlignment(Qt.AlignRight)    
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
            self.tableWidget.setItem(i, 2, item)  
            
            text = QString.number(float(controlpoint.getYlocal()), 'f', 3);
            item = QTableWidgetItem(text)  
            item.setFont(self.sansFont)            
            item.setTextAlignment(Qt.AlignRight)        
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)            
            self.tableWidget.setItem(i, 3, item)              
            
            text = QString.number(float(controlpoint.getXglobal()), 'f', 3);
            item = QTableWidgetItem(text)  
            item.setFont(self.sansFont)            
            item.setTextAlignment(Qt.AlignRight)        
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)            
            self.tableWidget.setItem(i, 4, item)  
            
            text = QString.number(float(controlpoint.getYglobal()), 'f', 3);
            item = QTableWidgetItem(text)  
            item.setFont(self.sansFont)            
            item.setTextAlignment(Qt.AlignRight)   
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)            
            self.tableWidget.setItem(i, 5, item)                        
            
            i += 1   






