Example #1
0
 def reinitSSGetClass(self):
    checkPointLayer = self.SSGetClass.checkPointLayer
    del self.SSGetClass
    self.SSGetClass = QadSSGetClass(self.plugIn)
    self.SSGetClass.onlyEditableLayers = False
    self.SSGetClass.checkDimLayers = False # scarto le quote
    self.SSGetClass.checkPointLayer = checkPointLayer
Example #2
0
class QadVirtualSelCommandClass(QadCommandClass):
    def instantiateNewCmd(self):
        """ istanzia un nuovo comando dello stesso tipo """
        return QadVirtualSelCommandClass(self.plugIn)

    def getName(self):
        return "QadVirtualSelCommandClass"

    def __init__(self, plugIn):
        QadCommandClass.__init__(self, plugIn)
        self.SSGetClass = QadSSGetClass(plugIn)
        self.SSGetClass.entitySet.set(
            plugIn.tool.entitySet)  # da usare solo con QadMapTool
        self.SSGetClass.exitAfterSelection = True
        self.SSGetClass.step = 1

    def __del__(self):
        QadCommandClass.__del__(self)
        del self.SSGetClass

    def getPointMapTool(self, drawMode=QadGetPointDrawModeEnum.NONE):
        return self.SSGetClass.getPointMapTool(drawMode)

    def run(self, msgMapTool=False, msg=None):
        res = self.SSGetClass.run(msgMapTool, msg)
        if res == True:
            self.plugIn.tool.entitySet.set(
                self.SSGetClass.entitySet)  # da usare solo con QadMapTool
            self.plugIn.tool.entitySet.selectOnLayer()
        return res
Example #3
0
class QadVirtualSelCommandClass(QadCommandClass):

   def instantiateNewCmd(self):
      """ istanzia un nuovo comando dello stesso tipo """
      return QadVirtualSelCommandClass(self.plugIn)
   
   def getName(self):
      return "QadVirtualSelCommandClass"

   def __init__(self, plugIn):
      QadCommandClass.__init__(self, plugIn)
      self.SSGetClass = QadSSGetClass(plugIn)
      self.SSGetClass.entitySet.set(plugIn.tool.entitySet) # da usare solo con QadMapTool
      self.SSGetClass.exitAfterSelection = True
      self.SSGetClass.step = 1
   
   def __del__(self):
      QadCommandClass.__del__(self)
      del self.SSGetClass
      
   def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):
      return self.SSGetClass.getPointMapTool(drawMode)

   def run(self, msgMapTool = False, msg = None):
      res = self.SSGetClass.run(msgMapTool, msg)
      if res == True:
         self.plugIn.tool.entitySet.set(self.SSGetClass.entitySet) # da usare solo con QadMapTool
         self.plugIn.tool.entitySet.selectOnLayer()
      return res
Example #4
0
 def __init__(self, plugIn):
     QadCommandClass.__init__(self, plugIn)
     self.SSGetClass = QadSSGetClass(plugIn)
     self.SSGetClass.entitySet.set(
         plugIn.tool.entitySet)  # da usare solo con QadMapTool
     self.SSGetClass.exitAfterSelection = True
     self.SSGetClass.step = 1
Example #5
0
 def __init__(self, plugIn):
    QadCommandClass.__init__(self, plugIn)
    self.SSGetClass = QadSSGetClass(plugIn)
    self.SSGetClass.onlyEditableLayers = True
    self.entitySet = QadEntitySet()
    self.firstMirrorPt = QgsPoint()
    self.secondMirrorPt = QgsPoint()
    self.copyFeatures = True
Example #6
0
 def __init__(self, plugIn):
     QadCommandClass.__init__(self, plugIn)
     self.SSGetClass = QadSSGetClass(plugIn)
     self.SSGetClass.onlyEditableLayers = True
     self.entitySet = QadEntitySet()
     self.basePt = None
     self.copyFeatures = False
     self.Pt1ReferenceLen = None
     self.ReferenceLen = 1
     self.Pt1NewLen = None
Example #7
0
 def __init__(self, plugIn):
    QadCommandClass.__init__(self, plugIn)
    self.SSGetClass = QadSSGetClass(plugIn)
    self.PLINECommand = None      
    self.RECTANGLECommand = None
    self.entitySet = QadEntitySet() # entità da tagliare o estendere
    self.limitEntitySet = QadEntitySet() # entità che fanno da limiti
    self.edgeMode = QadVariables.get(QadMsg.translate("Environment variables", "EDGEMODE"))
    self.defaultValue = None # usato per gestire il tasto dx del mouse
    self.nOperationsToUndo = 0
Example #8
0
 def __init__(self, plugIn):
     QadCommandClass.__init__(self, plugIn)
     # se questo flag = True il comando serve all'interno di un altro comando per disegnare un buffer
     # che non verrà salvato su un layer
     self.virtualCmd = False
     self.rubberBandBorderColor = None
     self.rubberBandFillColor = None
     self.SSGetClass = QadSSGetClass(plugIn)
     self.entitySet = QadEntitySet()
     self.width = 0
     self.segments = self.plugIn.segments  # il numero di segmenti per l'approssimazione delle curve
Example #9
0
 def __init__(self, plugIn):
    QadCommandClass.__init__(self, plugIn)
    self.SSGetClass = QadSSGetClass(plugIn)
    self.SSGetClass.onlyEditableLayers = True
    self.entitySet = QadEntitySet()
    self.basePt = QgsPoint()
    self.series = False
    self.seriesLen = 2
    self.adjust = False
    self.copyMode = QadVariables.get(QadMsg.translate("Environment variables", "COPYMODE"))
    
    self.featureCache = [] # lista di (layer, feature)
    self.nOperationsToUndo = 0
    def canvasPressEvent(self, event):
        # I wanted to put this event in the canvasReleaseEvent
        # But the right button does not generate that kind of event
        if event.button() == Qt.RightButton:
            self.displayPopupMenuOnQuiescentState(event.pos())
        elif event.button() == Qt.LeftButton:
            # I check if the shift key is pressed
            shiftKey = True if event.modifiers() & Qt.ShiftModifier else False
            # Current mouse position
            point = self.toMapCoordinates(event.pos())
            # I read the grip point that intersects the mouse position
            entityGripPoint = self.entitySetGripPoints.isIntersecting(point)
            if entityGripPoint is not None:
                if shiftKey == False:  # lancio il comando
                    selectedEntityGripPoints = self.entitySetGripPoints.getSelectedEntityGripPoints(
                    )
                    # se non ci sono già grip selezionati
                    if len(selectedEntityGripPoints) == 0:
                        # seleziono il corrente
                        if self.entitySetGripPoints.selectIntersectingGripPoints(
                                point) > 0:
                            selectedEntityGripPoints = self.entitySetGripPoints.getSelectedEntityGripPoints(
                            )

                    # lancio il comando
                    self.plugIn.runCommand("QadVirtualGripCommandsClass", [QadVirtualGripCommandsEnum.STRECTH, \
                                           self.entitySetGripPoints, entityGripPoint.getPoint()])
                else:  # Shift pressed
                    # Invert the state of grips intersecting the point
                    self.entitySetGripPoints.toggleSelectIntersectingGripPoints(
                        point)
            else:
                result = qad_utils.getEntSel(event.pos(), self, \
                                             QadVariables.get(QadMsg.translate("Environment variables", "PICKBOX")))
                if result is not None:
                    feature = result[0]
                    layer = result[1]
                    tmpEntity = QadEntity()
                    tmpEntity.set(layer, feature.id())
                    SSGetClass = QadSSGetClass(self.plugIn)
                    SSGetClass.entitySet.set(self.entitySet)
                    SSGetClass.elaborateEntity(tmpEntity, shiftKey)
                    self.plugIn.showMsg("\n", True)  # Repeat the prompt
                    self.entitySet.set(SSGetClass.entitySet)
                    del SSGetClass  # Which deselects objects
                    self.entitySet.selectOnLayer(False)
                    self.refreshEntityGripPoints(self.entitySet)
                else:
                    self.plugIn.runCommand("QadVirtualSelCommandClass", point)
Example #11
0
    def canvasPressEvent(self, event):
        # volevo mettere questo evento nel canvasReleaseEvent
        # ma il tasto destro non genera quel tipo di evento
        if event.button() == Qt.RightButton:
            self.displayPopupMenuOnQuiescentState(event.pos())
        elif event.button() == Qt.LeftButton:
            # verifico se tasto shift premuto
            shiftKey = True if event.modifiers() & Qt.ShiftModifier else False
            # posizione corrente del mouse
            point = self.toMapCoordinates(event.pos())
            # leggo il punto grip che si interseca alla posizione del mouse
            entityGripPoint = self.entitySetGripPoints.isIntersecting(point)
            if entityGripPoint is not None:
                if shiftKey == False:  # lancio il comando
                    selectedEntityGripPoints = self.entitySetGripPoints.getSelectedEntityGripPoints(
                    )
                    # se non ci sono già grip selezionati
                    if len(selectedEntityGripPoints) == 0:
                        # seleziono il corrente
                        if self.entitySetGripPoints.selectIntersectingGripPoints(
                                point) > 0:
                            selectedEntityGripPoints = self.entitySetGripPoints.getSelectedEntityGripPoints(
                            )

                    # lancio il comando
                    self.plugIn.runCommand("QadVirtualGripCommandsClass", [QadVirtualGripCommandsEnum.STRECTH, \
                                           self.entitySetGripPoints, entityGripPoint.getPoint()])
                else:  # shift premuto
                    # inverto lo stato ai grip che intersecano il punto
                    self.entitySetGripPoints.toggleSelectIntersectingGripPoints(
                        point)
            else:
                result = qad_utils.getEntSel(event.pos(), self, \
                                             QadVariables.get(QadMsg.translate("Environment variables", "PICKBOX")))
                if result is not None:
                    feature = result[0]
                    layer = result[1]
                    tmpEntity = QadEntity()
                    tmpEntity.set(layer, feature.id())
                    SSGetClass = QadSSGetClass(self.plugIn)
                    SSGetClass.entitySet.set(self.entitySet)
                    SSGetClass.elaborateEntity(tmpEntity, shiftKey)
                    self.plugIn.showMsg("\n", True)  # ripete il prompt
                    self.entitySet.set(SSGetClass.entitySet)
                    del SSGetClass  # che deseleziona gli oggetti
                    self.entitySet.selectOnLayer(False)
                    self.refreshEntityGripPoints(self.entitySet)
                else:
                    self.plugIn.runCommand("QadVirtualSelCommandClass", point)
Example #12
0
 def __init__(self, plugIn):
    QadCommandClass.__init__(self, plugIn)
    
    self.poligonEntity = QadEntity()
    
    self.SSGetClass = QadSSGetClass(plugIn)
    self.SSGetClass.onlyEditableLayers = False
    self.SSGetClass.checkDimLayers = False # scarto le quote
    
    self.entSelClass = None
    
    self.currSubGeom = None
    self.currAtSubGeom = None
   
    self.nOperationsToUndo = 0
Example #13
0
 def reinitSSGetClass(self):
    checkPointLayer = self.SSGetClass.checkPointLayer
    del self.SSGetClass
    self.SSGetClass = QadSSGetClass(self.plugIn)
    self.SSGetClass.onlyEditableLayers = False
    self.SSGetClass.checkDimLayers = False # scarto le quote
    self.SSGetClass.checkPointLayer = checkPointLayer
Example #14
0
 def __init__(self, plugIn):
    QadCommandClass.__init__(self, plugIn)
    self.SSGetClass = QadSSGetClass(plugIn)
    self.SSGetClass.onlyEditableLayers = True
    self.entitySet = QadEntitySet()
    self.firstMirrorPt = QgsPoint()
    self.secondMirrorPt = QgsPoint()
    self.copyFeatures = True
Example #15
0
   def canvasPressEvent(self, event):
      # volevo mettere questo evento nel canvasReleaseEvent
      # ma il tasto destro non genera quel tipo di evento
      if event.button() == Qt.RightButton:
         self.displayPopupMenuOnQuiescentState(event.pos())
      elif event.button() == Qt.LeftButton:
         # verifico se tasto shift premuto
         shiftKey = True if event.modifiers() & Qt.ShiftModifier else False
         # posizione corrente del mouse
         point = self.toMapCoordinates(event.pos())
         # leggo il punto grip che si interseca alla posizione del mouse
         entityGripPoint = self.entitySetGripPoints.isIntersecting(point)
         if entityGripPoint is not None:
            if shiftKey == False: # lancio il comando
               selectedEntityGripPoints = self.entitySetGripPoints.getSelectedEntityGripPoints()
               # se non ci sono già grip selezionati
               if len(selectedEntityGripPoints) == 0:
                  # seleziono il corrente
                  if self.entitySetGripPoints.selectIntersectingGripPoints(point) > 0:
                     selectedEntityGripPoints = self.entitySetGripPoints.getSelectedEntityGripPoints()

               # lancio il comando
               self.plugIn.runCommand("QadVirtualGripCommandsClass", [QadVirtualGripCommandsEnum.STRECTH, \
                                      self.entitySetGripPoints, entityGripPoint.getPoint()])
            else: # shift premuto
               # inverto lo stato ai grip che intersecano il punto 
               self.entitySetGripPoints.toggleSelectIntersectingGripPoints(point)
         else:
            result = qad_utils.getEntSel(event.pos(), self, \
                                         QadVariables.get(QadMsg.translate("Environment variables", "PICKBOX")))
            if result is not None:
               feature = result[0]
               layer = result[1]
               tmpEntity = QadEntity()
               tmpEntity.set(layer, feature.id())
               SSGetClass = QadSSGetClass(self.plugIn)
               SSGetClass.entitySet.set(self.entitySet)
               SSGetClass.elaborateEntity(tmpEntity, shiftKey)
               self.plugIn.showMsg("\n", True) # ripete il prompt
               self.entitySet.set(SSGetClass.entitySet)
               del SSGetClass # che deseleziona gli oggetti
               self.entitySet.selectOnLayer(False)
               self.refreshEntityGripPoints(self.entitySet)
            else:
               self.plugIn.runCommand("QadVirtualSelCommandClass", point)
Example #16
0
 def __init__(self, plugIn):
    QadCommandClass.__init__(self, plugIn)
    # se questo flag = True il comando serve all'interno di un altro comando per disegnare un buffer
    # che non verrà salvato su un layer
    self.virtualCmd = False
    self.SSGetClass = QadSSGetClass(plugIn)
    self.entitySet = QadEntitySet()
    self.width = 0
    self.segments = self.plugIn.segments
    self.segments = 3 # roby
Example #17
0
 def __init__(self, plugIn):
    QadCommandClass.__init__(self, plugIn)
    self.SSGetClass = QadSSGetClass(plugIn)
    self.SSGetClass.onlyEditableLayers = True
    self.entitySet = QadEntitySet()
    self.basePt = None
    self.copyFeatures = False
    self.Pt1ReferenceLen = None
    self.ReferenceLen = 1
    self.Pt1NewLen = None
Example #18
0
    def reinitSSGetClass(self):
        if self.SSGetClass is not None: del self.SSGetClass

        self.SSGetClass = QadSSGetClass(self.plugIn)
        self.SSGetClass.onlyEditableLayers = True
        self.SSGetClass.checkDimLayers = False  # scarto le quote
        geometryType = self.entity.layer.geometryType()
        if geometryType == QGis.Point:
            self.SSGetClass.checkPointLayer = True
            self.SSGetClass.checkLineLayer = False
            self.SSGetClass.checkPolygonLayer = False
        elif geometryType == QGis.Line:
            self.SSGetClass.checkPointLayer = False
            self.SSGetClass.checkLineLayer = True
            self.SSGetClass.checkPolygonLayer = True
        elif geometryType == QGis.Polygon:
            self.SSGetClass.checkPointLayer = False
            self.SSGetClass.checkLineLayer = True
            self.SSGetClass.checkPolygonLayer = True
Example #19
0
 def __init__(self, plugIn):
    QadCommandClass.__init__(self, plugIn)
    # se questo flag = True il comando serve all'interno di un altro comando per disegnare un buffer
    # che non verrà salvato su un layer
    self.virtualCmd = False
    self.rubberBandBorderColor = None
    self.rubberBandFillColor = None      
    self.SSGetClass = QadSSGetClass(plugIn)
    self.entitySet = QadEntitySet()
    self.width = 0
    self.segments = self.plugIn.segments # il numero di segmenti per l'approssimazione delle curve
Example #20
0
 def __init__(self, plugIn):
    QadCommandClass.__init__(self, plugIn)
    self.SSGetClass = QadSSGetClass(plugIn)
    self.SSGetClass.onlyEditableLayers = True
    self.entitySet = QadEntitySet()
    self.basePt = QgsPoint()
    self.series = False
    self.seriesLen = 2
    self.adjust = False
    self.copyMode = QadVariables.get(QadMsg.translate("Environment variables", "COPYMODE"))
    
    self.featureCache = [] # lista di (layer, feature)
    self.nOperationsToUndo = 0
Example #21
0
 def __init__(self, plugIn):
    QadCommandClass.__init__(self, plugIn)
    
    self.poligonEntity = QadEntity()
    
    self.SSGetClass = QadSSGetClass(plugIn)
    self.SSGetClass.onlyEditableLayers = False
    self.SSGetClass.checkDimLayers = False # scarto le quote
    
    self.entSelClass = None
    
    self.currSubGeom = None
    self.currAtSubGeom = None
   
    self.nOperationsToUndo = 0
Example #22
0
 def reinitSSGetClass(self):
    if self.SSGetClass is not None: del self.SSGetClass
    
    self.SSGetClass = QadSSGetClass(self.plugIn)
    self.SSGetClass.onlyEditableLayers = True
    self.SSGetClass.checkDimLayers = False # scarto le quote
    geometryType = self.entity.layer.geometryType()
    if geometryType == QGis.Point:
       self.SSGetClass.checkPointLayer = True
       self.SSGetClass.checkLineLayer = False
       self.SSGetClass.checkPolygonLayer = False
    elif geometryType == QGis.Line:
       self.SSGetClass.checkPointLayer = False
       self.SSGetClass.checkLineLayer = True
       self.SSGetClass.checkPolygonLayer = True
    elif geometryType == QGis.Polygon:
       self.SSGetClass.checkPointLayer = False
       self.SSGetClass.checkLineLayer = True
       self.SSGetClass.checkPolygonLayer = True
Example #23
0
class QadMIRRORCommandClass(QadCommandClass):
   
   def instantiateNewCmd(self):
      """ istanzia un nuovo comando dello stesso tipo """
      return QadMIRRORCommandClass(self.plugIn)
   
   def getName(self):
      return QadMsg.translate("Command_list", "MIRROR")

   def getEnglishName(self):
      return "MIRROR"

   def connectQAction(self, action):
      QObject.connect(action, SIGNAL("triggered()"), self.plugIn.runMIRRORCommand)

   def getIcon(self):
      return QIcon(":/plugins/qad/icons/mirror.png")

   def getNote(self):
      # impostare le note esplicative del comando      
      return QadMsg.translate("Command_MIRROR", "Creates a mirrored copy of selected objects.")
   
   def __init__(self, plugIn):
      QadCommandClass.__init__(self, plugIn)
      self.SSGetClass = QadSSGetClass(plugIn)
      self.SSGetClass.onlyEditableLayers = True
      self.entitySet = QadEntitySet()
      self.firstMirrorPt = QgsPoint()
      self.secondMirrorPt = QgsPoint()
      self.copyFeatures = True

   def __del__(self):
      QadCommandClass.__del__(self)
      del self.SSGetClass
      
   def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):
      if self.step == 0: # quando si é in fase di selezione entità
         return self.SSGetClass.getPointMapTool()
      else:
         if (self.plugIn is not None):
            if self.PointMapTool is None:
               self.PointMapTool = Qad_mirror_maptool(self.plugIn)
            return self.PointMapTool
         else:
            return None


   #============================================================================
   # scale
   #============================================================================
   def mirror(self, f, pt1, pt2, rotFldName, layerEntitySet, entitySet, dimEntity):
      
      if dimEntity is None:
         # scalo la feature e la rimuovo da entitySet (é la prima)
         f.setGeometry(qad_utils.mirrorQgsGeometry(f.geometry(), pt1, pt2))
         if len(rotFldName) > 0:
            rotValue = f.attribute(rotFldName)
            # a volte vale None e a volte null (vai a capire...)
            rotValue = 0 if rotValue is None or isinstance(rotValue, QPyNullVariant) else qad_utils.toRadians(rotValue) # la rotazione é in gradi nel campo della feature
            ptDummy = qad_utils.getPolarPointByPtAngle(pt1, rotValue, 1)
            mirrorAngle = qad_utils.getAngleBy2Pts(pt1, pt2)
            ptDummy = qad_utils.mirrorPoint(ptDummy, pt1, mirrorAngle)
            rotValue = qad_utils.getAngleBy2Pts(pt1, ptDummy)
            f.setAttribute(rotFldName, qad_utils.toDegrees(qad_utils.normalizeAngle(rotValue)))               
                  
         if self.copyFeatures == False:
            # plugIn, layer, feature, refresh, check_validity
            if qad_layer.updateFeatureToLayer(self.plugIn, layerEntitySet.layer, f, False, False) == False:
               self.plugIn.destroyEditCommand()
               return False
         else:             
            # plugIn, layer, features, coordTransform, refresh, check_validity
            if qad_layer.addFeatureToLayer(self.plugIn, layerEntitySet.layer, f, None, False, False) == False:
               self.plugIn.destroyEditCommand()
               return False

         del layerEntitySet.featureIds[0]
      else:
         # scalo la quota e la rimuovo da entitySet
         mirrorAngle = qad_utils.getAngleBy2Pts(pt1, pt2)
         dimEntitySet = dimEntity.getEntitySet()
         if self.copyFeatures == False:
            if dimEntity.deleteToLayers(self.plugIn) == False:
               return False
         newDimEntity = QadDimEntity(dimEntity) # la copio
         newDimEntity.mirror(pt1, mirrorAngle)
         if newDimEntity.addToLayers(self.plugIn) == False:
            return False             
         entitySet.subtract(dimEntitySet)


   #============================================================================
   # mirrorGeoms
   #============================================================================
   def mirrorGeoms(self):      
      # copio entitySet
      entitySet = QadEntitySet(self.entitySet)

      self.plugIn.beginEditCommand("Feature mirrored", self.entitySet.getLayerList())

      for layerEntitySet in entitySet.layerEntitySetList:
         layer = layerEntitySet.layer        

         transformedBasePt = self.mapToLayerCoordinates(layer, self.firstMirrorPt)
         transformedNewPt = self.mapToLayerCoordinates(layer, self.secondMirrorPt)
         
         rotFldName = ""
         if qad_layer.isTextLayer(layer):
            # se la rotazione dipende da un solo campo
            rotFldNames = qad_label.get_labelRotationFieldNames(layer)
            if len(rotFldNames) == 1 and len(rotFldNames[0]) > 0:
               rotFldName = rotFldNames[0]         
         elif qad_layer.isSymbolLayer(layer):
            rotFldName = qad_layer.get_symbolRotationFieldName(layer)
         
         while len(layerEntitySet.featureIds) > 0:
            featureId = layerEntitySet.featureIds[0]
            f = layerEntitySet.getFeature(featureId)

            entity = QadEntity()
            entity.set(layer, featureId)
            # verifico se l'entità appartiene ad uno stile di quotatura
            dimStyle, dimId = QadDimStyles.getDimIdByEntity(entity)

            if dimStyle is not None:
               dimEntity = QadDimEntity()
               if dimEntity.initByDimId(dimStyle, dimId) == False:
                  dimEntity = None
            else:
               dimEntity = None

            if self.mirror(f, transformedBasePt, transformedNewPt, rotFldName, layerEntitySet, entitySet, dimEntity) == False:  
               self.plugIn.destroyEditCommand()
               return

      self.plugIn.endEditCommand()
   

   def run(self, msgMapTool = False, msg = None):
      if self.plugIn.canvas.mapSettings().destinationCrs().geographicFlag():
         self.showMsg(QadMsg.translate("QAD", "\nThe coordinate reference system of the project must be a projected coordinate system.\n"))
         return True # fine comando
            
      #=========================================================================
      # RICHIESTA SELEZIONE OGGETTI
      if self.step == 0: # inizio del comando
         if self.SSGetClass.run(msgMapTool, msg) == True:
            # selezione terminata
            self.step = 1
            self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può essere variato dal maptool di selezione entità                    
            return self.run(msgMapTool, msg)
      
      #=========================================================================
      # SPECCHIA OGGETTI
      elif self.step == 1:
         self.entitySet.set(self.SSGetClass.entitySet)
         
         if self.entitySet.count() == 0:
            return True # fine comando

         # imposto il map tool
         self.getPointMapTool().entitySet.set(self.entitySet)
         self.getPointMapTool().setMode(Qad_mirror_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_FIRST_PT)                                
   
         # si appresta ad attendere un punto
         self.waitForPoint(QadMsg.translate("Command_MIRROR", "Specify first point of mirror line: "))
         self.step = 2      
         return False
         
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA PUNTO BASE (da step = 1)
      elif self.step == 2: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  # si appresta ad attendere un punto
                  self.waitForPoint(QadMsg.translate("Command_MIRROR", "Specify first point of mirror line: "))
                  return False
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         self.firstMirrorPt.set(value.x(), value.y())

         # imposto il map tool
         self.getPointMapTool().firstMirrorPt = self.firstMirrorPt
         self.getPointMapTool().setMode(Qad_mirror_maptool_ModeEnum.FIRST_PT_KNOWN_ASK_FOR_SECOND_PT)                                
         
         # si appresta ad attendere un punto
         self.waitForPoint(QadMsg.translate("Command_MIRROR", "Specify second point of mirror line: "))
         self.step = 3
         
         return False 
         
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER SPECCHIO (da step = 2)
      elif self.step == 3: # dopo aver atteso un punto si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  # si appresta ad attendere un punto
                  self.waitForPoint(QadMsg.translate("Command_MIRROR", "Specify second point of mirror line: "))
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if qad_utils.ptNear(self.firstMirrorPt, value):
            self.showMsg(QadMsg.translate("Command_MIRROR", "\nThe points must be different."))
            # si appresta ad attendere un punto
            self.waitForPoint(QadMsg.translate("Command_MIRROR", "Specify second point of mirror line: "))
            return False
         
         self.secondMirrorPt.set(value.x(), value.y())
         
         keyWords = QadMsg.translate("QAD", "Yes") + "/" + \
                    QadMsg.translate("QAD", "No")                                       
         if self.copyFeatures == False:
            default = QadMsg.translate("QAD", "Yes")
         else: 
            default = QadMsg.translate("QAD", "No")
         prompt = QadMsg.translate("Command_MIRROR", "Erase source objects ? [{0}] <{1}>: ").format(keyWords, default)
             
         englishKeyWords = "Yes" + "/" + "No"
         keyWords += "_" + englishKeyWords
         # si appresta ad attendere enter o una parola chiave         
         # msg, inputType, default, keyWords, nessun controllo
         self.waitFor(prompt, \
                      QadInputTypeEnum.KEYWORDS, \
                      default, \
                      keyWords, QadInputModeEnum.NONE)
         self.getPointMapTool().setMode(Qad_mirror_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_FIRST_PT)                                         
         self.step = 4

         return False
            

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DI CANCELLAZIONE OGGETTO SORGENTE (da step = 3)
      elif self.step == 4: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
               value = QadMsg.translate("QAD", "No")   
            else:
               self.setMapTool(self.getPointMapTool()) # riattivo il maptool
               return False
         else: # il valore arriva come parametro della funzione
            value = msg

         if type(value) == unicode:
            if value == QadMsg.translate("QAD", "Yes") or value == "Yes":
               self.copyFeatures = False
            elif value == QadMsg.translate("QAD", "No") or value == "No":
               self.copyFeatures = True
                     
            self.mirrorGeoms()
            return True # fine comando

         return False
Example #24
0
 def __init__(self, plugIn):
    QadCommandClass.__init__(self, plugIn)
    self.SSGetClass = QadSSGetClass(plugIn)
    self.SSGetClass.onlyEditableLayers = True
    self.entitySet = QadEntitySet()
    self.basePt = QgsPoint()
Example #25
0
class QadMBUFFERCommandClass(QadCommandClass):
   
   def instantiateNewCmd(self):
      """ istanzia un nuovo comando dello stesso tipo """
      return QadMBUFFERCommandClass(self.plugIn)
   
   def getName(self):
      return QadMsg.translate("Command_list", "MBUFFER")

   def getEnglishName(self):
      return "MBUFFER"

   def connectQAction(self, action):
      QObject.connect(action, SIGNAL("triggered()"), self.plugIn.runMBUFFERCommand)

   def getIcon(self):
      return QIcon(":/plugins/qad/icons/mbuffer.png")

   def getNote(self):
      # impostare le note esplicative del comando
      return QadMsg.translate("Command_MBUFFER", "Creates polygons by buffering selected objects.")
   
   def __init__(self, plugIn):
      QadCommandClass.__init__(self, plugIn)
      # se questo flag = True il comando serve all'interno di un altro comando per disegnare un buffer
      # che non verrà salvato su un layer
      self.virtualCmd = False
      self.rubberBandBorderColor = None
      self.rubberBandFillColor = None      
      self.SSGetClass = QadSSGetClass(plugIn)
      self.entitySet = QadEntitySet()
      self.width = 0
      self.segments = self.plugIn.segments # il numero di segmenti per l'approssimazione delle curve

   def __del__(self):
      QadCommandClass.__del__(self)
      del SSGetClass


   def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):
      if self.step == 0: # quando si é in fase di selezione entità
         return self.SSGetClass.getPointMapTool()
      else:
         if (self.plugIn is not None):
            if self.PointMapTool is None:
               self.PointMapTool = Qad_mbuffer_maptool(self.plugIn)
               self.PointMapTool.setRubberBandColor(self.rubberBandBorderColor, self.rubberBandFillColor)
            return self.PointMapTool
         else:
            return None


   def getCurrentContextualMenu(self):
      if self.step == 0: # quando si é in fase di selezione entità
         return self.SSGetClass.getCurrentContextualMenu()
      else:
         return self.contextualMenu

   
   def setRubberBandColor(self, rubberBandBorderColor, rubberBandFillColor):
      self.rubberBandBorderColor = rubberBandBorderColor
      self.rubberBandFillColor = rubberBandFillColor
      if self.PointMapTool is not None:
         self.PointMapTool.setRubberBandColor(self.rubberBandBorderColor, self.rubberBandFillColor)


   def AddGeoms(self, currLayer):
      bufferGeoms = []
      tolerance = QadVariables.get(QadMsg.translate("Environment variables", "TOLERANCE2APPROXCURVE"))
            
      for layerEntitySet in self.entitySet.layerEntitySetList:
         layer = layerEntitySet.layer
         geoms = layerEntitySet.getGeometryCollection()
         
         for geom in geoms:
            # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy
            newGeom = self.layerToMapCoordinates(layer, geom)
            g = qad_utils.ApproxCurvesOnGeom(newGeom.buffer(self.width, self.segments), \
                                             self.segments, self.segments, \
                                             tolerance)
            # trasformo la geometria nel crs del layer
            bufferGeoms.append(self.mapToLayerCoordinates(layer, g))

      self.plugIn.beginEditCommand("Feature buffered", currLayer)
      
      # filtro le features per tipo
      pointGeoms, lineGeoms, polygonGeoms = qad_utils.filterGeomsByType(bufferGeoms, \
                                                                        currLayer.geometryType())
      # aggiungo le geometrie del tipo corretto
      if currLayer.geometryType() == QGis.Line:
         polygonToLines = []
         # Riduco le geometrie in linee
         for g in polygonGeoms:
            lines = qad_utils.asPointOrPolyline(g)
            for l in lines:
               if l.type() == QGis.Line:
                   polygonToLines.append(l)
         # plugIn, layer, geoms, coordTransform , refresh, check_validity
         if qad_layer.addGeomsToLayer(self.plugIn, currLayer, polygonToLines, None, False, False) == False:
            self.plugIn.destroyEditCommand()
            return
            
         del polygonGeoms[:] # svuoto la lista

      # plugIn, layer, geoms, coordTransform , refresh, check_validity
      if qad_layer.addGeomsToLayer(self.plugIn, currLayer, bufferGeoms, None, False, False) == False:  
         self.plugIn.destroyEditCommand()
         return

      if pointGeoms is not None and len(pointGeoms) > 0:
         PointTempLayer = qad_layer.createQADTempLayer(self.plugIn, QGis.Point)
         self.plugIn.addLayerToLastEditCommand("Feature buffered", PointTempLayer)
      
      if lineGeoms is not None and len(lineGeoms) > 0:
         LineTempLayer = qad_layer.createQADTempLayer(self.plugIn, QGis.Line)
         self.plugIn.addLayerToLastEditCommand("Feature buffered", LineTempLayer)
         
      if polygonGeoms is not None and len(polygonGeoms) > 0:
         PolygonTempLayer = qad_layer.createQADTempLayer(self.plugIn, QGis.Polygon)
         self.plugIn.addLayerToLastEditCommand("Feature buffered", PolygonTempLayer)

      # aggiungo gli scarti nei layer temporanei di QAD
      # trasformo la geometria in quella dei layer temporanei 
      # plugIn, pointGeoms, lineGeoms, polygonGeoms, coord, refresh
      if qad_layer.addGeometriesToQADTempLayers(self.plugIn, pointGeoms, lineGeoms, polygonGeoms, \
                                                None, False) == False:
         self.plugIn.destroyEditCommand()
         return

      self.plugIn.endEditCommand()


   def run(self, msgMapTool = False, msg = None):
      if self.plugIn.canvas.mapSettings().destinationCrs().geographicFlag():
         self.showMsg(QadMsg.translate("QAD", "\nThe coordinate reference system of the project must be a projected coordinate system.\n"))
         return True # fine comando

      currLayer = None
      if self.virtualCmd == False: # se si vuole veramente salvare la polylinea in un layer   
         # il layer corrente deve essere editabile e di tipo linea o poligono
         currLayer, errMsg = qad_layer.getCurrLayerEditable(self.plugIn.canvas, [QGis.Line, QGis.Polygon])
         if currLayer is None:
            self.showErr(errMsg)
            return True # fine comando
         
         # il layer corrente non deve appartenere a quotature
         dimStyleList = QadDimStyles.getDimListByLayer(currLayer)
         if len(dimStyleList) > 0:
            dimStyleNames = ""
            for i in xrange(0, len(dimStyleList), 1):
               if i > 0:
                  dimStyleNames += ", "
               dimStyleNames += dimStyleList[i].name
            errMsg = QadMsg.translate("QAD", "\nCurrent layer is a layer referenced to {0} dimension style and it is not valid.\n")                        
            self.showErr(errMsg.format(dimStyleNames))
            return True # fine comando
            
      #=========================================================================
      # RICHIESTA SELEZIONE OGGETTI
      if self.step == 0: # inizio del comando
         if self.SSGetClass.run(msgMapTool, msg) == True:
            # selezione terminata
            self.step = 1
            self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può  essere variato dal maptool di selezione entità                     
            return self.run(msgMapTool, msg)
      
      #=========================================================================
      # BUFFER OGGETTI
      elif self.step == 1:
         self.entitySet.set(self.SSGetClass.entitySet)
         
         if self.entitySet.count() == 0:
            return True # fine comando

         # imposto il map tool
         self.getPointMapTool().setMode(Qad_mbuffer_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_FIRST_PT)
         if currLayer is not None:
            self.getPointMapTool().geomType = QGis.Line if currLayer.geometryType() == QGis.Line else QGis.Polygon                          
        
         # si appresta ad attendere un punto o un numero reale         
         # msg, inputType, default, keyWords, valori positivi
         msg = QadMsg.translate("Command_MBUFFER", "Specify the buffer length <{0}>: ")
         self.waitFor(msg.format(str(self.plugIn.lastRadius)), \
                      QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT, \
                      self.plugIn.lastRadius, "", \
                      QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)
                  
         self.step = 2     
         return False
         
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA LARGHEZZA (da step = 1)
      elif self.step == 2: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if type(value) == QgsPoint:
            self.startPtForBufferWidth = value
            
            # imposto il map tool
            self.getPointMapTool().startPtForBufferWidth = self.startPtForBufferWidth
            self.getPointMapTool().entitySet.set(self.entitySet)
            self.getPointMapTool().segments = self.segments
            self.getPointMapTool().setMode(Qad_mbuffer_maptool_ModeEnum.FIRST_PT_ASK_FOR_BUFFER_WIDTH)
         
            # si appresta ad attendere un punto
            self.waitForPoint(QadMsg.translate("Command_MBUFFER", "Specify second point: "))
            self.step = 3
            return False            
         else:
            self.width = value
            self.plugIn.setLastRadius(self.width)

            if self.virtualCmd == False: # se si vuole veramente salvare i buffer in un layer
               self.AddGeoms(currLayer)           

            return True # fine comando

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA SECONDO PUNTO DELLA LARGHEZZA BUFFER (da step = 2)
      elif self.step == 3: # dopo aver atteso un punto si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         self.width = qad_utils.getDistance(self.startPtForBufferWidth, value)
         self.plugIn.setLastRadius(self.width)     

         if self.virtualCmd == False: # se si vuole veramente salvare i buffer in un layer
            self.AddGeoms(currLayer)               

         return True # fine comando
Example #26
0
 def __init__(self, plugIn):
     QadCommandClass.__init__(self, plugIn)
     self.SSGetClass = QadSSGetClass(plugIn)
     self.firstTime = True
Example #27
0
class QadMOVECommandClass(QadCommandClass):
    def instantiateNewCmd(self):
        """ istanzia un nuovo comando dello stesso tipo """
        return QadMOVECommandClass(self.plugIn)

    def getName(self):
        return QadMsg.translate("Command_list", "MOVE")

    def getEnglishName(self):
        return "MOVE"

    def connectQAction(self, action):
        QObject.connect(action, SIGNAL("triggered()"),
                        self.plugIn.runMOVECommand)

    def getIcon(self):
        return QIcon(":/plugins/qad/icons/move.png")

    def getNote(self):
        # impostare le note esplicative del comando
        return QadMsg.translate("Command_MOVE", "Moves the selected objects.")

    def __init__(self, plugIn):
        QadCommandClass.__init__(self, plugIn)
        self.SSGetClass = QadSSGetClass(plugIn)
        self.SSGetClass.onlyEditableLayers = True
        self.entitySet = QadEntitySet()
        self.basePt = QgsPoint()

    def __del__(self):
        QadCommandClass.__del__(self)
        del self.SSGetClass

    def getPointMapTool(self, drawMode=QadGetPointDrawModeEnum.NONE):
        if self.step == 0:  # quando si é in fase di selezione entità
            return self.SSGetClass.getPointMapTool()
        else:
            if (self.plugIn is not None):
                if self.PointMapTool is None:
                    self.PointMapTool = Qad_move_maptool(self.plugIn)
                return self.PointMapTool
            else:
                return None

    #============================================================================
    # move
    #============================================================================
    def move(self, f, offSetX, offSetY, layerEntitySet, entitySet):
        # verifico se l'entità appartiene ad uno stile di quotatura
        dimEntity = QadDimStyles.getDimEntity(layerEntitySet.layer, f.id())

        if dimEntity is None:
            # sposto la feature e la rimuovo da entitySet (é la prima)
            f.setGeometry(
                qad_utils.moveQgsGeometry(f.geometry(), offSetX, offSetY))
            # plugIn, layer, feature, refresh, check_validity
            if qad_layer.updateFeatureToLayer(self.plugIn,
                                              layerEntitySet.layer, f, False,
                                              False) == False:
                return False
            del layerEntitySet.featureIds[0]
        else:
            # sposto la quota e la rimuovo da entitySet
            dimEntitySet = dimEntity.getEntitySet()
            if dimEntity.deleteToLayers(self.plugIn) == False:
                return False
            if dimEntity.move(offSetX, offSetY) == False:
                return False
            if dimEntity.addToLayers(self.plugIn) == False:
                return False
            entitySet.subtract(dimEntitySet)

        return True

    #============================================================================
    # moveGeoms
    #============================================================================
    def moveGeoms(self, newPt):
        # copio entitySet
        entitySet = QadEntitySet(self.entitySet)

        self.plugIn.beginEditCommand("Feature moved", entitySet.getLayerList())

        for layerEntitySet in entitySet.layerEntitySetList:
            transformedBasePt = self.mapToLayerCoordinates(
                layerEntitySet.layer, self.basePt)
            transformedNewPt = self.mapToLayerCoordinates(
                layerEntitySet.layer, newPt)
            offSetX = transformedNewPt.x() - transformedBasePt.x()
            offSetY = transformedNewPt.y() - transformedBasePt.y()

            while len(layerEntitySet.featureIds) > 0:
                featureId = layerEntitySet.featureIds[0]
                f = layerEntitySet.getFeature(featureId)

                if self.move(f, offSetX, offSetY, layerEntitySet,
                             entitySet) == False:
                    self.plugIn.destroyEditCommand()
                    return

        self.plugIn.endEditCommand()

    def run(self, msgMapTool=False, msg=None):
        if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():
            self.showMsg(
                QadMsg.translate(
                    "QAD",
                    "\nThe coordinate reference system of the project must be a projected coordinate system.\n"
                ))
            return True  # fine comando

        #=========================================================================
        # RICHIESTA SELEZIONE OGGETTI
        if self.step == 0:  # inizio del comando
            if self.SSGetClass.run(msgMapTool, msg) == True:
                # selezione terminata
                self.step = 1
                self.getPointMapTool().refreshSnapType(
                )  # aggiorno lo snapType che può essere variato dal maptool di selezione entità
                return self.run(msgMapTool, msg)

        #=========================================================================
        # SPOSTA OGGETTI
        elif self.step == 1:
            self.entitySet.set(self.SSGetClass.entitySet)

            if self.entitySet.count() == 0:
                return True  # fine comando

            # imposto il map tool
            self.getPointMapTool().entitySet.set(self.entitySet)
            self.getPointMapTool().setMode(
                Qad_move_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_BASE_PT)

            keyWords = QadMsg.translate("Command_MOVE", "Displacement")
            prompt = QadMsg.translate(
                "Command_MOVE",
                "Specify base point or [{0}] <{0}>: ").format(keyWords)

            englishKeyWords = "Displacement"
            keyWords += "_" + englishKeyWords
            # si appresta ad attendere un punto o enter o una parola chiave
            # msg, inputType, default, keyWords, nessun controllo
            self.waitFor(prompt, \
                         QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \
                         None, \
                         keyWords, QadInputModeEnum.NONE)
            self.step = 2
            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA PUNTO BASE (da step = 1)
        elif self.step == 2:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        pass  # opzione di default "spostamento"
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            if value is None or type(value) == unicode:
                self.basePt.set(0, 0)
                self.getPointMapTool().basePt = self.basePt
                self.getPointMapTool().setMode(
                    Qad_move_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_MOVE_PT)
                # si appresta ad attendere un punto
                msg = QadMsg.translate(
                    "Command_MOVE",
                    "Specify the displacement fom the origin point 0,0 <{0}, {1}>: "
                )
                # msg, inputType, default, keyWords, nessun controllo
                self.waitFor(msg.format(str(self.plugIn.lastOffsetPt.x()), str(self.plugIn.lastOffsetPt.y())), \
                             QadInputTypeEnum.POINT2D, \
                             self.plugIn.lastOffsetPt, \
                             "", QadInputModeEnum.NONE)
                self.step = 4
            elif type(value) == QgsPoint:  # se é stato inserito il punto base
                self.basePt.set(value.x(), value.y())

                # imposto il map tool
                self.getPointMapTool().basePt = self.basePt
                self.getPointMapTool().setMode(
                    Qad_move_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_MOVE_PT)

                # si appresta ad attendere un punto o enter o una parola chiave
                # msg, inputType, default, keyWords, nessun controllo
                self.waitFor(QadMsg.translate("Command_MOVE", "Specify the second point or <use first point as displacement from the origin point 0,0>: "), \
                             QadInputTypeEnum.POINT2D, \
                             None, \
                             "", QadInputModeEnum.NONE)
                self.step = 3

            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER SPOSTAMENTO (da step = 2)
        elif self.step == 3:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            if value is None:
                newPt = QgsPoint(self.basePt.x() * 2, self.basePt.y() * 2)
                self.moveGeoms(newPt)
            elif type(
                    value
            ) == QgsPoint:  # se é stato inserito lo spostamento con un punto
                self.moveGeoms(value)

            return True  # fine comando

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA DEL PUNTO DI SPOSTAMENTO (da step = 2)
        elif self.step == 4:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            self.plugIn.setLastOffsetPt(value)
            self.moveGeoms(value)
            return True
Example #28
0
 def __init__(self, plugIn):
    QadCommandClass.__init__(self, plugIn)
    self.SSGetClass = QadSSGetClass(plugIn)
    self.SSGetClass.entitySet.set(plugIn.tool.entitySet) # da usare solo con QadMapTool
    self.SSGetClass.exitAfterSelection = True
    self.SSGetClass.step = 1
Example #29
0
class QadMAPMPEDITCommandClass(QadCommandClass):

   def instantiateNewCmd(self):
      """ istanzia un nuovo comando dello stesso tipo """
      return QadMAPMPEDITCommandClass(self.plugIn)

   def getName(self):
      return QadMsg.translate("Command_list", "MAPMPEDIT")
   
   def getEnglishName(self):
      return "MAPMPEDIT"

   def connectQAction(self, action):
      QObject.connect(action, SIGNAL("triggered()"), self.plugIn.runMAPMPEDITCommand)

   def getIcon(self):
      return QIcon(":/plugins/qad/icons/mapmpedit.png")
   
   def getNote(self):
      # impostare le note esplicative del comando      
      return QadMsg.translate("Command_MAPMPEDIT", "Modifies existing polygon.")
   
   def __init__(self, plugIn):
      QadCommandClass.__init__(self, plugIn)
      
      self.poligonEntity = QadEntity()
      
      self.SSGetClass = QadSSGetClass(plugIn)
      self.SSGetClass.onlyEditableLayers = False
      self.SSGetClass.checkDimLayers = False # scarto le quote
      
      self.entSelClass = None
      
      self.currSubGeom = None
      self.currAtSubGeom = None
     
      self.nOperationsToUndo = 0
   
   def __del__(self):
      QadCommandClass.__del__(self)
      del self.SSGetClass
      self.poligonEntity.deselectOnLayer()

   def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):
      if self.step == 1 or self.step == 4: # quando si é in fase di selezione entità
         return self.entSelClass.getPointMapTool(drawMode)
      elif self.step == 3 or self.step == 5 or \
           self.step == 6 or self.step == 7 or self.step == 8: # quando si é in fase di selezione gruppo entità
         return self.SSGetClass.getPointMapTool()           
      else:
         return QadCommandClass.getPointMapTool(self, drawMode)


   def getCurrentContextualMenu(self):
      if self.step == 1 or self.step == 4: # quando si é in fase di selezione entità
         return self.entSelClass.getCurrentContextualMenu()
      elif self.step == 3 or self.step == 5 or \
           self.step == 6 or self.step == 7 or self.step == 8: # quando si é in fase di selezione gruppo entità
         return self.SSGetClass.getCurrentContextualMenu()           
      else:
         return self.contextualMenu


   def reinitSSGetClass(self):
      checkPointLayer = self.SSGetClass.checkPointLayer
      del self.SSGetClass
      self.SSGetClass = QadSSGetClass(self.plugIn)
      self.SSGetClass.onlyEditableLayers = False
      self.SSGetClass.checkDimLayers = False # scarto le quote
      self.SSGetClass.checkPointLayer = checkPointLayer


   #============================================================================
   # setCurrentSubGeom
   #============================================================================
   def setCurrentSubGeom(self, entSelClass):
      """
      Setta la sottogeometria corrente
      """
      self.currSubGeom = None
      self.currAtSubGeom = None

      # verifico che sia stata selezionata un'entità
      if entSelClass.entity.isInitialized() == False:
         self.showMsg(QadMsg.translate("QAD", "No geometries in this position."))
         return False
      # verifico che sia stata selezionata attraverso un punto
      # (per capire quale sottogeometria è stata selezionata)
      if entSelClass.point is None: return False
      # verifico che sia stato selezionato lo stesso polygono che è da modificare
      if self.poligonEntity != entSelClass.entity:
         self.showMsg(QadMsg.translate("Command_MAPMPEDIT", "The boundary doesn't belong to the selected polygon."))
         return False
      
      # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy
      geom = self.layerToMapCoordinates(entSelClass.entity.layer, entSelClass.entity.getGeometry())
      
      # ritorna una tupla (<The squared cartesian distance>,
      #                    <minDistPoint>
      #                    <afterVertex>
      #                    <leftOf>)
      dummy = qad_utils.closestSegmentWithContext(entSelClass.point, geom)
      if dummy[2] is None:
         return False
      # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)
      self.currSubGeom, self.currAtSubGeom = qad_utils.getSubGeomAtVertex(geom, dummy[2])
      if self.currSubGeom is None or self.currAtSubGeom is None:
         self.currSubGeom = None
         self.currAtSubGeom = None
         return False
      
      return True
   

   #============================================================================
   # addEntitySetToPolygon
   #============================================================================
   def addEntitySetToPolygon(self, entitySet, removeOriginals = False):
      """
      Aggiunge il set di entità al poligono da modificare
      """
      geom = self.poligonEntity.getGeometry()
      layerList = []
      layerList.append(self.poligonEntity.layer)
      
      for layerEntitySet in entitySet.layerEntitySetList:
         layer = layerEntitySet.layer
         if layer.geometryType() != QGis.Polygon and layer.geometryType() != QGis.Line:
            self.showMsg(QadMsg.translate("QAD", "Invalid object."))
            return False

         if removeOriginals: layerList.append(layer)
         coordTransform = QgsCoordinateTransform(layer.crs(), self.poligonEntity.layer.crs())

         for featureId in layerEntitySet.featureIds:
            # se la feature è quella di polygonEntity è errore 
            if layer.id() == self.poligonEntity.layerId() and featureId == self.poligonEntity.featureId:
               self.showMsg(QadMsg.translate("QAD", "Invalid object."))
               return False
            
            f = layerEntitySet.getFeature(featureId)
            # trasformo la geometria nel crs del layer del poligono da modificare
            geomToAdd = f.geometry()
            geomToAdd.transform(coordTransform)
            
            # se il poligono è contenuto nella geometria da aggiungere
            if geomToAdd.contains(geom):
               # Riduco la geometria in point o polyline
               simplifiedGeoms = qad_utils.asPointOrPolyline(geom)
               # deve essere un poligono senza ring
               if len(simplifiedGeoms) != 1 or simplifiedGeoms[0].wkbType() != QGis.WKBLineString:
                  self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                  return False
               points = simplifiedGeoms[0].asPolyline() # vettore di punti
               # aggiungo un'isola
               if geomToAdd.addRing(points) != 0: # 0 in case of success
                  self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                  return False
               del geom
               geom = QgsGeometry.fromPolygon(geomToAdd.asPolygon())
            else: # se il poligono non è contenuto nella geometria da aggiungere
               # Riduco la geometria in point o polyline
               simplifiedGeoms = qad_utils.asPointOrPolyline(geomToAdd)
               for simplifiedGeom in simplifiedGeoms:
                  points = simplifiedGeom.asPolyline() # vettore di punti                     
                  # se la geometria da aggiungere è contenuta nel poligono
                  if geom.contains(QgsGeometry.fromPolyline(points)):
                     # aggiungo un'isola
                     if geom.addRing(points) != 0: # 0 in case of success
                        self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                        return False
                  else:
                     # aggiungo una parte
                     if geom.addPart(points) != 0: # 0 in case of success
                        self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                        return False

      f = self.poligonEntity.getFeature()
      f.setGeometry(geom)

      layerList = entitySet.getLayerList()
      layerList.append(self.poligonEntity.layer)

      self.plugIn.beginEditCommand("Feature edited", layerList)
         
      # plugIn, layer, feature, refresh, check_validity
      if qad_layer.updateFeatureToLayer(self.plugIn, self.poligonEntity.layer, f, False, False) == False:
         self.plugIn.destroyEditCommand()
         return False

      if removeOriginals:
         for layerEntitySet in entitySet.layerEntitySetList:            
            if qad_layer.deleteFeaturesToLayer(self.plugIn, layerEntitySet.layer, layerEntitySet.featureIds, False) == False:
               self.plugIn.destroyEditCommand()
               return 

      self.plugIn.endEditCommand()
      self.nOperationsToUndo = self.nOperationsToUndo + 1

      return True
   

   #============================================================================
   # delCurrentSubGeomToPolygon
   #============================================================================
   def delCurrentSubGeomToPolygon(self):
      """
      Cancella la sotto-geometria corrente dal poligono da modificare
      """
      geom = self.poligonEntity.getGeometry()

       # la posizione é espressa con una lista (<index ogg. princ> [<index ogg. sec.>])
      part = self.currAtSubGeom[0]
      if len(self.currAtSubGeom) == 2:
         ring = self.currAtSubGeom[1]
         if geom.deleteRing(ring + 1, part) == False: # cancello una isola (Ring 0 is outer ring and can't be deleted)
            self.showMsg(QadMsg.translate("QAD", "Invalid object."))
            return False
      else:
         if geom.deletePart(part) == False: # cancello una parte
            self.showMsg(QadMsg.translate("QAD", "Invalid object."))
            return False

      f = self.poligonEntity.getFeature()
      f.setGeometry(geom)

      self.plugIn.beginEditCommand("Feature edited", self.poligonEntity.layer)
         
      # plugIn, layer, feature, refresh, check_validity
      if qad_layer.updateFeatureToLayer(self.plugIn, self.poligonEntity.layer, f, False, False) == False:
         self.plugIn.destroyEditCommand()
         return False

      self.plugIn.endEditCommand()
      self.nOperationsToUndo = self.nOperationsToUndo + 1


   #============================================================================
   # unionIntersSubtractEntitySetToPolygon
   #============================================================================
   def unionIntersSubtractEntitySetToPolygon(self, entitySet, opType, removeOriginals = False):
      """
      Unisce o interseca i poligoni di entitySet al poligono corrente
      """
      geom = self.poligonEntity.getGeometry()
      layerList = []
      layerList.append(self.poligonEntity.layer)
      
      geomList = []
      geomList.append(geom)
      for layerEntitySet in entitySet.layerEntitySetList:
         del geomList[:]
         layer = layerEntitySet.layer
         coordTransform = QgsCoordinateTransform(layer.crs(), self.poligonEntity.layer.crs())
         
         if layer.geometryType() == QGis.Polygon:
            for featureId in layerEntitySet.featureIds:
               # se la feature è quella di polygonEntity è errore 
               if layer.id() == self.poligonEntity.layerId() and featureId == self.poligonEntity.featureId:
                  self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                  return False
               f = layerEntitySet.getFeature(featureId)
               # trasformo la geometria nel crs del layer del poligono da modificare
               geomToAdd = f.geometry()

               geomToAdd.transform(coordTransform)

               if opType == QadMAPMPEDITCommandOpTypeEnum.UNION: geom = geom.combine(geomToAdd)
               elif opType == QadMAPMPEDITCommandOpTypeEnum.INTERSECTION: geom = geom.intersection(geomToAdd)
               elif opType == QadMAPMPEDITCommandOpTypeEnum.DIFFERENCE: geom = geom.difference(geomToAdd)
               
               if geom is None:
                  self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                  return False
               
               if removeOriginals and layer.id() != self.poligonEntity.layerId():
                  layerList.append(layer)

         elif layer.geometryType() == QGis.Line:
            for featureId in layerEntitySet.featureIds:
               f = layerEntitySet.getFeature(featureId)
               # trasformo la geometria nel crs del layer del poligono da modificare
               geomToAdd = f.geometry()
               geomToAdd.transform(coordTransform)
               # Riduco la geometria in point o polyline
               simplifiedGeoms = qad_utils.asPointOrPolyline(geomToAdd)
               for simplifiedGeom in simplifiedGeoms:
                  if simplifiedGeom.wkbType() != QGis.WKBLineString:
                     self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                     return False
                  points = simplifiedGeom.asPolyline() # vettore di punti
                  
                  if len(points) < 4 or points[0] != points[-1]: # polilinea chiusa con almeno 4 punti (primo e ultimo uguali)
                     self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                     return False
                  geomToAdd = QgsGeometry.fromPolygon([points])
                  
                  if opType == QadMAPMPEDITCommandOpTypeEnum.UNION: geom = geom.combine(geomToAdd)
                  elif opType == QadMAPMPEDITCommandOpTypeEnum.INTERSECTION: geom = geom.intersection(geomToAdd)
                  elif opType == QadMAPMPEDITCommandOpTypeEnum.DIFFERENCE: geom = geom.difference(geomToAdd)
                  
                  if geom is None or geom.type() != QGis.Polygon:
                     self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                     return False
                  
               if removeOriginals: layerList.append(layer)
         else:
            self.showMsg(QadMsg.translate("QAD", "Invalid object."))
            return False

      f = self.poligonEntity.getFeature()
      f.setGeometry(geom)

      self.plugIn.beginEditCommand("Feature edited", layerList)
         
      # plugIn, layer, feature, refresh, check_validity
      if qad_layer.updateFeatureToLayer(self.plugIn, self.poligonEntity.layer, f, False, False) == False:
         self.plugIn.destroyEditCommand()
         return False

      if removeOriginals:
         for layerEntitySet in entitySet.layerEntitySetList:            
            if qad_layer.deleteFeaturesToLayer(self.plugIn, layerEntitySet.layer, layerEntitySet.featureIds, False) == False:
               self.plugIn.destroyEditCommand()
               return 

      self.plugIn.endEditCommand()
      self.nOperationsToUndo = self.nOperationsToUndo + 1

      return True

   
   #============================================================================
   # convexHullEntitySetToPolygon
   #============================================================================
   def convexHullEntitySetToPolygon(self, entitySet, removeOriginals = False):
      """
      modifica il poligono corrente in modo che includa tutti i punti delle geometrie di entitySet
      """
      layerList = []
      layerList.append(self.poligonEntity.layer)
      pointsForConvexHull = []
      
      for layerEntitySet in entitySet.layerEntitySetList:
         layer = layerEntitySet.layer
         coordTransform = QgsCoordinateTransform(layer.crs(), self.poligonEntity.layer.crs())
         
         for featureId in layerEntitySet.featureIds:
            f = layerEntitySet.getFeature(featureId)
            # trasformo la geometria nel crs del layer del poligono da modificare
            geom = f.geometry()
            geom.transform(coordTransform)

            # Riduco la geometria in point o polyline
            simplifiedGeoms = qad_utils.asPointOrPolyline(geom)
            for simplifiedGeom in simplifiedGeoms:
               if simplifiedGeom.wkbType() == QGis.WKBLineString:
                  pointsForConvexHull.extend(simplifiedGeom.asPolyline())
               else:
                  pointsForConvexHull.append(simplifiedGeom.asPoint())
               
            if removeOriginals and layer.id() != self.poligonEntity.layerId():
               layerList.append(layer)

      geom = QgsGeometry.fromMultiPoint(pointsForConvexHull)
      geom = geom.convexHull()
      if geom is None:
         self.showMsg(QadMsg.translate("QAD", "Invalid object."))
         return False
         
      f = self.poligonEntity.getFeature()
      f.setGeometry(geom)

      self.plugIn.beginEditCommand("Feature edited", layerList)
         
      # plugIn, layer, feature, refresh, check_validity
      if qad_layer.updateFeatureToLayer(self.plugIn, self.poligonEntity.layer, f, False, False) == False:
         self.plugIn.destroyEditCommand()
         return False

      if removeOriginals:
         for layerEntitySet in entitySet.layerEntitySetList:            
            if qad_layer.deleteFeaturesToLayer(self.plugIn, layerEntitySet.layer, layerEntitySet.featureIds, False) == False:
               self.plugIn.destroyEditCommand()
               return 

      self.plugIn.endEditCommand()
      self.nOperationsToUndo = self.nOperationsToUndo + 1

      return True


   #============================================================================
   # dividePolygon
   #============================================================================
   def splitPolygon(self, splitLine, createNewEntities):
      """
      divide il poligono corrente usando una polilinea con i vertci in <plineVertices> in modo da generare o meno nuove entità
      """
      layerList = []
      layerList.append(self.poligonEntity.layer)
      
      splitLineTransformed = self.mapToLayerCoordinates(self.poligonEntity.layer, splitLine)
      f = self.poligonEntity.getFeature()
      geom = f.geometry()
      result, newGeoms, topologyTestPts = geom.splitGeometry(splitLineTransformed, False)

      if result <> 0 or len(newGeoms) == 0:
         self.showMsg(QadMsg.translate("QAD", "Invalid object."))
         return False
         
      newfeatures =[]
      if createNewEntities:
         for newGeom in newGeoms:
            newfeature = QgsFeature(f)
            newfeature.setGeometry(newGeom)
            newfeatures.append(newfeature)
      else:
         for newGeom in newGeoms:
            # Riduco la geometria in point o polyline
            simplifiedGeoms = qad_utils.asPointOrPolyline(newGeom)
            for simplifiedGeom in simplifiedGeoms:
               points = simplifiedGeom.asPolyline() # vettore di punti                     
               res = geom.addPart(points)
      
      f.setGeometry(geom)
      
      self.plugIn.beginEditCommand("Feature edited", layerList)
         
      # plugIn, layer, feature, refresh, check_validity
      if qad_layer.updateFeatureToLayer(self.plugIn, self.poligonEntity.layer, f, False, False) == False:
         self.plugIn.destroyEditCommand()
         return False

      if len(newfeatures) > 0:
         # plugIn, layer, features, coordTransform, refresh, check_validity
         if qad_layer.addFeaturesToLayer(self.plugIn, self.poligonEntity.layer, newfeatures, None, False, False) == False:
            self.plugIn.destroyEditCommand()
            return

      self.plugIn.endEditCommand()
      self.nOperationsToUndo = self.nOperationsToUndo + 1

      return True



   #============================================================================
   # waitForEntsel
   #============================================================================
   def waitForEntsel(self, msgMapTool, msg):
      if self.entSelClass is not None:
         del self.entSelClass
      self.step = 1
      self.entSelClass = QadEntSelClass(self.plugIn)
      self.entSelClass.msg = QadMsg.translate("Command_MAPMPEDIT", "Select polygon: ")
      # scarto la selezione di punti e polilinee
      self.entSelClass.checkPointLayer = False
      self.entSelClass.checkLineLayer = False
      self.entSelClass.checkPolygonLayer = True
      self.entSelClass.checkDimLayers = False     
      self.entSelClass.onlyEditableLayers = True

      self.entSelClass.run(msgMapTool, msg)
      

   #============================================================================
   # WaitForMainMenu
   #============================================================================
   def WaitForMainMenu(self):
      self.poligonEntity.selectOnLayer(False)
      keyWords = QadMsg.translate("Command_MAPMPEDIT", "Add") + "/" + \
                 QadMsg.translate("Command_MAPMPEDIT", "Delete") + "/" + \
                 QadMsg.translate("Command_MAPMPEDIT", "Union") + "/" + \
                 QadMsg.translate("Command_MAPMPEDIT", "Substract") + "/" + \
                 QadMsg.translate("Command_MAPMPEDIT", "Intersect") + "/" + \
                 QadMsg.translate("Command_MAPMPEDIT", "split Objects") + "/" + \
                 QadMsg.translate("Command_MAPMPEDIT", "split Parts") + "/" + \
                 QadMsg.translate("Command_MAPMPEDIT", "iNclude objs")
      englishKeyWords = "Add" + "/" + "Delete" + "/" + "Union" + "/" + "Substract" + "/" + "Intersect" "/" + \
                        "split Objects" + "/" + "split Parts" + "/" + "iNclude objs"

      if self.nOperationsToUndo > 0: # se c'è qualcosa che si può annullare
         keyWords = keyWords + "/" +  QadMsg.translate("Command_MAPMPEDIT", "Undo")
         englishKeyWords = englishKeyWords + "/" + "Undo"
      
      keyWords = keyWords + "/" + QadMsg.translate("Command_MAPMPEDIT", "eXit")
      englishKeyWords = englishKeyWords + "/" + "eXit"
                 
      default = QadMsg.translate("Command_MAPMPEDIT", "eXit")

      prompt = QadMsg.translate("Command_MAPMPEDIT", "Enter an option [{0}] <{1}>: ").format(keyWords, default)
      
      self.step = 2
      self.getPointMapTool().setSelectionMode(QadGetPointSelectionModeEnum.NONE)
      self.getPointMapTool().setDrawMode(QadGetPointDrawModeEnum.NONE)
      
      keyWords += "_" + englishKeyWords
      # si appresta ad attendere enter o una parola chiave         
      # msg, inputType, default, keyWords, nessun controllo
      self.waitFor(prompt, \
                   QadInputTypeEnum.KEYWORDS, \
                   None, \
                   keyWords, QadInputModeEnum.NONE)
      return False
      

   #============================================================================
   # waitForBoundary
   #============================================================================
   def waitForBoundary(self, msgMapTool, msg):
      if self.entSelClass is not None:
         del self.entSelClass
      self.entSelClass = QadEntSelClass(self.plugIn)
      self.entSelClass.msg = QadMsg.translate("Command_MAPMPEDIT", "Select boundary: ")
      # scarto la selezione di punti e polilinee
      self.entSelClass.checkPointLayer = False
      self.entSelClass.checkLineLayer = False
      self.entSelClass.checkPolygonLayer = True
      self.entSelClass.checkDimLayers = False
      self.entSelClass.onlyEditableLayers = True

      self.entSelClass.run(msgMapTool, msg)


   def run(self, msgMapTool = False, msg = None):
      if self.plugIn.canvas.mapSettings().destinationCrs().geographicFlag():
         self.showMsg(QadMsg.translate("QAD", "\nThe coordinate reference system of the project must be a projected coordinate system.\n"))
         return True # fine comando
      
      if self.step == 0:
         self.waitForEntsel(msgMapTool, msg) # seleziona il poligono da modificare
         return False # continua
      
      #=========================================================================
      # RISPOSTA ALLA SELEZIONE POLIGONO DA MODIFICARE
      elif self.step == 1:
         if self.entSelClass.run(msgMapTool, msg) == True:
            if self.entSelClass.entity.isInitialized():
               self.poligonEntity.set(self.entSelClass.entity.layer, self.entSelClass.entity.featureId)
               layer = self.entSelClass.entity.layer
               self.poligonEntity.deselectOnLayer()
               self.WaitForMainMenu()
            else:
               if self.entSelClass.canceledByUsr == True: # fine comando
                  return True
               self.showMsg(QadMsg.translate("QAD", "No geometries in this position."))
               self.waitForEntsel(msgMapTool, msg)

         return False # continua

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DEL MENU PRINCIPALE
      elif self.step == 2: # dopo aver atteso una opzione si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            self.WaitForMainMenu()
            return False 
         else: # l'opzione arriva come parametro della funzione
            value = msg

         self.poligonEntity.deselectOnLayer()

         if value == QadMsg.translate("Command_MAPMPEDIT", "Add") or value == "Add":
            self.SSGetClass.checkPointLayer = False # scarto i punto
            self.SSGetClass.run(msgMapTool, msg)
            self.step = 3
            return False
         elif value == QadMsg.translate("Command_MAPMPEDIT", "Delete") or value == "Delete":
            self.waitForBoundary(msgMapTool, msg)
            self.step = 4
            return False
         elif value == QadMsg.translate("Command_MAPMPEDIT", "Union") or value == "Union":
            self.SSGetClass.checkPointLayer = False # scarto i layer puntuali
            self.SSGetClass.run(msgMapTool, msg)
            self.step = 5
            return False
         elif value == QadMsg.translate("Command_MAPMPEDIT", "Substract") or value == "Substract":
            self.SSGetClass.checkPointLayer = False # scarto i layer puntuali
            self.SSGetClass.run(msgMapTool, msg)
            self.step = 6
            return False
         elif value == QadMsg.translate("Command_MAPMPEDIT", "Intersect") or value == "Intersect":
            self.SSGetClass.checkPointLayer = False # scarto i layer puntuali
            self.SSGetClass.run(msgMapTool, msg)
            self.step = 7
            return False
         elif value == QadMsg.translate("Command_MAPMPEDIT", "split Objects") or value == "split Objects":
            # Disegna una polilinea di divisione del poligono
            self.PLINECommand = QadPLINECommandClass(self.plugIn)
            # se questo flag = True il comando serve all'interno di un altro comando per disegnare una linea
            # che non verrà salvata su un layer
            self.PLINECommand.virtualCmd = True   
            self.PLINECommand.run(msgMapTool, msg)
            self.step = 9
            return False
         elif value == QadMsg.translate("Command_MAPMPEDIT", "split Parts") or value == "split Parts":
            # Disegna una polilinea di divisione del poligono
            self.PLINECommand = QadPLINECommandClass(self.plugIn)
            # se questo flag = True il comando serve all'interno di un altro comando per disegnare una linea
            # che non verrà salvata su un layer
            self.PLINECommand.virtualCmd = True   
            self.PLINECommand.run(msgMapTool, msg)
            self.step = 10
            return False
         elif value == QadMsg.translate("Command_MAPMPEDIT", "iNclude objs") or value == "iNclude objs":
            self.SSGetClass.checkPointLayer = True # includo i layer puntuali
            self.SSGetClass.run(msgMapTool, msg)
            self.step = 8
            return False
         elif value == QadMsg.translate("Command_MAPMPEDIT", "Undo") or value == "Undo":
            if self.nOperationsToUndo > 0: 
               self.nOperationsToUndo = self.nOperationsToUndo - 1           
               self.plugIn.undoEditCommand()
            else:
               self.showMsg(QadMsg.translate("QAD", "\nThe command has been canceled."))
         elif value == QadMsg.translate("Command_MAPMPEDIT", "eXit") or value == "eXit":
            return True # fine comando
         else:
            return True # fine comando
         
         self.WaitForMainMenu()
         return False      

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA MODALITA' DI ADD (da step = 2)
      elif self.step == 3:
         if self.SSGetClass.run(msgMapTool, msg) == True:
            if self.SSGetClass.entitySet.count() > 0:
               self.addEntitySetToPolygon(self.SSGetClass.entitySet)
            self.reinitSSGetClass()
            self.WaitForMainMenu()
         return False
      
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA MODALITA' DI DELETE (da step = 2)
      elif self.step == 4:
         if self.entSelClass.run(msgMapTool, msg) == True:
            if self.setCurrentSubGeom(self.entSelClass) == True:
               self.delCurrentSubGeomToPolygon()
               self.WaitForMainMenu()
               return False
            else:
               if self.entSelClass.canceledByUsr == True: # fine selezione entità
                  self.WaitForMainMenu()
               else:
                  self.waitForBoundary(msgMapTool, msg)
         return False # continua

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA MODALITA' DI UNION (da step = 2)
      elif self.step == 5: # dopo aver atteso una entità si riavvia il comando
         if self.SSGetClass.run(msgMapTool, msg) == True:
            if self.SSGetClass.entitySet.count() > 0:
               self.unionIntersSubtractEntitySetToPolygon(self.SSGetClass.entitySet, QadMAPMPEDITCommandOpTypeEnum.UNION)
            self.reinitSSGetClass()
            self.WaitForMainMenu()
         return False # continua

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA MODALITA' DI SUBTRACT (da step = 2)
      elif self.step == 6: # dopo aver atteso una entità si riavvia il comando
         if self.SSGetClass.run(msgMapTool, msg) == True:
            if self.SSGetClass.entitySet.count() > 0:
               self.unionIntersSubtractEntitySetToPolygon(self.SSGetClass.entitySet, QadMAPMPEDITCommandOpTypeEnum.DIFFERENCE)
            self.reinitSSGetClass()
            self.WaitForMainMenu()
         return False # continua

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA MODALITA' DI INTERSECT (da step = 2)
      elif self.step == 7: # dopo aver atteso una entità si riavvia il comando
         if self.SSGetClass.run(msgMapTool, msg) == True:
            if self.SSGetClass.entitySet.count() > 0:
               self.unionIntersSubtractEntitySetToPolygon(self.SSGetClass.entitySet, QadMAPMPEDITCommandOpTypeEnum.INTERSECTION)
            self.reinitSSGetClass()
            self.WaitForMainMenu()
         return False # continua

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA MODALITA' DI INCLUDE OBJS (da step = 2)
      elif self.step == 8: # dopo aver atteso una entità si riavvia il comando
         if self.SSGetClass.run(msgMapTool, msg) == True:
            if self.SSGetClass.entitySet.count() > 0:
               self.convexHullEntitySetToPolygon(self.SSGetClass.entitySet)
            self.reinitSSGetClass()
            self.WaitForMainMenu()
         return False # continua

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA LINEA DI DIVISIONE (da step = 2)
      elif self.step == 9: # dopo aver atteso un punto si riavvia il comando
         if self.PLINECommand.run(msgMapTool, msg) == True:
            self.showMsg("\n")
            self.splitPolygon(self.PLINECommand.vertices, True)
            del self.PLINECommand
            self.PLINECommand = None
            self.WaitForMainMenu()
         return False

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA LINEA DI DIVISIONE (da step = 2)
      elif self.step == 10: # dopo aver atteso un punto si riavvia il comando
         if self.PLINECommand.run(msgMapTool, msg) == True:
            self.showMsg("\n")
            self.splitPolygon(self.PLINECommand.vertices, False)
            del self.PLINECommand
            self.PLINECommand = None
            self.WaitForMainMenu()
         return False
Example #30
0
class QadJOINCommandClass(QadCommandClass):

   def instantiateNewCmd(self):
      """ istanzia un nuovo comando dello stesso tipo """
      return QadJOINCommandClass(self.plugIn)

   def getName(self):
      return QadMsg.translate("Command_list", "JOIN")
   
   def getEnglishName(self):
      return "JOIN"

   def connectQAction(self, action):
      QObject.connect(action, SIGNAL("triggered()"), self.plugIn.runJOINCommand)

   def getIcon(self):
      return QIcon(":/plugins/qad/icons/join.png")
   
   def getNote(self):
      # impostare le note esplicative del comando      
      return QadMsg.translate("Command_JOIN", "Join existing geometries.")
   
   def __init__(self, plugIn):
      QadCommandClass.__init__(self, plugIn)
      
      self.entity = QadEntity()
      
      self.SSGetClass = None
      self.entSelClass = None
   
   def __del__(self):
      QadCommandClass.__del__(self)
      if self.SSGetClass is not None:  del self.SSGetClass


   def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):
      if self.step == 1: # quando si é in fase di selezione entità
         return self.entSelClass.getPointMapTool(drawMode)
      elif self.step == 2: # quando si é in fase di selezione gruppo entità
         return self.SSGetClass.getPointMapTool()
      else:
         return QadCommandClass.getPointMapTool(self, drawMode)


   def getCurrentContextualMenu(self):
      if self.step == 1: # quando si é in fase di selezione entità
         return self.entSelClass.getCurrentContextualMenu()
      elif self.step == 2: # quando si é in fase di selezione gruppo entità
         return self.SSGetClass.getCurrentContextualMenu()()
      else:
         return self.contextualMenu


   def reinitSSGetClass(self):
      if self.SSGetClass is not None: del self.SSGetClass
      
      self.SSGetClass = QadSSGetClass(self.plugIn)
      self.SSGetClass.onlyEditableLayers = True
      self.SSGetClass.checkDimLayers = False # scarto le quote
      geometryType = self.entity.layer.geometryType()
      if geometryType == QGis.Point:
         self.SSGetClass.checkPointLayer = True
         self.SSGetClass.checkLineLayer = False
         self.SSGetClass.checkPolygonLayer = False
      elif geometryType == QGis.Line:
         self.SSGetClass.checkPointLayer = False
         self.SSGetClass.checkLineLayer = True
         self.SSGetClass.checkPolygonLayer = True
      elif geometryType == QGis.Polygon:
         self.SSGetClass.checkPointLayer = False
         self.SSGetClass.checkLineLayer = True
         self.SSGetClass.checkPolygonLayer = True
   

   #============================================================================
   # addEntitySetToPoint
   #============================================================================
   def addEntitySetToPoint(self, entitySet, removeOriginals = True):
      """
      Aggiunge il set di entità al punto da modificare
      """
      geom = self.entity.getGeometry()
      layerList = []
      layerList.append(self.entity.layer)
      
      for layerEntitySet in entitySet.layerEntitySetList:
         layer = layerEntitySet.layer
         if layer.geometryType() != QGis.Point:
            self.showMsg(QadMsg.translate("QAD", "Invalid object."))
            return False

         if removeOriginals: layerList.append(layer)
         coordTransform = QgsCoordinateTransform(layer.crs(), self.entity.layer.crs())

         for featureId in layerEntitySet.featureIds:
            # se la feature è quella di entity è errore 
            if layer.id() == self.entity.layerId() and featureId == self.entity.featureId:
               self.showMsg(QadMsg.translate("QAD", "Invalid object."))
               return False
            
            f = layerEntitySet.getFeature(featureId)
            # trasformo la geometria nel crs del layer dell'entità da modificare
            geomToAdd = f.geometry()
            geomToAdd.transform(coordTransform)
            
            simplifiedGeoms = qad_utils.asPointOrPolyline(geomToAdd)
            for simplifiedGeom in simplifiedGeoms:
               point = simplifiedGeom.asPoint()
               # aggiungo una parte
               if geom.addPart([point]) != 0: # 0 in case of success
                  self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                  return False

      f = self.entity.getFeature()
      f.setGeometry(geom)

      layerList = entitySet.getLayerList()
      layerList.append(self.entity.layer)

      self.plugIn.beginEditCommand("Feature edited", layerList)
         
      # plugIn, layer, feature, refresh, check_validity
      if qad_layer.updateFeatureToLayer(self.plugIn, self.entity.layer, f, False, False) == False:
         self.plugIn.destroyEditCommand()
         return False

      if removeOriginals:
         for layerEntitySet in entitySet.layerEntitySetList:            
            if qad_layer.deleteFeaturesToLayer(self.plugIn, layerEntitySet.layer, layerEntitySet.featureIds, False) == False:
               self.plugIn.destroyEditCommand()
               return 

      self.plugIn.endEditCommand()

      return True
   

   #============================================================================
   # addEntitySetToPolyline
   #============================================================================
   def addEntitySetToPolyline(self, entitySet, removeOriginals = True):
      """
      Aggiunge il set di entità alla polilinea da modificare
      """
      geom = self.entity.getGeometry()
      layerList = []
      layerList.append(self.entity.layer)
      
      for layerEntitySet in entitySet.layerEntitySetList:
         layer = layerEntitySet.layer
         if layer.geometryType() != QGis.Polygon and layer.geometryType() != QGis.Line:
            self.showMsg(QadMsg.translate("QAD", "Invalid object."))
            return False

         if removeOriginals: layerList.append(layer)
         coordTransform = QgsCoordinateTransform(layer.crs(), self.entity.layer.crs())

         for featureId in layerEntitySet.featureIds:
            # se la feature è quella di entity è errore 
            if layer.id() == self.entity.layerId() and featureId == self.entity.featureId:
               self.showMsg(QadMsg.translate("QAD", "Invalid object."))
               return False
            
            f = layerEntitySet.getFeature(featureId)
            # trasformo la geometria nel crs del layer dell'entità da modificare
            geomToAdd = f.geometry()
            geomToAdd.transform(coordTransform)
            
            # Riduco la geometria in point o polyline
            simplifiedGeoms = qad_utils.asPointOrPolyline(geomToAdd)
            for simplifiedGeom in simplifiedGeoms:
               points = simplifiedGeom.asPolyline() # vettore di punti                     
               # aggiungo una parte
               if geom.addPart(points) != 0: # 0 in case of success
                  self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                  return False

      f = self.entity.getFeature()
      f.setGeometry(geom)

      layerList = entitySet.getLayerList()
      layerList.append(self.entity.layer)

      self.plugIn.beginEditCommand("Feature edited", layerList)
         
      # plugIn, layer, feature, refresh, check_validity
      if qad_layer.updateFeatureToLayer(self.plugIn, self.entity.layer, f, False, False) == False:
         self.plugIn.destroyEditCommand()
         return False

      if removeOriginals:
         for layerEntitySet in entitySet.layerEntitySetList:            
            if qad_layer.deleteFeaturesToLayer(self.plugIn, layerEntitySet.layer, layerEntitySet.featureIds, False) == False:
               self.plugIn.destroyEditCommand()
               return 

      self.plugIn.endEditCommand()

      return True
   

   #============================================================================
   # addEntitySetToPolygon
   #============================================================================
   def addEntitySetToPolygon(self, entitySet, removeOriginals = True):
      """
      Aggiunge il set di entità al poligono da modificare
      """
      geom = self.entity.getGeometry()
      layerList = []
      layerList.append(self.entity.layer)
      
      for layerEntitySet in entitySet.layerEntitySetList:
         layer = layerEntitySet.layer
         if layer.geometryType() != QGis.Polygon and layer.geometryType() != QGis.Line:
            self.showMsg(QadMsg.translate("QAD", "Invalid object."))
            return False

         if removeOriginals: layerList.append(layer)
         coordTransform = QgsCoordinateTransform(layer.crs(), self.entity.layer.crs())

         for featureId in layerEntitySet.featureIds:
            # se la feature è quella di entity è errore 
            if layer.id() == self.entity.layerId() and featureId == self.entity.featureId:
               self.showMsg(QadMsg.translate("QAD", "Invalid object."))
               return False
            
            f = layerEntitySet.getFeature(featureId)
            # trasformo la geometria nel crs del layer del poligono da modificare
            geomToAdd = f.geometry()
            geomToAdd.transform(coordTransform)
            
            # se il poligono è contenuto nella geometria da aggiungere
            if geomToAdd.contains(geom):
               # Riduco la geometria in point o polyline
               simplifiedGeoms = qad_utils.asPointOrPolyline(geom)
               # deve essere un poligono senza ring
               if len(simplifiedGeoms) != 1 or simplifiedGeoms[0].wkbType() != QGis.WKBLineString:
                  self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                  return False
               points = simplifiedGeoms[0].asPolyline() # vettore di punti
               # aggiungo un'isola
               if geomToAdd.addRing(points) != 0: # 0 in case of success
                  self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                  return False
               del geom
               geom = QgsGeometry.fromPolygon(geomToAdd.asPolygon())
            else: # se il poligono non è contenuto nella geometria da aggiungere
               # Riduco la geometria in point o polyline
               simplifiedGeoms = qad_utils.asPointOrPolyline(geomToAdd)
               for simplifiedGeom in simplifiedGeoms:
                  points = simplifiedGeom.asPolyline() # vettore di punti                     
                  # se la geometria da aggiungere è contenuta nel poligono
                  if geom.contains(QgsGeometry.fromPolyline(points)):
                     # aggiungo un'isola
                     if geom.addRing(points) != 0: # 0 in case of success
                        self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                        return False
                  else:
                     # aggiungo una parte
                     if geom.addPart(points) != 0: # 0 in case of success
                        self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                        return False

      f = self.entity.getFeature()
      f.setGeometry(geom)

      layerList = entitySet.getLayerList()
      layerList.append(self.entity.layer)

      self.plugIn.beginEditCommand("Feature edited", layerList)
         
      # plugIn, layer, feature, refresh, check_validity
      if qad_layer.updateFeatureToLayer(self.plugIn, self.entity.layer, f, False, False) == False:
         self.plugIn.destroyEditCommand()
         return False

      if removeOriginals:
         for layerEntitySet in entitySet.layerEntitySetList:            
            if qad_layer.deleteFeaturesToLayer(self.plugIn, layerEntitySet.layer, layerEntitySet.featureIds, False) == False:
               self.plugIn.destroyEditCommand()
               return 

      self.plugIn.endEditCommand()

      return True


   #============================================================================
   # waitForEntsel
   #============================================================================
   def waitForEntsel(self, msgMapTool, msg):
      if self.entSelClass is not None:
         del self.entSelClass
      self.step = 1
      self.entSelClass = QadEntSelClass(self.plugIn)
      self.entSelClass.msg = QadMsg.translate("Command_JOIN", "Select object to join to: ")
      # scarto la selezione di quote
      self.entSelClass.checkDimLayers = False     
      self.entSelClass.onlyEditableLayers = True
      self.entSelClass.deselectOnFinish = True
      
      self.entSelClass.run(msgMapTool, msg)


   #============================================================================
   # waitForSSsel
   #============================================================================
   def waitForSSsel(self, msgMapTool, msg):
      self.reinitSSGetClass()
      self.step = 2
      self.showMsg(QadMsg.translate("Command_JOIN", "\nSelect objects to join: "))
      self.SSGetClass.run(msgMapTool, msg)


   def run(self, msgMapTool = False, msg = None):
      if self.plugIn.canvas.mapSettings().destinationCrs().geographicFlag():
         self.showMsg(QadMsg.translate("QAD", "\nThe coordinate reference system of the project must be a projected coordinate system.\n"))
         return True # fine comando
      
      if self.step == 0:
         self.waitForEntsel(msgMapTool, msg) # seleziona l'oggetto a cui aggregarsi
         return False # continua
      
      #=========================================================================
      # RISPOSTA ALLA SELEZIONE ENTITA' DA MODIFICARE
      elif self.step == 1:
         if self.entSelClass.run(msgMapTool, msg) == True:
            if self.entSelClass.entity.isInitialized():
               self.entity.set(self.entSelClass.entity)

               self.waitForSSsel(msgMapTool, msg)
            else:
               if self.entSelClass.canceledByUsr == True: # fine comando
                  return True
               self.showMsg(QadMsg.translate("QAD", "No geometries in this position."))
               self.waitForEntsel(msgMapTool, msg)

         return False # continua

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DEL GRUPPO DI SELEZIONE (da step = 1)
      elif self.step == 2:
         if self.SSGetClass.run(msgMapTool, msg) == True:
            if self.SSGetClass.entitySet.count() > 0:
               geometryType = self.entity.layer.geometryType()
               if geometryType == QGis.Point:
                  self.addEntitySetToPoint(self.SSGetClass.entitySet)
               elif geometryType == QGis.Line:
                  self.addEntitySetToPolyline(self.SSGetClass.entitySet)
               elif geometryType == QGis.Polygon:
                  self.addEntitySetToPolygon(self.SSGetClass.entitySet)
               
               return True
               
            self.waitForSSsel(msgMapTool, msg)
         return False
class QadSETCURRUPDATEABLELAYERBYGRAPHCommandClass(QadCommandClass):

   def instantiateNewCmd(self):
      """ istanzia un nuovo comando dello stesso tipo """
      return QadSETCURRUPDATEABLELAYERBYGRAPHCommandClass(self.plugIn)

   def getName(self):
      return QadMsg.translate("Command_list", "SETCURRUPDATEABLELAYERBYGRAPH")

   def getEnglishName(self):
      return "SETCURRUPDATEABLELAYERBYGRAPH"

   def connectQAction(self, action):
      QObject.connect(action, SIGNAL("triggered()"), self.plugIn.runSETCURRUPDATEABLELAYERBYGRAPHCommand)

   def getIcon(self):
      return QIcon(":/plugins/qad/icons/setcurrupdateablelayerbygraph.png")
   
   def getNote(self):
      # impostare le note esplicative del comando      
      return QadMsg.translate("Command_SETCURRUPDATEABLELAYERBYGRAPH", "Sets the layers of a graphical objects as editable.")
   
   def __init__(self, plugIn):
      QadCommandClass.__init__(self, plugIn)
      self.SSGetClass = QadSSGetClass(plugIn)
      self.firstTime = True

   def __del__(self):
      QadCommandClass.__del__(self)
      del self.SSGetClass
        
   def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):
      if self.step == 0: # quando si é in fase di selezione entità
         return self.SSGetClass.getPointMapTool(drawMode)
      else:
         return QadCommandClass.getPointMapTool(self, drawMode)
        
   def run(self, msgMapTool = False, msg = None):     
      if self.step == 0: # inizio del comando   
         if self.firstTime == True:
            self.showMsg(QadMsg.translate("Command_SETCURRUPDATEABLELAYERBYGRAPH", "\nSelect objects whose layers will be the editable: "))
            self.firstTime = False
            
         if self.SSGetClass.run(msgMapTool, msg) == True:
            # selezione terminata
            self.step = 1
            return self.run(msgMapTool, msg)
         else:
            return False # continua

      elif self.step == 1: # dopo aver atteso la selezione di oggetti
         message = ""    
         for layerEntitySet in self.SSGetClass.entitySet.layerEntitySetList:
            layer = layerEntitySet.layer       
            if layer.isEditable() == False:
               if layer.startEditing() == True:
                  self.plugIn.iface.legendInterface().refreshLayerSymbology(layer)
                  self.showMsg(QadMsg.translate("Command_SETCURRUPDATEABLELAYERBYGRAPH", "\nThe layer {0} is editable.").format(layer.name()))

         if len(self.SSGetClass.entitySet.layerEntitySetList) == 1:
            layer = self.SSGetClass.entitySet.layerEntitySetList[0].layer
            if self.plugIn.canvas.currentLayer() is None or \
               self.plugIn.canvas.currentLayer() != layer:               
               self.plugIn.canvas.setCurrentLayer(layer)
               self.plugIn.iface.setActiveLayer(layer) # lancia evento di deactivate e activate dei plugin
               self.plugIn.iface.legendInterface().refreshLayerSymbology(layer)
               self.showMsg(QadMsg.translate("Command_SETCURRUPDATEABLELAYERBYGRAPH", "\nThe current layer is {0}.").format(layer.name()))
         
         return True
Example #32
0
class QadSCALECommandClass(QadCommandClass):

   def instantiateNewCmd(self):
      """ istanzia un nuovo comando dello stesso tipo """
      return QadSCALECommandClass(self.plugIn)

   def getName(self):
      return QadMsg.translate("Command_list", "SCALE")

   def getEnglishName(self):
      return "SCALE"

   def connectQAction(self, action):
      QObject.connect(action, SIGNAL("triggered()"), self.plugIn.runSCALECommand)

   def getIcon(self):
      return QIcon(":/plugins/qad/icons/scale.png")

   def getNote(self):
      # impostare le note esplicative del comando      
      return QadMsg.translate("Command_SCALE", "Enlarges or reduces selected objects.")
   
   def __init__(self, plugIn):
      QadCommandClass.__init__(self, plugIn)
      self.SSGetClass = QadSSGetClass(plugIn)
      self.SSGetClass.onlyEditableLayers = True
      self.entitySet = QadEntitySet()
      self.basePt = None
      self.copyFeatures = False
      self.Pt1ReferenceLen = None
      self.ReferenceLen = 1
      self.Pt1NewLen = None

   def __del__(self):
      QadCommandClass.__del__(self)
      del self.SSGetClass
      
   def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):
      if self.step == 0: # quando si é in fase di selezione entità
         return self.SSGetClass.getPointMapTool()
      else:
         if (self.plugIn is not None):
            if self.PointMapTool is None:
               self.PointMapTool = Qad_scale_maptool(self.plugIn)
            return self.PointMapTool
         else:
            return None


   #============================================================================
   # scale
   #============================================================================
   def scale(self, f, basePt, scale, sizeFldName, layerEntitySet, entitySet):
      # verifico se l'entità appartiene ad uno stile di quotatura
      dimEntity = self.plugIn.dimStyles.getDimEntity(layerEntitySet.layer, f.id())
            
      if dimEntity is None:
         # scalo la feature e la rimuovo da entitySet (é la prima)
         f.setGeometry(qad_utils.scaleQgsGeometry(f.geometry(), basePt, scale))
         if sizeFldName is not None:
            sizeValue = f.attribute(sizeFldName)
            if sizeValue is None:
               sizeValue = 1
            sizeValue = sizeValue * scale
            f.setAttribute(sizeFldName, sizeValue)                           
         
         if self.copyFeatures == False:
            # plugIn, layer, feature, refresh, check_validity
            if qad_layer.updateFeatureToLayer(self.plugIn, layerEntitySet.layer, f, False, False) == False:
               self.plugIn.destroyEditCommand()
               return False
         else:             
            # plugIn, layer, features, coordTransform, refresh, check_validity
            if qad_layer.addFeatureToLayer(self.plugIn, layerEntitySet.layer, f, None, False, False) == False:
               self.plugIn.destroyEditCommand()
               return False

         del layerEntitySet.featureIds[0]
      else:
         # scalo la quota e la rimuovo da entitySet
         dimEntitySet = dimEntity.getEntitySet()
         if self.copyFeatures == False:
            if dimEntity.deleteToLayers(self.plugIn) == False:
               return False                      
         dimEntity.scale(self.plugIn,basePt, scale)
         if dimEntity.addToLayers(self.plugIn) == False:
            return False             
         entitySet.subtract(dimEntitySet)


   def scaleGeoms(self, scale):      
      # copio entitySet
      entitySet = QadEntitySet(self.entitySet)
      
      self.plugIn.beginEditCommand("Feature scaled", self.entitySet.getLayerList())
      
      for layerEntitySet in entitySet.layerEntitySetList:
         layer = layerEntitySet.layer
                              
         transformedBasePt = self.mapToLayerCoordinates(layer, self.basePt)
         
         sizeFldName = None
         if qad_layer.isTextLayer(layer):
            # se l'altezza testo dipende da un solo campo 
            sizeFldNames = qad_label.get_labelSizeFieldNames(layer)
            if len(sizeFldNames) == 1 and len(sizeFldNames[0]) > 0:
                sizeFldName = sizeFldNames[0]
         elif qad_layer.isSymbolLayer(layer):
            # se la scala dipende da un campo 
            sizeFldName = qad_layer.get_symbolScaleFieldName(layer)
            if len(sizeFldName) == 0:
               sizeFldName = None

         while len(layerEntitySet.featureIds) > 0:
            featureId = layerEntitySet.featureIds[0]
            f = layerEntitySet.getFeature(featureId)

            if self.scale(f, transformedBasePt, scale, sizeFldName, layerEntitySet, entitySet) == False:  
               self.plugIn.destroyEditCommand()
               return

      self.plugIn.endEditCommand()


   def waitForScale(self):
      # imposto il map tool
      self.getPointMapTool().setMode(Qad_scale_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_SCALE_PT)

      keyWords = QadMsg.translate("Command_SCALE", "Copy") + "/" + \
                 QadMsg.translate("Command_SCALE", "Reference")
      default = self.plugIn.lastScale
      prompt = QadMsg.translate("Command_SCALE", "Specify scale factor or [{0}] <{1}>: ").format(keyWords, str(default))                        
      
      englishKeyWords = "Copy" + "/" + "Reference"
      keyWords += "_" + englishKeyWords
      # si appresta ad attendere un punto o enter o una parola chiave         
      # msg, inputType, default, keyWords, valori positivi
      self.waitFor(prompt, \
                   QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT | QadInputTypeEnum.KEYWORDS, \
                   default, \
                   keyWords, QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)      
      self.step = 3      


   def waitForReferenceLen(self):
      # imposto il map tool
      self.getPointMapTool().setMode(Qad_scale_maptool_ModeEnum.ASK_FOR_FIRST_PT_REFERENCE_LEN)
      
      msg = QadMsg.translate("Command_SCALE", "Specify reference length <{0}>: ")
      # si appresta ad attendere un punto o enter     
      # msg, inputType, default, keyWords, valori positivi
      self.waitFor(msg.format(str(self.plugIn.lastReferenceLen)), \
                   QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT, \
                   self.plugIn.lastReferenceLen, \
                   "", QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)               
      self.step = 4


   def waitForNewReferenceLen(self):
      # imposto il map tool
      self.getPointMapTool().setMode(Qad_scale_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_NEW_LEN_PT)
      
      keyWords = QadMsg.translate("Command_SCALE", "Points")
      if self.plugIn.lastNewReferenceLen == 0:
         default = self.plugIn.lastScale
      else:
         default = self.plugIn.lastNewReferenceLen
      prompt = QadMsg.translate("Command_SCALE", "Specify new length or [{0}] <{1}>: ").format(keyWords, str(default))                        
         
      englishKeyWords = "Points"
      keyWords += "_" + englishKeyWords
      # si appresta ad attendere un punto o enter o una parola chiave         
      # msg, inputType, default, keyWords, valori positivi
      self.waitFor(prompt, \
                   QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT | QadInputTypeEnum.KEYWORDS, \
                   default, \
                   keyWords, QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)
      self.step = 6
   

   def run(self, msgMapTool = False, msg = None):
      if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():
         self.showMsg(QadMsg.translate("QAD", "\nThe coordinate reference system of the project must be a projected coordinate system.\n"))
         return True # fine comando
            
      #=========================================================================
      # RICHIESTA SELEZIONE OGGETTI
      if self.step == 0: # inizio del comando
         if self.SSGetClass.run(msgMapTool, msg) == True:
            # selezione terminata
            self.step = 1
            self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può essere variato dal maptool di selezione entità                    
            return self.run(msgMapTool, msg)
      
      #=========================================================================
      # RUOTA OGGETTI
      elif self.step == 1:
         self.entitySet.set(self.SSGetClass.entitySet)
         
         if self.entitySet.count() == 0:
            return True # fine comando

         # imposto il map tool
         self.getPointMapTool().setMode(Qad_scale_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_BASE_PT)                                

         # si appresta ad attendere un punto
         self.waitForPoint(QadMsg.translate("Command_SCALE", "Specify base point: "))
                  
         self.step = 2     
         return False
         
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA PUNTO BASE (da step = 1)
      elif self.step == 2: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         self.basePt = QgsPoint(value)

         self.getPointMapTool().basePt = self.basePt
         self.getPointMapTool().entitySet.set(self.entitySet)
         # si appresta ad attendere la scala                      
         self.waitForScale()
         
         return False 
         
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER SCALA (da step = 2)
      elif self.step == 3: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if type(value) == unicode:
            if value == QadMsg.translate("Command_SCALE", "Copy") or value == "Copy":
               self.copyFeatures = True
               self.showMsg(QadMsg.translate("Command_SCALE", "\nScale of a copy of the selected objects."))
               # si appresta ad attendere la scala               
               self.waitForScale()                
            elif value == QadMsg.translate("Command_SCALE", "Reference") or value == "Reference":
               # si appresta ad attendere la lunghezza di riferimento                      
               self.waitForReferenceLen()
         elif type(value) == QgsPoint or type(value) == float: # se é stato inserita la scala
            if type(value) == QgsPoint: # se é stato inserita la scala con un punto
               if value == self.basePt:
                  self.showMsg(QadMsg.translate("QAD", "\nThe value must be positive and not zero."))
                  # si appresta ad attendere un punto
                  self.waitForScale()
                  return False
                                      
               scale = qad_utils.getDistance(self.basePt, value)
            else:
               scale = value
            self.plugIn.setLastScale(scale)

            self.scaleGeoms(scale)
            return True # fine comando
         
         return False
               
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA PRIMO PUNTO PER LUNGHEZZA DI RIFERIMENTO (da step = 3)
      elif self.step == 4: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if type(value) == float: # se é stato inserita la lunghezza
            self.ReferenceLen = value
            self.getPointMapTool().ReferenceLen = self.ReferenceLen 
            # si appresta ad attendere la nuova lunghezza                    
            self.waitForNewReferenceLen()

         elif type(value) == QgsPoint: # se é stato inserito la scala con un punto                                 
            self.Pt1ReferenceLen = QgsPoint(value)
            self.getPointMapTool().Pt1ReferenceLen = self.Pt1ReferenceLen 
            # imposto il map tool
            self.getPointMapTool().setMode(Qad_scale_maptool_ModeEnum.FIRST_PT_KNOWN_ASK_FOR_SECOND_PT_REFERENCE_LEN)
            # si appresta ad attendere un punto
            self.waitForPoint(QadMsg.translate("Command_SCALE", "Specify second point: "))
            self.step = 5           
            
         return False

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER LUNGHEZZA DI RIFERIMENTO (da step = 4)
      elif self.step == 5: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if self.Pt1ReferenceLen == value:
            self.showMsg(QadMsg.translate("QAD", "\nThe value must be positive and not zero."))
            # si appresta ad attendere un punto
            self.waitForPoint(QadMsg.translate("Command_SCALE", "Specify second point: "))
            return False
            
         length = qad_utils.getDistance(self.Pt1ReferenceLen, value)
         self.ReferenceLen = length
         self.getPointMapTool().ReferenceLen = self.ReferenceLen
         # si appresta ad attendere la nuova lunghezza                    
         self.waitForNewReferenceLen()
            
         return False

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER NUOVA LUNGHEZZA (da step = 4 e 5)
      elif self.step == 6: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if type(value) == unicode:
            if value == QadMsg.translate("Command_SCALE", "Points") or value == "Points":
               # imposto il map tool
               self.getPointMapTool().setMode(Qad_scale_maptool_ModeEnum.ASK_FOR_FIRST_NEW_LEN_PT)
               # si appresta ad attendere un punto
               self.waitForPoint(QadMsg.translate("Command_SCALE", "Specify first point: "))
               self.step = 7
         elif type(value) == QgsPoint or type(value) == float: # se é stato inserita la lunghezza
            if type(value) == QgsPoint: # se é stato inserito la lunghezza con un punto
               if value == self.basePt:
                  self.showMsg(QadMsg.translate("QAD", "\nThe value must be positive and not zero."))
                  # si appresta ad attendere un punto
                  self.waitForNewReferenceLen()
                  return False
                                       
               length = qad_utils.getDistance(self.basePt, value)
            else:
               length = value
            
            scale = length / self.ReferenceLen
            self.plugIn.setLastScale(scale)
            self.scaleGeoms(scale)
            return True # fine comando

         return False
      
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA PRIMO PUNTO PER NUOVA LUNGHEZZA (da step = 6)
      elif self.step == 7: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg
      
         self.Pt1NewLen = value
         # imposto il map tool
         self.getPointMapTool().Pt1NewLen = self.Pt1NewLen
         self.getPointMapTool().setMode(Qad_scale_maptool_ModeEnum.FIRST_PT_KNOWN_ASK_FOR_SECOND_NEW_LEN_PT)
         # si appresta ad attendere un punto
         self.waitForPoint(QadMsg.translate("Command_SCALE", "Specify second point: "))
         self.step = 8
            
         return False

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER NUOVA LUNGHEZZA (da step = 7)
      elif self.step == 8: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if value == self.Pt1NewLen:
            self.showMsg(QadMsg.translate("QAD", "\nThe value must be positive and not zero."))
            # si appresta ad attendere un punto
            self.waitForPoint(QadMsg.translate("Command_SCALE", "Specify second point: "))
            return False
               
         length = qad_utils.getDistance(self.Pt1NewLen, value)
         
         scale = length / self.ReferenceLen
         self.plugIn.setLastScale(scale)
         self.scaleGeoms(scale)
         return True # fine comando
            
Example #33
0
 def __init__(self, plugIn):
    QadCommandClass.__init__(self, plugIn)
    self.SSGetClass = QadSSGetClass(plugIn)
    self.SSGetClass.onlyEditableLayers = True
Example #34
0
class QadERASECommandClass(QadCommandClass):

   def instantiateNewCmd(self):
      """ istanzia un nuovo comando dello stesso tipo """
      return QadERASECommandClass(self.plugIn)
   
   def getName(self):
      return QadMsg.translate("Command_list", "ERASE")

   def getEnglishName(self):
      return "ERASE"

   def connectQAction(self, action):
      QObject.connect(action, SIGNAL("triggered()"), self.plugIn.runERASECommand)

   def getIcon(self):
      return QIcon(":/plugins/qad/icons/erase.png")

   def getNote(self):
      # impostare le note esplicative del comando
      return QadMsg.translate("Command_ERASE", "Removes objects of the map.")
   
   def __init__(self, plugIn):
      QadCommandClass.__init__(self, plugIn)
      self.SSGetClass = QadSSGetClass(plugIn)
      self.SSGetClass.onlyEditableLayers = True

   def __del__(self):
      QadCommandClass.__del__(self)
      del self.SSGetClass
      
   def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):
      if self.step == 0: # quando si é in fase di selezione entità
         return self.SSGetClass.getPointMapTool(drawMode)
      else:
         return QadCommandClass.getPointMapTool(self, drawMode)

   def run(self, msgMapTool = False, msg = None):
            
      #=========================================================================
      # RICHIESTA PRIMO PUNTO PER SELEZIONE OGGETTI
      if self.step == 0: # inizio del comando
         if self.SSGetClass.run(msgMapTool, msg) == True:
            # selezione terminata
            self.step = 1
            return self.run(msgMapTool, msg)
         else:
            return False
      
      #=========================================================================
      # CANCELLAZIONE OGGETTI
      elif self.step == 1:
         self.plugIn.beginEditCommand("Feature deleted", self.SSGetClass.entitySet.getLayerList())
              
         for layerEntitySet in self.SSGetClass.entitySet.layerEntitySetList:
            # plugIn, layer, featureIds, refresh
            if qad_layer.deleteFeaturesToLayer(self.plugIn, layerEntitySet.layer, \
                                               layerEntitySet.featureIds, False) == False:
               self.plugIn.destroyEditCommand()
               return
            
         self.plugIn.endEditCommand()
            
         return True # fine comando
Example #35
0
class QadCOPYCommandClass(QadCommandClass):
    def instantiateNewCmd(self):
        """ istanzia un nuovo comando dello stesso tipo """
        return QadCOPYCommandClass(self.plugIn)

    def getName(self):
        return QadMsg.translate("Command_list", "COPY")

    def getEnglishName(self):
        return "COPY"

    def connectQAction(self, action):
        QObject.connect(action, SIGNAL("triggered()"),
                        self.plugIn.runCOPYCommand)

    def getIcon(self):
        return QIcon(":/plugins/qad/icons/copyEnt.png")

    def getNote(self):
        # impostare le note esplicative del comando
        return QadMsg.translate(
            "Command_COPY",
            "Copies selected objects a specified distance in a specified direction."
        )

    def __init__(self, plugIn):
        QadCommandClass.__init__(self, plugIn)
        self.SSGetClass = QadSSGetClass(plugIn)
        self.SSGetClass.onlyEditableLayers = True
        self.entitySet = QadEntitySet()
        self.basePt = QgsPoint()
        self.series = False
        self.seriesLen = 2
        self.adjust = False
        self.copyMode = QadVariables.get(
            QadMsg.translate("Environment variables", "COPYMODE"))

        self.featureCache = []  # lista di (layer, feature)
        self.nOperationsToUndo = 0

    def __del__(self):
        QadCommandClass.__del__(self)
        del self.SSGetClass

    def getPointMapTool(self, drawMode=QadGetPointDrawModeEnum.NONE):
        if self.step == 0:  # quando si é in fase di selezione entità
            return self.SSGetClass.getPointMapTool()
        else:
            if (self.plugIn is not None):
                if self.PointMapTool is None:
                    self.PointMapTool = Qad_copy_maptool(self.plugIn)
                return self.PointMapTool
            else:
                return None

    def getCurrentContextualMenu(self):
        if self.step == 0:  # quando si é in fase di selezione entità
            return self.SSGetClass.getCurrentContextualMenu()
        else:
            return self.contextualMenu

    #============================================================================
    # move
    #============================================================================
    def move(self, f, offSetX, offSetY, layerEntitySet, entitySet, dimEntity):
        if dimEntity is None:
            # sposto la feature e la rimuovo da entitySet (é la prima)
            f.setGeometry(
                qad_utils.moveQgsGeometry(f.geometry(), offSetX, offSetY))
            # plugIn, layer, feature, coordTransform, refresh, check_validity
            if qad_layer.addFeatureToLayer(self.plugIn, layerEntitySet.layer,
                                           f, None, False, False) == False:
                return False
        else:
            newDimEntity = QadDimEntity(dimEntity)  # la copio
            # sposto la quota
            newDimEntity.move(offSetX, offSetY)
            if newDimEntity.addToLayers(self.plugIn) == False:
                return False

        return True

    #============================================================================
    # copyGeoms
    #============================================================================
    def copyGeoms(self, newPt):
        # copio entitySet
        entitySet = QadEntitySet(self.entitySet)

        self.plugIn.beginEditCommand("Feature copied",
                                     entitySet.getLayerList())

        for layerEntitySet in entitySet.layerEntitySetList:
            layer = layerEntitySet.layer

            transformedBasePt = self.mapToLayerCoordinates(layer, self.basePt)
            transformedNewPt = self.mapToLayerCoordinates(layer, newPt)
            offSetX = transformedNewPt.x() - transformedBasePt.x()
            offSetY = transformedNewPt.y() - transformedBasePt.y()

            while len(layerEntitySet.featureIds) > 0:
                featureId = layerEntitySet.featureIds[0]
                f = layerEntitySet.getFeature(featureId)
                if f is None:
                    del layerEntitySet.featureIds[0]
                    continue

                # verifico se l'entità appartiene ad uno stile di quotatura
                dimEntity = QadDimStyles.getDimEntity(layerEntitySet.layer,
                                                      f.id())

                if self.series and self.seriesLen > 0:  # devo fare una serie
                    if self.adjust == True:
                        offSetX = offSetX / (self.seriesLen - 1)
                        offSetY = offSetY / (self.seriesLen - 1)

                    deltaX = offSetX
                    deltaY = offSetY

                    for i in xrange(1, self.seriesLen, 1):
                        if self.move(f, deltaX, deltaY, layerEntitySet,
                                     entitySet, dimEntity) == False:
                            self.plugIn.destroyEditCommand()
                            return
                        deltaX = deltaX + offSetX
                        deltaY = deltaY + offSetY
                else:
                    if self.move(f, offSetX, offSetY, layerEntitySet,
                                 entitySet, dimEntity) == False:
                        self.plugIn.destroyEditCommand()
                        return

                # la rimuovo da entitySet
                if dimEntity is None:
                    del layerEntitySet.featureIds[0]
                else:
                    dimEntitySet = dimEntity.getEntitySet()
                    entitySet.subtract(dimEntitySet)

        self.plugIn.endEditCommand()
        self.nOperationsToUndo = self.nOperationsToUndo + 1

    #============================================================================
    # waitForBasePt
    #============================================================================
    def waitForBasePt(self):
        # imposto il map tool
        self.getPointMapTool().setMode(
            Qad_copy_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_BASE_PT)

        if self.copyMode == 0:  # Imposta il comando COPIA in modo che venga ripetuto automaticamente
            keyWords = QadMsg.translate("Command_COPY", "Displacement") + "/" + \
                       QadMsg.translate("Command_COPY", "mOde")
            englishKeyWords = "Displacement" + "/" + "mOde"

        else:
            # l'opzione Multiple viene tradotta in italiano in "MUltiplo" nel contesto "waitForBasePt"
            # l'opzione Multiple viene tradotta in italiano in "Multipla" nel contesto "waitForMode"
            # e "Multipla" nel caso di modalità di copia
            keyWords = QadMsg.translate("Command_COPY", "Displacement") + "/" + \
                       QadMsg.translate("Command_COPY", "mOde") + "/" + \
                       QadMsg.translate("Command_COPY", "Multiple", "waitForBasePt")
            englishKeyWords = "Displacement" + "/" + "mOde" + "/" + "Multiple"

        default = QadMsg.translate("Command_COPY", "Displacement")
        prompt = QadMsg.translate(
            "Command_COPY",
            "Specify base point or [{0}] <{1}>: ").format(keyWords, default)

        keyWords += "_" + englishKeyWords
        # si appresta ad attendere un punto o enter o una parola chiave
        # msg, inputType, default, keyWords, nessun controllo
        self.waitFor(prompt, \
                     QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \
                     default, \
                     keyWords, QadInputModeEnum.NONE)
        self.step = 2

    #============================================================================
    # waitForSeries
    #============================================================================
    def waitForSeries(self):
        # si appresta ad attendere un numero intero
        msg = QadMsg.translate("Command_COPY",
                               "Number of Items to Array <{0}>: ")
        # msg, inputType, default, keyWords, valori positivi
        self.waitFor(msg.format(str(self.seriesLen)), \
                     QadInputTypeEnum.INT, \
                     self.seriesLen, \
                     "", \
                     QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)
        self.step = 6

    #============================================================================
    # waitForSecondPt
    #============================================================================
    def waitForSecondPt(self):
        self.series = False
        self.adjust = False
        self.getPointMapTool().seriesLen = 0
        self.getPointMapTool().setMode(
            Qad_copy_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_COPY_PT)

        if len(self.featureCache) > 0:
            keyWords = QadMsg.translate("Command_COPY", "Array") + "/" + \
                       QadMsg.translate("Command_COPY", "Exit") + "/" + \
                       QadMsg.translate("Command_COPY", "Undo")
            default = QadMsg.translate("Command_COPY", "Exit")
            prompt = QadMsg.translate(
                "Command_COPY",
                "Specify second point or [{0}] <{1}>: ").format(
                    keyWords, default)

            englishKeyWords = "Array" + "/" + "Exit" + "/" + "Undo" + "/" + "Exit"
            keyWords += "_" + englishKeyWords
            # si appresta ad attendere un punto o enter o una parola chiave
            # msg, inputType, default, keyWords, nessun controllo
            self.waitFor(prompt, \
                         QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \
                         default, \
                         keyWords, QadInputModeEnum.NONE)
        else:
            keyWords = QadMsg.translate("Command_COPY", "Array")
            prompt = QadMsg.translate(
                "Command_COPY",
                "Specify second point or [{0}] <use first point as displacement from origin point 0,0>: "
            ).format(keyWords)

            englishKeyWords = "Array"
            keyWords += "_" + englishKeyWords
            # si appresta ad attendere un punto o enter o una parola chiave
            # msg, inputType, default, keyWords, nessun controllo
            self.waitFor(prompt, \
                         QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \
                         None, \
                         keyWords, QadInputModeEnum.NONE)

        self.step = 3

    #============================================================================
    # waitForSecondPtBySeries
    #============================================================================
    def waitForSecondPtBySeries(self):
        if self.adjust == False:
            keyWords = QadMsg.translate("Command_COPY", "Fit")
            englishKeyWords = "Fit"
        else:
            keyWords = QadMsg.translate("Command_COPY", "Array")
            englishKeyWords = "Array"
        prompt = QadMsg.translate(
            "Command_COPY", "Specify second point or [{0}]: ").format(keyWords)

        keyWords += "_" + englishKeyWords
        # si appresta ad attendere un punto o enter o una parola chiave
        # msg, inputType, default, keyWords, valore nullo non permesso
        self.waitFor(prompt, \
                     QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \
                     "", \
                     keyWords, QadInputModeEnum.NOT_NULL)
        self.step = 7

    #============================================================================
    # run
    #============================================================================
    def run(self, msgMapTool=False, msg=None):
        if self.plugIn.canvas.mapSettings().destinationCrs().geographicFlag():
            self.showMsg(
                QadMsg.translate(
                    "QAD",
                    "\nThe coordinate reference system of the project must be a projected coordinate system.\n"
                ))
            return True  # fine comando

        #=========================================================================
        # RICHIESTA SELEZIONE OGGETTI
        if self.step == 0:  # inizio del comando
            if self.SSGetClass.run(msgMapTool, msg) == True:
                # selezione terminata
                self.step = 1
                return self.run(msgMapTool, msg)

        #=========================================================================
        # COPIA OGGETTI
        elif self.step == 1:
            self.entitySet.set(self.SSGetClass.entitySet)

            if self.entitySet.count() == 0:
                return True  # fine comando

            CurrSettingsMsg = QadMsg.translate("QAD", "\nCurrent settings: ")
            if self.copyMode == 0:  # 0 = multipla
                CurrSettingsMsg = CurrSettingsMsg + QadMsg.translate(
                    "Command_COPY", "Copy mode = Multiple")
            else:  # 1 = singola
                CurrSettingsMsg = CurrSettingsMsg + QadMsg.translate(
                    "Command_COPY", "Copy mode = Single")
            self.showMsg(CurrSettingsMsg)

            self.getPointMapTool().entitySet.set(self.entitySet)
            self.waitForBasePt()
            self.getPointMapTool().refreshSnapType(
            )  # riagggiorno lo snapType che può essere variato dal maptool di selezione entità
            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA PUNTO BASE (da step = 1)
        elif self.step == 2:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        pass  # opzione di default "spostamento"
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            if value is None:
                value = QadMsg.translate("Command_COPY", "Displacement")

            if type(value) == unicode:
                if value == QadMsg.translate(
                        "Command_COPY",
                        "Displacement") or value == "Displacement":
                    self.basePt.set(0, 0)
                    self.getPointMapTool().basePt = self.basePt
                    self.getPointMapTool().setMode(
                        Qad_copy_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_COPY_PT
                    )
                    # si appresta ad attendere un punto
                    msg = QadMsg.translate(
                        "Command_COPY",
                        "Specify the displacement from the origin point 0,0 <{0}, {1}>: "
                    )
                    # msg, inputType, default, keyWords, nessun controllo
                    self.waitFor(msg.format(str(self.plugIn.lastOffsetPt.x()), str(self.plugIn.lastOffsetPt.y())), \
                                 QadInputTypeEnum.POINT2D, \
                                 self.plugIn.lastOffsetPt, \
                                 "", QadInputModeEnum.NONE)
                    self.step = 4
                elif value == QadMsg.translate("Command_COPY",
                                               "mOde") or value == "mOde":
                    # l'opzione Multiple viene tradotta in italiano in "Multipla" nel contesto "waitForMode"
                    keyWords = QadMsg.translate("Command_COPY", "Single") + "/" + \
                               QadMsg.translate("Command_COPY", "Multiple", "waitForMode")
                    englishKeyWords = "Single" + "/" + "Multiple"

                    if self.copyMode == 0:  # Imposta il comando COPIA in modo che venga ripetuto automaticamente
                        # l'opzione Multiple viene tradotta in italiano in "Multipla" nel contesto "waitForMode"
                        default = QadMsg.translate("Command_COPY", "Multiple",
                                                   "waitForMode")
                    else:
                        default = QadMsg.translate("Command_COPY", "Single")
                    prompt = QadMsg.translate(
                        "Command_COPY",
                        "Enter a copy mode option [{0}] <{1}>: ").format(
                            keyWords, default)

                    keyWords += "_" + englishKeyWords
                    # si appresta ad attendere enter o una parola chiave
                    # msg, inputType, default, keyWords, nessun controllo
                    self.waitFor(prompt, \
                                 QadInputTypeEnum.KEYWORDS, \
                                 default, \
                                 keyWords, QadInputModeEnum.NONE)
                    self.step = 5
                # l'opzione Multiple viene tradotta in italiano in "MUltiplo" nel contesto "waitForBasePt"
                elif value == QadMsg.translate(
                        "Command_COPY", "Multiple",
                        "waitForBasePt") or value == "Multiple":
                    self.copyMode = 0  # Imposta il comando COPIA in modo che venga ripetuto automaticamente
                    self.waitForBasePt()
            elif type(value) == QgsPoint:  # se é stato inserito il punto base
                self.basePt.set(value.x(), value.y())

                # imposto il map tool
                self.getPointMapTool().basePt = self.basePt
                self.waitForSecondPt()

            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER COPIA (da step = 2)
        elif self.step == 3:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        if len(self.featureCache) > 0:
                            value = QadMsg.translate("Command_COPY", "Exit")
                        else:
                            value = None
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False
                else:
                    value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            if value is None:
                if len(self.featureCache) > 0:
                    value = QadMsg.translate("Command_COPY", "Exit")
                else:
                    # utilizzare il primo punto come spostamento
                    value = QgsPoint(self.basePt)
                    self.basePt.set(0, 0)
                    self.copyGeoms(value)
                    return True  # fine comando

            if type(value) == unicode:
                if value == QadMsg.translate("Command_COPY",
                                             "Array") or value == "Array":
                    self.waitForSeries()
                elif value == QadMsg.translate("Command_COPY",
                                               "Exit") or value == "Exit":
                    return True  # fine comando
                elif value == QadMsg.translate("Command_COPY",
                                               "Undo") or value == "Undo":
                    if self.nOperationsToUndo > 0:
                        self.nOperationsToUndo = self.nOperationsToUndo - 1
                        self.plugIn.undoEditCommand()
                    else:
                        self.showMsg(
                            QadMsg.translate(
                                "QAD", "\nThe command has been canceled."))
                    self.waitForSecondPt()
            elif type(
                    value
            ) == QgsPoint:  # se é stato inserito lo spostamento con un punto
                self.copyGeoms(value)
                if self.copyMode == 1:  # "Singola"
                    return True  # fine comando
                self.waitForSecondPt()

            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA DEL PUNTO DI SPOSTAMENTO (da step = 2)
        elif self.step == 4:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            self.plugIn.setLastOffsetPt(value)
            self.copyGeoms(value)
            return True  # fine comando

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA DELLA MODALITA' (SINGOLA / MULTIPLA) (da step = 2)
        elif self.step == 5:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # la parola chiave arriva come parametro della funzione
                value = msg

            if type(value) == unicode:
                if value == QadMsg.translate("Command_COPY",
                                             "Single") or value == "Single":
                    self.copyMode = 1
                    QadVariables.set(
                        QadMsg.translate("Environment variables", "COPYMODE"),
                        1)
                    QadVariables.save()
                # l'opzione Multiple viene tradotta in italiano in "Multipla" nel contesto "waitForMode"
                elif value == QadMsg.translate(
                        "Command_COPY", "Multiple",
                        "waitForMode") or value == "Multiple":
                    self.copyMode = 0
                    QadVariables.set(
                        QadMsg.translate("Environment variables", "COPYMODE"),
                        0)
                    QadVariables.save()

            self.waitForBasePt()
            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA DELLA SERIE (da step = 3)
        elif self.step == 6:  # dopo aver atteso un numero intero si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                if self.getPointMapTool(
                ).rightButton == True:  # se usato il tasto destro del mouse
                    value = self.seriesLen
                else:
                    value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            if value < 2:
                self.showMsg(
                    QadMsg.translate(
                        "Command_COPY",
                        "\nThe value must be between 2 and 32767."))
                self.waitForSeries()
            else:
                self.series = True
                self.seriesLen = value
                self.getPointMapTool().seriesLen = self.seriesLen

                self.waitForSecondPtBySeries()

            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER COPIA DA SERIE (da step = 6)
        elif self.step == 7:  # dopo aver atteso un punto o una parola chiave
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            if type(value) == unicode:
                if value == QadMsg.translate("Command_COPY",
                                             "Array") or value == "Array":
                    self.adjust = False
                    self.getPointMapTool().adjust = self.adjust
                    self.waitForSecondPtBySeries()
                elif value == QadMsg.translate("Command_COPY",
                                               "Fit") or value == "Fit":
                    self.adjust = True
                    self.getPointMapTool().adjust = self.adjust
                    self.waitForSecondPtBySeries()
            elif type(
                    value
            ) == QgsPoint:  # se é stato inserito lo spostamento con un punto
                self.copyGeoms(value)
                if self.copyMode == 1:  # "Singola"
                    return True  # fine comando
                self.waitForSecondPt()

            return False
class QadROTATECommandClass(QadCommandClass):
    def instantiateNewCmd(self):
        """ istanzia un nuovo comando dello stesso tipo """
        return QadROTATECommandClass(self.plugIn)

    def getName(self):
        return QadMsg.translate("Command_list", "ROTATE")

    def getEnglishName(self):
        return "ROTATE"

    def connectQAction(self, action):
        QObject.connect(action, SIGNAL("triggered()"),
                        self.plugIn.runROTATECommand)

    def getIcon(self):
        return QIcon(":/plugins/qad/icons/rotate.png")

    def getNote(self):
        # impostare le note esplicative del comando
        return QadMsg.translate("Command_ROTATE",
                                "Rotates objects around a base point.")

    def __init__(self, plugIn):
        QadCommandClass.__init__(self, plugIn)
        self.SSGetClass = QadSSGetClass(plugIn)
        self.SSGetClass.onlyEditableLayers = True
        self.entitySet = QadEntitySet()
        self.basePt = None
        self.copyFeatures = False
        self.Pt1ReferenceAng = None
        self.ReferenceAng = 0
        self.Pt1NewAng = None

    def __del__(self):
        QadCommandClass.__del__(self)
        del self.SSGetClass

    def getPointMapTool(self, drawMode=QadGetPointDrawModeEnum.NONE):
        if self.step == 0:  # quando si é in fase di selezione entità
            return self.SSGetClass.getPointMapTool()
        else:
            if (self.plugIn is not None):
                if self.PointMapTool is None:
                    self.PointMapTool = Qad_rotate_maptool(self.plugIn)
                return self.PointMapTool
            else:
                return None

    #============================================================================
    # rotate
    #============================================================================
    def rotate(self, f, basePt, angle, rotFldName, layerEntitySet, entitySet):
        # verifico se l'entità appartiene ad uno stile di quotatura
        dimEntity = QadDimStyles.getDimEntity(layerEntitySet.layer, f.id())

        if dimEntity is None:
            # ruoto la feature e la rimuovo da entitySet (é la prima)
            f.setGeometry(
                qad_utils.rotateQgsGeometry(f.geometry(), basePt, angle))

            if len(rotFldName) > 0:
                rotValue = f.attribute(rotFldName)
                # a volte vale None e a volte null (vai a capire...)
                rotValue = 0 if rotValue is None or isinstance(
                    rotValue, QPyNullVariant) else qad_utils.toRadians(
                        rotValue
                    )  # la rotazione é in gradi nel campo della feature
                rotValue = rotValue + angle
                f.setAttribute(
                    rotFldName,
                    qad_utils.toDegrees(qad_utils.normalizeAngle(rotValue)))

            if self.copyFeatures == False:
                # plugIn, layer, feature, refresh, check_validity
                if qad_layer.updateFeatureToLayer(self.plugIn,
                                                  layerEntitySet.layer, f,
                                                  False, False) == False:
                    self.plugIn.destroyEditCommand()
                    return False
            else:
                # plugIn, layer, features, coordTransform, refresh, check_validity
                if qad_layer.addFeatureToLayer(self.plugIn,
                                               layerEntitySet.layer, f, None,
                                               False, False) == False:
                    self.plugIn.destroyEditCommand()
                    return False
            del layerEntitySet.featureIds[0]
        else:
            # ruoto la quota e la rimuovo da entitySet
            dimEntitySet = dimEntity.getEntitySet()
            if self.copyFeatures == False:
                if dimEntity.deleteToLayers(self.plugIn) == False:
                    return False
            newDimEntity = QadDimEntity(dimEntity)  # la copio
            newDimEntity.rotate(basePt, angle)
            if newDimEntity.addToLayers(self.plugIn) == False:
                return False
            entitySet.subtract(dimEntitySet)

        return True

    def RotateGeoms(self, angle):
        # copio entitySet
        entitySet = QadEntitySet(self.entitySet)

        self.plugIn.beginEditCommand("Feature rotated",
                                     entitySet.getLayerList())

        for layerEntitySet in entitySet.layerEntitySetList:
            layer = layerEntitySet.layer

            transformedBasePt = self.mapToLayerCoordinates(layer, self.basePt)

            rotFldName = ""
            if qad_layer.isTextLayer(layer):
                # se la rotazione dipende da un solo campo
                rotFldNames = qad_label.get_labelRotationFieldNames(layer)
                if len(rotFldNames) == 1 and len(rotFldNames[0]) > 0:
                    rotFldName = rotFldNames[0]
            elif qad_layer.isSymbolLayer(layer):
                rotFldName = qad_layer.get_symbolRotationFieldName(layer)

            while len(layerEntitySet.featureIds) > 0:
                featureId = layerEntitySet.featureIds[0]
                f = layerEntitySet.getFeature(featureId)

                if self.rotate(f, transformedBasePt, angle, rotFldName,
                               layerEntitySet, entitySet) == False:
                    self.plugIn.destroyEditCommand()
                    return

        self.plugIn.endEditCommand()

    def waitForRotation(self):
        # imposto il map tool
        self.getPointMapTool().setMode(
            Qad_rotate_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_ROTATION_PT)

        keyWords = QadMsg.translate("Command_ROTATE", "Copy") + "/" + \
                   QadMsg.translate("Command_ROTATE", "Reference")
        prompt = QadMsg.translate("Command_ROTATE", "Specify rotation angle or [{0}] <{1}>: ").format(keyWords, \
                 str(qad_utils.toDegrees(self.plugIn.lastRot)))

        englishKeyWords = "Copy" + "/" + "Reference"
        keyWords += "_" + englishKeyWords
        # si appresta ad attendere un punto, un numero reale o enter o una parola chiave
        # msg, inputType, default, keyWords, nessun controllo
        self.waitFor(prompt, QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT | QadInputTypeEnum.KEYWORDS, \
                     self.plugIn.lastRot, \
                     keyWords, QadInputModeEnum.NONE)
        self.step = 3

    def waitForReferenceRot(self):
        # imposto il map tool
        self.getPointMapTool().setMode(
            Qad_rotate_maptool_ModeEnum.ASK_FOR_FIRST_PT_REFERENCE_ANG)

        msg = QadMsg.translate("Command_ROTATE",
                               "Specify reference angle <{0}>: ")
        # si appresta ad attendere un punto o enter o una parola chiave
        # msg, inputType, default, keyWords, nessun controllo
        self.waitFor(msg.format(str(qad_utils.toDegrees(self.plugIn.lastReferenceRot))), \
                     QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT, \
                     self.plugIn.lastReferenceRot, \
                     "")
        self.step = 4

    def waitForNewReferenceRot(self):
        # imposto il map tool
        self.getPointMapTool().setMode(
            Qad_rotate_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_NEW_ROTATION_PT)

        keyWords = QadMsg.translate("Command_ROTATE", "Points")
        if self.plugIn.lastNewReferenceRot == 0:
            angle = self.plugIn.lastRot
        else:
            angle = self.plugIn.lastNewReferenceRot
        prompt = QadMsg.translate("Command_ROTATE",
                                  "Specify new angle or [{0}] <{1}>: ").format(
                                      keyWords,
                                      str(qad_utils.toDegrees(angle)))

        englishKeyWords = "Points"
        keyWords += "_" + englishKeyWords
        # si appresta ad attendere un punto o enter o una parola chiave
        # msg, inputType, default, keyWords, nessun controllo
        self.waitFor(prompt, \
                     QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT | QadInputTypeEnum.KEYWORDS, \
                     angle, \
                     keyWords)
        self.step = 6

    def run(self, msgMapTool=False, msg=None):
        if self.plugIn.canvas.mapSettings().destinationCrs().geographicFlag():
            self.showMsg(
                QadMsg.translate(
                    "QAD",
                    "\nThe coordinate reference system of the project must be a projected coordinate system.\n"
                ))
            return True  # fine comando

        #=========================================================================
        # RICHIESTA SELEZIONE OGGETTI
        if self.step == 0:  # inizio del comando
            if self.SSGetClass.run(msgMapTool, msg) == True:
                # selezione terminata
                self.step = 1
                self.getPointMapTool().refreshSnapType(
                )  # aggiorno lo snapType che può essere variato dal maptool di selezione entità
                return self.run(msgMapTool, msg)

        #=========================================================================
        # RUOTA OGGETTI
        elif self.step == 1:
            self.entitySet.set(self.SSGetClass.entitySet)

            if self.entitySet.count() == 0:
                return True  # fine comando

            # imposto il map tool
            self.getPointMapTool().setMode(
                Qad_rotate_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_BASE_PT)

            # si appresta ad attendere un punto
            self.waitForPoint(
                QadMsg.translate("Command_ROTATE", "Specify base point: "))

            self.step = 2
            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA PUNTO BASE (da step = 1)
        elif self.step == 2:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            self.basePt = QgsPoint(value)

            self.getPointMapTool().basePt = self.basePt
            self.getPointMapTool().entitySet.set(self.entitySet)
            # si appresta ad attendere l'angolo di rotazione
            self.waitForRotation()

            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER ANGOLO ROTAZIONE (da step = 2)
        elif self.step == 3:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            if type(value) == unicode:
                if value == QadMsg.translate("Command_ROTATE",
                                             "Copy") or value == "Copy":
                    self.copyFeatures = True
                    self.showMsg(
                        QadMsg.translate(
                            "Command_ROTATE",
                            "\nRotation of a copy of the selected objects."))
                    # si appresta ad attendere l'angolo di rotazione
                    self.waitForRotation()
                elif value == QadMsg.translate(
                        "Command_ROTATE", "Reference") or value == "Reference":
                    # si appresta ad attendere l'angolo di riferimento
                    self.waitForReferenceRot()
            elif type(value) == QgsPoint or type(
                    value
            ) == float:  # se é stato inserito l'angolo di rotazione
                if type(
                        value
                ) == QgsPoint:  # se é stato inserito l'angolo di rotazione con un punto
                    angle = qad_utils.getAngleBy2Pts(self.basePt, value)
                else:
                    angle = qad_utils.toRadians(value)
                self.plugIn.setLastRot(angle)

                self.RotateGeoms(angle)
                return True  # fine comando

            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA PRIMO PUNTO PER ANGOLO ROTAZIONE DI RIFERIMENTO (da step = 3)
        elif self.step == 4:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            if type(value
                    ) == float:  # se é stato inserito l'angolo di rotazione
                self.ReferenceAng = qad_utils.toRadians(value)
                self.getPointMapTool().ReferenceAng = self.ReferenceAng
                # si appresta ad attendere il nuovo angolo
                self.waitForNewReferenceRot()

            elif type(
                    value
            ) == QgsPoint:  # se é stato inserito l'angolo di rotazione con un punto
                self.Pt1ReferenceAng = QgsPoint(value)
                self.getPointMapTool().Pt1ReferenceAng = self.Pt1ReferenceAng
                # imposto il map tool
                self.getPointMapTool().setMode(
                    Qad_rotate_maptool_ModeEnum.
                    FIRST_PT_KNOWN_ASK_FOR_SECOND_PT_REFERENCE_ANG)
                # si appresta ad attendere un punto
                self.waitForPoint(
                    QadMsg.translate("Command_ROTATE",
                                     "Specify second point: "))
                self.step = 5

            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER ANGOLO ROTAZIONE DI RIFERIMENTO (da step = 4)
        elif self.step == 5:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            angle = qad_utils.getAngleBy2Pts(self.Pt1ReferenceAng, value)
            self.ReferenceAng = angle
            self.getPointMapTool().ReferenceAng = self.ReferenceAng
            # si appresta ad attendere il nuovo angolo
            self.waitForNewReferenceRot()

            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER NUOVO ANGOLO ROTAZIONE (da step = 4 e 5)
        elif self.step == 6:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            if type(value) == unicode:
                if value == QadMsg.translate("Command_ROTATE",
                                             "Points") or value == "Points":
                    # imposto il map tool
                    self.getPointMapTool().setMode(
                        Qad_rotate_maptool_ModeEnum.
                        ASK_FOR_FIRST_NEW_ROTATION_PT)
                    # si appresta ad attendere un punto
                    self.waitForPoint(
                        QadMsg.translate("Command_ROTATE",
                                         "Specify first point: "))
                    self.step = 7
            elif type(value) == QgsPoint or type(
                    value
            ) == float:  # se é stato inserito l'angolo di rotazione
                if type(
                        value
                ) == QgsPoint:  # se é stato inserito l'angolo di rotazione con un punto
                    angle = qad_utils.getAngleBy2Pts(self.basePt, value)
                else:
                    angle = qad_utils.toRadians(value)

                angle = angle - self.ReferenceAng
                self.plugIn.setLastRot(angle)
                self.RotateGeoms(angle)
                return True  # fine comando

            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA PRIMO PUNTO PER NUOVO ANGOLO ROTAZIONE (da step = 6)
        elif self.step == 7:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            self.Pt1NewAng = value
            # imposto il map tool
            self.getPointMapTool().Pt1NewAng = self.Pt1NewAng
            self.getPointMapTool().setMode(
                Qad_rotate_maptool_ModeEnum.
                FIRST_PT_KNOWN_ASK_FOR_SECOND_NEW_ROTATION_PT)
            # si appresta ad attendere un punto
            self.waitForPoint(
                QadMsg.translate("Command_ROTATE", "Specify second point: "))
            self.step = 8

            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER NUOVO ANGOLO ROTAZIONE (da step = 7)
        elif self.step == 8:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            angle = qad_utils.getAngleBy2Pts(self.Pt1NewAng, value)

            angle = angle - self.ReferenceAng
            self.plugIn.setLastRot(angle)
            self.RotateGeoms(angle)
            return True  # fine comando
Example #37
0
class QadERASECommandClass(QadCommandClass):
    def instantiateNewCmd(self):
        """ istanzia un nuovo comando dello stesso tipo """
        return QadERASECommandClass(self.plugIn)

    def getName(self):
        return QadMsg.translate("Command_list", "ERASE")

    def getEnglishName(self):
        return "ERASE"

    def connectQAction(self, action):
        QObject.connect(action, SIGNAL("triggered()"),
                        self.plugIn.runERASECommand)

    def getIcon(self):
        return QIcon(":/plugins/qad/icons/erase.png")

    def getNote(self):
        # impostare le note esplicative del comando
        return QadMsg.translate("Command_ERASE", "Removes objects of the map.")

    def __init__(self, plugIn):
        QadCommandClass.__init__(self, plugIn)
        self.SSGetClass = QadSSGetClass(plugIn)
        self.SSGetClass.onlyEditableLayers = True

    def __del__(self):
        QadCommandClass.__del__(self)
        del self.SSGetClass

    def getPointMapTool(self, drawMode=QadGetPointDrawModeEnum.NONE):
        if self.step == 0:  # quando si é in fase di selezione entità
            return self.SSGetClass.getPointMapTool(drawMode)
        else:
            return QadCommandClass.getPointMapTool(self, drawMode)

    def run(self, msgMapTool=False, msg=None):

        #=========================================================================
        # RICHIESTA PRIMO PUNTO PER SELEZIONE OGGETTI
        if self.step == 0:  # inizio del comando
            if self.SSGetClass.run(msgMapTool, msg) == True:
                # selezione terminata
                self.step = 1
                return self.run(msgMapTool, msg)
            else:
                return False

        #=========================================================================
        # CANCELLAZIONE OGGETTI
        elif self.step == 1:
            self.plugIn.beginEditCommand(
                "Feature deleted", self.SSGetClass.entitySet.getLayerList())

            for layerEntitySet in self.SSGetClass.entitySet.layerEntitySetList:
                # plugIn, layer, featureIds, refresh
                if qad_layer.deleteFeaturesToLayer(self.plugIn, layerEntitySet.layer, \
                                                   layerEntitySet.featureIds, False) == False:
                    self.plugIn.destroyEditCommand()
                    return

            self.plugIn.endEditCommand()

            return True  # fine comando
Example #38
0
 def __init__(self, plugIn):
     QadCommandClass.__init__(self, plugIn)
     self.SSGetClass = QadSSGetClass(plugIn)
     self.SSGetClass.onlyEditableLayers = True
     self.entitySet = QadEntitySet()
     self.basePt = QgsPoint()
Example #39
0
 def __init__(self, plugIn):
     QadCommandClass.__init__(self, plugIn)
     self.SSGetClass = QadSSGetClass(plugIn)
     self.SSGetClass.onlyEditableLayers = True
Example #40
0
class QadMBUFFERCommandClass(QadCommandClass):
    def instantiateNewCmd(self):
        """ istanzia un nuovo comando dello stesso tipo """
        return QadMBUFFERCommandClass(self.plugIn)

    def getName(self):
        return QadMsg.translate("Command_list", "MBUFFER")

    def getEnglishName(self):
        return "MBUFFER"

    def connectQAction(self, action):
        QObject.connect(action, SIGNAL("triggered()"),
                        self.plugIn.runMBUFFERCommand)

    def getIcon(self):
        return QIcon(":/plugins/qad/icons/mbuffer.png")

    def getNote(self):
        # impostare le note esplicative del comando
        return QadMsg.translate(
            "Command_MBUFFER",
            "Creates polygons by buffering selected objects.")

    def __init__(self, plugIn):
        QadCommandClass.__init__(self, plugIn)
        # se questo flag = True il comando serve all'interno di un altro comando per disegnare un buffer
        # che non verrà salvato su un layer
        self.virtualCmd = False
        self.rubberBandBorderColor = None
        self.rubberBandFillColor = None
        self.SSGetClass = QadSSGetClass(plugIn)
        self.entitySet = QadEntitySet()
        self.width = 0
        self.segments = self.plugIn.segments  # il numero di segmenti per l'approssimazione delle curve

    def __del__(self):
        QadCommandClass.__del__(self)
        del SSGetClass

    def getPointMapTool(self, drawMode=QadGetPointDrawModeEnum.NONE):
        if self.step == 0:  # quando si é in fase di selezione entità
            return self.SSGetClass.getPointMapTool()
        else:
            if (self.plugIn is not None):
                if self.PointMapTool is None:
                    self.PointMapTool = Qad_mbuffer_maptool(self.plugIn)
                    self.PointMapTool.setRubberBandColor(
                        self.rubberBandBorderColor, self.rubberBandFillColor)
                return self.PointMapTool
            else:
                return None

    def getCurrentContextualMenu(self):
        if self.step == 0:  # quando si é in fase di selezione entità
            return None  # return self.SSGetClass.getCurrentContextualMenu()
        else:
            return self.contextualMenu

    def setRubberBandColor(self, rubberBandBorderColor, rubberBandFillColor):
        self.rubberBandBorderColor = rubberBandBorderColor
        self.rubberBandFillColor = rubberBandFillColor
        if self.PointMapTool is not None:
            self.PointMapTool.setRubberBandColor(self.rubberBandBorderColor,
                                                 self.rubberBandFillColor)

    def AddGeoms(self, currLayer):
        bufferGeoms = []
        tolerance = QadVariables.get(
            QadMsg.translate("Environment variables", "TOLERANCE2APPROXCURVE"))

        for layerEntitySet in self.entitySet.layerEntitySetList:
            layer = layerEntitySet.layer
            geoms = layerEntitySet.getGeometryCollection()

            for geom in geoms:
                # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy
                newGeom = self.layerToMapCoordinates(layer, geom)
                g = qad_utils.ApproxCurvesOnGeom(newGeom.buffer(self.width, self.segments), \
                                                 self.segments, self.segments, \
                                                 tolerance)
                # trasformo la geometria nel crs del layer
                bufferGeoms.append(self.mapToLayerCoordinates(layer, g))

        self.plugIn.beginEditCommand("Feature buffered", currLayer)

        # filtro le features per tipo
        pointGeoms, lineGeoms, polygonGeoms = qad_utils.filterGeomsByType(bufferGeoms, \
                                                                          currLayer.geometryType())
        # aggiungo le geometrie del tipo corretto
        if currLayer.geometryType() == QGis.Line:
            polygonToLines = []
            # Riduco le geometrie in linee
            for g in polygonGeoms:
                lines = qad_utils.asPointOrPolyline(g)
                for l in lines:
                    if l.type() == QGis.Line:
                        polygonToLines.append(l)
            # plugIn, layer, geoms, coordTransform , refresh, check_validity
            if qad_layer.addGeomsToLayer(self.plugIn, currLayer,
                                         polygonToLines, None, False,
                                         False) == False:
                self.plugIn.destroyEditCommand()
                return

            del polygonGeoms[:]  # svuoto la lista

        # plugIn, layer, geoms, coordTransform , refresh, check_validity
        if qad_layer.addGeomsToLayer(self.plugIn, currLayer, bufferGeoms, None,
                                     False, False) == False:
            self.plugIn.destroyEditCommand()
            return

        if pointGeoms is not None and len(pointGeoms) > 0:
            PointTempLayer = qad_layer.createQADTempLayer(
                self.plugIn, QGis.Point)
            self.plugIn.addLayerToLastEditCommand("Feature buffered",
                                                  PointTempLayer)

        if lineGeoms is not None and len(lineGeoms) > 0:
            LineTempLayer = qad_layer.createQADTempLayer(
                self.plugIn, QGis.Line)
            self.plugIn.addLayerToLastEditCommand("Feature buffered",
                                                  LineTempLayer)

        if polygonGeoms is not None and len(polygonGeoms) > 0:
            PolygonTempLayer = qad_layer.createQADTempLayer(
                self.plugIn, QGis.Polygon)
            self.plugIn.addLayerToLastEditCommand("Feature buffered",
                                                  PolygonTempLayer)

        # aggiungo gli scarti nei layer temporanei di QAD
        # trasformo la geometria in quella dei layer temporanei
        # plugIn, pointGeoms, lineGeoms, polygonGeoms, coord, refresh
        if qad_layer.addGeometriesToQADTempLayers(self.plugIn, pointGeoms, lineGeoms, polygonGeoms, \
                                                  None, False) == False:
            self.plugIn.destroyEditCommand()
            return

        self.plugIn.endEditCommand()

    def run(self, msgMapTool=False, msg=None):
        if self.plugIn.canvas.mapSettings().destinationCrs().geographicFlag():
            self.showMsg(
                QadMsg.translate(
                    "QAD",
                    "\nThe coordinate reference system of the project must be a projected coordinate system.\n"
                ))
            return True  # fine comando

        currLayer = None
        if self.virtualCmd == False:  # se si vuole veramente salvare la polylinea in un layer
            # il layer corrente deve essere editabile e di tipo linea o poligono
            currLayer, errMsg = qad_layer.getCurrLayerEditable(
                self.plugIn.canvas, [QGis.Line, QGis.Polygon])
            if currLayer is None:
                self.showErr(errMsg)
                return True  # fine comando

            # il layer corrente non deve appartenere a quotature
            dimStyleList = QadDimStyles.getDimListByLayer(currLayer)
            if len(dimStyleList) > 0:
                dimStyleNames = ""
                for i in xrange(0, len(dimStyleList), 1):
                    if i > 0:
                        dimStyleNames += ", "
                    dimStyleNames += dimStyleList[i].name
                errMsg = QadMsg.translate(
                    "QAD",
                    "\nCurrent layer is a layer referenced to {0} dimension style and it is not valid.\n"
                )
                self.showErr(errMsg.format(dimStyleNames))
                return True  # fine comando

        #=========================================================================
        # RICHIESTA SELEZIONE OGGETTI
        if self.step == 0:  # inizio del comando
            if self.SSGetClass.run(msgMapTool, msg) == True:
                # selezione terminata
                self.step = 1
                self.getPointMapTool().refreshSnapType(
                )  # aggiorno lo snapType che può  essere variato dal maptool di selezione entità
                return self.run(msgMapTool, msg)

        #=========================================================================
        # BUFFER OGGETTI
        elif self.step == 1:
            self.entitySet.set(self.SSGetClass.entitySet)

            if self.entitySet.count() == 0:
                return True  # fine comando

            # imposto il map tool
            self.getPointMapTool().setMode(
                Qad_mbuffer_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_FIRST_PT)
            if currLayer is not None:
                self.getPointMapTool(
                ).geomType = QGis.Line if currLayer.geometryType(
                ) == QGis.Line else QGis.Polygon

            # si appresta ad attendere un punto o un numero reale
            # msg, inputType, default, keyWords, valori positivi
            msg = QadMsg.translate("Command_MBUFFER",
                                   "Specify the buffer length <{0}>: ")
            self.waitFor(msg.format(str(self.plugIn.lastRadius)), \
                         QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT, \
                         self.plugIn.lastRadius, "", \
                         QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)

            self.step = 2
            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA LARGHEZZA (da step = 1)
        elif self.step == 2:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            if type(value) == QgsPoint:
                self.startPtForBufferWidth = value

                # imposto il map tool
                self.getPointMapTool(
                ).startPtForBufferWidth = self.startPtForBufferWidth
                self.getPointMapTool().entitySet.set(self.entitySet)
                self.getPointMapTool().segments = self.segments
                self.getPointMapTool().setMode(
                    Qad_mbuffer_maptool_ModeEnum.FIRST_PT_ASK_FOR_BUFFER_WIDTH)

                # si appresta ad attendere un punto
                self.waitForPoint(
                    QadMsg.translate("Command_MBUFFER",
                                     "Specify second point: "))
                self.step = 3
                return False
            else:
                self.width = value
                self.plugIn.setLastRadius(self.width)

                if self.virtualCmd == False:  # se si vuole veramente salvare i buffer in un layer
                    self.AddGeoms(currLayer)

                return True  # fine comando

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA SECONDO PUNTO DELLA LARGHEZZA BUFFER (da step = 2)
        elif self.step == 3:  # dopo aver atteso un punto si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            self.width = qad_utils.getDistance(self.startPtForBufferWidth,
                                               value)
            self.plugIn.setLastRadius(self.width)

            if self.virtualCmd == False:  # se si vuole veramente salvare i buffer in un layer
                self.AddGeoms(currLayer)

            return True  # fine comando
Example #41
0
class QadCOPYCommandClass(QadCommandClass):

   def instantiateNewCmd(self):
      """ istanzia un nuovo comando dello stesso tipo """
      return QadCOPYCommandClass(self.plugIn)
   
   def getName(self):
      return QadMsg.translate("Command_list", "COPY")

   def getEnglishName(self):
      return "COPY"

   def connectQAction(self, action):
      QObject.connect(action, SIGNAL("triggered()"), self.plugIn.runCOPYCommand)

   def getIcon(self):
      return QIcon(":/plugins/qad/icons/copyEnt.png")

   def getNote(self):
      # impostare le note esplicative del comando
      return QadMsg.translate("Command_COPY", "Copies selected objects a specified distance in a specified direction.")
   
   def __init__(self, plugIn):
      QadCommandClass.__init__(self, plugIn)
      self.SSGetClass = QadSSGetClass(plugIn)
      self.SSGetClass.onlyEditableLayers = True
      self.entitySet = QadEntitySet()
      self.basePt = QgsPoint()
      self.series = False
      self.seriesLen = 2
      self.adjust = False
      self.copyMode = QadVariables.get(QadMsg.translate("Environment variables", "COPYMODE"))
      
      self.featureCache = [] # lista di (layer, feature)
      self.nOperationsToUndo = 0

   def __del__(self):
      QadCommandClass.__del__(self)
      del self.SSGetClass
      
   def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):
      if self.step == 0: # quando si é in fase di selezione entità
         return self.SSGetClass.getPointMapTool()
      else:
         if (self.plugIn is not None):
            if self.PointMapTool is None:
               self.PointMapTool = Qad_copy_maptool(self.plugIn)
            return self.PointMapTool
         else:
            return None


   #============================================================================
   # move
   #============================================================================
   def move(self, f, offSetX, offSetY, layerEntitySet, entitySet, dimEntity):
      if dimEntity is None:
         # sposto la feature e la rimuovo da entitySet (é la prima)
         f.setGeometry(qad_utils.moveQgsGeometry(f.geometry(), offSetX, offSetY))
         # plugIn, layer, feature, coordTransform, refresh, check_validity
         if qad_layer.addFeatureToLayer(self.plugIn, layerEntitySet.layer, f, None, False, False) == False:  
            return False
      else:
         # sposto la quota
         dimEntity.move(offSetX, offSetY)                               
         if dimEntity.addToLayers(self.plugIn) == False:
            return False             
            
      return True


   #============================================================================
   # copyGeoms
   #============================================================================
   def copyGeoms(self, newPt):
      # copio entitySet
      entitySet = QadEntitySet(self.entitySet)
      
      self.plugIn.beginEditCommand("Feature copied", entitySet.getLayerList())

      for layerEntitySet in entitySet.layerEntitySetList:
         layer = layerEntitySet.layer
         
         transformedBasePt = self.mapToLayerCoordinates(layer, self.basePt)
         transformedNewPt = self.mapToLayerCoordinates(layer, newPt)
         offSetX = transformedNewPt.x() - transformedBasePt.x()
         offSetY = transformedNewPt.y() - transformedBasePt.y()
         
         while len(layerEntitySet.featureIds) > 0:
            featureId = layerEntitySet.featureIds[0]
            f = layerEntitySet.getFeature(featureId)

            # verifico se l'entità appartiene ad uno stile di quotatura
            dimEntity = self.plugIn.dimStyles.getDimEntity(layerEntitySet.layer, f.id())
            
            if self.series and self.seriesLen > 0: # devo fare una serie
               if self.adjust == True:
                  offSetX = offSetX / (self.seriesLen - 1)
                  offSetY = offSetY / (self.seriesLen - 1)
   
               deltaX = offSetX
               deltaY = offSetY
                              
               for i in xrange(1, self.seriesLen, 1):
                  if self.move(f, deltaX, deltaY, layerEntitySet, entitySet, dimEntity) == False:  
                     self.plugIn.destroyEditCommand()
                     return
                  deltaX = deltaX + offSetX
                  deltaY = deltaY + offSetY
            else:
               if self.move(f, offSetX, offSetY, layerEntitySet, entitySet, dimEntity) == False:  
                  self.plugIn.destroyEditCommand()
                  return
               
            # la rimuovo da entitySet
            if dimEntity is None:
               del layerEntitySet.featureIds[0]
            else:
               dimEntitySet = dimEntity.getEntitySet()
               entitySet.subtract(dimEntitySet)
               
      self.plugIn.endEditCommand()
      self.nOperationsToUndo = self.nOperationsToUndo + 1


   #============================================================================
   # waitForBasePt
   #============================================================================
   def waitForBasePt(self):
      # imposto il map tool
      self.getPointMapTool().setMode(Qad_copy_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_BASE_PT)                                

      if self.copyMode == 0: # Imposta il comando COPIA in modo che venga ripetuto automaticamente
         keyWords = QadMsg.translate("Command_COPY", "Displacement") + "/" + \
                    QadMsg.translate("Command_COPY", "mOde")
         englishKeyWords = "Displacement" + "/" + "mOde"
                    
      else:
         # l'opzione Multiple viene tradotta in italiano in "MUltiplo" nel contesto "waitForBasePt"
         # l'opzione Multiple viene tradotta in italiano in "Multipla" nel contesto "waitForMode"
         # e "Multipla" nel caso di modalità di copia
         keyWords = QadMsg.translate("Command_COPY", "Displacement") + "/" + \
                    QadMsg.translate("Command_COPY", "mOde") + "/" + \
                    QadMsg.translate("Command_COPY", "Multiple", "waitForBasePt")
         englishKeyWords = "Displacement" + "/" + "mOde" + "/" + "Multiple"

      default = QadMsg.translate("Command_COPY", "Displacement")                   
      prompt = QadMsg.translate("Command_COPY", "Specify base point or [{0}] <{1}>: ").format(keyWords, default)
      
      keyWords += "_" + englishKeyWords
      # si appresta ad attendere un punto o enter o una parola chiave         
      # msg, inputType, default, keyWords, nessun controllo
      self.waitFor(prompt, \
                   QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \
                   default, \
                   keyWords, QadInputModeEnum.NONE)      
      self.step = 2      
   
   #============================================================================
   # waitForSeries
   #============================================================================
   def waitForSeries(self):
      # si appresta ad attendere un numero intero
      msg = QadMsg.translate("Command_COPY", "Number of Items to Array <{0}>: ")
      # msg, inputType, default, keyWords, valori positivi
      self.waitFor(msg.format(str(self.seriesLen)), \
                   QadInputTypeEnum.INT, \
                   self.seriesLen, \
                   "", \
                   QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)                                      
      self.step = 6        
      
   #============================================================================
   # waitForSecondPt
   #============================================================================
   def waitForSecondPt(self):
      self.series = False
      self.adjust = False
      self.getPointMapTool().seriesLen = 0
      self.getPointMapTool().setMode(Qad_copy_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_COPY_PT)
                                      
      if len(self.featureCache) > 0:
         keyWords = QadMsg.translate("Command_COPY", "Array") + "/" + \
                    QadMsg.translate("Command_COPY", "Exit") + "/" + \
                    QadMsg.translate("Command_COPY", "Undo")
         default = QadMsg.translate("Command_COPY", "Exit")
         prompt = QadMsg.translate("Command_COPY", "Specify second point or [{0}] <{1}>: ").format(keyWords, default)
   
         englishKeyWords = "Array" + "/" + "Exit" + "/" + "Undo" + "/" + "Exit"
         keyWords += "_" + englishKeyWords
         # si appresta ad attendere un punto o enter o una parola chiave         
         # msg, inputType, default, keyWords, nessun controllo
         self.waitFor(prompt, \
                      QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \
                      default, \
                      keyWords, QadInputModeEnum.NONE)
      else:
         keyWords = QadMsg.translate("Command_COPY", "Array")
         prompt = QadMsg.translate("Command_COPY", "Specify second point or [{0}] <use first point as displacement from origin point 0,0>: ").format(keyWords)
                   
         englishKeyWords = "Array"
         keyWords += "_" + englishKeyWords
         # si appresta ad attendere un punto o enter o una parola chiave         
         # msg, inputType, default, keyWords, nessun controllo
         self.waitFor(prompt, \
                      QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \
                      None, \
                      keyWords, QadInputModeEnum.NONE)      
            
      self.step = 3           

   #============================================================================
   # waitForSecondPtBySeries
   #============================================================================
   def waitForSecondPtBySeries(self):
      if self.adjust == False:
         keyWords = QadMsg.translate("Command_COPY", "Fit")
         englishKeyWords = "Fit"        
      else:
         keyWords = QadMsg.translate("Command_COPY", "Array")
         englishKeyWords = "Array"        
      prompt = QadMsg.translate("Command_COPY", "Specify second point or [{0}]: ").format(keyWords)

      keyWords += "_" + englishKeyWords
      # si appresta ad attendere un punto o enter o una parola chiave         
      # msg, inputType, default, keyWords, valore nullo non permesso
      self.waitFor(prompt, \
                   QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \
                   "", \
                   keyWords, QadInputModeEnum.NOT_NULL)      
      self.step = 7

   #============================================================================
   # run
   #============================================================================
   def run(self, msgMapTool = False, msg = None):
      if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():
         self.showMsg(QadMsg.translate("QAD", "\nThe coordinate reference system of the project must be a projected coordinate system.\n"))
         return True # fine comando
            
      #=========================================================================
      # RICHIESTA SELEZIONE OGGETTI
      if self.step == 0: # inizio del comando
         if self.SSGetClass.run(msgMapTool, msg) == True:
            # selezione terminata
            self.step = 1
            return self.run(msgMapTool, msg)
      
      #=========================================================================
      # COPIA OGGETTI
      elif self.step == 1:
         self.entitySet.set(self.SSGetClass.entitySet)
         
         if self.entitySet.count() == 0:
            return True # fine comando

         CurrSettingsMsg = QadMsg.translate("QAD", "\nCurrent settings: ")
         if self.copyMode == 0: # 0 = multipla 
            CurrSettingsMsg = CurrSettingsMsg + QadMsg.translate("Command_COPY", "Copy mode = Multiple")         
         else: # 1 = singola
            CurrSettingsMsg = CurrSettingsMsg + QadMsg.translate("Command_COPY", "Copy mode = Single")         
         self.showMsg(CurrSettingsMsg)         

         self.getPointMapTool().entitySet.set(self.entitySet)
         self.waitForBasePt()
         self.getPointMapTool().refreshSnapType() # riagggiorno lo snapType che può essere variato dal maptool di selezione entità                    
         return False
         
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA PUNTO BASE (da step = 1)
      elif self.step == 2: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  pass # opzione di default "spostamento"
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if value is None:
            value = QadMsg.translate("Command_COPY", "Displacement")

         if type(value) == unicode:
            if value == QadMsg.translate("Command_COPY", "Displacement") or value == "Displacement":
               self.basePt.set(0, 0)
               self.getPointMapTool().basePt = self.basePt
               self.getPointMapTool().setMode(Qad_copy_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_COPY_PT)                                
               # si appresta ad attendere un punto
               msg = QadMsg.translate("Command_COPY", "Specify the displacement from the origin point 0,0 <{0}, {1}>: ")
               # msg, inputType, default, keyWords, nessun controllo
               self.waitFor(msg.format(str(self.plugIn.lastOffsetPt.x()), str(self.plugIn.lastOffsetPt.y())), \
                            QadInputTypeEnum.POINT2D, \
                            self.plugIn.lastOffsetPt, \
                            "", QadInputModeEnum.NONE)                                      
               self.step = 4
            elif value == QadMsg.translate("Command_COPY", "mOde") or value == "mOde":
               # l'opzione Multiple viene tradotta in italiano in "Multipla" nel contesto "waitForMode"
               keyWords = QadMsg.translate("Command_COPY", "Single") + "/" + \
                          QadMsg.translate("Command_COPY", "Multiple", "waitForMode")
               englishKeyWords = "Single" + "/" + "Multiple"
                          
               if self.copyMode == 0: # Imposta il comando COPIA in modo che venga ripetuto automaticamente
                  # l'opzione Multiple viene tradotta in italiano in "Multipla" nel contesto "waitForMode"
                  default = QadMsg.translate("Command_COPY", "Multiple", "waitForMode")
               else:
                  default = QadMsg.translate("Command_COPY", "Single")               
               prompt = QadMsg.translate("Command_COPY", "Enter a copy mode option [{0}] <{1}>: ").format(keyWords, default)

               keyWords += "_" + englishKeyWords
               # si appresta ad attendere enter o una parola chiave         
               # msg, inputType, default, keyWords, nessun controllo
               self.waitFor(prompt, \
                            QadInputTypeEnum.KEYWORDS, \
                            default, \
                            keyWords, QadInputModeEnum.NONE)
               self.step = 5
            # l'opzione Multiple viene tradotta in italiano in "MUltiplo" nel contesto "waitForBasePt"
            elif value == QadMsg.translate("Command_COPY", "Multiple", "waitForBasePt") or value == "Multiple":
               self.copyMode = 0 # Imposta il comando COPIA in modo che venga ripetuto automaticamente
               self.waitForBasePt()                         
         elif type(value) == QgsPoint: # se é stato inserito il punto base
            self.basePt.set(value.x(), value.y())

            # imposto il map tool
            self.getPointMapTool().basePt = self.basePt           
            self.waitForSecondPt()
         
         return False 
         
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER COPIA (da step = 2)
      elif self.step == 3: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  if len(self.featureCache) > 0:
                     value = QadMsg.translate("Command_COPY", "Exit")
                  else:
                     value = None
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False
            else:
               value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if value is None:
            if len(self.featureCache) > 0:
               value = QadMsg.translate("Command_COPY", "Exit")
            else:               
               # utilizzare il primo punto come spostamento
               value = QgsPoint(self.basePt)
               self.basePt.set(0, 0)
               self.copyGeoms(value)
               return True # fine comando
         
         if type(value) == unicode:
            if value == QadMsg.translate("Command_COPY", "Array") or value == "Array":
               self.waitForSeries()               
            elif value == QadMsg.translate("Command_COPY", "Exit") or value == "Exit":
               return True # fine comando
            elif value == QadMsg.translate("Command_COPY", "Undo") or value == "Undo":
               if self.nOperationsToUndo > 0: 
                  self.nOperationsToUndo = self.nOperationsToUndo - 1
                  self.plugIn.undoEditCommand()
               else:
                  self.showMsg(QadMsg.translate("QAD", "The command has been canceled."))                  
               self.waitForSecondPt()
         elif type(value) == QgsPoint: # se é stato inserito lo spostamento con un punto
            self.copyGeoms(value)
            if self.copyMode == 1: # "Singola" 
               return True # fine comando
            self.waitForSecondPt()
         
         return False
               
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DEL PUNTO DI SPOSTAMENTO (da step = 2)
      elif self.step == 4: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         self.plugIn.setLastOffsetPt(value)
         self.copyGeoms(value)
         return True # fine comando


      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA MODALITA' (SINGOLA / MULTIPLA) (da step = 2)
      elif self.step == 5: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # la parola chiave arriva come parametro della funzione
            value = msg

         if type(value) == unicode:
            if value == QadMsg.translate("Command_COPY", "Single") or value == "Single":
               self.copyMode = 1
               QadVariables.set(QadMsg.translate("Environment variables", "COPYMODE"), 1)
               QadVariables.save()
            # l'opzione Multiple viene tradotta in italiano in "Multipla" nel contesto "waitForMode"
            elif value == QadMsg.translate("Command_COPY", "Multiple", "waitForMode") or value == "Multiple":
               self.copyMode = 0
               QadVariables.set(QadMsg.translate("Environment variables", "COPYMODE"), 0)
               QadVariables.save()
            
         self.waitForBasePt()
         return False

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA SERIE (da step = 3)
      elif self.step == 6: # dopo aver atteso un numero intero si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
               value = self.seriesLen
            else:
               value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if value < 2:
            self.showMsg(QadMsg.translate("Command_COPY", "\nThe value must be between 2 and 32767."))
            self.waitForSeries()
         else:
            self.series = True
            self.seriesLen = value
            self.getPointMapTool().seriesLen = self.seriesLen

            self.waitForSecondPtBySeries()
            
         return False

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER COPIA DA SERIE (da step = 6)
      elif self.step == 7: # dopo aver atteso un punto o una parola chiave
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if type(value) == unicode:
            if value == QadMsg.translate("Command_COPY", "Array") or value == "Array":
               self.adjust = False
               self.getPointMapTool().adjust = self.adjust
               self.waitForSecondPtBySeries()
            elif value == QadMsg.translate("Command_COPY", "Fit") or value == "Fit":
               self.adjust = True
               self.getPointMapTool().adjust = self.adjust
               self.waitForSecondPtBySeries()
         elif type(value) == QgsPoint: # se é stato inserito lo spostamento con un punto
            self.copyGeoms(value)
            if self.copyMode == 1: # "Singola" 
               return True # fine comando            
            self.waitForSecondPt()
          
         return False
Example #42
0
class QadSCALECommandClass(QadCommandClass):
    def instantiateNewCmd(self):
        """ istanzia un nuovo comando dello stesso tipo """
        return QadSCALECommandClass(self.plugIn)

    def getName(self):
        return QadMsg.translate("Command_list", "SCALE")

    def getEnglishName(self):
        return "SCALE"

    def connectQAction(self, action):
        QObject.connect(action, SIGNAL("triggered()"),
                        self.plugIn.runSCALECommand)

    def getIcon(self):
        return QIcon(":/plugins/qad/icons/scale.png")

    def getNote(self):
        # impostare le note esplicative del comando
        return QadMsg.translate("Command_SCALE",
                                "Enlarges or reduces selected objects.")

    def __init__(self, plugIn):
        QadCommandClass.__init__(self, plugIn)
        self.SSGetClass = QadSSGetClass(plugIn)
        self.SSGetClass.onlyEditableLayers = True
        self.entitySet = QadEntitySet()
        self.basePt = None
        self.copyFeatures = False
        self.Pt1ReferenceLen = None
        self.ReferenceLen = 1
        self.Pt1NewLen = None

    def __del__(self):
        QadCommandClass.__del__(self)
        del self.SSGetClass

    def getPointMapTool(self, drawMode=QadGetPointDrawModeEnum.NONE):
        if self.step == 0:  # quando si é in fase di selezione entità
            return self.SSGetClass.getPointMapTool()
        else:
            if (self.plugIn is not None):
                if self.PointMapTool is None:
                    self.PointMapTool = Qad_scale_maptool(self.plugIn)
                return self.PointMapTool
            else:
                return None

    #============================================================================
    # scale
    #============================================================================
    def scale(self, f, basePt, scale, sizeFldName, layerEntitySet, entitySet):
        # verifico se l'entità appartiene ad uno stile di quotatura
        dimEntity = QadDimStyles.getDimEntity(layerEntitySet.layer, f.id())

        if dimEntity is None:
            # scalo la feature e la rimuovo da entitySet (é la prima)
            f.setGeometry(
                qad_utils.scaleQgsGeometry(f.geometry(), basePt, scale))
            if sizeFldName is not None:
                sizeValue = f.attribute(sizeFldName)
                if sizeValue is None:
                    sizeValue = 1
                sizeValue = sizeValue * scale
                f.setAttribute(sizeFldName, sizeValue)

            if self.copyFeatures == False:
                # plugIn, layer, feature, refresh, check_validity
                if qad_layer.updateFeatureToLayer(self.plugIn,
                                                  layerEntitySet.layer, f,
                                                  False, False) == False:
                    self.plugIn.destroyEditCommand()
                    return False
            else:
                # plugIn, layer, features, coordTransform, refresh, check_validity
                if qad_layer.addFeatureToLayer(self.plugIn,
                                               layerEntitySet.layer, f, None,
                                               False, False) == False:
                    self.plugIn.destroyEditCommand()
                    return False

            del layerEntitySet.featureIds[0]
        else:
            # scalo la quota e la rimuovo da entitySet
            dimEntitySet = dimEntity.getEntitySet()
            if self.copyFeatures == False:
                if dimEntity.deleteToLayers(self.plugIn) == False:
                    return False
            dimEntity.scale(self.plugIn, basePt, scale)
            if dimEntity.addToLayers(self.plugIn) == False:
                return False
            entitySet.subtract(dimEntitySet)

    def scaleGeoms(self, scale):
        # copio entitySet
        entitySet = QadEntitySet(self.entitySet)

        self.plugIn.beginEditCommand("Feature scaled",
                                     self.entitySet.getLayerList())

        for layerEntitySet in entitySet.layerEntitySetList:
            layer = layerEntitySet.layer

            transformedBasePt = self.mapToLayerCoordinates(layer, self.basePt)

            sizeFldName = None
            if qad_layer.isTextLayer(layer):
                # se l'altezza testo dipende da un solo campo
                sizeFldNames = qad_label.get_labelSizeFieldNames(layer)
                if len(sizeFldNames) == 1 and len(sizeFldNames[0]) > 0:
                    sizeFldName = sizeFldNames[0]
            elif qad_layer.isSymbolLayer(layer):
                # se la scala dipende da un campo
                sizeFldName = qad_layer.get_symbolScaleFieldName(layer)
                if len(sizeFldName) == 0:
                    sizeFldName = None

            while len(layerEntitySet.featureIds) > 0:
                featureId = layerEntitySet.featureIds[0]
                f = layerEntitySet.getFeature(featureId)

                if self.scale(f, transformedBasePt, scale, sizeFldName,
                              layerEntitySet, entitySet) == False:
                    self.plugIn.destroyEditCommand()
                    return

        self.plugIn.endEditCommand()

    def waitForScale(self):
        # imposto il map tool
        self.getPointMapTool().setMode(
            Qad_scale_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_SCALE_PT)

        keyWords = QadMsg.translate("Command_SCALE", "Copy") + "/" + \
                   QadMsg.translate("Command_SCALE", "Reference")
        default = self.plugIn.lastScale
        prompt = QadMsg.translate(
            "Command_SCALE", "Specify scale factor or [{0}] <{1}>: ").format(
                keyWords, str(default))

        englishKeyWords = "Copy" + "/" + "Reference"
        keyWords += "_" + englishKeyWords
        # si appresta ad attendere un punto o enter o una parola chiave
        # msg, inputType, default, keyWords, valori positivi
        self.waitFor(prompt, \
                     QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT | QadInputTypeEnum.KEYWORDS, \
                     default, \
                     keyWords, QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)
        self.step = 3

    def waitForReferenceLen(self):
        # imposto il map tool
        self.getPointMapTool().setMode(
            Qad_scale_maptool_ModeEnum.ASK_FOR_FIRST_PT_REFERENCE_LEN)

        msg = QadMsg.translate("Command_SCALE",
                               "Specify reference length <{0}>: ")
        # si appresta ad attendere un punto o enter
        # msg, inputType, default, keyWords, valori positivi
        self.waitFor(msg.format(str(self.plugIn.lastReferenceLen)), \
                     QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT, \
                     self.plugIn.lastReferenceLen, \
                     "", QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)
        self.step = 4

    def waitForNewReferenceLen(self):
        # imposto il map tool
        self.getPointMapTool().setMode(
            Qad_scale_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_NEW_LEN_PT)

        keyWords = QadMsg.translate("Command_SCALE", "Points")
        if self.plugIn.lastNewReferenceLen == 0:
            default = self.plugIn.lastScale
        else:
            default = self.plugIn.lastNewReferenceLen
        prompt = QadMsg.translate(
            "Command_SCALE", "Specify new length or [{0}] <{1}>: ").format(
                keyWords, str(default))

        englishKeyWords = "Points"
        keyWords += "_" + englishKeyWords
        # si appresta ad attendere un punto o enter o una parola chiave
        # msg, inputType, default, keyWords, valori positivi
        self.waitFor(prompt, \
                     QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT | QadInputTypeEnum.KEYWORDS, \
                     default, \
                     keyWords, QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)
        self.step = 6

    def run(self, msgMapTool=False, msg=None):
        if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():
            self.showMsg(
                QadMsg.translate(
                    "QAD",
                    "\nThe coordinate reference system of the project must be a projected coordinate system.\n"
                ))
            return True  # fine comando

        #=========================================================================
        # RICHIESTA SELEZIONE OGGETTI
        if self.step == 0:  # inizio del comando
            if self.SSGetClass.run(msgMapTool, msg) == True:
                # selezione terminata
                self.step = 1
                self.getPointMapTool().refreshSnapType(
                )  # aggiorno lo snapType che può essere variato dal maptool di selezione entità
                return self.run(msgMapTool, msg)

        #=========================================================================
        # RUOTA OGGETTI
        elif self.step == 1:
            self.entitySet.set(self.SSGetClass.entitySet)

            if self.entitySet.count() == 0:
                return True  # fine comando

            # imposto il map tool
            self.getPointMapTool().setMode(
                Qad_scale_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_BASE_PT)

            # si appresta ad attendere un punto
            self.waitForPoint(
                QadMsg.translate("Command_SCALE", "Specify base point: "))

            self.step = 2
            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA PUNTO BASE (da step = 1)
        elif self.step == 2:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            self.basePt = QgsPoint(value)

            self.getPointMapTool().basePt = self.basePt
            self.getPointMapTool().entitySet.set(self.entitySet)
            # si appresta ad attendere la scala
            self.waitForScale()

            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER SCALA (da step = 2)
        elif self.step == 3:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            if type(value) == unicode:
                if value == QadMsg.translate("Command_SCALE",
                                             "Copy") or value == "Copy":
                    self.copyFeatures = True
                    self.showMsg(
                        QadMsg.translate(
                            "Command_SCALE",
                            "\nScale of a copy of the selected objects."))
                    # si appresta ad attendere la scala
                    self.waitForScale()
                elif value == QadMsg.translate(
                        "Command_SCALE", "Reference") or value == "Reference":
                    # si appresta ad attendere la lunghezza di riferimento
                    self.waitForReferenceLen()
            elif type(value) == QgsPoint or type(
                    value) == float:  # se é stato inserita la scala
                if type(
                        value
                ) == QgsPoint:  # se é stato inserita la scala con un punto
                    if value == self.basePt:
                        self.showMsg(
                            QadMsg.translate(
                                "QAD",
                                "\nThe value must be positive and not zero."))
                        # si appresta ad attendere un punto
                        self.waitForScale()
                        return False

                    scale = qad_utils.getDistance(self.basePt, value)
                else:
                    scale = value
                self.plugIn.setLastScale(scale)

                self.scaleGeoms(scale)
                return True  # fine comando

            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA PRIMO PUNTO PER LUNGHEZZA DI RIFERIMENTO (da step = 3)
        elif self.step == 4:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            if type(value) == float:  # se é stato inserita la lunghezza
                self.ReferenceLen = value
                self.getPointMapTool().ReferenceLen = self.ReferenceLen
                # si appresta ad attendere la nuova lunghezza
                self.waitForNewReferenceLen()

            elif type(
                    value
            ) == QgsPoint:  # se é stato inserito la scala con un punto
                self.Pt1ReferenceLen = QgsPoint(value)
                self.getPointMapTool().Pt1ReferenceLen = self.Pt1ReferenceLen
                # imposto il map tool
                self.getPointMapTool().setMode(
                    Qad_scale_maptool_ModeEnum.
                    FIRST_PT_KNOWN_ASK_FOR_SECOND_PT_REFERENCE_LEN)
                # si appresta ad attendere un punto
                self.waitForPoint(
                    QadMsg.translate("Command_SCALE",
                                     "Specify second point: "))
                self.step = 5

            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER LUNGHEZZA DI RIFERIMENTO (da step = 4)
        elif self.step == 5:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            if self.Pt1ReferenceLen == value:
                self.showMsg(
                    QadMsg.translate(
                        "QAD", "\nThe value must be positive and not zero."))
                # si appresta ad attendere un punto
                self.waitForPoint(
                    QadMsg.translate("Command_SCALE",
                                     "Specify second point: "))
                return False

            length = qad_utils.getDistance(self.Pt1ReferenceLen, value)
            self.ReferenceLen = length
            self.getPointMapTool().ReferenceLen = self.ReferenceLen
            # si appresta ad attendere la nuova lunghezza
            self.waitForNewReferenceLen()

            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER NUOVA LUNGHEZZA (da step = 4 e 5)
        elif self.step == 6:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            if type(value) == unicode:
                if value == QadMsg.translate("Command_SCALE",
                                             "Points") or value == "Points":
                    # imposto il map tool
                    self.getPointMapTool().setMode(
                        Qad_scale_maptool_ModeEnum.ASK_FOR_FIRST_NEW_LEN_PT)
                    # si appresta ad attendere un punto
                    self.waitForPoint(
                        QadMsg.translate("Command_SCALE",
                                         "Specify first point: "))
                    self.step = 7
            elif type(value) == QgsPoint or type(
                    value) == float:  # se é stato inserita la lunghezza
                if type(
                        value
                ) == QgsPoint:  # se é stato inserito la lunghezza con un punto
                    if value == self.basePt:
                        self.showMsg(
                            QadMsg.translate(
                                "QAD",
                                "\nThe value must be positive and not zero."))
                        # si appresta ad attendere un punto
                        self.waitForNewReferenceLen()
                        return False

                    length = qad_utils.getDistance(self.basePt, value)
                else:
                    length = value

                scale = length / self.ReferenceLen
                self.plugIn.setLastScale(scale)
                self.scaleGeoms(scale)
                return True  # fine comando

            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA PRIMO PUNTO PER NUOVA LUNGHEZZA (da step = 6)
        elif self.step == 7:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            self.Pt1NewLen = value
            # imposto il map tool
            self.getPointMapTool().Pt1NewLen = self.Pt1NewLen
            self.getPointMapTool().setMode(
                Qad_scale_maptool_ModeEnum.
                FIRST_PT_KNOWN_ASK_FOR_SECOND_NEW_LEN_PT)
            # si appresta ad attendere un punto
            self.waitForPoint(
                QadMsg.translate("Command_SCALE", "Specify second point: "))
            self.step = 8

            return False

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER NUOVA LUNGHEZZA (da step = 7)
        elif self.step == 8:  # dopo aver atteso un punto o un numero reale si riavvia il comando
            if msgMapTool == True:  # il punto arriva da una selezione grafica
                # la condizione seguente si verifica se durante la selezione di un punto
                # é stato attivato un altro plugin che ha disattivato Qad
                # quindi stato riattivato il comando che torna qui senza che il maptool
                # abbia selezionato un punto
                if self.getPointMapTool(
                ).point is None:  # il maptool é stato attivato senza un punto
                    if self.getPointMapTool(
                    ).rightButton == True:  # se usato il tasto destro del mouse
                        return True  # fine comando
                    else:
                        self.setMapTool(
                            self.getPointMapTool())  # riattivo il maptool
                        return False

                value = self.getPointMapTool().point
            else:  # il punto arriva come parametro della funzione
                value = msg

            if value == self.Pt1NewLen:
                self.showMsg(
                    QadMsg.translate(
                        "QAD", "\nThe value must be positive and not zero."))
                # si appresta ad attendere un punto
                self.waitForPoint(
                    QadMsg.translate("Command_SCALE",
                                     "Specify second point: "))
                return False

            length = qad_utils.getDistance(self.Pt1NewLen, value)

            scale = length / self.ReferenceLen
            self.plugIn.setLastScale(scale)
            self.scaleGeoms(scale)
            return True  # fine comando
Example #43
0
class QadSETCURRUPDATEABLELAYERBYGRAPHCommandClass(QadCommandClass):
    def instantiateNewCmd(self):
        """ istanzia un nuovo comando dello stesso tipo """
        return QadSETCURRUPDATEABLELAYERBYGRAPHCommandClass(self.plugIn)

    def getName(self):
        return QadMsg.translate("Command_list",
                                "SETCURRUPDATEABLELAYERBYGRAPH")

    def getEnglishName(self):
        return "SETCURRUPDATEABLELAYERBYGRAPH"

    def connectQAction(self, action):
        QObject.connect(action, SIGNAL("triggered()"),
                        self.plugIn.runSETCURRUPDATEABLELAYERBYGRAPHCommand)

    def getIcon(self):
        return QIcon(":/plugins/qad/icons/setcurrupdateablelayerbygraph.png")

    def getNote(self):
        # impostare le note esplicative del comando
        return QadMsg.translate(
            "Command_SETCURRUPDATEABLELAYERBYGRAPH",
            "Sets the layers of a graphical objects as editable.")

    def __init__(self, plugIn):
        QadCommandClass.__init__(self, plugIn)
        self.SSGetClass = QadSSGetClass(plugIn)
        self.firstTime = True

    def __del__(self):
        QadCommandClass.__del__(self)
        del self.SSGetClass

    def getPointMapTool(self, drawMode=QadGetPointDrawModeEnum.NONE):
        if self.step == 0:  # quando si é in fase di selezione entità
            return self.SSGetClass.getPointMapTool(drawMode)
        else:
            return QadCommandClass.getPointMapTool(self, drawMode)

    def run(self, msgMapTool=False, msg=None):
        if self.step == 0:  # inizio del comando
            if self.firstTime == True:
                self.showMsg(
                    QadMsg.translate(
                        "Command_SETCURRUPDATEABLELAYERBYGRAPH",
                        "\nSelect objects whose layers will be the editable: ")
                )
                self.firstTime = False

            if self.SSGetClass.run(msgMapTool, msg) == True:
                # selezione terminata
                self.step = 1
                return self.run(msgMapTool, msg)
            else:
                return False  # continua

        elif self.step == 1:  # dopo aver atteso la selezione di oggetti
            message = ""
            for layerEntitySet in self.SSGetClass.entitySet.layerEntitySetList:
                layer = layerEntitySet.layer
                if layer.isEditable() == False:
                    if layer.startEditing() == True:
                        self.plugIn.iface.legendInterface(
                        ).refreshLayerSymbology(layer)
                        self.showMsg(
                            QadMsg.translate(
                                "Command_SETCURRUPDATEABLELAYERBYGRAPH",
                                "\nThe layer {0} is editable.").format(
                                    layer.name()))

            if len(self.SSGetClass.entitySet.layerEntitySetList) == 1:
                layer = self.SSGetClass.entitySet.layerEntitySetList[0].layer
                if self.plugIn.canvas.currentLayer() is None or \
                   self.plugIn.canvas.currentLayer() != layer:
                    self.plugIn.canvas.setCurrentLayer(layer)
                    self.plugIn.iface.setActiveLayer(
                        layer
                    )  # lancia evento di deactivate e activate dei plugin
                    self.plugIn.iface.legendInterface().refreshLayerSymbology(
                        layer)
                    self.showMsg(
                        QadMsg.translate(
                            "Command_SETCURRUPDATEABLELAYERBYGRAPH",
                            "\nThe current layer is {0}.").format(
                                layer.name()))

            return True
Example #44
0
class QadJOINCommandClass(QadCommandClass):
    def instantiateNewCmd(self):
        """ istanzia un nuovo comando dello stesso tipo """
        return QadJOINCommandClass(self.plugIn)

    def getName(self):
        return QadMsg.translate("Command_list", "JOIN")

    def getEnglishName(self):
        return "JOIN"

    def connectQAction(self, action):
        QObject.connect(action, SIGNAL("triggered()"),
                        self.plugIn.runJOINCommand)

    def getIcon(self):
        return QIcon(":/plugins/qad/icons/join.png")

    def getNote(self):
        # impostare le note esplicative del comando
        return QadMsg.translate("Command_JOIN", "Join existing geometries.")

    def __init__(self, plugIn):
        QadCommandClass.__init__(self, plugIn)

        self.entity = QadEntity()

        self.SSGetClass = None
        self.entSelClass = None

    def __del__(self):
        QadCommandClass.__del__(self)
        if self.SSGetClass is not None: del self.SSGetClass

    def getPointMapTool(self, drawMode=QadGetPointDrawModeEnum.NONE):
        if self.step == 1:  # quando si é in fase di selezione entità
            return self.entSelClass.getPointMapTool(drawMode)
        elif self.step == 2:  # quando si é in fase di selezione gruppo entità
            return self.SSGetClass.getPointMapTool()
        else:
            return QadCommandClass.getPointMapTool(self, drawMode)

    def getCurrentContextualMenu(self):
        if self.step == 1:  # quando si é in fase di selezione entità
            return self.entSelClass.getCurrentContextualMenu()
        elif self.step == 2:  # quando si é in fase di selezione gruppo entità
            return self.SSGetClass.getCurrentContextualMenu()()
        else:
            return self.contextualMenu

    def reinitSSGetClass(self):
        if self.SSGetClass is not None: del self.SSGetClass

        self.SSGetClass = QadSSGetClass(self.plugIn)
        self.SSGetClass.onlyEditableLayers = True
        self.SSGetClass.checkDimLayers = False  # scarto le quote
        geometryType = self.entity.layer.geometryType()
        if geometryType == QGis.Point:
            self.SSGetClass.checkPointLayer = True
            self.SSGetClass.checkLineLayer = False
            self.SSGetClass.checkPolygonLayer = False
        elif geometryType == QGis.Line:
            self.SSGetClass.checkPointLayer = False
            self.SSGetClass.checkLineLayer = True
            self.SSGetClass.checkPolygonLayer = True
        elif geometryType == QGis.Polygon:
            self.SSGetClass.checkPointLayer = False
            self.SSGetClass.checkLineLayer = True
            self.SSGetClass.checkPolygonLayer = True

    #============================================================================
    # addEntitySetToPoint
    #============================================================================
    def addEntitySetToPoint(self, entitySet, removeOriginals=True):
        """
      Aggiunge il set di entità al punto da modificare
      """
        geom = self.entity.getGeometry()
        layerList = []
        layerList.append(self.entity.layer)

        for layerEntitySet in entitySet.layerEntitySetList:
            layer = layerEntitySet.layer
            if layer.geometryType() != QGis.Point:
                self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                return False

            if removeOriginals: layerList.append(layer)
            coordTransform = QgsCoordinateTransform(layer.crs(),
                                                    self.entity.layer.crs())

            for featureId in layerEntitySet.featureIds:
                # se la feature è quella di entity è errore
                if layer.id() == self.entity.layerId(
                ) and featureId == self.entity.featureId:
                    self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                    return False

                f = layerEntitySet.getFeature(featureId)
                # trasformo la geometria nel crs del layer dell'entità da modificare
                geomToAdd = f.geometry()
                geomToAdd.transform(coordTransform)

                simplifiedGeoms = qad_utils.asPointOrPolyline(geomToAdd)
                for simplifiedGeom in simplifiedGeoms:
                    point = simplifiedGeom.asPoint()
                    # aggiungo una parte
                    if geom.addPart([point]) != 0:  # 0 in case of success
                        self.showMsg(QadMsg.translate("QAD",
                                                      "Invalid object."))
                        return False

        f = self.entity.getFeature()
        f.setGeometry(geom)

        layerList = entitySet.getLayerList()
        layerList.append(self.entity.layer)

        self.plugIn.beginEditCommand("Feature edited", layerList)

        # plugIn, layer, feature, refresh, check_validity
        if qad_layer.updateFeatureToLayer(self.plugIn, self.entity.layer, f,
                                          False, False) == False:
            self.plugIn.destroyEditCommand()
            return False

        if removeOriginals:
            for layerEntitySet in entitySet.layerEntitySetList:
                if qad_layer.deleteFeaturesToLayer(self.plugIn,
                                                   layerEntitySet.layer,
                                                   layerEntitySet.featureIds,
                                                   False) == False:
                    self.plugIn.destroyEditCommand()
                    return

        self.plugIn.endEditCommand()

        return True

    #============================================================================
    # addEntitySetToPolyline
    #============================================================================
    def addEntitySetToPolyline(self, entitySet, removeOriginals=True):
        """
      Aggiunge il set di entità alla polilinea da modificare
      """
        geom = self.entity.getGeometry()
        layerList = []
        layerList.append(self.entity.layer)

        for layerEntitySet in entitySet.layerEntitySetList:
            layer = layerEntitySet.layer
            if layer.geometryType() != QGis.Polygon and layer.geometryType(
            ) != QGis.Line:
                self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                return False

            if removeOriginals: layerList.append(layer)
            coordTransform = QgsCoordinateTransform(layer.crs(),
                                                    self.entity.layer.crs())

            for featureId in layerEntitySet.featureIds:
                # se la feature è quella di entity è errore
                if layer.id() == self.entity.layerId(
                ) and featureId == self.entity.featureId:
                    self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                    return False

                f = layerEntitySet.getFeature(featureId)
                # trasformo la geometria nel crs del layer dell'entità da modificare
                geomToAdd = f.geometry()
                geomToAdd.transform(coordTransform)

                # Riduco la geometria in point o polyline
                simplifiedGeoms = qad_utils.asPointOrPolyline(geomToAdd)
                for simplifiedGeom in simplifiedGeoms:
                    points = simplifiedGeom.asPolyline()  # vettore di punti
                    # aggiungo una parte
                    if geom.addPart(points) != 0:  # 0 in case of success
                        self.showMsg(QadMsg.translate("QAD",
                                                      "Invalid object."))
                        return False

        f = self.entity.getFeature()
        f.setGeometry(geom)

        layerList = entitySet.getLayerList()
        layerList.append(self.entity.layer)

        self.plugIn.beginEditCommand("Feature edited", layerList)

        # plugIn, layer, feature, refresh, check_validity
        if qad_layer.updateFeatureToLayer(self.plugIn, self.entity.layer, f,
                                          False, False) == False:
            self.plugIn.destroyEditCommand()
            return False

        if removeOriginals:
            for layerEntitySet in entitySet.layerEntitySetList:
                if qad_layer.deleteFeaturesToLayer(self.plugIn,
                                                   layerEntitySet.layer,
                                                   layerEntitySet.featureIds,
                                                   False) == False:
                    self.plugIn.destroyEditCommand()
                    return

        self.plugIn.endEditCommand()

        return True

    #============================================================================
    # addEntitySetToPolygon
    #============================================================================
    def addEntitySetToPolygon(self, entitySet, removeOriginals=True):
        """
      Aggiunge il set di entità al poligono da modificare
      """
        geom = self.entity.getGeometry()
        layerList = []
        layerList.append(self.entity.layer)

        for layerEntitySet in entitySet.layerEntitySetList:
            layer = layerEntitySet.layer
            if layer.geometryType() != QGis.Polygon and layer.geometryType(
            ) != QGis.Line:
                self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                return False

            if removeOriginals: layerList.append(layer)
            coordTransform = QgsCoordinateTransform(layer.crs(),
                                                    self.entity.layer.crs())

            for featureId in layerEntitySet.featureIds:
                # se la feature è quella di entity è errore
                if layer.id() == self.entity.layerId(
                ) and featureId == self.entity.featureId:
                    self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                    return False

                f = layerEntitySet.getFeature(featureId)
                # trasformo la geometria nel crs del layer del poligono da modificare
                geomToAdd = f.geometry()
                geomToAdd.transform(coordTransform)

                # se il poligono è contenuto nella geometria da aggiungere
                if geomToAdd.contains(geom):
                    # Riduco la geometria in point o polyline
                    simplifiedGeoms = qad_utils.asPointOrPolyline(geom)
                    # deve essere un poligono senza ring
                    if len(simplifiedGeoms) != 1 or simplifiedGeoms[0].wkbType(
                    ) != QGis.WKBLineString:
                        self.showMsg(QadMsg.translate("QAD",
                                                      "Invalid object."))
                        return False
                    points = simplifiedGeoms[0].asPolyline(
                    )  # vettore di punti
                    # aggiungo un'isola
                    if geomToAdd.addRing(points) != 0:  # 0 in case of success
                        self.showMsg(QadMsg.translate("QAD",
                                                      "Invalid object."))
                        return False
                    del geom
                    geom = QgsGeometry.fromPolygon(geomToAdd.asPolygon())
                else:  # se il poligono non è contenuto nella geometria da aggiungere
                    # Riduco la geometria in point o polyline
                    simplifiedGeoms = qad_utils.asPointOrPolyline(geomToAdd)
                    for simplifiedGeom in simplifiedGeoms:
                        points = simplifiedGeom.asPolyline(
                        )  # vettore di punti
                        # se la geometria da aggiungere è contenuta nel poligono
                        if geom.contains(QgsGeometry.fromPolyline(points)):
                            # aggiungo un'isola
                            if geom.addRing(
                                    points) != 0:  # 0 in case of success
                                self.showMsg(
                                    QadMsg.translate("QAD", "Invalid object."))
                                return False
                        else:
                            # aggiungo una parte
                            if geom.addPart(
                                    points) != 0:  # 0 in case of success
                                self.showMsg(
                                    QadMsg.translate("QAD", "Invalid object."))
                                return False

        f = self.entity.getFeature()
        f.setGeometry(geom)

        layerList = entitySet.getLayerList()
        layerList.append(self.entity.layer)

        self.plugIn.beginEditCommand("Feature edited", layerList)

        # plugIn, layer, feature, refresh, check_validity
        if qad_layer.updateFeatureToLayer(self.plugIn, self.entity.layer, f,
                                          False, False) == False:
            self.plugIn.destroyEditCommand()
            return False

        if removeOriginals:
            for layerEntitySet in entitySet.layerEntitySetList:
                if qad_layer.deleteFeaturesToLayer(self.plugIn,
                                                   layerEntitySet.layer,
                                                   layerEntitySet.featureIds,
                                                   False) == False:
                    self.plugIn.destroyEditCommand()
                    return

        self.plugIn.endEditCommand()

        return True

    #============================================================================
    # waitForEntsel
    #============================================================================
    def waitForEntsel(self, msgMapTool, msg):
        if self.entSelClass is not None:
            del self.entSelClass
        self.step = 1
        self.entSelClass = QadEntSelClass(self.plugIn)
        self.entSelClass.msg = QadMsg.translate("Command_JOIN",
                                                "Select object to join to: ")
        # scarto la selezione di quote
        self.entSelClass.checkDimLayers = False
        self.entSelClass.onlyEditableLayers = True
        self.entSelClass.deselectOnFinish = True

        self.entSelClass.run(msgMapTool, msg)

    #============================================================================
    # waitForSSsel
    #============================================================================
    def waitForSSsel(self, msgMapTool, msg):
        self.reinitSSGetClass()
        self.step = 2
        self.showMsg(
            QadMsg.translate("Command_JOIN", "\nSelect objects to join: "))
        self.SSGetClass.run(msgMapTool, msg)

    def run(self, msgMapTool=False, msg=None):
        if self.plugIn.canvas.mapSettings().destinationCrs().geographicFlag():
            self.showMsg(
                QadMsg.translate(
                    "QAD",
                    "\nThe coordinate reference system of the project must be a projected coordinate system.\n"
                ))
            return True  # fine comando

        if self.step == 0:
            self.waitForEntsel(msgMapTool,
                               msg)  # seleziona l'oggetto a cui aggregarsi
            return False  # continua

        #=========================================================================
        # RISPOSTA ALLA SELEZIONE ENTITA' DA MODIFICARE
        elif self.step == 1:
            if self.entSelClass.run(msgMapTool, msg) == True:
                if self.entSelClass.entity.isInitialized():
                    self.entity.set(self.entSelClass.entity)

                    self.waitForSSsel(msgMapTool, msg)
                else:
                    if self.entSelClass.canceledByUsr == True:  # fine comando
                        return True
                    self.showMsg(
                        QadMsg.translate("QAD",
                                         "No geometries in this position."))
                    self.waitForEntsel(msgMapTool, msg)

            return False  # continua

        #=========================================================================
        # RISPOSTA ALLA RICHIESTA DEL GRUPPO DI SELEZIONE (da step = 1)
        elif self.step == 2:
            if self.SSGetClass.run(msgMapTool, msg) == True:
                if self.SSGetClass.entitySet.count() > 0:
                    geometryType = self.entity.layer.geometryType()
                    if geometryType == QGis.Point:
                        self.addEntitySetToPoint(self.SSGetClass.entitySet)
                    elif geometryType == QGis.Line:
                        self.addEntitySetToPolyline(self.SSGetClass.entitySet)
                    elif geometryType == QGis.Polygon:
                        self.addEntitySetToPolygon(self.SSGetClass.entitySet)

                    return True

                self.waitForSSsel(msgMapTool, msg)
            return False
 def __init__(self, plugIn):
    QadCommandClass.__init__(self, plugIn)
    self.SSGetClass = QadSSGetClass(plugIn)
    self.firstTime = True
Example #46
0
class QadTRIMCommandClass(QadCommandClass):

   def instantiateNewCmd(self):
      """ istanzia un nuovo comando dello stesso tipo """
      return QadTRIMCommandClass(self.plugIn)
   
   def getName(self):
      return QadMsg.translate("Command_list", "TRIM")

   def getEnglishName(self):
      return "TRIM"

   def connectQAction(self, action):
      QObject.connect(action, SIGNAL("triggered()"), self.plugIn.runTRIMCommand)

   def getIcon(self):
      return QIcon(":/plugins/qad/icons/trim.png")

   def getNote(self):
      # impostare le note esplicative del comando
      return QadMsg.translate("Command_TRIM", "Trims (or extends) objects to meet the edges of other objects.")
   
   def __init__(self, plugIn):
      QadCommandClass.__init__(self, plugIn)
      self.SSGetClass = QadSSGetClass(plugIn)
      self.PLINECommand = None      
      self.RECTANGLECommand = None
      self.entitySet = QadEntitySet() # entità da tagliare o estendere
      self.limitEntitySet = QadEntitySet() # entità che fanno da limiti
      self.edgeMode = QadVariables.get(QadMsg.translate("Environment variables", "EDGEMODE"))
      self.defaultValue = None # usato per gestire il tasto dx del mouse
      self.nOperationsToUndo = 0

   def __del__(self):
      QadCommandClass.__del__(self)

   def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):
      if self.step == 3: # quando si é in fase di disegno linea
         return self.PLINECommand.getPointMapTool(drawMode)
      elif self.step == 4: # quando si é in fase di disegno rettangolo 
         return self.RECTANGLECommand.getPointMapTool(drawMode)      
      else:
         return QadCommandClass.getPointMapTool(self, drawMode)

   #============================================================================
   # trimFeatures
   #============================================================================
   def trimFeatures(self, geom, toExtend):
      # geom è in map coordinates
      tolerance2ApproxCurve = QadVariables.get(QadMsg.translate("Environment variables", "TOLERANCE2APPROXCURVE"))
      LineTempLayer = None
      self.plugIn.beginEditCommand("Feature extended" if toExtend else "Feature trimmed", \
                                   self.entitySet.getLayerList())
      
      for layerEntitySet in self.entitySet.layerEntitySetList:
         layer = layerEntitySet.layer

         for featureId in layerEntitySet.featureIds:
            f = qad_utils.getFeatureById(layer, featureId)
            if f is None:
               continue
            # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy
            f_geom = self.layerToMapCoordinates(layer, f.geometry())
            
            if geom.type() == QGis.Point:
               # ritorna una tupla (<The squared cartesian distance>,
               #                    <minDistPoint>
               #                    <afterVertex>
               #                    <leftOf>)
               dummy = qad_utils.closestSegmentWithContext(geom.asPoint(), f_geom)
               if dummy[1] is not None:
                  intPts = [dummy[1]]
            else:
               intPts = qad_utils.getIntersectionPoints(geom, f_geom)
               
            for intPt in intPts:               
               if toExtend:
                  newGeom = qad_utils.extendQgsGeometry(self.plugIn.canvas.mapRenderer().destinationCrs(), f_geom, intPt, \
                                                        self.limitEntitySet, self.edgeMode, \
                                                        tolerance2ApproxCurve)
                  if newGeom is not None:
                     # aggiorno la feature con la geometria estesa
                     extendedFeature = QgsFeature(f)
                     # trasformo la geometria nel crs del layer
                     extendedFeature.setGeometry(self.mapToLayerCoordinates(layer, newGeom))
                     # plugIn, layer, feature, refresh, check_validity
                     if qad_layer.updateFeatureToLayer(self.plugIn, layer, extendedFeature, False, False) == False:
                        self.plugIn.destroyEditCommand()
                        return
               else: # trim
                  result = qad_utils.trimQgsGeometry(self.plugIn.canvas.mapRenderer().destinationCrs(), f_geom, intPt, \
                                                     self.limitEntitySet, self.edgeMode, \
                                                     tolerance2ApproxCurve)                  
                  if result is not None:
                     line1 = result[0]
                     line2 = result[1]
                     atSubGeom = result[2]
                     if layer.geometryType() == QGis.Line:
                        updGeom = qad_utils.setSubGeom(f_geom, line1, atSubGeom)
                        if updGeom is None:
                           self.plugIn.destroyEditCommand()
                           return
                        trimmedFeature1 = QgsFeature(f)
                        # trasformo la geometria nel crs del layer
                        trimmedFeature1.setGeometry(self.mapToLayerCoordinates(layer, updGeom))
                        # plugIn, layer, feature, refresh, check_validity
                        if qad_layer.updateFeatureToLayer(self.plugIn, layer, trimmedFeature1, False, False) == False:
                           self.plugIn.destroyEditCommand()
                           return
                        if line2 is not None:
                           trimmedFeature2 = QgsFeature(f)      
                           # trasformo la geometria nel crs del layer
                           trimmedFeature2.setGeometry(self.mapToLayerCoordinates(layer, line2))
                           # plugIn, layer, feature, coordTransform, refresh, check_validity
                           if qad_layer.addFeatureToLayer(self.plugIn, layer, trimmedFeature2, None, False, False) == False:
                              self.plugIn.destroyEditCommand()
                              return                        
                     else:
                        # aggiungo le linee nei layer temporanei di QAD
                        if LineTempLayer is None:
                           LineTempLayer = qad_layer.createQADTempLayer(self.plugIn, QGis.Line)
                           self.plugIn.addLayerToLastEditCommand("Feature trimmed", LineTempLayer)
                        
                        lineGeoms = [line1]
                        if line2 is not None:
                           lineGeoms.append(line2)

                        # trasformo la geometria in quella dei layer temporanei
                        # plugIn, pointGeoms, lineGeoms, polygonGeoms, coord, refresh
                        if qad_layer.addGeometriesToQADTempLayers(self.plugIn, None, lineGeoms, None, None, False) == False:
                           self.plugIn.destroyEditCommand()
                           return
                                                      
                        updGeom = qad_utils.delSubGeom(f_geom, atSubGeom)
                        
                        if updGeom is None or updGeom.isGeosEmpty(): # da cancellare
                           # plugIn, layer, feature id, refresh
                           if qad_layer.deleteFeatureToLayer(self.plugIn, layer, f.id(), False) == False:
                              self.plugIn.destroyEditCommand()
                              return
                        else:
                           trimmedFeature1 = QgsFeature(f)
                           # trasformo la geometria nel crs del layer
                           trimmedFeature1.setGeometry(self.mapToLayerCoordinates(layer, updGeom))
                           # plugIn, layer, feature, refresh, check_validity
                           if qad_layer.updateFeatureToLayer(self.plugIn, layer, trimmedFeature1, False, False) == False:
                              self.plugIn.destroyEditCommand()
                              return

      self.plugIn.endEditCommand()
      self.nOperationsToUndo = self.nOperationsToUndo + 1
                                                      
      
   #============================================================================
   # waitForObjectSel
   #============================================================================
   def waitForObjectSel(self):      
      self.step = 2      
      # imposto il map tool
      self.getPointMapTool().setSelectionMode(QadGetPointSelectionModeEnum.ENTITY_SELECTION_DYNAMIC)
      # solo layer lineari editabili che non appartengano a quote
      layerList = []
      for layer in qad_utils.getVisibleVectorLayers(self.plugIn.canvas): # Tutti i layer vettoriali visibili
         if layer.geometryType() == QGis.Line and layer.isEditable():
            if len(QadDimStyles.getDimListByLayer(layer)) == 0:
               layerList.append(layer)
            
      self.getPointMapTool().layersToCheck = layerList
      self.getPointMapTool().setDrawMode(QadGetPointDrawModeEnum.NONE)
      self.getPointMapTool().onlyEditableLayers = True
      
      keyWords = QadMsg.translate("Command_TRIM", "Fence") + "/" + \
                 QadMsg.translate("Command_TRIM", "Crossing") + "/" + \
                 QadMsg.translate("Command_TRIM", "Edge") + "/" + \
                 QadMsg.translate("Command_TRIM", "Undo")      
      prompt = QadMsg.translate("Command_TRIM", "Select the object to trim or shift-select to extend or [{0}]: ").format(keyWords)                        
      
      englishKeyWords = "Fence" + "/" + "Crossing" + "/" + "Edge" + "/" + "Undo"
      keyWords += "_" + englishKeyWords
      # si appresta ad attendere un punto o enter o una parola chiave         
      # msg, inputType, default, keyWords, nessun controllo
      self.waitFor(prompt, \
                   QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \
                   None, \
                   keyWords, QadInputModeEnum.NONE)      


   #============================================================================
   # run
   #============================================================================
   def run(self, msgMapTool = False, msg = None):
      if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():
         self.showMsg(QadMsg.translate("QAD", "\nThe coordinate reference system of the project must be a projected coordinate system.\n"))
         return True # fine comando

      #=========================================================================
      # RICHIESTA SELEZIONE OGGETTI LIMITI
      if self.step == 0: # inizio del comando
         CurrSettingsMsg = QadMsg.translate("QAD", "\nCurrent settings: ")
         if self.edgeMode == 0: # 0 = nessuna estensione
            CurrSettingsMsg = CurrSettingsMsg + QadMsg.translate("Command_TRIM", "Edge = No extend")
         else:
            CurrSettingsMsg = CurrSettingsMsg + QadMsg.translate("Command_TRIM", "Edge = Extend")
                  
         self.showMsg(CurrSettingsMsg)         
         self.showMsg(QadMsg.translate("Command_TRIM", "\nSelect trim limits..."))
         
         if self.SSGetClass.run(msgMapTool, msg) == True:
            # selezione terminata
            self.step = 1
            return self.run(msgMapTool, msg)        
      
      #=========================================================================
      # RISPOSTA ALLA SELEZIONE OGGETTI LIMITI
      elif self.step == 1:
         self.limitEntitySet.set(self.SSGetClass.entitySet)
         
         if self.limitEntitySet.count() == 0:
            return True # fine comando

         # si appresta ad attendere la selezione degli oggetti da estendere/tagliare
         self.waitForObjectSel()
         return False
      
      #=========================================================================
      # RISPOSTA ALLA SELEZIONE OGGETTI DA ESTENDERE
      elif self.step == 2:
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False
            else:
               value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if type(value) == unicode:
            if value == QadMsg.translate("Command_TRIM", "Fence") or value == "Fence":
               # Seleziona tutti gli oggetti che intersecano una polilinea
               self.PLINECommand = QadPLINECommandClass(self.plugIn)
               # se questo flag = True il comando serve all'interno di un altro comando per disegnare una linea
               # che non verrà salvata su un layer
               self.PLINECommand.virtualCmd = True   
               self.PLINECommand.run(msgMapTool, msg)
               self.step = 3
               return False               
            elif value == QadMsg.translate("Command_TRIM", "Crossing") or value == "Crossing":
               # Seleziona tutti gli oggetti che intersecano un rettangolo                                  
               self.RECTANGLECommand = QadRECTANGLECommandClass(self.plugIn)
               # se questo flag = True il comando serve all'interno di un altro comando per disegnare una linea
               # che non verrà salvata su un layer
               self.RECTANGLECommand.virtualCmd = True   
               self.RECTANGLECommand.run(msgMapTool, msg)
               self.step = 4
               return False               
            elif value == QadMsg.translate("Command_TRIM", "Edge") or value == "Edge":
               # Per estendere un oggetto usando anche le estensioni degli oggetti di riferimento
               # vedi variabile EDGEMODE
               keyWords = QadMsg.translate("Command_TRIM", "Extend") + "/" + \
                          QadMsg.translate("Command_TRIM", "No extend")
               if self.edgeMode == 0: # 0 = nessuna estensione
                  self.defaultValue = QadMsg.translate("Command_TRIM", "No")
               else: 
                  self.defaultValue = QadMsg.translate("Command_TRIM", "Extend")
               prompt = QadMsg.translate("Command_TRIM", "Specify an extension mode [{0}] <{1}>: ").format(keyWords, self.defaultValue)                        
                   
               englishKeyWords = "Extend" + "/" + "No extend"
               keyWords += "_" + englishKeyWords
               # si appresta ad attendere enter o una parola chiave         
               # msg, inputType, default, keyWords, nessun controllo
               self.waitFor(prompt, \
                            QadInputTypeEnum.KEYWORDS, \
                            self.defaultValue, \
                            keyWords, QadInputModeEnum.NONE)
               self.step = 5               
               return False               
            elif value == QadMsg.translate("Command_TRIM", "Undo") or value == "Undo":
               if self.nOperationsToUndo > 0: 
                  self.nOperationsToUndo = self.nOperationsToUndo - 1
                  self.plugIn.undoEditCommand()
               else:
                  self.showMsg(QadMsg.translate("QAD", "\nThe command has been canceled."))
         elif type(value) == QgsPoint: # se é stato selezionato un punto
            self.entitySet.clear()
            if self.getPointMapTool().entity.isInitialized():
               self.entitySet.addEntity(self.getPointMapTool().entity)
               ToExtend = True if self.getPointMapTool().shiftKey == True else False
               self.trimFeatures(QgsGeometry.fromPoint(value), ToExtend)
            else:
               # cerco se ci sono entità nel punto indicato considerando
               # solo layer lineari editabili che non appartengano a quote
               layerList = []
               for layer in qad_utils.getVisibleVectorLayers(self.plugIn.canvas): # Tutti i layer vettoriali visibili
                  if layer.geometryType() == QGis.Line and layer.isEditable():
                     if len(QadDimStyles.getDimListByLayer(layer)) == 0:
                        layerList.append(layer)
               
               result = qad_utils.getEntSel(self.getPointMapTool().toCanvasCoordinates(value),
                                            self.getPointMapTool(), \
                                            QadVariables.get(QadMsg.translate("Environment variables", "PICKBOX")), \
                                            layerList)
               if result is not None:
                  feature = result[0]
                  layer = result[1]
                  point = result[2]
                  self.entitySet.addEntity(QadEntity().set(layer, feature.id()))
                  self.trimFeatures(QgsGeometry.fromPoint(point), False)
         else:
            return True # fine comando
         
         # si appresta ad attendere la selezione degli oggetti da estendere/tagliare
         self.waitForObjectSel()
                                          
         return False 

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA PUNTO PER MODALITA' INTERCETTA (da step = 2)
      elif self.step == 3: # dopo aver atteso un punto si riavvia il comando
         if self.PLINECommand.run(msgMapTool, msg) == True:
            if len(self.PLINECommand.vertices) > 1:
               if msgMapTool == True: # se la polilinea arriva da una selezione grafica
                  ToExtend = True if self.getPointMapTool().shiftKey == True else False
               else:
                  ToExtend = False

               # cerco tutte le geometrie passanti per la polilinea saltando i layer punto e poligono
               # e considerando solo layer editabili       
               self.entitySet = qad_utils.getSelSet("F", self.getPointMapTool(), self.PLINECommand.vertices, \
                                                    None, False, True, False, \
                                                    True)            
               self.trimFeatures(QgsGeometry.fromPolyline(self.PLINECommand.vertices), ToExtend)
            del self.PLINECommand
            self.PLINECommand = None

            # si appresta ad attendere la selezione degli oggetti da estendere/tagliare
            self.waitForObjectSel()
            self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può essere variato dal maptool di pline                     
                                             
         return False

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA PUNTO PER MODALITA' INTERSECA (da step = 2)
      elif self.step == 4: # dopo aver atteso un punto si riavvia il comando
         if self.RECTANGLECommand.run(msgMapTool, msg) == True:            
            if len(self.RECTANGLECommand.vertices) > 1:
               if msgMapTool == True: # se la polilinea arriva da una selezione grafica
                  ToExtend = True if self.getPointMapTool().shiftKey == True else False
               else:
                  ToExtend = False
               
               # cerco tutte le geometrie passanti per la polilinea saltando i layer punto e poligono
               # e considerando solo layer editabili       
               self.entitySet = qad_utils.getSelSet("F", self.getPointMapTool(), self.RECTANGLECommand.vertices, \
                                                    None, False, True, False, \
                                                    True)            
               self.trimFeatures(QgsGeometry.fromPolyline(self.RECTANGLECommand.vertices), ToExtend)
            del self.RECTANGLECommand
            self.RECTANGLECommand = None

            # si appresta ad attendere la selezione degli oggetti da estendere/tagliare
            self.waitForObjectSel()                                 
            self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può essere variato dal maptool di rectangle                     
         return False

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DI TIPO DI ESTENSIONE (da step = 2)
      elif self.step == 5: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
               value = self.defaultValue 
            else:
               self.setMapTool(self.getPointMapTool()) # riattivo il maptool
               return False
         else: # il valore arriva come parametro della funzione
            value = msg

         if type(value) == unicode:
            if value == QadMsg.translate("Command_TRIM", "No") or value == "No":
               self.edgeMode = 0
               QadVariables.set(QadMsg.translate("Environment variables", "EDGEMODE"), self.edgeMode)
               QadVariables.save()
               # si appresta ad attendere la selezione degli oggetti da estendere/tagliare
               self.waitForObjectSel()
            elif value == QadMsg.translate("Command_TRIM", "Extend") or value == "Extend":
               self.edgeMode = 1
               QadVariables.set(QadMsg.translate("Environment variables", "EDGEMODE"), self.edgeMode)
               QadVariables.save()
               # si appresta ad attendere la selezione degli oggetti da estendere/tagliare
               self.waitForObjectSel()
         
         return False
Example #47
0
class QadMOVECommandClass(QadCommandClass):

   def instantiateNewCmd(self):
      """ istanzia un nuovo comando dello stesso tipo """
      return QadMOVECommandClass(self.plugIn)
   
   def getName(self):
      return QadMsg.translate("Command_list", "MOVE")

   def getEnglishName(self):
      return "MOVE"

   def connectQAction(self, action):
      QObject.connect(action, SIGNAL("triggered()"), self.plugIn.runMOVECommand)

   def getIcon(self):
      return QIcon(":/plugins/qad/icons/move.png")

   def getNote(self):
      # impostare le note esplicative del comando      
      return QadMsg.translate("Command_MOVE", "Moves the selected objects.")
   
   def __init__(self, plugIn):
      QadCommandClass.__init__(self, plugIn)
      self.SSGetClass = QadSSGetClass(plugIn)
      self.SSGetClass.onlyEditableLayers = True
      self.entitySet = QadEntitySet()
      self.basePt = QgsPoint()

   def __del__(self):
      QadCommandClass.__del__(self)
      del self.SSGetClass
      
   def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):
      if self.step == 0: # quando si é in fase di selezione entità
         return self.SSGetClass.getPointMapTool()
      else:
         if (self.plugIn is not None):
            if self.PointMapTool is None:
               self.PointMapTool = Qad_move_maptool(self.plugIn)
            return self.PointMapTool
         else:
            return None


   #============================================================================
   # move
   #============================================================================
   def move(self, f, offSetX, offSetY, layerEntitySet, entitySet):
      # verifico se l'entità appartiene ad uno stile di quotatura
      dimEntity = QadDimStyles.getDimEntity(layerEntitySet.layer, f.id())
            
      if dimEntity is None:
         # sposto la feature e la rimuovo da entitySet (é la prima)
         f.setGeometry(qad_utils.moveQgsGeometry(f.geometry(), offSetX, offSetY))
         # plugIn, layer, feature, refresh, check_validity
         if qad_layer.updateFeatureToLayer(self.plugIn, layerEntitySet.layer, f, False, False) == False:
            return False
         del layerEntitySet.featureIds[0]
      else:
         # sposto la quota e la rimuovo da entitySet
         dimEntitySet = dimEntity.getEntitySet()
         if dimEntity.deleteToLayers(self.plugIn) == False:
            return False 
         newDimEntity = QadDimEntity(dimEntity) # la copio
         if newDimEntity.move(offSetX, offSetY) == False:
            return False             
         if newDimEntity.addToLayers(self.plugIn) == False:
            return False             
         entitySet.subtract(dimEntitySet)
            
      return True


   #============================================================================
   # moveGeoms
   #============================================================================
   def moveGeoms(self, newPt):      
      # copio entitySet
      entitySet = QadEntitySet(self.entitySet)
      
      self.plugIn.beginEditCommand("Feature moved", entitySet.getLayerList())
      
      for layerEntitySet in entitySet.layerEntitySetList:                        
         transformedBasePt = self.mapToLayerCoordinates(layerEntitySet.layer, self.basePt)
         transformedNewPt = self.mapToLayerCoordinates(layerEntitySet.layer, newPt)
         offSetX = transformedNewPt.x() - transformedBasePt.x()
         offSetY = transformedNewPt.y() - transformedBasePt.y()
         
         while len(layerEntitySet.featureIds) > 0:
            featureId = layerEntitySet.featureIds[0]
            f = layerEntitySet.getFeature(featureId)
            
            if self.move(f, offSetX, offSetY, layerEntitySet, entitySet) == False:  
               self.plugIn.destroyEditCommand()
               return
   
      self.plugIn.endEditCommand()

   def run(self, msgMapTool = False, msg = None):
      if self.plugIn.canvas.mapSettings().destinationCrs().geographicFlag():
         self.showMsg(QadMsg.translate("QAD", "\nThe coordinate reference system of the project must be a projected coordinate system.\n"))
         return True # fine comando
            
      #=========================================================================
      # RICHIESTA SELEZIONE OGGETTI
      if self.step == 0: # inizio del comando
         if self.SSGetClass.run(msgMapTool, msg) == True:
            # selezione terminata
            self.step = 1
            self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può essere variato dal maptool di selezione entità                    
            return self.run(msgMapTool, msg)
      
      #=========================================================================
      # SPOSTA OGGETTI
      elif self.step == 1:
         self.entitySet.set(self.SSGetClass.entitySet)
         
         if self.entitySet.count() == 0:
            return True # fine comando

         # imposto il map tool
         self.getPointMapTool().entitySet.set(self.entitySet)
         self.getPointMapTool().setMode(Qad_move_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_BASE_PT)                                
   
         keyWords = QadMsg.translate("Command_MOVE", "Displacement")
         prompt = QadMsg.translate("Command_MOVE", "Specify base point or [{0}] <{0}>: ").format(keyWords)
         
         englishKeyWords = "Displacement"
         keyWords += "_" + englishKeyWords
         # si appresta ad attendere un punto o enter o una parola chiave         
         # msg, inputType, default, keyWords, nessun controllo
         self.waitFor(prompt, \
                      QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \
                      None, \
                      keyWords, QadInputModeEnum.NONE)      
         self.step = 2      
         return False
         
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA PUNTO BASE (da step = 1)
      elif self.step == 2: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  pass # opzione di default "spostamento"
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if value is None or type(value) == unicode:
            self.basePt.set(0, 0)
            self.getPointMapTool().basePt = self.basePt
            self.getPointMapTool().setMode(Qad_move_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_MOVE_PT)                                
            # si appresta ad attendere un punto
            msg = QadMsg.translate("Command_MOVE", "Specify the displacement fom the origin point 0,0 <{0}, {1}>: ")
            # msg, inputType, default, keyWords, nessun controllo
            self.waitFor(msg.format(str(self.plugIn.lastOffsetPt.x()), str(self.plugIn.lastOffsetPt.y())), \
                         QadInputTypeEnum.POINT2D, \
                         self.plugIn.lastOffsetPt, \
                         "", QadInputModeEnum.NONE)                                      
            self.step = 4           
         elif type(value) == QgsPoint: # se é stato inserito il punto base
            self.basePt.set(value.x(), value.y())

            # imposto il map tool
            self.getPointMapTool().basePt = self.basePt
            self.getPointMapTool().setMode(Qad_move_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_MOVE_PT)                                
            
            # si appresta ad attendere un punto o enter o una parola chiave         
            # msg, inputType, default, keyWords, nessun controllo
            self.waitFor(QadMsg.translate("Command_MOVE", "Specify the second point or <use first point as displacement from the origin point 0,0>: "), \
                         QadInputTypeEnum.POINT2D, \
                         None, \
                         "", QadInputModeEnum.NONE)      
            self.step = 3      
         
         return False 
         
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER SPOSTAMENTO (da step = 2)
      elif self.step == 3: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if value is None:
            newPt = QgsPoint(self.basePt.x() * 2, self.basePt.y() * 2)
            self.moveGeoms(newPt)
         elif type(value) == QgsPoint: # se é stato inserito lo spostamento con un punto
            self.moveGeoms(value)
            
         return True # fine comando
               
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DEL PUNTO DI SPOSTAMENTO (da step = 2)
      elif self.step == 4: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         self.plugIn.setLastOffsetPt(value)
         self.moveGeoms(value)
         return True
Example #48
0
class QadROTATECommandClass(QadCommandClass):

   def instantiateNewCmd(self):
      """ istanzia un nuovo comando dello stesso tipo """
      return QadROTATECommandClass(self.plugIn)

   def getName(self):
      return QadMsg.translate("Command_list", "ROTATE")

   def getEnglishName(self):
      return "ROTATE"

   def connectQAction(self, action):
      QObject.connect(action, SIGNAL("triggered()"), self.plugIn.runROTATECommand)

   def getIcon(self):
      return QIcon(":/plugins/qad/icons/rotate.png")

   def getNote(self):
      # impostare le note esplicative del comando      
      return QadMsg.translate("Command_ROTATE", "Rotates objects around a base point.")
   
   def __init__(self, plugIn):
      QadCommandClass.__init__(self, plugIn)
      self.SSGetClass = QadSSGetClass(plugIn)
      self.SSGetClass.onlyEditableLayers = True
      self.entitySet = QadEntitySet()
      self.basePt = None
      self.copyFeatures = False
      self.Pt1ReferenceAng = None
      self.ReferenceAng = 0
      self.Pt1NewAng = None

   def __del__(self):
      QadCommandClass.__del__(self)
      del self.SSGetClass
      
   def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):
      if self.step == 0: # quando si é in fase di selezione entità
         return self.SSGetClass.getPointMapTool()
      else:
         if (self.plugIn is not None):
            if self.PointMapTool is None:
               self.PointMapTool = Qad_rotate_maptool(self.plugIn)
            return self.PointMapTool
         else:
            return None


   #============================================================================
   # rotate
   #============================================================================
   def rotate(self, f, basePt, angle, rotFldName, layerEntitySet, entitySet):
      # verifico se l'entità appartiene ad uno stile di quotatura
      dimEntity = QadDimStyles.getDimEntity(layerEntitySet.layer, f.id())
      
      if dimEntity is None:
         # ruoto la feature e la rimuovo da entitySet (é la prima)
         f.setGeometry(qad_utils.rotateQgsGeometry(f.geometry(), basePt, angle))

         if len(rotFldName) > 0:
            rotValue = f.attribute(rotFldName)
            rotValue = 0 if rotValue is None else qad_utils.toRadians(rotValue) # la rotazione é in gradi nel campo della feature
            rotValue = rotValue + angle
            f.setAttribute(rotFldName, qad_utils.toDegrees(qad_utils.normalizeAngle(rotValue)))               

         if self.copyFeatures == False:
            # plugIn, layer, feature, refresh, check_validity
            if qad_layer.updateFeatureToLayer(self.plugIn, layerEntitySet.layer, f, False, False) == False:
               self.plugIn.destroyEditCommand()
               return False
         else:             
            # plugIn, layer, features, coordTransform, refresh, check_validity
            if qad_layer.addFeatureToLayer(self.plugIn, layerEntitySet.layer, f, None, False, False) == False:
               self.plugIn.destroyEditCommand()
               return False
         del layerEntitySet.featureIds[0]
      else:
         # ruoto la quota e la rimuovo da entitySet
         dimEntitySet = dimEntity.getEntitySet()
         if self.copyFeatures == False:
            if dimEntity.deleteToLayers(self.plugIn) == False:
               return False                      
         dimEntity.rotate(self.plugIn, basePt, angle)
         if dimEntity.addToLayers(self.plugIn) == False:
            return False             
         entitySet.subtract(dimEntitySet)
            
      return True


   def RotateGeoms(self, angle):      
      # copio entitySet
      entitySet = QadEntitySet(self.entitySet)
      
      self.plugIn.beginEditCommand("Feature rotated", entitySet.getLayerList())
      
      for layerEntitySet in entitySet.layerEntitySetList:
         layer = layerEntitySet.layer
         
         transformedBasePt = self.mapToLayerCoordinates(layer, self.basePt)

         rotFldName = ""
         if qad_layer.isTextLayer(layer):
            # se la rotazione dipende da un solo campo
            rotFldNames = qad_label.get_labelRotationFieldNames(layer)
            if len(rotFldNames) == 1 and len(rotFldNames[0]) > 0:
               rotFldName = rotFldNames[0]         
         elif qad_layer.isSymbolLayer(layer):
            rotFldName = qad_layer.get_symbolRotationFieldName(layer)
                     
         while len(layerEntitySet.featureIds) > 0:
            featureId = layerEntitySet.featureIds[0]
            f = layerEntitySet.getFeature(featureId)

            if self.rotate(f, transformedBasePt, angle, rotFldName, layerEntitySet, entitySet) == False:  
               self.plugIn.destroyEditCommand()
               return

      self.plugIn.endEditCommand()


   def waitForRotation(self):
      # imposto il map tool
      self.getPointMapTool().setMode(Qad_rotate_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_ROTATION_PT)

      keyWords = QadMsg.translate("Command_ROTATE", "Copy") + "/" + \
                 QadMsg.translate("Command_ROTATE", "Reference")
      prompt = QadMsg.translate("Command_ROTATE", "Specify rotation angle or [{0}] <{1}>: ").format(keyWords, \
               str(qad_utils.toDegrees(self.plugIn.lastRot)))
      
      englishKeyWords = "Copy" + "/" + "Reference"
      keyWords += "_" + englishKeyWords
      # si appresta ad attendere un punto, un numero reale o enter o una parola chiave
      # msg, inputType, default, keyWords, nessun controllo
      self.waitFor(prompt, QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT | QadInputTypeEnum.KEYWORDS, \
                   self.plugIn.lastRot, \
                   keyWords, QadInputModeEnum.NONE)      
      self.step = 3      


   def waitForReferenceRot(self):
      # imposto il map tool
      self.getPointMapTool().setMode(Qad_rotate_maptool_ModeEnum.ASK_FOR_FIRST_PT_REFERENCE_ANG)
      
      msg = QadMsg.translate("Command_ROTATE", "Specify reference angle <{0}>: ")
      # si appresta ad attendere un punto o enter o una parola chiave         
      # msg, inputType, default, keyWords, nessun controllo
      self.waitFor(msg.format(str(qad_utils.toDegrees(self.plugIn.lastReferenceRot))), \
                   QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT, \
                   self.plugIn.lastReferenceRot, \
                   "")               
      self.step = 4


   def waitForNewReferenceRot(self):
      # imposto il map tool
      self.getPointMapTool().setMode(Qad_rotate_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_NEW_ROTATION_PT)
      
      keyWords = QadMsg.translate("Command_ROTATE", "Points")
      if self.plugIn.lastNewReferenceRot == 0:
         angle = self.plugIn.lastRot
      else:
         angle = self.plugIn.lastNewReferenceRot         
      prompt = QadMsg.translate("Command_ROTATE", "Specify new angle or [{0}] <{1}>: ").format(keyWords, str(qad_utils.toDegrees(angle)))                        
         
      englishKeyWords = "Points"
      keyWords += "_" + englishKeyWords
      # si appresta ad attendere un punto o enter o una parola chiave         
      # msg, inputType, default, keyWords, nessun controllo
      self.waitFor(prompt, \
                   QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT | QadInputTypeEnum.KEYWORDS, \
                   angle, \
                   keyWords)
      self.step = 6
   

   def run(self, msgMapTool = False, msg = None):
      if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():
         self.showMsg(QadMsg.translate("QAD", "\nThe coordinate reference system of the project must be a projected coordinate system.\n"))
         return True # fine comando
            
      #=========================================================================
      # RICHIESTA SELEZIONE OGGETTI
      if self.step == 0: # inizio del comando
         if self.SSGetClass.run(msgMapTool, msg) == True:
            # selezione terminata
            self.step = 1
            self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può essere variato dal maptool di selezione entità                    
            return self.run(msgMapTool, msg)
      
      #=========================================================================
      # RUOTA OGGETTI
      elif self.step == 1:
         self.entitySet.set(self.SSGetClass.entitySet)
         
         if self.entitySet.count() == 0:
            return True # fine comando

         # imposto il map tool
         self.getPointMapTool().setMode(Qad_rotate_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_BASE_PT)

         # si appresta ad attendere un punto
         self.waitForPoint(QadMsg.translate("Command_ROTATE", "Specify base point: "))
                  
         self.step = 2     
         return False
         
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA PUNTO BASE (da step = 1)
      elif self.step == 2: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         self.basePt = QgsPoint(value)

         self.getPointMapTool().basePt = self.basePt
         self.getPointMapTool().entitySet.set(self.entitySet)
         # si appresta ad attendere l'angolo di rotazione                      
         self.waitForRotation()
         
         return False 
         
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER ANGOLO ROTAZIONE (da step = 2)
      elif self.step == 3: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if type(value) == unicode:
            if value == QadMsg.translate("Command_ROTATE", "Copy") or value == "Copy":
               self.copyFeatures = True
               self.showMsg(QadMsg.translate("Command_ROTATE", "\nRotation of a copy of the selected objects."))
               # si appresta ad attendere l'angolo di rotazione               
               self.waitForRotation()                
            elif value == QadMsg.translate("Command_ROTATE", "Reference") or value == "Reference":
               # si appresta ad attendere l'angolo di riferimento                      
               self.waitForReferenceRot()
         elif type(value) == QgsPoint or type(value) == float: # se é stato inserito l'angolo di rotazione
            if type(value) == QgsPoint: # se é stato inserito l'angolo di rotazione con un punto
               angle = qad_utils.getAngleBy2Pts(self.basePt, value)
            else:
               angle = qad_utils.toRadians(value)
            self.plugIn.setLastRot(angle)

            self.RotateGeoms(angle)
            return True # fine comando
         
         return False

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA PRIMO PUNTO PER ANGOLO ROTAZIONE DI RIFERIMENTO (da step = 3)
      elif self.step == 4: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if type(value) == float: # se é stato inserito l'angolo di rotazione
            self.ReferenceAng = qad_utils.toRadians(value)
            self.getPointMapTool().ReferenceAng = self.ReferenceAng 
            # si appresta ad attendere il nuovo angolo                    
            self.waitForNewReferenceRot()

         elif type(value) == QgsPoint: # se é stato inserito l'angolo di rotazione con un punto                                 
            self.Pt1ReferenceAng = QgsPoint(value)
            self.getPointMapTool().Pt1ReferenceAng = self.Pt1ReferenceAng 
            # imposto il map tool
            self.getPointMapTool().setMode(Qad_rotate_maptool_ModeEnum.FIRST_PT_KNOWN_ASK_FOR_SECOND_PT_REFERENCE_ANG)
            # si appresta ad attendere un punto
            self.waitForPoint(QadMsg.translate("Command_ROTATE", "Specify second point: "))
            self.step = 5           
            
         return False

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER ANGOLO ROTAZIONE DI RIFERIMENTO (da step = 4)
      elif self.step == 5: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         angle = qad_utils.getAngleBy2Pts(self.Pt1ReferenceAng, value)
         self.ReferenceAng = angle
         self.getPointMapTool().ReferenceAng = self.ReferenceAng 
         # si appresta ad attendere il nuovo angolo                    
         self.waitForNewReferenceRot()
            
         return False

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER NUOVO ANGOLO ROTAZIONE (da step = 4 e 5)
      elif self.step == 6: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if type(value) == unicode:
            if value == QadMsg.translate("Command_ROTATE", "Points") or value == "Points":
               # imposto il map tool
               self.getPointMapTool().setMode(Qad_rotate_maptool_ModeEnum.ASK_FOR_FIRST_NEW_ROTATION_PT)
               # si appresta ad attendere un punto
               self.waitForPoint(QadMsg.translate("Command_ROTATE", "Specify first point: "))
               self.step = 7
         elif type(value) == QgsPoint or type(value) == float: # se é stato inserito l'angolo di rotazione
            if type(value) == QgsPoint: # se é stato inserito l'angolo di rotazione con un punto                        
               angle = qad_utils.getAngleBy2Pts(self.basePt, value)
            else:
               angle = qad_utils.toRadians(value)
            
            angle = angle - self.ReferenceAng
            self.plugIn.setLastRot(angle)
            self.RotateGeoms(angle)
            return True # fine comando

         return False
      
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA PRIMO PUNTO PER NUOVO ANGOLO ROTAZIONE (da step = 6)
      elif self.step == 7: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg
      
         self.Pt1NewAng = value
         # imposto il map tool
         self.getPointMapTool().Pt1NewAng = self.Pt1NewAng
         self.getPointMapTool().setMode(Qad_rotate_maptool_ModeEnum.FIRST_PT_KNOWN_ASK_FOR_SECOND_NEW_ROTATION_PT)
         # si appresta ad attendere un punto
         self.waitForPoint(QadMsg.translate("Command_ROTATE", "Specify second point: "))
         self.step = 8
            
         return False

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER NUOVO ANGOLO ROTAZIONE (da step = 7)
      elif self.step == 8: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg
               
         angle = qad_utils.getAngleBy2Pts(self.Pt1NewAng, value)
         
         angle = angle - self.ReferenceAng
         self.plugIn.setLastRot(angle)
         self.RotateGeoms(angle)
         return True # fine comando
Example #49
0
class QadMIRRORCommandClass(QadCommandClass):
   
   def instantiateNewCmd(self):
      """ istanzia un nuovo comando dello stesso tipo """
      return QadMIRRORCommandClass(self.plugIn)
   
   def getName(self):
      return QadMsg.translate("Command_list", "MIRROR")

   def getEnglishName(self):
      return "MIRROR"

   def connectQAction(self, action):
      QObject.connect(action, SIGNAL("triggered()"), self.plugIn.runMIRRORCommand)

   def getIcon(self):
      return QIcon(":/plugins/qad/icons/mirror.png")

   def getNote(self):
      # impostare le note esplicative del comando      
      return QadMsg.translate("Command_MIRROR", "Creates a mirrored copy of selected objects.")
   
   def __init__(self, plugIn):
      QadCommandClass.__init__(self, plugIn)
      self.SSGetClass = QadSSGetClass(plugIn)
      self.SSGetClass.onlyEditableLayers = True
      self.entitySet = QadEntitySet()
      self.firstMirrorPt = QgsPoint()
      self.secondMirrorPt = QgsPoint()
      self.copyFeatures = True

   def __del__(self):
      QadCommandClass.__del__(self)
      del self.SSGetClass
      
   def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):
      if self.step == 0: # quando si é in fase di selezione entità
         return self.SSGetClass.getPointMapTool()
      else:
         if (self.plugIn is not None):
            if self.PointMapTool is None:
               self.PointMapTool = Qad_mirror_maptool(self.plugIn)
            return self.PointMapTool
         else:
            return None


   #============================================================================
   # scale
   #============================================================================
   def mirror(self, f, pt1, pt2, rotFldName, layerEntitySet, entitySet, dimEntity):
      
      if dimEntity is None:
         # scalo la feature e la rimuovo da entitySet (é la prima)
         f.setGeometry(qad_utils.mirrorQgsGeometry(f.geometry(), pt1, pt2))
         if len(rotFldName) > 0:
            rotValue = f.attribute(rotFldName)
            rotValue = 0 if rotValue is None else qad_utils.toRadians(rotValue) # la rotazione é in gradi nel campo della feature
            ptDummy = qad_utils.getPolarPointByPtAngle(pt1, rotValue, 1)
            mirrorAngle = qad_utils.getAngleBy2Pts(pt1, pt2)
            ptDummy = qad_utils.mirrorPoint(ptDummy, pt1, mirrorAngle)
            rotValue = qad_utils.getAngleBy2Pts(pt1, ptDummy)
            f.setAttribute(rotFldName, qad_utils.toDegrees(qad_utils.normalizeAngle(rotValue)))               
                  
         if self.copyFeatures == False:
            # plugIn, layer, feature, refresh, check_validity
            if qad_layer.updateFeatureToLayer(self.plugIn, layerEntitySet.layer, f, False, False) == False:
               self.plugIn.destroyEditCommand()
               return False
         else:             
            # plugIn, layer, features, coordTransform, refresh, check_validity
            if qad_layer.addFeatureToLayer(self.plugIn, layerEntitySet.layer, f, None, False, False) == False:
               self.plugIn.destroyEditCommand()
               return False

         del layerEntitySet.featureIds[0]
      else:
         # scalo la quota e la rimuovo da entitySet
         mirrorAngle = qad_utils.getAngleBy2Pts(pt1, pt2)
         dimEntitySet = dimEntity.getEntitySet()
         if self.copyFeatures == False:
            if dimEntity.deleteToLayers(self.plugIn) == False:
               return False                      
         dimEntity.mirror(self.plugIn, pt1, mirrorAngle)
         if dimEntity.addToLayers(self.plugIn) == False:
            return False             
         entitySet.subtract(dimEntitySet)


   #============================================================================
   # mirrorGeoms
   #============================================================================
   def mirrorGeoms(self):      
      # copio entitySet
      entitySet = QadEntitySet(self.entitySet)

      self.plugIn.beginEditCommand("Feature mirrored", self.entitySet.getLayerList())

      for layerEntitySet in entitySet.layerEntitySetList:
         layer = layerEntitySet.layer        

         transformedBasePt = self.mapToLayerCoordinates(layer, self.firstMirrorPt)
         transformedNewPt = self.mapToLayerCoordinates(layer, self.secondMirrorPt)
         
         rotFldName = ""
         if qad_layer.isTextLayer(layer):
            # se la rotazione dipende da un solo campo
            rotFldNames = qad_label.get_labelRotationFieldNames(layer)
            if len(rotFldNames) == 1 and len(rotFldNames[0]) > 0:
               rotFldName = rotFldNames[0]         
         elif qad_layer.isSymbolLayer(layer):
            rotFldName = qad_layer.get_symbolRotationFieldName(layer)
         
         while len(layerEntitySet.featureIds) > 0:
            featureId = layerEntitySet.featureIds[0]
            f = layerEntitySet.getFeature(featureId)

            entity = QadEntity()
            entity.set(layer, featureId)
            # verifico se l'entità appartiene ad uno stile di quotatura
            dimStyle, dimId = QadDimStyles.getDimIdByEntity(entity)

            if dimStyle is not None:
               dimEntity = QadDimEntity()
               if dimEntity.initByDimId(dimStyle, dimId) == False:
                  dimEntity = None
            else:
               dimEntity = None

            if self.mirror(f, transformedBasePt, transformedNewPt, rotFldName, layerEntitySet, entitySet, dimEntity) == False:  
               self.plugIn.destroyEditCommand()
               return

      self.plugIn.endEditCommand()
   

   def run(self, msgMapTool = False, msg = None):
      if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():
         self.showMsg(QadMsg.translate("QAD", "\nThe coordinate reference system of the project must be a projected coordinate system.\n"))
         return True # fine comando
            
      #=========================================================================
      # RICHIESTA SELEZIONE OGGETTI
      if self.step == 0: # inizio del comando
         if self.SSGetClass.run(msgMapTool, msg) == True:
            # selezione terminata
            self.step = 1
            self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può essere variato dal maptool di selezione entità                    
            return self.run(msgMapTool, msg)
      
      #=========================================================================
      # SPECCHIA OGGETTI
      elif self.step == 1:
         self.entitySet.set(self.SSGetClass.entitySet)
         
         if self.entitySet.count() == 0:
            return True # fine comando

         # imposto il map tool
         self.getPointMapTool().entitySet.set(self.entitySet)
         self.getPointMapTool().setMode(Qad_mirror_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_FIRST_PT)                                
   
         # si appresta ad attendere un punto
         self.waitForPoint(QadMsg.translate("Command_MIRROR", "Specify first point of mirror line: "))
         self.step = 2      
         return False
         
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA PUNTO BASE (da step = 1)
      elif self.step == 2: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  # si appresta ad attendere un punto
                  self.waitForPoint(QadMsg.translate("Command_MIRROR", "Specify first point of mirror line: "))
                  return False
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         self.firstMirrorPt.set(value.x(), value.y())

         # imposto il map tool
         self.getPointMapTool().firstMirrorPt = self.firstMirrorPt
         self.getPointMapTool().setMode(Qad_mirror_maptool_ModeEnum.FIRST_PT_KNOWN_ASK_FOR_SECOND_PT)                                
         
         # si appresta ad attendere un punto
         self.waitForPoint(QadMsg.translate("Command_MIRROR", "Specify second point of mirror line: "))
         self.step = 3
         
         return False 
         
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER SPECCHIO (da step = 2)
      elif self.step == 3: # dopo aver atteso un punto si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  # si appresta ad attendere un punto
                  self.waitForPoint(QadMsg.translate("Command_MIRROR", "Specify second point of mirror line: "))
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            value = self.getPointMapTool().point
         else: # il punto arriva come parametro della funzione
            value = msg

         if qad_utils.ptNear(self.firstMirrorPt, value):
            self.showMsg(QadMsg.translate("Command_MIRROR", "\nThe points must be different."))
            # si appresta ad attendere un punto
            self.waitForPoint(QadMsg.translate("Command_MIRROR", "Specify second point of mirror line: "))
            return False
         
         self.secondMirrorPt.set(value.x(), value.y())
         
         keyWords = QadMsg.translate("QAD", "Yes") + "/" + \
                    QadMsg.translate("QAD", "No")                                       
         if self.copyFeatures == False:
            default = QadMsg.translate("QAD", "Yes")
         else: 
            default = QadMsg.translate("QAD", "No")
         prompt = QadMsg.translate("Command_MIRROR", "Erase source objects ? [{0}] <{1}>: ").format(keyWords, default)
             
         englishKeyWords = "Yes" + "/" + "No"
         keyWords += "_" + englishKeyWords
         # si appresta ad attendere enter o una parola chiave         
         # msg, inputType, default, keyWords, nessun controllo
         self.waitFor(prompt, \
                      QadInputTypeEnum.KEYWORDS, \
                      default, \
                      keyWords, QadInputModeEnum.NONE)
         self.getPointMapTool().setMode(Qad_mirror_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_FIRST_PT)                                         
         self.step = 4

         return False
            

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DI CANCELLAZIONE OGGETTO SORGENTE (da step = 3)
      elif self.step == 4: # dopo aver atteso un punto o un numero reale si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
               value = QadMsg.translate("QAD", "No")   
            else:
               self.setMapTool(self.getPointMapTool()) # riattivo il maptool
               return False
         else: # il valore arriva come parametro della funzione
            value = msg

         if type(value) == unicode:
            if value == QadMsg.translate("QAD", "Yes") or value == "Yes":
               self.copyFeatures = False
            elif value == QadMsg.translate("QAD", "No") or value == "No":
               self.copyFeatures = True
                     
            self.mirrorGeoms()
            return True # fine comando

         return False
Example #50
0
class QadSETCURRUPDATEABLELAYERBYGRAPHCommandClass(QadCommandClass):
    def instantiateNewCmd(self):
        """ Instantiates a new command of the same type """
        return QadSETCURRUPDATEABLELAYERBYGRAPHCommandClass(self.plugIn)

    def getName(self):
        return QadMsg.translate("Command_list",
                                "SETCURRUPDATEABLELAYERBYGRAPH")

    def getEnglishName(self):
        return "SETCURRUPDATEABLELAYERBYGRAPH"

    def connectQAction(self, action):
        QObject.connect(action, SIGNAL("triggered()"),
                        self.plugIn.runSETCURRUPDATEABLELAYERBYGRAPHCommand)

    def getIcon(self):
        return QIcon(":/plugins/qad/icons/setcurrupdateablelayerbygraph.png")

    def getNote(self):
        # Set the explanatory notes to the command
        return QadMsg.translate(
            "Command_SETCURRUPDATEABLELAYERBYGRAPH",
            "Sets the layers of a graphical objects as editable.")

    def __init__(self, plugIn):
        QadCommandClass.__init__(self, plugIn)
        self.SSGetClass = QadSSGetClass(plugIn)
        self.firstTime = True

    def __del__(self):
        QadCommandClass.__del__(self)
        del self.SSGetClass

    def getPointMapTool(self, drawMode=QadGetPointDrawModeEnum.NONE):
        if self.step == 0:  # When you are being selected
            return self.SSGetClass.getPointMapTool(drawMode)
        else:
            return QadCommandClass.getPointMapTool(self, drawMode)

    def getCurrentContextualMenu(self):
        if self.step == 0 or self.step == 1:  # When you are being selected
            return None  # return self.SSGetClass.getCurrentContextualMenu()
        else:
            return self.contextualMenu

    def run(self, msgMapTool=False, msg=None):
        if self.step == 0:  # Start of the command
            if self.firstTime == True:
                self.showMsg(
                    QadMsg.translate(
                        "Command_SETCURRUPDATEABLELAYERBYGRAPH",
                        "\nSelect objects whose layers will be the editable: ")
                )
                self.firstTime = False

            if self.SSGetClass.run(msgMapTool, msg) == True:
                # Selection terminated
                self.step = 1
                return self.run(msgMapTool, msg)
            else:
                return False  # continua

        elif self.step == 1:  # After waiting for the selection of objects
            message = ""
            for layerEntitySet in self.SSGetClass.entitySet.layerEntitySetList:
                layer = layerEntitySet.layer
                if layer.isEditable() == False:
                    if layer.startEditing() == True:
                        self.plugIn.iface.layerTreeView(
                        ).refreshLayerSymbology(layer.id())
                        self.showMsg(
                            QadMsg.translate(
                                "Command_SETCURRUPDATEABLELAYERBYGRAPH",
                                "\nThe layer {0} is editable.").format(
                                    layer.name()))

            if len(self.SSGetClass.entitySet.layerEntitySetList) == 1:
                layer = self.SSGetClass.entitySet.layerEntitySetList[0].layer
                if self.plugIn.canvas.currentLayer() is None or \
                   self.plugIn.canvas.currentLayer() != layer:
                    self.plugIn.canvas.setCurrentLayer(layer)
                    self.plugIn.iface.setActiveLayer(
                        layer
                    )  # Launches event to deactivate and activate plugins
                    self.plugIn.iface.layerTreeView().setCurrentLayer(layer)
                    self.plugIn.iface.layerTreeView().refreshLayerSymbology(
                        layer.id())
                    self.showMsg(
                        QadMsg.translate(
                            "Command_SETCURRUPDATEABLELAYERBYGRAPH",
                            "\nThe current layer is {0}.").format(
                                layer.name()))

            return True
Example #51
0
class QadMAPMPEDITCommandClass(QadCommandClass):

   def instantiateNewCmd(self):
      """ istanzia un nuovo comando dello stesso tipo """
      return QadMAPMPEDITCommandClass(self.plugIn)

   def getName(self):
      return QadMsg.translate("Command_list", "MAPMPEDIT")
   
   def getEnglishName(self):
      return "MAPMPEDIT"

   def connectQAction(self, action):
      QObject.connect(action, SIGNAL("triggered()"), self.plugIn.runMAPMPEDITCommand)

   def getIcon(self):
      return QIcon(":/plugins/qad/icons/mapmpedit.png")
   
   def getNote(self):
      # impostare le note esplicative del comando      
      return QadMsg.translate("Command_MAPMPEDIT", "Modifies existing polygon.")
   
   def __init__(self, plugIn):
      QadCommandClass.__init__(self, plugIn)
      
      self.poligonEntity = QadEntity()
      
      self.SSGetClass = QadSSGetClass(plugIn)
      self.SSGetClass.onlyEditableLayers = False
      self.SSGetClass.checkDimLayers = False # scarto le quote
      
      self.entSelClass = None
      
      self.currSubGeom = None
      self.currAtSubGeom = None
     
      self.nOperationsToUndo = 0
   
   def __del__(self):
      QadCommandClass.__del__(self)
      del self.SSGetClass
      self.poligonEntity.deselectOnLayer()

   def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):
      if self.step == 1 or self.step == 4: # quando si é in fase di selezione entità
         return self.entSelClass.getPointMapTool(drawMode)
      elif self.step == 3 or self.step == 5 or \
           self.step == 6 or self.step == 7 or self.step == 8: # quando si é in fase di selezione gruppo entità
         return self.SSGetClass.getPointMapTool()           
      else:
         return QadCommandClass.getPointMapTool(self, drawMode)


   def getCurrentContextualMenu(self):
      if self.step == 1 or self.step == 4: # quando si é in fase di selezione entità
         return self.entSelClass.getCurrentContextualMenu()
      elif self.step == 3 or self.step == 5 or \
           self.step == 6 or self.step == 7 or self.step == 8: # quando si é in fase di selezione gruppo entità
         return None # return self.SSGetClass.getCurrentContextualMenu()           
      else:
         return self.contextualMenu


   def reinitSSGetClass(self):
      checkPointLayer = self.SSGetClass.checkPointLayer
      del self.SSGetClass
      self.SSGetClass = QadSSGetClass(self.plugIn)
      self.SSGetClass.onlyEditableLayers = False
      self.SSGetClass.checkDimLayers = False # scarto le quote
      self.SSGetClass.checkPointLayer = checkPointLayer


   #============================================================================
   # setCurrentSubGeom
   #============================================================================
   def setCurrentSubGeom(self, entSelClass):
      """
      Setta la sottogeometria corrente
      """
      self.currSubGeom = None
      self.currAtSubGeom = None

      # verifico che sia stata selezionata un'entità
      if entSelClass.entity.isInitialized() == False:
         self.showMsg(QadMsg.translate("QAD", "No geometries in this position."))
         return False
      # verifico che sia stata selezionata attraverso un punto
      # (per capire quale sottogeometria è stata selezionata)
      if entSelClass.point is None: return False
      # verifico che sia stato selezionato lo stesso polygono che è da modificare
      if self.poligonEntity != entSelClass.entity:
         self.showMsg(QadMsg.translate("Command_MAPMPEDIT", "The boundary doesn't belong to the selected polygon."))
         return False
      
      # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy
      geom = self.layerToMapCoordinates(entSelClass.entity.layer, entSelClass.entity.getGeometry())
      
      # ritorna una tupla (<The squared cartesian distance>,
      #                    <minDistPoint>
      #                    <afterVertex>
      #                    <leftOf>)
      dummy = qad_utils.closestSegmentWithContext(entSelClass.point, geom)
      if dummy[2] is None:
         return False
      # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)
      self.currSubGeom, self.currAtSubGeom = qad_utils.getSubGeomAtVertex(geom, dummy[2])
      if self.currSubGeom is None or self.currAtSubGeom is None:
         self.currSubGeom = None
         self.currAtSubGeom = None
         return False
      
      return True
   

   #============================================================================
   # addEntitySetToPolygon
   #============================================================================
   def addEntitySetToPolygon(self, entitySet, removeOriginals = False):
      """
      Aggiunge il set di entità al poligono da modificare
      """
      geom = self.poligonEntity.getGeometry()
      layerList = []
      layerList.append(self.poligonEntity.layer)
      
      for layerEntitySet in entitySet.layerEntitySetList:
         layer = layerEntitySet.layer
         if layer.geometryType() != QGis.Polygon and layer.geometryType() != QGis.Line:
            self.showMsg(QadMsg.translate("QAD", "Invalid object."))
            return False

         if removeOriginals: layerList.append(layer)
         coordTransform = QgsCoordinateTransform(layer.crs(), self.poligonEntity.layer.crs())

         for featureId in layerEntitySet.featureIds:
            # se la feature è quella di polygonEntity è errore 
            if layer.id() == self.poligonEntity.layerId() and featureId == self.poligonEntity.featureId:
               self.showMsg(QadMsg.translate("QAD", "Invalid object."))
               return False
            
            f = layerEntitySet.getFeature(featureId)
            # trasformo la geometria nel crs del layer del poligono da modificare
            geomToAdd = f.geometry()
            geomToAdd.transform(coordTransform)
            
            # se il poligono è contenuto nella geometria da aggiungere
            if geomToAdd.contains(geom):
               # Riduco la geometria in point o polyline
               simplifiedGeoms = qad_utils.asPointOrPolyline(geom)
               # deve essere un poligono senza ring
               if len(simplifiedGeoms) != 1 or simplifiedGeoms[0].wkbType() != QGis.WKBLineString:
                  self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                  return False
               points = simplifiedGeoms[0].asPolyline() # vettore di punti
               # aggiungo un'isola
               if geomToAdd.addRing(points) != 0: # 0 in case of success
                  self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                  return False
               del geom
               geom = QgsGeometry.fromPolygon(geomToAdd.asPolygon())
            else: # se il poligono non è contenuto nella geometria da aggiungere
               # Riduco la geometria in point o polyline
               simplifiedGeoms = qad_utils.asPointOrPolyline(geomToAdd)
               for simplifiedGeom in simplifiedGeoms:
                  points = simplifiedGeom.asPolyline() # vettore di punti                     
                  # se la geometria da aggiungere è contenuta nel poligono
                  if geom.contains(QgsGeometry.fromPolyline(points)):
                     # aggiungo un'isola
                     if geom.addRing(points) != 0: # 0 in case of success
                        self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                        return False
                  else:
                     # aggiungo una parte
                     if geom.addPart(points) != 0: # 0 in case of success
                        self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                        return False

      f = self.poligonEntity.getFeature()
      f.setGeometry(geom)

      layerList = entitySet.getLayerList()
      layerList.append(self.poligonEntity.layer)

      self.plugIn.beginEditCommand("Feature edited", layerList)
         
      # plugIn, layer, feature, refresh, check_validity
      if qad_layer.updateFeatureToLayer(self.plugIn, self.poligonEntity.layer, f, False, False) == False:
         self.plugIn.destroyEditCommand()
         return False

      if removeOriginals:
         for layerEntitySet in entitySet.layerEntitySetList:            
            if qad_layer.deleteFeaturesToLayer(self.plugIn, layerEntitySet.layer, layerEntitySet.featureIds, False) == False:
               self.plugIn.destroyEditCommand()
               return 

      self.plugIn.endEditCommand()
      self.nOperationsToUndo = self.nOperationsToUndo + 1

      return True
   

   #============================================================================
   # delCurrentSubGeomToPolygon
   #============================================================================
   def delCurrentSubGeomToPolygon(self):
      """
      Cancella la sotto-geometria corrente dal poligono da modificare
      """
      geom = self.poligonEntity.getGeometry()

       # la posizione é espressa con una lista (<index ogg. princ> [<index ogg. sec.>])
      part = self.currAtSubGeom[0]
      if len(self.currAtSubGeom) == 2:
         ring = self.currAtSubGeom[1]
         if geom.deleteRing(ring + 1, part) == False: # cancello una isola (Ring 0 is outer ring and can't be deleted)
            self.showMsg(QadMsg.translate("QAD", "Invalid object."))
            return False
      else:
         if geom.deletePart(part) == False: # cancello una parte
            self.showMsg(QadMsg.translate("QAD", "Invalid object."))
            return False

      f = self.poligonEntity.getFeature()
      f.setGeometry(geom)

      self.plugIn.beginEditCommand("Feature edited", self.poligonEntity.layer)
         
      # plugIn, layer, feature, refresh, check_validity
      if qad_layer.updateFeatureToLayer(self.plugIn, self.poligonEntity.layer, f, False, False) == False:
         self.plugIn.destroyEditCommand()
         return False

      self.plugIn.endEditCommand()
      self.nOperationsToUndo = self.nOperationsToUndo + 1


   #============================================================================
   # unionIntersSubtractEntitySetToPolygon
   #============================================================================
   def unionIntersSubtractEntitySetToPolygon(self, entitySet, opType, removeOriginals = False):
      """
      Unisce o interseca i poligoni di entitySet al poligono corrente
      """
      geom = self.poligonEntity.getGeometry()
      layerList = []
      layerList.append(self.poligonEntity.layer)
      
      geomList = []
      geomList.append(geom)
      for layerEntitySet in entitySet.layerEntitySetList:
         del geomList[:]
         layer = layerEntitySet.layer
         coordTransform = QgsCoordinateTransform(layer.crs(), self.poligonEntity.layer.crs())
         
         if layer.geometryType() == QGis.Polygon:
            for featureId in layerEntitySet.featureIds:
               # se la feature è quella di polygonEntity è errore 
               if layer.id() == self.poligonEntity.layerId() and featureId == self.poligonEntity.featureId:
                  self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                  return False
               f = layerEntitySet.getFeature(featureId)
               # trasformo la geometria nel crs del layer del poligono da modificare
               geomToAdd = f.geometry()

               geomToAdd.transform(coordTransform)

               if opType == QadMAPMPEDITCommandOpTypeEnum.UNION: geom = geom.combine(geomToAdd)
               elif opType == QadMAPMPEDITCommandOpTypeEnum.INTERSECTION: geom = geom.intersection(geomToAdd)
               elif opType == QadMAPMPEDITCommandOpTypeEnum.DIFFERENCE: geom = geom.difference(geomToAdd)
               
               if geom is None:
                  self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                  return False
               
               if removeOriginals and layer.id() != self.poligonEntity.layerId():
                  layerList.append(layer)

         elif layer.geometryType() == QGis.Line:
            for featureId in layerEntitySet.featureIds:
               f = layerEntitySet.getFeature(featureId)
               # trasformo la geometria nel crs del layer del poligono da modificare
               geomToAdd = f.geometry()
               geomToAdd.transform(coordTransform)
               # Riduco la geometria in point o polyline
               simplifiedGeoms = qad_utils.asPointOrPolyline(geomToAdd)
               for simplifiedGeom in simplifiedGeoms:
                  if simplifiedGeom.wkbType() != QGis.WKBLineString:
                     self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                     return False
                  points = simplifiedGeom.asPolyline() # vettore di punti
                  
                  if len(points) < 4 or points[0] != points[-1]: # polilinea chiusa con almeno 4 punti (primo e ultimo uguali)
                     self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                     return False
                  geomToAdd = QgsGeometry.fromPolygon([points])
                  
                  if opType == QadMAPMPEDITCommandOpTypeEnum.UNION: geom = geom.combine(geomToAdd)
                  elif opType == QadMAPMPEDITCommandOpTypeEnum.INTERSECTION: geom = geom.intersection(geomToAdd)
                  elif opType == QadMAPMPEDITCommandOpTypeEnum.DIFFERENCE: geom = geom.difference(geomToAdd)
                  
                  if geom is None or geom.type() != QGis.Polygon:
                     self.showMsg(QadMsg.translate("QAD", "Invalid object."))
                     return False
                  
               if removeOriginals: layerList.append(layer)
         else:
            self.showMsg(QadMsg.translate("QAD", "Invalid object."))
            return False

      f = self.poligonEntity.getFeature()
      f.setGeometry(geom)

      self.plugIn.beginEditCommand("Feature edited", layerList)
         
      # plugIn, layer, feature, refresh, check_validity
      if qad_layer.updateFeatureToLayer(self.plugIn, self.poligonEntity.layer, f, False, False) == False:
         self.plugIn.destroyEditCommand()
         return False

      if removeOriginals:
         for layerEntitySet in entitySet.layerEntitySetList:            
            if qad_layer.deleteFeaturesToLayer(self.plugIn, layerEntitySet.layer, layerEntitySet.featureIds, False) == False:
               self.plugIn.destroyEditCommand()
               return 

      self.plugIn.endEditCommand()
      self.nOperationsToUndo = self.nOperationsToUndo + 1

      return True

   
   #============================================================================
   # convexHullEntitySetToPolygon
   #============================================================================
   def convexHullEntitySetToPolygon(self, entitySet, removeOriginals = False):
      """
      modifica il poligono corrente in modo che includa tutti i punti delle geometrie di entitySet
      """
      layerList = []
      layerList.append(self.poligonEntity.layer)
      pointsForConvexHull = []
      
      for layerEntitySet in entitySet.layerEntitySetList:
         layer = layerEntitySet.layer
         coordTransform = QgsCoordinateTransform(layer.crs(), self.poligonEntity.layer.crs())
         
         for featureId in layerEntitySet.featureIds:
            f = layerEntitySet.getFeature(featureId)
            # trasformo la geometria nel crs del layer del poligono da modificare
            geom = f.geometry()
            geom.transform(coordTransform)

            # Riduco la geometria in point o polyline
            simplifiedGeoms = qad_utils.asPointOrPolyline(geom)
            for simplifiedGeom in simplifiedGeoms:
               if simplifiedGeom.wkbType() == QGis.WKBLineString:
                  pointsForConvexHull.extend(simplifiedGeom.asPolyline())
               else:
                  pointsForConvexHull.append(simplifiedGeom.asPoint())
               
            if removeOriginals and layer.id() != self.poligonEntity.layerId():
               layerList.append(layer)

      geom = QgsGeometry.fromMultiPoint(pointsForConvexHull)
      geom = geom.convexHull()
      if geom is None:
         self.showMsg(QadMsg.translate("QAD", "Invalid object."))
         return False
         
      f = self.poligonEntity.getFeature()
      f.setGeometry(geom)

      self.plugIn.beginEditCommand("Feature edited", layerList)
         
      # plugIn, layer, feature, refresh, check_validity
      if qad_layer.updateFeatureToLayer(self.plugIn, self.poligonEntity.layer, f, False, False) == False:
         self.plugIn.destroyEditCommand()
         return False

      if removeOriginals:
         for layerEntitySet in entitySet.layerEntitySetList:            
            if qad_layer.deleteFeaturesToLayer(self.plugIn, layerEntitySet.layer, layerEntitySet.featureIds, False) == False:
               self.plugIn.destroyEditCommand()
               return 

      self.plugIn.endEditCommand()
      self.nOperationsToUndo = self.nOperationsToUndo + 1

      return True


   #============================================================================
   # dividePolygon
   #============================================================================
   def splitPolygon(self, splitLine, createNewEntities):
      """
      divide il poligono corrente usando una polilinea con i vertci in <plineVertices> in modo da generare o meno nuove entità
      """
      layerList = []
      layerList.append(self.poligonEntity.layer)
      
      splitLineTransformed = self.mapToLayerCoordinates(self.poligonEntity.layer, splitLine)
      f = self.poligonEntity.getFeature()
      geom = f.geometry()
      result, newGeoms, topologyTestPts = geom.splitGeometry(splitLineTransformed, False)

      if result <> 0 or len(newGeoms) == 0:
         self.showMsg(QadMsg.translate("QAD", "Invalid object."))
         return False
         
      newfeatures =[]
      if createNewEntities:
         for newGeom in newGeoms:
            newfeature = QgsFeature(f)
            newfeature.setGeometry(newGeom)
            newfeatures.append(newfeature)
      else:
         for newGeom in newGeoms:
            # Riduco la geometria in point o polyline
            simplifiedGeoms = qad_utils.asPointOrPolyline(newGeom)
            for simplifiedGeom in simplifiedGeoms:
               points = simplifiedGeom.asPolyline() # vettore di punti                     
               res = geom.addPart(points)
      
      f.setGeometry(geom)
      
      self.plugIn.beginEditCommand("Feature edited", layerList)
         
      # plugIn, layer, feature, refresh, check_validity
      if qad_layer.updateFeatureToLayer(self.plugIn, self.poligonEntity.layer, f, False, False) == False:
         self.plugIn.destroyEditCommand()
         return False

      if len(newfeatures) > 0:
         # plugIn, layer, features, coordTransform, refresh, check_validity
         if qad_layer.addFeaturesToLayer(self.plugIn, self.poligonEntity.layer, newfeatures, None, False, False) == False:
            self.plugIn.destroyEditCommand()
            return

      self.plugIn.endEditCommand()
      self.nOperationsToUndo = self.nOperationsToUndo + 1

      return True



   #============================================================================
   # waitForEntsel
   #============================================================================
   def waitForEntsel(self, msgMapTool, msg):
      if self.entSelClass is not None:
         del self.entSelClass
      self.step = 1
      self.entSelClass = QadEntSelClass(self.plugIn)
      self.entSelClass.msg = QadMsg.translate("Command_MAPMPEDIT", "Select polygon: ")
      # scarto la selezione di punti e polilinee
      self.entSelClass.checkPointLayer = False
      self.entSelClass.checkLineLayer = False
      self.entSelClass.checkPolygonLayer = True
      self.entSelClass.checkDimLayers = False     
      self.entSelClass.onlyEditableLayers = True

      self.entSelClass.run(msgMapTool, msg)
      

   #============================================================================
   # WaitForMainMenu
   #============================================================================
   def WaitForMainMenu(self):
      self.poligonEntity.selectOnLayer(False)
      keyWords = QadMsg.translate("Command_MAPMPEDIT", "Add") + "/" + \
                 QadMsg.translate("Command_MAPMPEDIT", "Delete") + "/" + \
                 QadMsg.translate("Command_MAPMPEDIT", "Union") + "/" + \
                 QadMsg.translate("Command_MAPMPEDIT", "Substract") + "/" + \
                 QadMsg.translate("Command_MAPMPEDIT", "Intersect") + "/" + \
                 QadMsg.translate("Command_MAPMPEDIT", "split Objects") + "/" + \
                 QadMsg.translate("Command_MAPMPEDIT", "split Parts") + "/" + \
                 QadMsg.translate("Command_MAPMPEDIT", "iNclude objs")
      englishKeyWords = "Add" + "/" + "Delete" + "/" + "Union" + "/" + "Substract" + "/" + "Intersect" "/" + \
                        "split Objects" + "/" + "split Parts" + "/" + "iNclude objs"

      if self.nOperationsToUndo > 0: # se c'è qualcosa che si può annullare
         keyWords = keyWords + "/" +  QadMsg.translate("Command_MAPMPEDIT", "Undo")
         englishKeyWords = englishKeyWords + "/" + "Undo"
      
      keyWords = keyWords + "/" + QadMsg.translate("Command_MAPMPEDIT", "eXit")
      englishKeyWords = englishKeyWords + "/" + "eXit"
                 
      default = QadMsg.translate("Command_MAPMPEDIT", "eXit")

      prompt = QadMsg.translate("Command_MAPMPEDIT", "Enter an option [{0}] <{1}>: ").format(keyWords, default)
      
      self.step = 2
      self.getPointMapTool().setSelectionMode(QadGetPointSelectionModeEnum.NONE)
      self.getPointMapTool().setDrawMode(QadGetPointDrawModeEnum.NONE)
      
      keyWords += "_" + englishKeyWords
      # si appresta ad attendere enter o una parola chiave         
      # msg, inputType, default, keyWords, nessun controllo
      self.waitFor(prompt, \
                   QadInputTypeEnum.KEYWORDS, \
                   None, \
                   keyWords, QadInputModeEnum.NONE)
      return False
      

   #============================================================================
   # waitForBoundary
   #============================================================================
   def waitForBoundary(self, msgMapTool, msg):
      if self.entSelClass is not None:
         del self.entSelClass
      self.entSelClass = QadEntSelClass(self.plugIn)
      self.entSelClass.msg = QadMsg.translate("Command_MAPMPEDIT", "Select boundary: ")
      # scarto la selezione di punti e polilinee
      self.entSelClass.checkPointLayer = False
      self.entSelClass.checkLineLayer = False
      self.entSelClass.checkPolygonLayer = True
      self.entSelClass.checkDimLayers = False
      self.entSelClass.onlyEditableLayers = True

      self.entSelClass.run(msgMapTool, msg)


   def run(self, msgMapTool = False, msg = None):
      if self.plugIn.canvas.mapSettings().destinationCrs().geographicFlag():
         self.showMsg(QadMsg.translate("QAD", "\nThe coordinate reference system of the project must be a projected coordinate system.\n"))
         return True # fine comando
      
      if self.step == 0:
         self.waitForEntsel(msgMapTool, msg) # seleziona il poligono da modificare
         return False # continua
      
      #=========================================================================
      # RISPOSTA ALLA SELEZIONE POLIGONO DA MODIFICARE
      elif self.step == 1:
         if self.entSelClass.run(msgMapTool, msg) == True:
            if self.entSelClass.entity.isInitialized():
               self.poligonEntity.set(self.entSelClass.entity.layer, self.entSelClass.entity.featureId)
               layer = self.entSelClass.entity.layer
               self.poligonEntity.deselectOnLayer()
               self.WaitForMainMenu()
            else:
               if self.entSelClass.canceledByUsr == True: # fine comando
                  return True
               self.showMsg(QadMsg.translate("QAD", "No geometries in this position."))
               self.waitForEntsel(msgMapTool, msg)

         return False # continua

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DEL MENU PRINCIPALE
      elif self.step == 2: # dopo aver atteso una opzione si riavvia il comando
         if msgMapTool == True: # il punto arriva da una selezione grafica
            # la condizione seguente si verifica se durante la selezione di un punto
            # é stato attivato un altro plugin che ha disattivato Qad
            # quindi stato riattivato il comando che torna qui senza che il maptool
            # abbia selezionato un punto            
            if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto
               if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse
                  return True # fine comando
               else:
                  self.setMapTool(self.getPointMapTool()) # riattivo il maptool
                  return False

            self.WaitForMainMenu()
            return False 
         else: # l'opzione arriva come parametro della funzione
            value = msg

         self.poligonEntity.deselectOnLayer()

         if value == QadMsg.translate("Command_MAPMPEDIT", "Add") or value == "Add":
            self.SSGetClass.checkPointLayer = False # scarto i punto
            self.SSGetClass.run(msgMapTool, msg)
            self.step = 3
            return False
         elif value == QadMsg.translate("Command_MAPMPEDIT", "Delete") or value == "Delete":
            self.waitForBoundary(msgMapTool, msg)
            self.step = 4
            return False
         elif value == QadMsg.translate("Command_MAPMPEDIT", "Union") or value == "Union":
            self.SSGetClass.checkPointLayer = False # scarto i layer puntuali
            self.SSGetClass.run(msgMapTool, msg)
            self.step = 5
            return False
         elif value == QadMsg.translate("Command_MAPMPEDIT", "Substract") or value == "Substract":
            self.SSGetClass.checkPointLayer = False # scarto i layer puntuali
            self.SSGetClass.run(msgMapTool, msg)
            self.step = 6
            return False
         elif value == QadMsg.translate("Command_MAPMPEDIT", "Intersect") or value == "Intersect":
            self.SSGetClass.checkPointLayer = False # scarto i layer puntuali
            self.SSGetClass.run(msgMapTool, msg)
            self.step = 7
            return False
         elif value == QadMsg.translate("Command_MAPMPEDIT", "split Objects") or value == "split Objects":
            # Disegna una polilinea di divisione del poligono
            self.PLINECommand = QadPLINECommandClass(self.plugIn)
            # se questo flag = True il comando serve all'interno di un altro comando per disegnare una linea
            # che non verrà salvata su un layer
            self.PLINECommand.virtualCmd = True   
            self.PLINECommand.run(msgMapTool, msg)
            self.step = 9
            return False
         elif value == QadMsg.translate("Command_MAPMPEDIT", "split Parts") or value == "split Parts":
            # Disegna una polilinea di divisione del poligono
            self.PLINECommand = QadPLINECommandClass(self.plugIn)
            # se questo flag = True il comando serve all'interno di un altro comando per disegnare una linea
            # che non verrà salvata su un layer
            self.PLINECommand.virtualCmd = True   
            self.PLINECommand.run(msgMapTool, msg)
            self.step = 10
            return False
         elif value == QadMsg.translate("Command_MAPMPEDIT", "iNclude objs") or value == "iNclude objs":
            self.SSGetClass.checkPointLayer = True # includo i layer puntuali
            self.SSGetClass.run(msgMapTool, msg)
            self.step = 8
            return False
         elif value == QadMsg.translate("Command_MAPMPEDIT", "Undo") or value == "Undo":
            if self.nOperationsToUndo > 0: 
               self.nOperationsToUndo = self.nOperationsToUndo - 1           
               self.plugIn.undoEditCommand()
            else:
               self.showMsg(QadMsg.translate("QAD", "\nThe command has been canceled."))
         elif value == QadMsg.translate("Command_MAPMPEDIT", "eXit") or value == "eXit":
            return True # fine comando
         else:
            return True # fine comando
         
         self.WaitForMainMenu()
         return False      

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA MODALITA' DI ADD (da step = 2)
      elif self.step == 3:
         if self.SSGetClass.run(msgMapTool, msg) == True:
            if self.SSGetClass.entitySet.count() > 0:
               self.addEntitySetToPolygon(self.SSGetClass.entitySet)
            self.reinitSSGetClass()
            self.WaitForMainMenu()
         return False
      
      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA MODALITA' DI DELETE (da step = 2)
      elif self.step == 4:
         if self.entSelClass.run(msgMapTool, msg) == True:
            if self.setCurrentSubGeom(self.entSelClass) == True:
               self.delCurrentSubGeomToPolygon()
               self.WaitForMainMenu()
               return False
            else:
               if self.entSelClass.canceledByUsr == True: # fine selezione entità
                  self.WaitForMainMenu()
               else:
                  self.waitForBoundary(msgMapTool, msg)
         return False # continua

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA MODALITA' DI UNION (da step = 2)
      elif self.step == 5: # dopo aver atteso una entità si riavvia il comando
         if self.SSGetClass.run(msgMapTool, msg) == True:
            if self.SSGetClass.entitySet.count() > 0:
               self.unionIntersSubtractEntitySetToPolygon(self.SSGetClass.entitySet, QadMAPMPEDITCommandOpTypeEnum.UNION)
            self.reinitSSGetClass()
            self.WaitForMainMenu()
         return False # continua

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA MODALITA' DI SUBTRACT (da step = 2)
      elif self.step == 6: # dopo aver atteso una entità si riavvia il comando
         if self.SSGetClass.run(msgMapTool, msg) == True:
            if self.SSGetClass.entitySet.count() > 0:
               self.unionIntersSubtractEntitySetToPolygon(self.SSGetClass.entitySet, QadMAPMPEDITCommandOpTypeEnum.DIFFERENCE)
            self.reinitSSGetClass()
            self.WaitForMainMenu()
         return False # continua

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA MODALITA' DI INTERSECT (da step = 2)
      elif self.step == 7: # dopo aver atteso una entità si riavvia il comando
         if self.SSGetClass.run(msgMapTool, msg) == True:
            if self.SSGetClass.entitySet.count() > 0:
               self.unionIntersSubtractEntitySetToPolygon(self.SSGetClass.entitySet, QadMAPMPEDITCommandOpTypeEnum.INTERSECTION)
            self.reinitSSGetClass()
            self.WaitForMainMenu()
         return False # continua

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA MODALITA' DI INCLUDE OBJS (da step = 2)
      elif self.step == 8: # dopo aver atteso una entità si riavvia il comando
         if self.SSGetClass.run(msgMapTool, msg) == True:
            if self.SSGetClass.entitySet.count() > 0:
               self.convexHullEntitySetToPolygon(self.SSGetClass.entitySet)
            self.reinitSSGetClass()
            self.WaitForMainMenu()
         return False # continua

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA LINEA DI DIVISIONE (da step = 2)
      elif self.step == 9: # dopo aver atteso un punto si riavvia il comando
         if self.PLINECommand.run(msgMapTool, msg) == True:
            self.showMsg("\n")
            self.splitPolygon(self.PLINECommand.vertices, True)
            del self.PLINECommand
            self.PLINECommand = None
            self.WaitForMainMenu()
         return False

      #=========================================================================
      # RISPOSTA ALLA RICHIESTA DELLA LINEA DI DIVISIONE (da step = 2)
      elif self.step == 10: # dopo aver atteso un punto si riavvia il comando
         if self.PLINECommand.run(msgMapTool, msg) == True:
            self.showMsg("\n")
            self.splitPolygon(self.PLINECommand.vertices, False)
            del self.PLINECommand
            self.PLINECommand = None
            self.WaitForMainMenu()
         return False