Esempio n. 1
0
void
WhatsHotWidget::infoSystemInfo( Tomahawk::InfoSystem::InfoRequestData requestData, QVariant output )
{
    if ( requestData.caller != s_whatsHotIdentifier )
        return;

    if ( output.isNull() )
    {
        tDebug( LOGVERBOSE ) << Q_FUNC_INFO << "Info came back empty";
        return;
    }

    if ( !output.canConvert< QVariantMap >() )
    {
        tDebug( LOGVERBOSE ) << Q_FUNC_INFO << "WhatsHot: Could not parse output into a map";
        return;
    }

    QVariantMap returnedData = output.toMap();
    switch ( requestData.type )
    {
    case InfoSystem::InfoChartCapabilities:
    {
        QStandardItem *rootItem= m_crumbModelLeft->invisibleRootItem();
        QVariantMap defaults;
        if ( returnedData.contains( "defaults" ) )
            defaults = returnedData.take( "defaults" ).toMap();
        QString defaultSource = returnedData.take( "defaultSource" ).toString();

        foreach ( const QString label, returnedData.keys() )
        {
            QStandardItem *childItem = parseNode( rootItem, label, returnedData[label] );
            rootItem->appendRow(childItem);
        }

        // Set the default source
        // Set the default chart for each source
        for ( int i = 0; i < rootItem->rowCount(); i++ )
        {
            QStandardItem* source = rootItem->child( i, 0 );
            if ( defaultSource.toLower() == source->text().toLower() )
            {
                source->setData( true, Breadcrumb::DefaultRole );
            }

            if ( defaults.contains( source->text().toLower() ) )
            {
                QStringList defaultIndices = defaults[ source->text().toLower() ].toStringList();
                QStandardItem* cur = source;

                foreach( const QString& index, defaultIndices )
                {
                    // Go through the children of the current item, marking the default one as default
                    for ( int k = 0; k < cur->rowCount(); k++ )
                    {
                        if ( cur->child( k, 0 )->text() == index )
                        {
                            cur = cur->child( k, 0 ); // this is the default, drill down into the default to pick the next default
                            cur->setData( true, Breadcrumb::DefaultRole );
                            break;
                        }
                    }
                }
            }
        }

        m_sortedProxy->setSourceModel( m_crumbModelLeft );
        m_sortedProxy->sort( 0, Qt::AscendingOrder );
        ui->breadCrumbLeft->setModel( m_sortedProxy );
        break;
    }

    case InfoSystem::InfoChart:
    {
        if( !returnedData.contains("type") )
            break;
        const QString type = returnedData["type"].toString();
        if( !returnedData.contains(type) )
            break;
        const QString side = requestData.customData["whatshot_side"].toString();
        const QString chartId = requestData.input.value< Tomahawk::InfoSystem::InfoStringHash >().value( "chart_id" );

        m_queuedFetches.remove( chartId );

        ChartDataLoader* loader = new ChartDataLoader();
        loader->setProperty( "chartid", chartId );
        loader->moveToThread( m_workerThread );

        if ( type == "artists" )
        {
            loader->setType( ChartDataLoader::Artist );
            loader->setData( returnedData[ "artists" ].value< QStringList >() );

            connect( loader, SIGNAL( artists( Tomahawk::ChartDataLoader*, QList< Tomahawk::artist_ptr > ) ), this, SLOT( chartArtistsLoaded( Tomahawk::ChartDataLoader*, QList< Tomahawk::artist_ptr > ) ) );

            TreeModel* artistsModel = new TreeModel( ui->artistsViewLeft );
            artistsModel->setMode( InfoSystemMode );
            artistsModel->setStyle( PlayableModel::Collection );

            m_artistModels[ chartId ] = artistsModel;

            if ( m_queueItemToShow == chartId )
                setLeftViewArtists( artistsModel );
        }
        else if ( type == "albums" )
Esempio n. 2
0
void QgsPgTableModel::setSql( const QModelIndex &index, const QString &sql )
{
  if ( !index.isValid() || !index.parent().isValid() )
  {
    return;
  }

  //find out schema name and table name
  QModelIndex schemaSibling = index.sibling( index.row(), dbtmSchema );
  QModelIndex tableSibling = index.sibling( index.row(), dbtmTable );
  QModelIndex geomSibling = index.sibling( index.row(), dbtmGeomCol );

  if ( !schemaSibling.isValid() || !tableSibling.isValid() || !geomSibling.isValid() )
  {
    return;
  }

  QString schemaName = itemFromIndex( schemaSibling )->text();
  QString tableName = itemFromIndex( tableSibling )->text();
  QString geomName = itemFromIndex( geomSibling )->text();

  QList<QStandardItem*> schemaItems = findItems( schemaName, Qt::MatchExactly, dbtmSchema );
  if ( schemaItems.size() < 1 )
  {
    return;
  }

  QStandardItem* schemaItem = schemaItems.at( dbtmSchema );

  int n = schemaItem->rowCount();
  for ( int i = 0; i < n; i++ )
  {
    QModelIndex currentChildIndex = indexFromItem( schemaItem->child( i, dbtmSchema ) );
    if ( !currentChildIndex.isValid() )
    {
      continue;
    }

    QModelIndex currentTableIndex = currentChildIndex.sibling( i, dbtmTable );
    if ( !currentTableIndex.isValid() )
    {
      continue;
    }

    QModelIndex currentGeomIndex = currentChildIndex.sibling( i, dbtmGeomCol );
    if ( !currentGeomIndex.isValid() )
    {
      continue;
    }

    if ( itemFromIndex( currentTableIndex )->text() == tableName && itemFromIndex( currentGeomIndex )->text() == geomName )
    {
      QModelIndex sqlIndex = currentChildIndex.sibling( i, dbtmSql );
      if ( sqlIndex.isValid() )
      {
        itemFromIndex( sqlIndex )->setText( sql );
        break;
      }
    }
  }
}
Esempio n. 3
0
void Project::addFile(QTreeView* treeView, QSortFilterProxyModel* sort, const QString &fileName)
{
    if (_files.contains(fileName))
        return;
    QFileInfo fi(fileName);
    QString absFileName = fi.absoluteFilePath();
    QString relFileName;
    if (!projectRoot.isEmpty()) {
        QDir projectDir(QFileInfo(projectRoot).absoluteDir());
        relFileName = projectDir.relativeFilePath(absFileName);
    } else {
        relFileName = absFileName;
    }

    QStringList path = relFileName.split(QDir::separator());
    while (path.first().isEmpty()) {
        path.pop_front();
    }
    QStandardItem* curItem;
    bool isMiniZinc = true;
    bool isCoursera = false;
    //if (fi.suffix()=="mzn") {
    //    curItem = mzn;
    if (fi.suffix()=="zinc") {
        curItem = zinc;
    } else if (fi.suffix()=="dzn") {
        curItem = dzn;
    } else if (fi.suffix()=="fzn") {
        return;
    } else {
        curItem = other;
        isMiniZinc = false;
        isCoursera = fi.completeBaseName()=="_coursera";
    }

    if (isCoursera) {
        if (_courseraProject) {
            QMessageBox::warning(treeView,"Zinc IDE",
                                "Cannot add second Coursera options file",
                                QMessageBox::Ok);
            return;
        }
        QFile metadata(absFileName);
        if (!metadata.open(QIODevice::ReadOnly)) {
            QMessageBox::warning(treeView,"Zinc IDE",
                                 "Cannot open Coursera options file",
                                 QMessageBox::Ok);
            return;
        }
        QTextStream in(&metadata);
        CourseraProject* cp = new CourseraProject;
        if (in.status() != QTextStream::Ok) {
            delete cp;
            goto coursera_done;
        }
        cp->course = in.readLine();
        if (in.status() != QTextStream::Ok) {
            delete cp;
            goto coursera_done;
        }
        cp->checkpwdSid= in.readLine();
        if (in.status() != QTextStream::Ok) {
            delete cp;
            goto coursera_done;
        }
        cp->name = in.readLine();
        QString nSolutions_s = in.readLine();
        int nSolutions = nSolutions_s.toInt();
        for (int i=0; i<nSolutions; i++) {
            if (in.status() != QTextStream::Ok) {
                delete cp;
                goto coursera_done;
            }
            QString line = in.readLine();
            QStringList tokens = line.split(", ");
            if (tokens.size() < 5) {
                delete cp;
                goto coursera_done;
            }
            CourseraItem item(tokens[0].trimmed(),tokens[1].trimmed(),tokens[2].trimmed(),
                              tokens[3].trimmed(),tokens[4].trimmed());
            cp->problems.append(item);
        }
        if (in.status() != QTextStream::Ok) {
            delete cp;
            goto coursera_done;
        }
        nSolutions_s = in.readLine();
        nSolutions = nSolutions_s.toInt();
        for (int i=0; i<nSolutions; i++) {
            if (in.status() != QTextStream::Ok) {
                delete cp;
                goto coursera_done;
            }
            QString line = in.readLine();
            QStringList tokens = line.split(", ");
            if (tokens.size() < 3) {
                delete cp;
                goto coursera_done;
            }
            CourseraItem item(tokens[0].trimmed(),tokens[1].trimmed(),tokens[2].trimmed());
            cp->models.append(item);
        }
        _courseraProject = cp;
        ui->actionSubmit_to_Coursera->setVisible(true);
    }
coursera_done:

    setModified(true, true);
    QStandardItem* prevItem = curItem;
    treeView->expand(sort->mapFromSource(curItem->index()));
    curItem = curItem->child(0);
    int i=0;
    while (curItem != NULL) {
        if (curItem->text() == path.first()) {
            path.pop_front();
            treeView->expand(sort->mapFromSource(curItem->index()));
            prevItem = curItem;
            curItem = curItem->child(0);
            i = 0;
        } else {
            i += 1;
            curItem = curItem->parent()->child(i);
        }
    }
    for (int i=0; i<path.size(); i++) {
        QStandardItem* newItem = new QStandardItem(path[i]);
        prevItem->appendRow(newItem);
        if (i<path.size()-1) {
            newItem->setIcon(QIcon(":/icons/images/folder.png"));
        } else {
            _files.insert(absFileName,newItem->index());
            if (isMiniZinc) {
                newItem->setIcon(QIcon(":/images/mznicon.png"));
            }
        }
        treeView->expand(sort->mapFromSource(newItem->index()));
        prevItem = newItem;
    }
}
Esempio n. 4
0
/*!
   \brief TreeModel::slotItemChanged
 */
void TreeModel::slotItemChanged( QStandardItem* item )
{
    // Item should always be there.
    Q_ASSERT( item );

    // Get property name.
    QStandardItem* propNameItem = QStandardItemModel::item( item->row(), 0 );
    Q_ASSERT( propNameItem );
    QString propertyName;
    if ( item->parent() &&
         item->parent() != invisibleRootItem() )
    {
        propertyName = item->parent()->text();
    }
    else
    {
        propertyName = propNameItem->text();
    }

    int propertyIndex = mp_object->metaObject()->indexOfProperty( propertyName.toStdString().c_str() );
    QMetaProperty metaProperty  = mp_object->metaObject()->property( propertyIndex );
    QVariant value = mp_object->property( metaProperty.name() );
    if ( metaProperty.isWritable() )
    {
        // Interupt connection
        ConnectionHelper connectionHelper( mp_object,
                                           metaProperty.notifySignal(),
                                           this,
                                           m_updateSlot );
        if ( value.canConvert<QVector3D>() )
        {
            QVector3D vec;
            vec.setX( propNameItem->child( 0, 0 )->data( Qt::EditRole ).toFloat() );
            vec.setY( propNameItem->child( 0, 1 )->data( Qt::EditRole ).toFloat() );
            vec.setZ( propNameItem->child( 0, 2 )->data( Qt::EditRole ).toFloat() );

            mp_object->setProperty( metaProperty.name(), QVariant::fromValue( vec ) );
        }
        else if ( value.canConvert<cv::Size>() )
        {
            cv::Size size;
            size.width = propNameItem->child( 0, 0 )->data( Qt::EditRole ).toInt();
            size.height= propNameItem->child( 0, 1 )->data( Qt::EditRole ).toInt();

            mp_object->setProperty( metaProperty.name(), QVariant::fromValue( size ) );
        }
        else if ( value.canConvert<FixedPropertyVector>() )
        {
            int count = propNameItem->rowCount();

            FixedPropertyVector vec ( count );
            for ( int i = 0; i < vec.size(); ++i )
            {
                vec.setData( i, propNameItem->child( i, 1 )->data( Qt::EditRole).toFloat() );
            }
            mp_object->setProperty( metaProperty.name(), QVariant::fromValue( vec ) );
        }
        else
        {
            // case : Standardprocedure
            mp_object->setProperty( metaProperty.name(), item->data( Qt::EditRole ) );
        }
    }
}
Esempio n. 5
0
void ResultsTree::RefreshTree()
{
    mVisibleErrors = false;
    //Get the amount of files in the tree
    int filecount = mModel.rowCount();

    for (int i = 0; i < filecount; i++) {
        //Get file i
        QStandardItem *file = mModel.item(i, 0);
        if (!file) {
            continue;
        }

        //Get the amount of errors this file contains
        int errorcount = file->rowCount();

        //By default it shouldn't be visible
        bool show = false;

        for (int j = 0; j < errorcount; j++) {
            //Get the error itself
            QStandardItem *child = file->child(j, 0);
            if (!child) {
                continue;
            }

            //Get error's user data
            QVariant userdata = child->data();
            //Convert it to QVariantMap
            QVariantMap data = userdata.toMap();

            //Check if this error should be hidden
            bool hide = (data["hide"].toBool() || !mShowSeverities.isShown(ShowTypes::VariantToShowType(data["severity"])));

            //If specified, filter on summary, message, filename, and id
            if (!hide && !mFilter.isEmpty()) {
                if (!data["summary"].toString().contains(mFilter, Qt::CaseInsensitive) &&
                    !data["message"].toString().contains(mFilter, Qt::CaseInsensitive) &&
                    !data["file"].toString().contains(mFilter, Qt::CaseInsensitive) &&
                    !data["id"].toString().contains(mFilter, Qt::CaseInsensitive)) {
                    hide = true;
                }
            }

            if (!hide) {
                mVisibleErrors = true;
            }

            //Hide/show accordingly
            setRowHidden(j, file->index(), hide);

            //If it was shown then the file itself has to be shown as well
            if (!hide) {
                show = true;
            }
        }

        //Hide the file if its "hide" attribute is set
        if (file->data().toMap()["hide"].toBool()) {
            show = false;
        }

        //Show the file if any of it's errors are visible
        setRowHidden(i, QModelIndex(), !show);
    }
}
Esempio n. 6
0
QSizeF QgsComposerLegend::paintAndDetermineSize( QPainter* painter )
{
  QSizeF size;
  double maxXCoord = 0;



  //go through model...
  QStandardItem* rootItem = mLegendModel.invisibleRootItem();
  if ( !rootItem )
  {
    return size;
  }


  if ( painter )
  {
    painter->save();
    drawBackground( painter );
    painter->setPen( QPen( QColor( 0, 0, 0 ) ) );
  }

  int numLayerItems = rootItem->rowCount();
  QStandardItem* currentLayerItem = 0;
  double currentYCoordinate = mBoxSpace;

  //font metrics

  //draw title
  currentYCoordinate += fontAscentMillimeters( mTitleFont );
  if ( painter )
  {
    painter->setPen( QColor( 0, 0, 0 ) );
    drawText( painter, mBoxSpace, currentYCoordinate, mTitle, mTitleFont );
  }


  maxXCoord = 2 * mBoxSpace + textWidthMillimeters( mTitleFont, mTitle );

  double currentItemMaxX = 0; //maximum x-coordinate for current item
  for ( int i = 0; i < numLayerItems; ++i )
  {
    currentLayerItem = rootItem->child( i );
    QgsComposerLegendItem* currentLegendItem = dynamic_cast<QgsComposerLegendItem*>( currentLayerItem );
    if ( currentLegendItem )
    {
      QgsComposerLegendItem::ItemType type = currentLegendItem->itemType();
      if ( type == QgsComposerLegendItem::GroupItem )
      {
        drawGroupItem( painter, dynamic_cast<QgsComposerGroupItem*>( currentLegendItem ), currentYCoordinate, currentItemMaxX );
        maxXCoord = qMax( maxXCoord, currentItemMaxX );
      }
      else if ( type == QgsComposerLegendItem::LayerItem )
      {
        drawLayerItem( painter, dynamic_cast<QgsComposerLayerItem*>( currentLegendItem ), currentYCoordinate, currentItemMaxX );
        maxXCoord = qMax( maxXCoord, currentItemMaxX );
      }
    }
  }

  currentYCoordinate += mBoxSpace;

  size.setHeight( currentYCoordinate );
  size.setWidth( maxXCoord );

  //adjust box if width or height is to small
  if ( painter && currentYCoordinate > rect().height() )
  {
    setSceneRect( QRectF( transform().dx(), transform().dy(), rect().width(), currentYCoordinate ) );
  }
  if ( painter && maxXCoord > rect().width() )
  {
    setSceneRect( QRectF( transform().dx(), transform().dy(), maxXCoord, rect().height() ) );
  }

  if ( painter )
  {
    painter->restore();

    //draw frame and selection boxes if necessary
    drawFrame( painter );
    if ( isSelected() )
    {
      drawSelectionBoxes( painter );
    }
  }

  return size;
}
Esempio n. 7
0
void iA3DLabelledVolumeVis::multiClassRendering( QList<QColor> const & classColors, QStandardItem* rootItem, double alpha )
{
	double backAlpha = 0.00005;
	double backRGB[3];
	backRGB[0] = classColors.at(0).redF();
	backRGB[1] = classColors.at(0).greenF();
	backRGB[2] = classColors.at(0).blueF();

	double red = 0.0;
	double green = 0.0;
	double blue = 0.0;
	int CID = 0;

	// clear existing points
	oTF->RemoveAllPoints();
	cTF->RemoveAllPoints();

	// set background opacity and color
	oTF->ClampingOff();
	cTF->ClampingOff();

	// Iterate through all classes to render, starting with 0 unclassified, 1 Class1,...
	for (int i = 0; i < classColors.size(); i++)
	{
		red   = classColors.at(i).redF();
		green = classColors.at(i).greenF();
		blue  = classColors.at(i).blueF();

		QStandardItem *item = rootItem->child(i, 0);
		int itemL = item->rowCount();

		// Class has no objects, proceed with next class
		if (!itemL)
			continue;

		int hid = 0, next_hid = 1;
		bool starting = false;

		for (int j = 0; j < itemL; ++j)
		{
			hid = item->child(j, 0)->text().toInt();

			if ((j + 1) < itemL)
			{
				next_hid = item->child(j + 1, 0)->text().toInt();
			}
			else
			{
				if (starting)
				{
					oTF->AddPoint(hid, alpha, 0.5, 1.0);
					oTF->AddPoint(hid + 0.3, backAlpha, 0.5, 1.0);
					cTF->AddRGBPoint(hid, red, green, blue, 0.5, 1.0);
					cTF->AddRGBPoint(hid + 0.3, backRGB[0], backRGB[1], backRGB[2], 0.5, 1.0);
					break;
				}
				else
				{
					oTF->AddPoint(hid - 0.5, backAlpha, 0.5, 1.0);
					oTF->AddPoint(hid, alpha, 0.5, 1.0);
					cTF->AddRGBPoint(hid - 0.5, backRGB[0], backRGB[1], backRGB[2], 0.5, 1.0);
					cTF->AddRGBPoint(hid, red, green, blue, 0.5, 1.0);
					oTF->AddPoint(hid + 0.3, backAlpha, 0.5, 1.0);
					cTF->AddRGBPoint(hid + 0.3, backRGB[0], backRGB[1], backRGB[2], 0.5, 1.0);
					break;
				}
			}

			//Create one single tooth
			if (next_hid > hid + 1 && !starting)
			{
				oTF->AddPoint(hid - 0.5, backAlpha, 0.5, 1.0);
				oTF->AddPoint(hid, alpha, 0.5, 1.0);
				oTF->AddPoint(hid + 0.3, backAlpha, 0.5, 1.0);
				cTF->AddRGBPoint(hid - 0.5, backRGB[0], backRGB[1], backRGB[2], 0.5, 1.0);
				cTF->AddRGBPoint(hid, red, green, blue, 0.5, 1.0);
				cTF->AddRGBPoint(hid + 0.3, backRGB[0], backRGB[1], backRGB[2], 0.5, 1.0);
			}
			else if (next_hid == hid + 1 && !starting)
			{
				starting = true;
				oTF->AddPoint(hid - 0.5, backAlpha, 0.5, 1.0);
				oTF->AddPoint(hid, alpha, 0.5, 1.0);
				cTF->AddRGBPoint(hid - 0.5, backRGB[0], backRGB[1], backRGB[2], 0.5, 1.0);
				cTF->AddRGBPoint(hid, red, green, blue, 0.5, 1.0);
			}
			else if (next_hid == hid + 1 && starting)
				continue;

			else if (next_hid > hid + 1 && starting)
			{
				starting = false;
				oTF->AddPoint(hid, alpha, 0.5, 1.0);
				oTF->AddPoint(hid + 0.3, backAlpha, 0.5, 1.0);
				cTF->AddRGBPoint(hid, red, green, blue, 0.5, 1.0);
				cTF->AddRGBPoint(hid + 0.3, backRGB[0], backRGB[1], backRGB[2], 0.5, 1.0);
			}
		}

		if ( hid < m_objectTable->GetNumberOfRows() )
		{
			oTF->AddPoint(m_objectTable->GetNumberOfRows() + 0.3, backAlpha, 0.5, 1.0);
			cTF->AddRGBPoint(m_objectTable->GetNumberOfRows() + 0.3, backRGB[0], backRGB[1], backRGB[2], 0.5, 1.0);
		}
	}
	updateRenderer();
}
Esempio n. 8
0
void ParseTreeLablerForm::selectionChangedSlot(const QItemSelection & /*newSelection*/, const QItemSelection & /*oldSelection*/)
{
    //get the text of the selected item
    const QModelIndex index = widget.treeView->selectionModel()->currentIndex();
    QString selectedText = index.data(Qt::DisplayRole).toString();
    string name = getCppString(selectedText);
    QStandardItem *parNode = nameToTreeNode[name];
    int numChildren = parNode->rowCount();
        segNumToColor.clear();
        Node nd(name);
            if (nd.type == "Terminal")
            {
                segNumToColor[nd.id] = randColor();
            }
        colorMapTableModel->clearAll();
    for (int i = 0; i < numChildren; i++)
    {
        QStandardItem *child = parNode->child(i, 0);
                        


        queue<QStandardItem *> bfsQueue;
        float color = randColor();
                        ColorRGB colorRGB(color);
                        colorMapTableModel->addItem(getCppString(child->text()),QColor(colorRGB.r*255,colorRGB.g*255,colorRGB.b*255));
        bfsQueue.push(child);
        //boost::random::uniform_int_distribution<> randSix(0,5);
        // distribution that maps to 1..6
        // see random number distributions
        while (!bfsQueue.empty())
        {
            QStandardItem *curNode = bfsQueue.front();
            bfsQueue.pop();
            int numChildren = curNode->rowCount();
            string parName = getCppString(curNode->text());
            //cout << "selseg:" << parName.substr(0, 10) << endl;
            //cout << "selseg:" << "Terminal__" << endl;
            
            Node ndp(parName);

            if (ndp.type == "Terminal")
            {

                segNumToColor[ndp.id] = color;
                continue;
            }
            
            //cout << parName << endl;

            for (int i = 0; i < numChildren; i++)
            {
                QStandardItem *child = curNode->child(i, 0);
              //  cout << "child:" << getCppString(child->text()) << endl;
                bfsQueue.push(child);
            }

        }
    }
    colorSegs(segNumToColor, true);
    updatePCDVis();
    
     
 }
Esempio n. 9
0
void StitcherWorkspace::onOptimizeGeometryClicked() {
    geometrically_constrained_system * gc = geometrically_constrained_system_alloc();

    /* create positioned images */
    QMap<ImageItem *, positioned_image *> pos_image_map;
    QList<QGraphicsItem *> graphicsItems = _stitcherView->items();
    for(int i = 0; i < graphicsItems.size(); i++) {
        if(ImageItem * item = qgraphicsitem_cast<ImageItem *>(graphicsItems[i])) {
            positioned_image * p = create_positioned_image(item->getImage());
            set_image_position(p,DeltaX,item->dx());
            if(!item->dxLocked()) {
                geometrically_constrained_system_add_variable(gc,create_geometry_variable(p,DeltaX));
            }
            set_image_position(p,DeltaY,item->dy());
            if(!item->dyLocked()) {
                geometrically_constrained_system_add_variable(gc,create_geometry_variable(p,DeltaY));
            }
            set_image_position(p,Zoom,1.0/item->dz());
            if(!item->dzLocked()) {
                geometrically_constrained_system_add_variable(gc,create_geometry_variable(p,Zoom));
            }

            set_image_position(p,Theta,item->theta());
            if(!item->thetaLocked()) {
                geometrically_constrained_system_add_variable(gc,create_geometry_variable(p,Theta));
            }
            set_image_position(p,Alpha,item->alpha());
            if(!item->alphaLocked()) {
                geometrically_constrained_system_add_variable(gc,create_geometry_variable(p,Alpha));
            }

            pos_image_map.insert(item,p);
        }
    }


    QStandardItemModel * model = qobject_cast<QStandardItemModel *>(constraintsTree->model());
    int total_points = 0;
    for(int i = 0; i<model->rowCount(); i++) {

        QStandardItem * it = model->item(i,0);
        geometric_constraint c =  geometric_constraint_init((GeometryConstraintType)it->data(Qt::UserRole + 3).toInt(),0);
        QList<QVariant> item_details = it->data(Qt::UserRole + 1).value<QList<QVariant> >();
        QList<QVariant> point_details = it->data(Qt::UserRole + 2).value<QList<QVariant> >();
        total_points += item_details.size();
        for(int i = 0; i<item_details.size(); i++) {
            ImageItem * item = item_details[i].value<ImageItem *>();
            QPointF pos = point_details[i].value<QPointF>();
            positioned_image * a = pos_image_map.value(item);
            control_point cp = create_control_point(a,pos.x(),pos.y());
            geometric_constraint_add_point(&c,cp);
        }
        geometrically_constrained_system_add_constraint(gc,c);
    }
    if(total_points < gc->n_variables+gc->n_constraints) {
        QMessageBox::warning(this,"Geometry Optimization","<p>Too few control points."
                             " The number of control points must be equal or greater to the degrees of freedom.</p>"
                             "<p>Optimization aborted!</p>");
        return ;
    }
    if(model->rowCount()) {
        geometry_contraint_minimizer(gc);
    }
    _stitcherView->clearConstraintFits();
    for(int i = 0; i<model->rowCount(); i++) {
        QStandardItem * it = model->item(i,0);
        for(int j = 0; j<it->rowCount()-1; j++) {
            it->child(j,1)->setText(QString("%0").arg(gc->constraints[i].error[j]));
        }
        it->child(it->rowCount()-1,1)->setText(QString("%0").arg(gc->constraints[i].best_fit));
        _stitcherView->drawConstraintFit(gc);
    }

    for(int i = 0; i<gc->n_variables; i++) {
        ImageItem * item = pos_image_map.keys(gc->variables[i].parent).first();
        if(gc->variables[i].type == DeltaX) {
            item->setDx(gc->variables[i].parent->pos[DeltaX]);
        }
        if(gc->variables[i].type == DeltaY) {
            item->setDy(gc->variables[i].parent->pos[DeltaY]);
        }
        if(gc->variables[i].type == Zoom) {
            item->setDz(1.0/gc->variables[i].parent->pos[Zoom]);
        }
        if(gc->variables[i].type == Theta) {
            item->setTheta(gc->variables[i].parent->pos[Theta]);
        }
        if(gc->variables[i].type == Alpha) {
            item->setAlpha(gc->variables[i].parent->pos[Alpha]);
        }
    }
    loadGeometry();
}
void QgsDbTableModel::setGeometryTypesForTable( const QString& schema, const QString& table, const QString& attribute, const QString& type )
{
  bool typeIsEmpty = type.isEmpty(); //true means the table has no valid geometry entry and the item for this table should be removed
  QStringList typeList = type.split( "," );

  //find schema item and table item
  QStandardItem* schemaItem;
  QList<QStandardItem*> schemaItems = findItems( schema, Qt::MatchExactly, 0 );

  if ( schemaItems.size() < 1 )
  {
    return;
  }
  schemaItem = schemaItems.at( 0 );
  int numChildren = schemaItem->rowCount();

  QModelIndex currentChildIndex;
  QModelIndex currentTableIndex;
  QModelIndex currentTypeIndex;
  QModelIndex currentGeomColumnIndex;

  for ( int i = 0; i < numChildren; ++i )
  {
    currentChildIndex = indexFromItem( schemaItem->child( i, 0 ) );
    if ( !currentChildIndex.isValid() )
    {
      continue;
    }
    currentTableIndex = currentChildIndex.sibling( i, 1 );
    currentTypeIndex = currentChildIndex.sibling( i, 2 );
    currentGeomColumnIndex = currentChildIndex.sibling( i, 3 );
    QString geomColText = itemFromIndex( currentGeomColumnIndex )->text();

    if ( !currentTypeIndex.isValid() || !currentTableIndex.isValid() || !currentGeomColumnIndex.isValid() )
    {
      continue;
    }

    if ( itemFromIndex( currentTableIndex )->text() == table &&
         ( geomColText == attribute || geomColText.startsWith( attribute + " AS " ) ) )
    {
      if ( typeIsEmpty )
      {
        removeRow( i, indexFromItem( schemaItem ) );
        return;
      }

      QGis::WkbType wkbType = qgisTypeFromDbType( typeList.at( 0 ) );
      QIcon myIcon = iconForType( wkbType );
      itemFromIndex( currentTypeIndex )->setText( typeList.at( 0 ) ); //todo: add other rows
      itemFromIndex( currentTypeIndex )->setIcon( myIcon );
      if ( !geomColText.contains( " AS " ) )
      {
        itemFromIndex( currentGeomColumnIndex )->setText( geomColText + " AS " + typeList.at( 0 ) );
      }

      for ( int j = 1; j < typeList.size(); ++j )
      {
        //todo: add correct type
        addTableEntry( typeList.at( j ), schema, table, geomColText + " AS " + typeList.at( j ), "" );
      }
    }
  }
}