Exemplo n.º 1
0
static void _readOldLegendGroup( const QDomElement &groupElem, QgsLayerTreeGroup *parent )
{
  QDomNodeList groupChildren = groupElem.childNodes();

  QgsLayerTreeGroup *groupNode = new QgsLayerTreeGroup( groupElem.attribute( QStringLiteral( "name" ) ) );

  groupNode->setItemVisibilityChecked( QgsLayerTreeUtils::checkStateFromXml( groupElem.attribute( QStringLiteral( "checked" ) ) ) != Qt::Unchecked );
  groupNode->setExpanded( groupElem.attribute( QStringLiteral( "open" ) ) == QLatin1String( "true" ) );

  if ( groupElem.attribute( QStringLiteral( "embedded" ) ) == QLatin1String( "1" ) )
  {
    groupNode->setCustomProperty( QStringLiteral( "embedded" ), 1 );
    groupNode->setCustomProperty( QStringLiteral( "embedded_project" ), groupElem.attribute( QStringLiteral( "project" ) ) );
  }

  for ( int i = 0; i < groupChildren.size(); ++i )
  {
    QDomElement currentChildElem = groupChildren.at( i ).toElement();
    if ( currentChildElem.tagName() == QLatin1String( "legendlayer" ) )
    {
      _readOldLegendLayer( currentChildElem, groupNode );
    }
    else if ( currentChildElem.tagName() == QLatin1String( "legendgroup" ) )
    {
      _readOldLegendGroup( currentChildElem, groupNode );
    }
  }

  parent->addChildNode( groupNode );
}
void QgsLayerTreeViewDefaultActions::addGroup()
{
  QgsLayerTreeGroup* group = mView->currentGroupNode();

  QgsLayerTreeGroup* newGroup = group->addGroup( uniqueGroupName( group ) );
  mView->edit( mView->layerTreeModel()->node2index( newGroup ) );
}
Exemplo n.º 3
0
bool QgsLayerTreeModel::setData( const QModelIndex& index, const QVariant& value, int role )
{
  QgsLayerTreeModelLegendNode *sym = index2symnode( index );
  if ( sym )
  {
    if ( role == Qt::CheckStateRole && !testFlag( AllowSymbologyChangeState ) )
      return false;
    bool res = sym->setData( value, role );
    if ( res )
      emit dataChanged( index, index );
    return res;
  }

  QgsLayerTreeNode* node = index2node( index );
  if ( !node )
    return QgsLayerTreeModel::setData( index, value, role );

  if ( role == Qt::CheckStateRole )
  {
    if ( !testFlag( AllowNodeChangeVisibility ) )
      return false;

    if ( QgsLayerTree::isLayer( node ) )
    {
      QgsLayerTreeLayer* layer = QgsLayerTree::toLayer( node );
      layer->setVisible(( Qt::CheckState )value.toInt() );
      return true;
    }

    if ( QgsLayerTree::isGroup( node ) )
    {
      QgsLayerTreeGroup* group = QgsLayerTree::toGroup( node );
      group->setVisible(( Qt::CheckState )value.toInt() );
      return true;
    }

    return true;
  }
  else if ( role == Qt::EditRole )
  {
    if ( !testFlag( AllowNodeRename ) )
      return false;

    if ( QgsLayerTree::isLayer( node ) )
    {
      QgsLayerTreeLayer* layer = QgsLayerTree::toLayer( node );
      layer->setLayerName( value.toString() );
      emit dataChanged( index, index );
    }
    else if ( QgsLayerTree::isGroup( node ) )
    {
      QgsLayerTree::toGroup( node )->setName( value.toString() );
      emit dataChanged( index, index );
    }
  }

  return QAbstractItemModel::setData( index, value, role );
}
Exemplo n.º 4
0
QgsLayerTreeLayer *QgsLayerTreeUtils::insertLayerBelow( QgsLayerTreeGroup *group, const QgsMapLayer *refLayer, QgsMapLayer *layerToInsert )
{
  // get the index of the reflayer
  QgsLayerTreeLayer *inTree = group->findLayer( refLayer->id() );
  if ( !inTree )
    return nullptr;

  int idx = 0;
  const auto constChildren = inTree->parent()->children();
  for ( QgsLayerTreeNode *vl : constChildren )
  {
    if ( vl->nodeType() == QgsLayerTreeNode::NodeLayer && static_cast<QgsLayerTreeLayer *>( vl )->layer() == refLayer )
    {
      break;
    }
    idx++;
  }
  // insert the new layer
  QgsLayerTreeGroup *parent = static_cast<QgsLayerTreeGroup *>( inTree->parent() ) ? static_cast<QgsLayerTreeGroup *>( inTree->parent() ) : group;
  return parent->insertLayer( idx, layerToInsert );
}
Exemplo n.º 5
0
static void _readOldLegendGroup( QDomElement& elem, QgsLayerTreeGroup* parentGroup, QgsProject* project )
{
  QDomElement itemElem = elem.firstChildElement();

  while ( !itemElem.isNull() )
  {

    if ( itemElem.tagName() == QLatin1String( "LayerItem" ) )
    {
      QString layerId = itemElem.attribute( QStringLiteral( "layerId" ) );
      if ( QgsMapLayer* layer = project->mapLayer( layerId ) )
      {
        QgsLayerTreeLayer* nodeLayer = parentGroup->addLayer( layer );
        QString userText = itemElem.attribute( QStringLiteral( "userText" ) );
        if ( !userText.isEmpty() )
          nodeLayer->setCustomProperty( QStringLiteral( "legend/title-label" ), userText );
        QString style = itemElem.attribute( QStringLiteral( "style" ) );
        if ( !style.isEmpty() )
          nodeLayer->setCustomProperty( QStringLiteral( "legend/title-style" ), style );
        QString showFeatureCount = itemElem.attribute( QStringLiteral( "showFeatureCount" ) );
        if ( showFeatureCount.toInt() )
          nodeLayer->setCustomProperty( QStringLiteral( "showFeatureCount" ), 1 );

        // support for individual legend items (user text, order) not implemented yet
      }
    }
    else if ( itemElem.tagName() == QLatin1String( "GroupItem" ) )
    {
      QgsLayerTreeGroup* nodeGroup = parentGroup->addGroup( itemElem.attribute( QStringLiteral( "userText" ) ) );
      QString style = itemElem.attribute( QStringLiteral( "style" ) );
      if ( !style.isEmpty() )
        nodeGroup->setCustomProperty( QStringLiteral( "legend/title-style" ), style );

      _readOldLegendGroup( itemElem, nodeGroup, project );
    }

    itemElem = itemElem.nextSiblingElement();
  }
}
Exemplo n.º 6
0
void QgsDwgImportDialog::buttonBox_accepted()
{
  QgsTemporaryCursorOverride waitCursor( Qt::BusyCursor );

  QMap<QString, bool> layers;
  bool allLayers = true;
  for ( int i = 0; i < mLayers->rowCount(); i++ )
  {
    QTableWidgetItem *item = mLayers->item( i, 0 );
    if ( item->checkState() == Qt::Unchecked )
    {
      allLayers = false;
      continue;
    }

    layers.insert( item->text(), mLayers->item( i, 1 )->checkState() == Qt::Checked );
  }

  if ( cbMergeLayers->isChecked() )
  {
    if ( allLayers )
      layers.clear();

    createGroup( QgisApp::instance()->layerTreeView()->layerTreeModel()->rootGroup(), leLayerGroup->text(), layers.keys(), true );
  }
  else
  {
    QgsLayerTreeGroup *dwgGroup = QgisApp::instance()->layerTreeView()->layerTreeModel()->rootGroup()->addGroup( leLayerGroup->text() );
    Q_ASSERT( dwgGroup );

    const auto constKeys = layers.keys();
    for ( const QString &layer : constKeys )
    {
      createGroup( dwgGroup, layer, QStringList( layer ), layers[layer] );
    }

    dwgGroup->setExpanded( false );
  }
}
Exemplo n.º 7
0
bool QgsLayerTreeUtils::hasLegendFilterExpression( const QgsLayerTreeGroup &group )
{
  const auto constFindLayers = group.findLayers();
  for ( QgsLayerTreeLayer *l : constFindLayers )
  {
    bool exprEnabled;
    QString expr = legendFilterByExpression( *l, &exprEnabled );
    if ( exprEnabled && !expr.isEmpty() )
    {
      return true;
    }
  }
  return false;
}
Exemplo n.º 8
0
QList<QDomElement> QgsServerProjectParser::setLegendGroupElementsWithLayerTree( QgsLayerTreeGroup* layerTreeGroup, const QDomElement& legendElement ) const
{
  QList<QDomElement> LegendGroupElemList;
  QList< QgsLayerTreeNode * > layerTreeGroupChildren = layerTreeGroup->children();
  QDomNodeList legendElementChildNodes = legendElement.childNodes();
  int g = 0; // index of the last child layer tree group
  for ( int i = 0; i < legendElementChildNodes.size(); ++i )
  {
    QDomNode legendElementNode = legendElementChildNodes.at( i );
    if ( !legendElementNode.isElement() )
      continue;
    QDomElement legendElement = legendElementNode.toElement();
    if ( legendElement.tagName() != "legendgroup" )
      continue;
    for ( int j = g; j < i + 1; ++j )
    {
      QgsLayerTreeNode* layerTreeNode = layerTreeGroupChildren.at( j );
      if ( layerTreeNode->nodeType() != QgsLayerTreeNode::NodeGroup )
        continue;
      QgsLayerTreeGroup* layerTreeGroup = static_cast<QgsLayerTreeGroup *>( layerTreeNode );
      if ( layerTreeGroup->name() == legendElement.attribute( "name" ) )
      {
        g = j;
        QString shortName = layerTreeGroup->customProperty( "wmsShortName" ).toString();
        if ( !shortName.isEmpty() )
          legendElement.setAttribute( "shortName", shortName );
        QString title = layerTreeGroup->customProperty( "wmsTitle" ).toString();
        if ( !title.isEmpty() )
          legendElement.setAttribute( "title", title );
        LegendGroupElemList.append( setLegendGroupElementsWithLayerTree( layerTreeGroup, legendElement ) );
      }
    }
    LegendGroupElemList.push_back( legendElement );
  }
  return LegendGroupElemList;
}
Exemplo n.º 9
0
QVariant QgsLayerTreeModel::data( const QModelIndex &index, int role ) const
{
  if ( !index.isValid() )
    return QVariant();

  if ( QgsLayerTreeModelLegendNode* sym = index2symnode( index ) )
  {
    if ( role == Qt::CheckStateRole && !testFlag( AllowSymbologyChangeState ) )
      return QVariant();
    return sym->data( role );
  }

  QgsLayerTreeNode* node = index2node( index );
  if ( role == Qt::DisplayRole || role == Qt::EditRole )
  {
    if ( QgsLayerTree::isGroup( node ) )
      return QgsLayerTree::toGroup( node )->name();
    else if ( QgsLayerTree::isLayer( node ) )
    {
      QgsLayerTreeLayer* nodeLayer = QgsLayerTree::toLayer( node );
      QString name = nodeLayer->layerName();
      if ( nodeLayer->customProperty( "showFeatureCount", 0 ).toInt() && role == Qt::DisplayRole )
      {
        QgsVectorLayer* vlayer = qobject_cast<QgsVectorLayer*>( nodeLayer->layer() );
        if ( vlayer && vlayer->pendingFeatureCount() >= 0 )
          name += QString( " [%1]" ).arg( vlayer->pendingFeatureCount() );
      }
      return name;
    }
  }
  else if ( role == Qt::DecorationRole && index.column() == 0 )
  {
    if ( QgsLayerTree::isGroup( node ) )
      return iconGroup();
    else if ( QgsLayerTree::isLayer( node ) )
    {
      QgsLayerTreeLayer* nodeLayer = QgsLayerTree::toLayer( node );

      // if there's just on legend entry that should be embedded in layer - do that!
      if ( testFlag( ShowSymbology ) && mSymbologyNodes[nodeLayer].count() == 1 && mSymbologyNodes[nodeLayer][0]->isEmbeddedInParent() )
        return mSymbologyNodes[nodeLayer][0]->data( Qt::DecorationRole );

      QgsMapLayer* layer = QgsLayerTree::toLayer( node )->layer();
      if ( !layer )
        return QVariant();
      if ( layer->type() == QgsMapLayer::RasterLayer )
      {
        if ( testFlag( ShowRasterPreviewIcon ) )
        {
          QgsRasterLayer* rlayer = qobject_cast<QgsRasterLayer *>( layer );
          return QIcon( rlayer->previewAsPixmap( QSize( 32, 32 ) ) );
        }
        else
          return QgsLayerItem::iconRaster();
      }
      else if ( layer->type() == QgsMapLayer::VectorLayer )
      {
        QgsVectorLayer* vlayer = static_cast<QgsVectorLayer*>( layer );
        if ( vlayer->isEditable() )
        {
          if ( vlayer->isModified() )
            return QIcon( QgsApplication::getThemePixmap( "/mIconEditableEdits.png" ) );
          else
            return QIcon( QgsApplication::getThemePixmap( "/mIconEditable.png" ) );
        }

        if ( vlayer->geometryType() == QGis::Point )
          return QgsLayerItem::iconPoint();
        else if ( vlayer->geometryType() == QGis::Line )
          return QgsLayerItem::iconLine();
        else if ( vlayer->geometryType() == QGis::Polygon )
          return QgsLayerItem::iconPolygon();
        else if ( vlayer->geometryType() == QGis::NoGeometry )
          return QgsLayerItem::iconTable();
      }
      return QgsLayerItem::iconDefault();
    }
  }
  else if ( role == Qt::CheckStateRole )
  {
    if ( !testFlag( AllowNodeChangeVisibility ) )
      return QVariant();

    if ( QgsLayerTree::isLayer( node ) )
    {
      QgsLayerTreeLayer* nodeLayer = QgsLayerTree::toLayer( node );
      if ( nodeLayer->layer() && nodeLayer->layer()->type() == QgsMapLayer::VectorLayer )
      {
        if ( qobject_cast<QgsVectorLayer*>( nodeLayer->layer() )->geometryType() == QGis::NoGeometry )
          return QVariant(); // do not show checkbox for non-spatial tables
      }
      return nodeLayer->isVisible();
    }
    else if ( QgsLayerTree::isGroup( node ) )
    {
      QgsLayerTreeGroup* nodeGroup = QgsLayerTree::toGroup( node );
      return nodeGroup->isVisible();
    }
  }
  else if ( role == Qt::FontRole )
  {
    QFont f( QgsLayerTree::isLayer( node ) ? mFontLayer : ( QgsLayerTree::isGroup( node ) ? mFontGroup : QFont() ) );
    if ( node->customProperty( "embedded" ).toInt() )
      f.setItalic( true );
    if ( index == mCurrentIndex )
      f.setUnderline( true );
    return f;
  }
  else if ( role == Qt::ToolTipRole )
  {
    if ( QgsLayerTree::isLayer( node ) )
    {
      if ( QgsMapLayer* layer = QgsLayerTree::toLayer( node )->layer() )
        return layer->publicSource();
    }
  }

  return QVariant();
}
Exemplo n.º 10
0
QVariant QgsLayerTreeModel::data( const QModelIndex &index, int role ) const
{
    if ( !index.isValid() || index.column() > 1 )
        return QVariant();

    if ( QgsLayerTreeModelLegendNode* sym = index2legendNode( index ) )
        return legendNodeData( sym, role );

    QgsLayerTreeNode* node = index2node( index );
    if ( role == Qt::DisplayRole || role == Qt::EditRole )
    {
        if ( QgsLayerTree::isGroup( node ) )
            return QgsLayerTree::toGroup( node )->name();

        if ( QgsLayerTree::isLayer( node ) )
        {
            QgsLayerTreeLayer* nodeLayer = QgsLayerTree::toLayer( node );
            QString name = nodeLayer->layerName();
            if ( nodeLayer->customProperty( "showFeatureCount", 0 ).toInt() && role == Qt::DisplayRole )
            {
                QgsVectorLayer* vlayer = qobject_cast<QgsVectorLayer*>( nodeLayer->layer() );
                if ( vlayer && vlayer->featureCount() >= 0 )
                    name += QString( " [%1]" ).arg( vlayer->featureCount() );
            }
            return name;
        }
    }
    else if ( role == Qt::DecorationRole && index.column() == 0 )
    {
        if ( QgsLayerTree::isGroup( node ) )
            return iconGroup();

        if ( QgsLayerTree::isLayer( node ) )
        {
            QgsLayerTreeLayer *nodeLayer = QgsLayerTree::toLayer( node );

            QgsMapLayer *layer = nodeLayer->layer();
            if ( !layer )
                return QVariant();

            // icons possibly overriding default icon
            if ( layer->type() == QgsMapLayer::RasterLayer )
            {
                if ( testFlag( ShowRasterPreviewIcon ) )
                {
                    QgsRasterLayer* rlayer = qobject_cast<QgsRasterLayer *>( layer );
                    return QIcon( QPixmap::fromImage( rlayer->previewAsImage( QSize( 32, 32 ) ) ) );
                }
                else
                {
                    return QgsLayerItem::iconRaster();
                }
            }

            QgsVectorLayer *vlayer = dynamic_cast<QgsVectorLayer*>( layer );
            QIcon icon;

            // if there's just on legend entry that should be embedded in layer - do that!
            if ( testFlag( ShowLegend ) && legendEmbeddedInParent( nodeLayer ) )
            {
                icon = legendIconEmbeddedInParent( nodeLayer );
            }
            else if ( vlayer && layer->type() == QgsMapLayer::VectorLayer )
            {
                if ( vlayer->geometryType() == QGis::Point )
                    icon = QgsLayerItem::iconPoint();
                else if ( vlayer->geometryType() == QGis::Line )
                    icon = QgsLayerItem::iconLine();
                else if ( vlayer->geometryType() == QGis::Polygon )
                    icon = QgsLayerItem::iconPolygon();
                else if ( vlayer->geometryType() == QGis::NoGeometry )
                    icon = QgsLayerItem::iconTable();
                else
                    icon = QgsLayerItem::iconDefault();
            }

            if ( vlayer && vlayer->isEditable() )
            {
                QPixmap pixmap( icon.pixmap( 16, 16 ) );

                QPainter painter( &pixmap );
                painter.drawPixmap( 0, 0, 16, 16, QgsApplication::getThemePixmap( vlayer->isModified() ? "/mIconEditableEdits.png" : "/mIconEditable.png" ) );
                painter.end();

                icon = QIcon( pixmap );
            }

            return icon;
        }
    }
    else if ( role == Qt::CheckStateRole )
    {
        if ( !testFlag( AllowNodeChangeVisibility ) )
            return QVariant();

        if ( QgsLayerTree::isLayer( node ) )
        {
            QgsLayerTreeLayer* nodeLayer = QgsLayerTree::toLayer( node );
            if ( nodeLayer->layer() && nodeLayer->layer()->type() == QgsMapLayer::VectorLayer )
            {
                if ( qobject_cast<QgsVectorLayer*>( nodeLayer->layer() )->geometryType() == QGis::NoGeometry )
                    return QVariant(); // do not show checkbox for non-spatial tables
            }
            return nodeLayer->isVisible();
        }
        else if ( QgsLayerTree::isGroup( node ) )
        {
            QgsLayerTreeGroup* nodeGroup = QgsLayerTree::toGroup( node );
            return nodeGroup->isVisible();
        }
    }
    else if ( role == Qt::FontRole )
    {
        QFont f( QgsLayerTree::isLayer( node ) ? mFontLayer : ( QgsLayerTree::isGroup( node ) ? mFontGroup : QFont() ) );
        if ( node->customProperty( "embedded" ).toInt() )
            f.setItalic( true );
        if ( index == mCurrentIndex )
            f.setUnderline( true );
        return f;
    }
    else if ( role == Qt::ToolTipRole )
    {
        if ( QgsLayerTree::isLayer( node ) )
        {
            if ( QgsMapLayer* layer = QgsLayerTree::toLayer( node )->layer() )
                return layer->publicSource();
        }
    }

    return QVariant();
}
Exemplo n.º 11
0
  QUrlQuery translateWmtsParamToWmsQueryItem( const QString &request, const QgsWmtsParameters &params,
      const QgsProject *project, QgsServerInterface *serverIface )
  {
#ifndef HAVE_SERVER_PYTHON_PLUGINS
    ( void )serverIface;
#endif

    //defining Layer
    QString layer = params.layer();
    //read Layer
    if ( layer.isEmpty() )
    {
      throw QgsRequestNotWellFormedException( QStringLiteral( "Layer is mandatory" ) );
    }
    //check layer value
    bool wmtsProject = project->readBoolEntry( QStringLiteral( "WMTSLayers" ), QStringLiteral( "Project" ) );
    QStringList wmtsGroupNameList = project->readListEntry( QStringLiteral( "WMTSLayers" ), QStringLiteral( "Group" ) );
    QStringList wmtsLayerIdList = project->readListEntry( QStringLiteral( "WMTSLayers" ), QStringLiteral( "Layer" ) );
    QStringList wmtsLayerIds;
    if ( wmtsProject )
    {
      // Root Layer name
      QString rootLayerId = QgsServerProjectUtils::wmsRootName( *project );
      if ( rootLayerId.isEmpty() )
      {
        rootLayerId = project->title();
      }
      if ( !rootLayerId.isEmpty() )
      {
        wmtsLayerIds << rootLayerId;
      }
    }
    if ( !wmtsGroupNameList.isEmpty() )
    {
      QgsLayerTreeGroup *treeRoot = project->layerTreeRoot();
      for ( const QString &gName : wmtsGroupNameList )
      {
        QgsLayerTreeGroup *treeGroup = treeRoot->findGroup( gName );
        if ( !treeGroup )
        {
          continue;
        }
        QString groupLayerId = treeGroup->customProperty( QStringLiteral( "wmsShortName" ) ).toString();
        if ( groupLayerId.isEmpty() )
        {
          groupLayerId = gName;
        }
        wmtsLayerIds << groupLayerId;
      }
    }
    if ( !wmtsLayerIdList.isEmpty() )
    {
#ifdef HAVE_SERVER_PYTHON_PLUGINS
      QgsAccessControl *accessControl = serverIface->accessControls();
#endif
      for ( const QString &lId : wmtsLayerIdList )
      {
        QgsMapLayer *l = project->mapLayer( lId );
        if ( !l )
        {
          continue;
        }
#ifdef HAVE_SERVER_PYTHON_PLUGINS
        if ( !accessControl->layerReadPermission( l ) )
        {
          continue;
        }
#endif
        QString layerLayerId = l->shortName();
        if ( layerLayerId.isEmpty() )
        {
          layerLayerId = l->name();
        }
        wmtsLayerIds << layerLayerId;
      }
    }
    if ( !wmtsLayerIds.contains( layer ) )
    {
      QString msg = QObject::tr( "Layer '%1' not found" ).arg( layer );
      throw QgsBadRequestException( QStringLiteral( "LayerNotDefined" ), msg );
    }

    //defining Format
    QString format = params.formatAsString();
    //read Format
    if ( format.isEmpty() )
    {
      throw QgsRequestNotWellFormedException( QStringLiteral( "Format is mandatory" ) );
    }

    //defining TileMatrixSet ref
    QString tms_ref = params.tileMatrixSet();
    //read TileMatrixSet
    if ( tms_ref.isEmpty() )
    {
      throw QgsRequestNotWellFormedException( QStringLiteral( "TileMatrixSet is mandatory" ) );
    }

    // verifying TileMatrixSet value
    QList< tileMatrixSetDef > tmsList = getTileMatrixSetList( project, tms_ref );
    if ( tmsList.isEmpty() )
    {
      throw QgsRequestNotWellFormedException( QStringLiteral( "TileMatrixSet is unknown" ) );
    }
    tileMatrixSetDef tms = tmsList[0];
    if ( tms.ref != tms_ref )
    {
      throw QgsRequestNotWellFormedException( QStringLiteral( "TileMatrixSet is unknown" ) );
    }

    //defining TileMatrix idx
    int tm_idx = params.tileMatrixAsInt();
    //read TileMatrix
    if ( tm_idx < 0 || tms.tileMatrixList.count() < tm_idx )
    {
      throw QgsRequestNotWellFormedException( QStringLiteral( "TileMatrix is unknown" ) );
    }
    tileMatrixDef tm = tms.tileMatrixList.at( tm_idx );

    //defining TileRow
    int tr = params.tileRowAsInt();
    //read TileRow
    if ( tr < 0 || tm.row <= tr )
    {
      throw QgsRequestNotWellFormedException( QStringLiteral( "TileRow is unknown" ) );
    }

    //defining TileCol
    int tc = params.tileColAsInt();
    //read TileCol
    if ( tc < 0 || tm.col <= tc )
    {
      throw QgsRequestNotWellFormedException( QStringLiteral( "TileCol is unknown" ) );
    }

    double res = tm.resolution;
    double minx = tm.left + tc * ( tileSize * res );
    double miny = tm.top - ( tr + 1 ) * ( tileSize * res );
    double maxx = tm.left + ( tc + 1 ) * ( tileSize * res );
    double maxy = tm.top - tr * ( tileSize * res );
    QString bbox;
    if ( tms.hasAxisInverted )
    {
      bbox = qgsDoubleToString( miny, 6 ) + ',' +
             qgsDoubleToString( minx, 6 ) + ',' +
             qgsDoubleToString( maxy, 6 ) + ',' +
             qgsDoubleToString( maxx, 6 );
    }
    else
    {
      bbox = qgsDoubleToString( minx, 6 ) + ',' +
             qgsDoubleToString( miny, 6 ) + ',' +
             qgsDoubleToString( maxx, 6 ) + ',' +
             qgsDoubleToString( maxy, 6 );
    }

    QUrlQuery query;
    if ( !params.value( QStringLiteral( "MAP" ) ).isEmpty() )
    {
      query.addQueryItem( QgsServerParameter::name( QgsServerParameter::MAP ), params.value( QStringLiteral( "MAP" ) ) );
    }
    query.addQueryItem( QgsServerParameter::name( QgsServerParameter::SERVICE ), QStringLiteral( "WMS" ) );
    query.addQueryItem( QgsServerParameter::name( QgsServerParameter::VERSION_SERVICE ), QStringLiteral( "1.3.0" ) );
    query.addQueryItem( QgsServerParameter::name( QgsServerParameter::REQUEST ), request );
    query.addQueryItem( QgsWmsParameterForWmts::name( QgsWmsParameterForWmts::LAYERS ), layer );
    query.addQueryItem( QgsWmsParameterForWmts::name( QgsWmsParameterForWmts::STYLES ), QString() );
    query.addQueryItem( QgsWmsParameterForWmts::name( QgsWmsParameterForWmts::CRS ), tms.ref );
    query.addQueryItem( QgsWmsParameterForWmts::name( QgsWmsParameterForWmts::BBOX ), bbox );
    query.addQueryItem( QgsWmsParameterForWmts::name( QgsWmsParameterForWmts::WIDTH ), QStringLiteral( "256" ) );
    query.addQueryItem( QgsWmsParameterForWmts::name( QgsWmsParameterForWmts::HEIGHT ), QStringLiteral( "256" ) );
    query.addQueryItem( QgsWmsParameterForWmts::name( QgsWmsParameterForWmts::FORMAT ), format );
    if ( params.format() == QgsWmtsParameters::Format::PNG )
    {
      query.addQueryItem( QgsWmsParameterForWmts::name( QgsWmsParameterForWmts::TRANSPARENT ), QStringLiteral( "true" ) );
    }
    query.addQueryItem( QgsWmsParameterForWmts::name( QgsWmsParameterForWmts::DPI ), QStringLiteral( "96" ) );

    return query;
  }
Exemplo n.º 12
0
  QList< layerDef > getWmtsLayerList( QgsServerInterface *serverIface, const QgsProject *project )
  {
    QList< layerDef > wmtsLayers;
#ifdef HAVE_SERVER_PYTHON_PLUGINS
    QgsAccessControl *accessControl = serverIface->accessControls();
#else
    ( void )serverIface;
#endif

    // WMTS Project configuration
    bool wmtsProject = project->readBoolEntry( QStringLiteral( "WMTSLayers" ), QStringLiteral( "Project" ) );

    // Root Layer name
    QString rootLayerName = QgsServerProjectUtils::wmsRootName( *project );
    if ( rootLayerName.isEmpty() && !project->title().isEmpty() )
    {
      rootLayerName = project->title();
    }

    if ( wmtsProject && !rootLayerName.isEmpty() )
    {
      layerDef pLayer;
      pLayer.id = rootLayerName;

      if ( !project->title().isEmpty() )
      {
        pLayer.title = project->title();
        pLayer.abstract = project->title();
      }

      //transform the project native CRS into WGS84
      QgsRectangle projRect = QgsServerProjectUtils::wmsExtent( *project );
      QgsCoordinateReferenceSystem projCrs = project->crs();
      QgsCoordinateTransform exGeoTransform( projCrs, wgs84, project );
      try
      {
        pLayer.wgs84BoundingRect = exGeoTransform.transformBoundingBox( projRect );
      }
      catch ( const QgsCsException & )
      {
        pLayer.wgs84BoundingRect = QgsRectangle( -180, -90, 180, 90 );
      }

      // Formats
      bool wmtsPngProject = project->readBoolEntry( QStringLiteral( "WMTSPngLayers" ), QStringLiteral( "Project" ) );
      if ( wmtsPngProject )
        pLayer.formats << QStringLiteral( "image/png" );
      bool wmtsJpegProject = project->readBoolEntry( QStringLiteral( "WMTSJpegLayers" ), QStringLiteral( "Project" ) );
      if ( wmtsJpegProject )
        pLayer.formats << QStringLiteral( "image/jpeg" );

      // Project is not queryable in WMS
      //pLayer.queryable = ( nonIdentifiableLayers.count() != project->count() );
      pLayer.queryable = false;

      wmtsLayers.append( pLayer );
    }

    QStringList wmtsGroupNameList = project->readListEntry( QStringLiteral( "WMTSLayers" ), QStringLiteral( "Group" ) );
    if ( !wmtsGroupNameList.isEmpty() )
    {
      QgsLayerTreeGroup *treeRoot = project->layerTreeRoot();

      QStringList wmtsPngGroupNameList = project->readListEntry( QStringLiteral( "WMTSPngLayers" ), QStringLiteral( "Group" ) );
      QStringList wmtsJpegGroupNameList = project->readListEntry( QStringLiteral( "WMTSJpegLayers" ), QStringLiteral( "Group" ) );

      for ( const QString &gName : wmtsGroupNameList )
      {
        QgsLayerTreeGroup *treeGroup = treeRoot->findGroup( gName );
        if ( !treeGroup )
        {
          continue;
        }

        layerDef pLayer;
        pLayer.id = treeGroup->customProperty( QStringLiteral( "wmsShortName" ) ).toString();
        if ( pLayer.id.isEmpty() )
          pLayer.id = gName;

        pLayer.title = treeGroup->customProperty( QStringLiteral( "wmsTitle" ) ).toString();
        if ( pLayer.title.isEmpty() )
          pLayer.title = gName;

        pLayer.abstract = treeGroup->customProperty( QStringLiteral( "wmsAbstract" ) ).toString();

        QgsRectangle wgs84BoundingRect;
        bool queryable = false;
        double maxScale = 0.0;
        double minScale = 0.0;
        for ( QgsLayerTreeLayer *layer : treeGroup->findLayers() )
        {
          QgsMapLayer *l = layer->layer();
          if ( !l )
          {
            continue;
          }
          //transform the layer native CRS into WGS84
          QgsCoordinateReferenceSystem layerCrs = l->crs();
          QgsCoordinateTransform exGeoTransform( layerCrs, wgs84, project );
          try
          {
            wgs84BoundingRect.combineExtentWith( exGeoTransform.transformBoundingBox( l->extent() ) );
          }
          catch ( const QgsCsException & )
          {
            wgs84BoundingRect.combineExtentWith( QgsRectangle( -180, -90, 180, 90 ) );
          }
          if ( !queryable && l->flags().testFlag( QgsMapLayer::Identifiable ) )
          {
            queryable = true;
          }

          if ( l->hasScaleBasedVisibility() )
          {
            double lMaxScale = l->maximumScale();
            if ( lMaxScale > 0.0 && lMaxScale > maxScale )
            {
              maxScale = lMaxScale;
            }
            double lMinScale = l->minimumScale();
            if ( lMinScale > 0.0 && ( minScale == 0.0 || lMinScale < minScale ) )
            {
              minScale = lMinScale;
            }
          }
        }
        pLayer.wgs84BoundingRect = wgs84BoundingRect;
        pLayer.queryable = queryable;
        pLayer.maxScale = maxScale;
        pLayer.minScale = minScale;

        // Formats
        if ( wmtsPngGroupNameList.contains( gName ) )
          pLayer.formats << QStringLiteral( "image/png" );
        if ( wmtsJpegGroupNameList.contains( gName ) )
          pLayer.formats << QStringLiteral( "image/jpeg" );

        wmtsLayers.append( pLayer );
      }
    }

    QStringList wmtsLayerIdList = project->readListEntry( QStringLiteral( "WMTSLayers" ), QStringLiteral( "Layer" ) );
    QStringList wmtsPngLayerIdList = project->readListEntry( QStringLiteral( "WMTSPngLayers" ), QStringLiteral( "Layer" ) );
    QStringList wmtsJpegLayerIdList = project->readListEntry( QStringLiteral( "WMTSJpegLayers" ), QStringLiteral( "Layer" ) );

    for ( const QString &lId : wmtsLayerIdList )
    {
      QgsMapLayer *l = project->mapLayer( lId );
      if ( !l )
      {
        continue;
      }
#ifdef HAVE_SERVER_PYTHON_PLUGINS
      if ( !accessControl->layerReadPermission( l ) )
      {
        continue;
      }
#endif

      layerDef pLayer;
      pLayer.id = l->name();
      if ( !l->shortName().isEmpty() )
        pLayer.id = l->shortName();
      pLayer.id = pLayer.id.replace( ' ', '_' );

      pLayer.title = l->title();
      pLayer.abstract = l->abstract();

      //transform the layer native CRS into WGS84
      QgsCoordinateReferenceSystem layerCrs = l->crs();
      QgsCoordinateTransform exGeoTransform( layerCrs, wgs84, project );
      try
      {
        pLayer.wgs84BoundingRect = exGeoTransform.transformBoundingBox( l->extent() );
      }
      catch ( const QgsCsException & )
      {
        pLayer.wgs84BoundingRect = QgsRectangle( -180, -90, 180, 90 );
      }

      // Formats
      if ( wmtsPngLayerIdList.contains( lId ) )
        pLayer.formats << QStringLiteral( "image/png" );
      if ( wmtsJpegLayerIdList.contains( lId ) )
        pLayer.formats << QStringLiteral( "image/jpeg" );

      pLayer.queryable = ( l->flags().testFlag( QgsMapLayer::Identifiable ) );

      if ( l->hasScaleBasedVisibility() )
      {
        pLayer.maxScale = l->maximumScale();
        pLayer.minScale = l->minimumScale();
      }
      else
      {
        pLayer.maxScale = 0.0;
        pLayer.minScale = 0.0;
      }

      wmtsLayers.append( pLayer );
    }
    return wmtsLayers;
  }
Exemplo n.º 13
0
void QgsDwgImportDialog::createGroup( QgsLayerTreeGroup *group, const QString &name, const QStringList &layers, bool visible )
{
  QgsLayerTreeGroup *layerGroup = group->addGroup( name );
  QgsDebugMsg( QStringLiteral( " %1" ).arg( name ) ) ;
  Q_ASSERT( layerGroup );

  QString layerFilter;
  if ( !layers.isEmpty() )
  {
    QStringList exprlist;
    const auto constLayers = layers;
    for ( QString layer : constLayers )
    {
      exprlist.append( QStringLiteral( "'%1'" ).arg( layer.replace( QLatin1String( "'" ), QLatin1String( "''" ) ) ) );
    }
    layerFilter = QStringLiteral( "layer IN (%1) AND " ).arg( exprlist.join( QStringLiteral( "," ) ) );
  }

  QgsVectorLayer *l = nullptr;
  QgsSymbol *sym = nullptr;

  l = layer( layerGroup, layerFilter, QStringLiteral( "hatches" ) );
  if ( l )
  {
    QgsSimpleFillSymbolLayer *sfl = new QgsSimpleFillSymbolLayer();
    sfl->setDataDefinedProperty( QgsSymbolLayer::PropertyFillColor, QgsProperty::fromField( QStringLiteral( "color" ) ) );
    sfl->setStrokeStyle( Qt::NoPen );
    sym = new QgsFillSymbol();
    sym->changeSymbolLayer( 0, sfl );
    l->setRenderer( new QgsSingleSymbolRenderer( sym ) );
  }

  l = layer( layerGroup, layerFilter, QStringLiteral( "lines" ) );
  if ( l )
  {
    QgsSimpleLineSymbolLayer *sll = new QgsSimpleLineSymbolLayer();
    sll->setDataDefinedProperty( QgsSymbolLayer::PropertyStrokeColor, QgsProperty::fromField( QStringLiteral( "color" ) ) );
    sll->setPenJoinStyle( Qt::MiterJoin );
    sll->setDataDefinedProperty( QgsSymbolLayer::PropertyStrokeWidth, QgsProperty::fromField( QStringLiteral( "linewidth" ) ) );
    // sll->setUseCustomDashPattern( true );
    // sll->setCustomDashPatternUnit( QgsSymbolV2::MapUnit );
    // sll->setDataDefinedProperty( QgsSymbolLayer::PropertyCustomDash, QgsProperty::fromField( "linetype" ) );
    sym = new QgsLineSymbol();
    sym->changeSymbolLayer( 0, sll );
    sym->setOutputUnit( QgsUnitTypes::RenderMillimeters );
    l->setRenderer( new QgsSingleSymbolRenderer( sym ) );
  }

  l = layer( layerGroup, layerFilter, QStringLiteral( "polylines" ) );
  if ( l )
  {
    sym = new QgsLineSymbol();

    QgsSimpleLineSymbolLayer *sll = new QgsSimpleLineSymbolLayer();
    sll->setDataDefinedProperty( QgsSymbolLayer::PropertyStrokeColor, QgsProperty::fromField( QStringLiteral( "color" ) ) );
    sll->setPenJoinStyle( Qt::MiterJoin );
    sll->setDataDefinedProperty( QgsSymbolLayer::PropertyStrokeWidth, QgsProperty::fromField( QStringLiteral( "width" ) ) );
    sll->setDataDefinedProperty( QgsSymbolLayer::PropertyLayerEnabled, QgsProperty::fromExpression( QStringLiteral( "width>0" ) ) );
    sll->setOutputUnit( QgsUnitTypes::RenderMapUnits );
    // sll->setUseCustomDashPattern( true );
    // sll->setCustomDashPatternUnit( QgsSymbolV2::MapUnit );
    // sll->setDataDefinedProperty( QgsSymbolLayer::PropertyCustomDash, QgsProperty::fromField( "linetype" ) );
    sym->changeSymbolLayer( 0, sll );

    sll = new QgsSimpleLineSymbolLayer();
    sll->setDataDefinedProperty( QgsSymbolLayer::PropertyStrokeColor, QgsProperty::fromField( QStringLiteral( "color" ) ) );
    sll->setPenJoinStyle( Qt::MiterJoin );
    sll->setDataDefinedProperty( QgsSymbolLayer::PropertyStrokeWidth, QgsProperty::fromField( QStringLiteral( "linewidth" ) ) );
    sll->setDataDefinedProperty( QgsSymbolLayer::PropertyLayerEnabled, QgsProperty::fromExpression( QStringLiteral( "width=0" ) ) );
    sll->setOutputUnit( QgsUnitTypes::RenderMillimeters );
    sym->appendSymbolLayer( sll );

    l->setRenderer( new QgsSingleSymbolRenderer( sym ) );
  }

  l = layer( layerGroup, layerFilter, QStringLiteral( "texts" ) );
  if ( l )
  {
    l->setRenderer( new QgsNullSymbolRenderer() );

    QgsTextFormat tf;
    tf.setSizeUnit( QgsUnitTypes::RenderMapUnits );

    QgsPalLayerSettings pls;
    pls.setFormat( tf );

    pls.drawLabels = true;
    pls.fieldName = QStringLiteral( "text" );
    pls.wrapChar = QStringLiteral( "\\P" );

    pls.dataDefinedProperties().setProperty( QgsPalLayerSettings::Size, QgsProperty::fromField( QStringLiteral( "height" ) ) );
    pls.dataDefinedProperties().setProperty( QgsPalLayerSettings::Color, QgsProperty::fromField( QStringLiteral( "color" ) ) );
    pls.dataDefinedProperties().setProperty( QgsPalLayerSettings::MultiLineHeight, QgsProperty::fromExpression( QStringLiteral( "CASE WHEN interlin<0 THEN 1 ELSE interlin*1.5 END" ) ) );
    pls.dataDefinedProperties().setProperty( QgsPalLayerSettings::PositionX, QgsProperty::fromExpression( QStringLiteral( "$x" ) ) );
    pls.dataDefinedProperties().setProperty( QgsPalLayerSettings::PositionY, QgsProperty::fromExpression( QStringLiteral( "$y" ) ) );

    // DXF TEXT
    // vertical: 0 = Base, 1 = Bottom, 2 = Middle, 3 = Top,  default Base
    // horizontal: 0 = Left, 1 = Center, 2 = Right, 3 = Aligned (if Base), 4 = Middle (if Base), default Left

    // DXF MTEXT
    // 1 = Top left;    2 = Top center;    3 = Top right
    // 4 = Middle left; 5 = Middle center; 6 = Middle right
    // 7 = Bottom left; 8 = Bottom center; 9 = Bottom right

    // QGIS Quadrant
    // 0 QuadrantAboveLeft, 1 QuadrantAbove, 2 QuadrantAboveRight,
    // 3 QuadrantLeft,      4 QuadrantOver,  5 QuadrantRight,
    // 6 QuadrantBelowLeft, 7 QuadrantBelow, 8 QuadrantBelowRight,

    pls.dataDefinedProperties().setProperty(
      QgsPalLayerSettings::Hali,
      QgsProperty::fromExpression( QStringLiteral(
                                     "CASE"
                                     " WHEN etype=%1 THEN"
                                     " CASE"
                                     " WHEN textgen % 3=2 THEN 'Center'"
                                     " WHEN textgen % 3=0 THEN 'Right'"
                                     " ELSE 'Left'"
                                     " END"
                                     " ELSE"
                                     " CASE"
                                     " WHEN alignh=1 THEN 'Center'"
                                     " WHEN alignh=2 THEN 'Right'"
                                     " ELSE 'Left'"
                                     " END"
                                     " END"
                                   ).arg( DRW::MTEXT )
                                 )
    );

    pls.dataDefinedProperties().setProperty(
      QgsPalLayerSettings::Vali,
      QgsProperty::fromExpression( QStringLiteral(
                                     "CASE"
                                     " WHEN etype=%1 THEN"
                                     " CASE"
                                     " WHEN textgen<4 THEN 'Top'"
                                     " WHEN textgen<7 THEN 'Half'"
                                     " ELSE 'Bottom'"
                                     " END"
                                     " ELSE"
                                     " CASE"
                                     " WHEN alignv=1 THEN 'Bottom'"
                                     " WHEN alignv=2 THEN 'Half'"
                                     " WHEN alignv=3 THEN 'Top'"
                                     " ELSE 'Base'"
                                     " END"
                                     " END"
                                   ).arg( DRW::MTEXT )
                                 )
    );

    pls.dataDefinedProperties().setProperty( QgsPalLayerSettings::LabelRotation, QgsProperty::fromExpression( QStringLiteral( "360-angle" ) ) );
    pls.dataDefinedProperties().setProperty( QgsPalLayerSettings::AlwaysShow, QgsProperty::fromExpression( QStringLiteral( "1" ) ) );

    l->setLabeling( new QgsVectorLayerSimpleLabeling( pls ) );
    l->setLabelsEnabled( true );
  }

  l = layer( layerGroup, layerFilter, QStringLiteral( "points" ) );
  if ( l )
  {
    // FIXME: use PDMODE?
    l->setRenderer( new QgsNullSymbolRenderer() );
  }

  if ( !cbExpandInserts->isChecked() )
    layer( layerGroup, layerFilter, QStringLiteral( "inserts" ) );

  if ( !layerGroup->children().isEmpty() )
  {
    layerGroup->setExpanded( false );
    layerGroup->setItemVisibilityChecked( visible );
  }
  else
  {
    layerGroup->parent()->takeChild( layerGroup );
    delete layerGroup;
  }
}
Exemplo n.º 14
0
QgsComposition* QgsWMSConfigParser::createPrintComposition( const QString& composerTemplate, QgsMapRenderer* mapRenderer, const QMap< QString, QString >& parameterMap ) const
{
  QList<QgsComposerMap*> composerMaps;
  QList<QgsComposerLegend*> composerLegends;
  QList<QgsComposerLabel*> composerLabels;
  QList<const QgsComposerHtml*> composerHtmls;

  QgsComposition* c = initComposition( composerTemplate, mapRenderer, composerMaps, composerLegends, composerLabels, composerHtmls );
  if ( !c )
  {
    return 0;
  }

  QString dpi = parameterMap.value( "DPI" );
  if ( !dpi.isEmpty() )
  {
    c->setPrintResolution( dpi.toInt() );
  }

  //replace composer map parameters
  Q_FOREACH ( QgsComposerMap* currentMap, composerMaps )
  {
    if ( !currentMap )
    {
      continue;
    }

    QString mapId = "MAP" + QString::number( currentMap->id() );

    QString extent = parameterMap.value( mapId + ":EXTENT" );
    if ( extent.isEmpty() ) //map extent is mandatory
    {
      //remove map from composition if not referenced by the request
      c->removeItem( currentMap ); delete currentMap; continue;
    }

    QStringList coordList = extent.split( "," );
    if ( coordList.size() < 4 )
    {
      c->removeItem( currentMap ); delete currentMap; continue; //need at least four coordinates
    }

    bool xMinOk, yMinOk, xMaxOk, yMaxOk;
    double xmin = coordList.at( 0 ).toDouble( &xMinOk );
    double ymin = coordList.at( 1 ).toDouble( &yMinOk );
    double xmax = coordList.at( 2 ).toDouble( &xMaxOk );
    double ymax = coordList.at( 3 ).toDouble( &yMaxOk );
    if ( !xMinOk || !yMinOk || !xMaxOk || !yMaxOk )
    {
      c->removeItem( currentMap ); delete currentMap; continue;
    }

    QgsRectangle r( xmin, ymin, xmax, ymax );

    //Change x- and y- of extent for WMS 1.3.0 if axis inverted
    QString version = parameterMap.value( "VERSION" );
    if ( version == "1.3.0" && mapRenderer && mapRenderer->destinationCrs().axisInverted() )
    {
      r.invert();
    }
    currentMap->setNewExtent( r );

    //scale
    QString scaleString = parameterMap.value( mapId + ":SCALE" );
    if ( !scaleString.isEmpty() )
    {
      bool scaleOk;
      double scale = scaleString.toDouble( &scaleOk );
      if ( scaleOk )
      {
        currentMap->setNewScale( scale );
      }
    }

    //rotation
    QString rotationString = parameterMap.value( mapId + ":ROTATION" );
    if ( !rotationString.isEmpty() )
    {
      bool rotationOk;
      double rotation = rotationString.toDouble( &rotationOk );
      if ( rotationOk )
      {
        currentMap->setMapRotation( rotation );
      }
    }

    //layers / styles
    QString layers = parameterMap.value( mapId + ":LAYERS" );
    QString styles = parameterMap.value( mapId + ":STYLES" );
    if ( !layers.isEmpty() )
    {
      QStringList layerSet;
      QStringList wmsLayerList = layers.split( ",", QString::SkipEmptyParts );
      QStringList wmsStyleList;

      if ( !styles.isEmpty() )
      {
        wmsStyleList = styles.split( ",", QString::SkipEmptyParts );
      }

      for ( int i = 0; i < wmsLayerList.size(); ++i )
      {
        QString wmsLayer = wmsLayerList.at( i );
        QString styleName;
        if ( wmsStyleList.size() > i )
        {
          styleName = wmsStyleList.at( i );
        }
        
        bool allowCaching = true;
        if ( wmsLayerList.count( wmsLayer ) > 1 )
        {
          allowCaching = false;
        }

        QList<QgsMapLayer*> layerList = mapLayerFromStyle( wmsLayer, styleName, allowCaching );
        int listIndex;
        for ( listIndex = layerList.size() - 1; listIndex >= 0; listIndex-- )
        {
          QgsMapLayer* layer = layerList.at( listIndex );
          if ( layer )
          {
            layerSet.push_back( layer->id() );
          }
        }
      }

      currentMap->setLayerSet( layerSet );
      currentMap->setKeepLayerSet( true );
    }

    //grid space x / y
    currentMap->grid()->setIntervalX( parameterMap.value( mapId + ":GRID_INTERVAL_X" ).toDouble() );
    currentMap->grid()->setIntervalY( parameterMap.value( mapId + ":GRID_INTERVAL_Y" ).toDouble() );
  }
  //update legend
  // if it has an auto-update model
  Q_FOREACH ( QgsComposerLegend* currentLegend, composerLegends )
  {
    if ( !currentLegend )
    {
      continue;
    }

    if ( currentLegend->autoUpdateModel() || currentLegend->legendFilterByMapEnabled() )
    {
      // the legend has an auto-update model or
      // has to be filter by map
      // we will update it with map's layers
      const QgsComposerMap* map = currentLegend->composerMap();
      if ( !map )
      {
        continue;
      }

      // get model and layer tree root of the legend
      QgsLegendModelV2* model = currentLegend->modelV2();
      QgsLayerTreeGroup* root = model->rootGroup();


      // get layerIds find in the layer tree root
      QStringList layerIds = root->findLayerIds();
      // get map layerIds
      QStringList layerSet = map->layerSet();

      // get map scale
      double scale = map->scale();

      // Q_FOREACH layer find in the layer tree
      // remove it if the layer id is not in map layerIds
      Q_FOREACH ( const QString& layerId, layerIds )
      {
        QgsLayerTreeLayer* nodeLayer = root->findLayer( layerId );
        if ( !nodeLayer )
        {
          continue;
        }
        if ( !layerSet.contains( layerId ) )
        {
          qobject_cast<QgsLayerTreeGroup*>( nodeLayer->parent() )->removeChildNode( nodeLayer );
        }
        else
        {
          QgsMapLayer* layer = nodeLayer->layer();
          if ( layer->hasScaleBasedVisibility() )
          {
            if ( layer->minimumScale() > scale )
              qobject_cast<QgsLayerTreeGroup*>( nodeLayer->parent() )->removeChildNode( nodeLayer );
            else if ( layer->maximumScale() < scale )
              qobject_cast<QgsLayerTreeGroup*>( nodeLayer->parent() )->removeChildNode( nodeLayer );
          }
        }
      }
      root->removeChildrenGroupWithoutLayers();
    }
  }