Exemplo n.º 1
0
void Sonos::loadEmptyModels()
{
  QList<QPair<ListModel*, SONOS::LockGuard> > left;
  {
    SONOS::Locked<ManagedContents>::pointer mc = m_library.Get();
    for (ManagedContents::iterator it = mc->begin(); it != mc->end(); ++it)
      if (!it->model->m_loaded)
        left.push_back(qMakePair(it->model, SONOS::LockGuard(it->model->m_lock)));
  }
  emit loadingStarted();
  if (!left.empty())
  {
    while (!left.isEmpty())
    {
      QPair<ListModel*, SONOS::LockGuard> item = left.front();
      item.first->load();
      left.pop_front();
    }
  }
  emit loadingFinished();
}
Exemplo n.º 2
0
void TestPJobFile::readParameterCombination(){
	createTestParametercombinationFile("testReadParameterCombination.xml");
	QList<PJobFileParameter> parameters = PJobFile::readParameterCombination("testReadParameterCombination.xml");
	QFile::remove("testReadParameterCombination.xml");

	QCOMPARE(parameters.size(), 2);

	PJobFileParameter p1 = parameters.front();
	parameters.pop_front();
	PJobFileParameter p2 = parameters.front();

	QCOMPARE(p1.name(), QString("length"));
	QCOMPARE(p1.isVariation(), false);
	QCOMPARE(p1.value(), 100.);

	QCOMPARE(p2.name(), QString("power"));
	QCOMPARE(p2.isVariation(), true);
	QCOMPARE(p2.minValue(), 1.);
	QCOMPARE(p2.maxValue(), 15.);
	QCOMPARE(p2.step(), 1.);
}
Exemplo n.º 3
0
void TreeModel::clear()
{
  if(_rootItem->childCount())
  {
    QList<TreeItem*> items = QList<TreeItem*>();
    QList<TreeItem*> del = QList<TreeItem*>();

    items << _rootItem;
    del   << _rootItem;
    while(items.count()) {
      
      TreeItem* parent = items.first();
      
      for(int i = 0; i < parent->childCount(); i++) {
        
        del   << parent->child(i);
        items << parent->child(i);
      }
      
      items.pop_front();
      
    }

    // удаляем начиная с конца, т.е. сначала удаляем наследников, потом, 
    // поднимаясь наверх - предков, пока не дойдем до rootItem
    beginResetModel();

    while(1) {
      
//      qDebug() << del.last()->data(0).toString();
      del.last()->removeChildren(0, del.last()->childCount());
      if(_rootItem == del.last()) break;
      del.pop_back();
    }
//    rootItem->removeChildren(0, 3/*rootItem->childCount()*/); //! !!!!!!!!!
    endResetModel();
    
  }
}
Exemplo n.º 4
0
void TestPJobFile::readResultDefinitions(){
	createTestResultDefinitions("testReadResultDefinitions.xml");
	QList<PJobResultFile> resultFiles = PJobFile::readResultDefintions("testReadResultDefinitions.xml");
	QFile::remove("testReadResultDefinitions.xml");
	
	QCOMPARE(resultFiles.size(), 1);

	PJobResultFile p = resultFiles.front();
	QList<PJobResult> results = p.results();

	QCOMPARE(p.filename(), QString("ParameterVariation.txt"));
	QCOMPARE(results.size(), 2);

	PJobResult r1  = results.front();
	results.pop_front();
	PJobResult r2 = results.front();

	QCOMPARE(r1.name(), QString("EOP"));
	QCOMPARE(r1.unit(), QString(""));
	QCOMPARE(r2.name(), QString("Q"));
	QCOMPARE(r2.unit(), QString("dB"));
}
Exemplo n.º 5
0
void TestPJobFile::readParameterDefinitions(){
	createTestParameterdefinitionFile("testReadParameterDefinitions.xml");
	QList<PJobFileParameterDefinition> parameters = PJobFile::readParameterDefinitions("testReadParameterDefinitions.xml");
	QFile::remove("testReadParameterDefinitions.xml");

	QCOMPARE(parameters.size(), 2);

	PJobFileParameterDefinition p1 = parameters.front();
	parameters.pop_front();
	PJobFileParameterDefinition p2 = parameters.front();

	QCOMPARE(p1.name(), QString("length"));
	QCOMPARE(p1.defaultValue(), 100.);
	QCOMPARE(p1.hasMinValue(), false);
	QCOMPARE(p1.hasMaxValue(), false);

	QCOMPARE(p2.name(), QString("power"));
	QCOMPARE(p2.defaultValue(), 5.);
	QCOMPARE(p2.hasMinValue(), true);
	QCOMPARE(p2.hasMaxValue(), true);
	QCOMPARE(p2.minValue(), 1.);
	QCOMPARE(p2.maxValue(), 15.);
}
Exemplo n.º 6
0
	QModelIndex cast( NifModel * nif, const QModelIndex & index ) override final
	{
		QModelIndex iData = getStripsData( nif, index );
		QModelIndex iLength = nif->getIndex( iData, "Strip Lengths" );
		QModelIndex iPoints = nif->getIndex( iData, "Points" );

		if ( !( iLength.isValid() && iPoints.isValid() ) )
			return index;

		QList<QVector<quint16> > strips;

		for ( int r = 0; r < nif->rowCount( iPoints ); r++ )
			strips += nif->getArray<quint16>( iPoints.child( r, 0 ) );

		if ( strips.isEmpty() )
			return index;

		QVector<quint16> strip = strips.first();
		strips.pop_front();

		for ( const QVector<quint16>& s : strips ) {
			// TODO: optimize this
			if ( strip.count() & 1 )
				strip << strip.last() << s.first() << s.first() << s;
			else
				strip << strip.last() << s.first() << s;
		}

		nif->set<int>( iData, "Num Strips", 1 );
		nif->updateArray( iLength );
		nif->set<int>( iLength.child( 0, 0 ), strip.size() );
		nif->updateArray( iPoints );
		nif->updateArray( iPoints.child( 0, 0 ) );
		nif->setArray<quint16>( iPoints.child( 0, 0 ), strip );

		return index;
	}
Exemplo n.º 7
0
//-----------------------------------------------------------
CenaObjetos::~CenaObjetos(void)
{
 QGraphicsItemGroup *item=NULL;
 QList<QGraphicsItem *> itens;
 TipoObjetoBase tipos[]={ OBJETO_RELACAO, OBJETO_CAIXA_TEXTO,
                          OBJETO_VISAO, OBJETO_TABELA };
 unsigned i;

 this->removeItem(ret_selecao);
 this->removeItem(linha_rel);

 //Remove os objetos em ordem conforme o vetor tipos[]
 for(i=0; i < 4; i++)
 {
  itens=this->items();

  while(!itens.isEmpty())
  {
   //Obtém o item e já tentando convertê-lo para QGraphicsItemGroup
   item=dynamic_cast<QGraphicsItemGroup *>(itens.front());
      /* Caso o objeto seja um grupo de itens e possa ser convertido para uma das
      classes OGRelacionamento, OGTabela, OGCaixaTexto ou OGVisao, significa que
      o item pode ser removido */
   if(item && !item->parentItem() &&
      ((dynamic_cast<OGRelacionamento *>(item) && tipos[i]==OBJETO_RELACAO) ||
       (dynamic_cast<OGCaixaTexto *>(item) && tipos[i]==OBJETO_CAIXA_TEXTO) ||
       (dynamic_cast<OGVisao *>(item) && tipos[i]==OBJETO_VISAO) ||
       (dynamic_cast<OGTabela *>(item) && tipos[i]==OBJETO_TABELA)))

   {
    this->removeItem(item);
   }

   itens.pop_front();
  }
 }
}
Exemplo n.º 8
0
    void DialogDistance::selectObjects() {
  
      static bool select_allowed = true;

      if (select_allowed == false)
        return;

      QList<QListWidgetItem*> selectedItems = objectList->selectedItems();

      if (selectedItems.size() < 2) 
        return;
  
      select_allowed = false;

      while (selectedItems.size() > 2) {
        selectedItems.front()->setSelected(false);
        selectedItems.pop_front();
      }

      selectedNodes.clear();
      selectedJoints.clear();

      for (unsigned int i = 0 ; i < (unsigned int)selectedItems.size(); i++) {
        int m = selectedItems[i]->text().indexOf(" ");
        int n = selectedItems[i]->text().indexOf(":");
        unsigned long object_id = selectedItems[i]->text().mid(m, n-m).toULong();
        if (selectedItems[i]->text().left(m) == "Node") 
          selectedNodes.push_back(object_id);
        else 
          selectedJoints.push_back(object_id);
      }

      updateProperties();
 
      select_allowed = true;
    }
Exemplo n.º 9
0
void ActorEditTool::selectActor(wt::ASceneActor* actor){
	if(mState == eSTATE_NORMAL){
		if(mSelectedActor){
			mSelectedActor->setBoundingBoxColor(wt::Color::Green());
		}

		mSelectedActor = actor;

		ui.transform->setEnabled(actor!=NULL);

		if(!actor){
			return;
		}

		mSelectedActor->setBoundingBoxColor(wt::Color::Red());

		wt::Scene& scene = *mScene;

		glm::vec3 pos;
		mSelectedActor->getTransformable()->getTranslation(pos);

		glm::vec3 eyePos;
		mScene->getCamera().getTranslation(eyePos);

		if(actor->getActorType() == wt::ASceneActor::eTYPE_MODELLED){
			// We don't want this to emit a signal
			ui.comboBoxAnimation->blockSignals(true);
			ui.comboBoxAnimation->clear();

			ui.comboBoxAnimation->setEnabled(true);
			ui.comboBoxAnimation->addItem("none");

			wt::ModelledActor* modelledActor = static_cast<wt::ModelledActor*>(actor);

			if(static_cast<wt::ModelledActor*>(actor)->getModel()){
				// Populate the animation combo box with the current actors animations
				uint32_t index = 1;
				int32_t activeIndex = -1;
				for(wt::Model::AnimationMap::iterator i=static_cast<wt::ModelledActor*>(actor)->getModel()->getAnimations().begin(); i!=static_cast<wt::ModelledActor*>(actor)->getModel()->getAnimations().end(); i++){
					ui.comboBoxAnimation->addItem(i->first.c_str());

					if(modelledActor->getAnimationPlayer()->getCurrentAnimation() == i->second){
						activeIndex = index;
					}

					++index;
				}

				ui.comboBoxAnimation->blockSignals(false);

				if(activeIndex > 0){
					ui.comboBoxAnimation->setCurrentIndex(activeIndex);
				}
			}

			ui.stackedWidget->setCurrentIndex(0);

			ui.comboBoxAnimation->blockSignals(false);
		}
		else if(actor->getActorType() == wt::ASceneActor::eTYPE_PARTICLE_EFFECT){
			ui.stackedWidget->setCurrentIndex(1);
		}
		else if(actor->getActorType() == wt::ASceneActor::eTYPE_POINT_LIGHT){
			ui.stackedWidget->setCurrentIndex(2);

			const wt::PointLight* light = static_cast<const wt::PointLight*>(actor);
		
			ui.lightAttenuation->setValue(glm::vec3(
				light->getDesc().attenuation.constant,
				light->getDesc().attenuation.linear,
				light->getDesc().attenuation.quadratic
			));

			ui.lightColor->setColor(
				light->getDesc().color
			);

			ui.lightAmbientIntensity->setValue(
				light->getDesc().ambientIntensity
			);

			ui.lightDiffuseIntensity->setValue(
				light->getDesc().diffuseIntensity
			);
		}
		else if(actor->getActorType() == wt::ASceneActor::eTYPE_SOUND){
			ui.stackedWidget->setCurrentIndex(3);

			const wt::Sound* sound = dynamic_cast<const wt::Sound*>(actor);

			ui.volume->setValue( sound->getSound()->getVolume()*100.0f );

			ui.attenuation->setValue( sound->getSound()->getAttenuation() );

			ui.minDistance->setValue( sound->getSound()->getMinimumDistance() );

			ui.pitch->setValue( sound->getSound()->getPitch() );
		}
		else if(actor->getActorType() == wt::ASceneActor::eTYPE_COLLIDER){
			ui.stackedWidget->setCurrentIndex(4);
		}
		else{
			WT_THROW("Unsupported actor type");
		}

		// Update tarnsform information
		updateSelectionStats();
	}
	else if(mState == eSTATE_PICK_ATTACH_ACTOR){
		if(actor == NULL){
			mAttachActor = NULL;
		}

		if(actor->getActorType() == wt::ASceneActor::eTYPE_MODELLED){
			 mAttachActor = dynamic_cast<wt::ModelledActor*>(actor);

			 

			 if(mAttachActor->getModel()->hasSkeleton()){
				 QList<wt::SkeletonBone*> bones;
				 bones << mAttachActor->getModel()->getSkeleton();

				 ui.attachBone->clear();

				 while(!bones.empty()){
					 wt::SkeletonBone* bone = bones.front();
					 bones.pop_front();

					 for(uint32_t i=0; i<bone->getNumChildren(false); i++){
						 bones.push_back(bone->getChildAt(i));
					 }

					 QString boneName = QString(bone->getName().c_str());
					 ui.attachBone->addItem( boneName );
				 }
			 }
		}
		
		mState = eSTATE_NORMAL;
		
	}
}
Exemplo n.º 10
0
void MainWindow::compareFiles()
{
    if(list_hist.size() != 0)
    {
        QDir dir;
        QStringList filtros ;
        filtros << "*.jpg" << ".*png" << "*.bmp";

        QString fileName = QFileDialog::getOpenFileName(this,
                                                        tr("Load Image to Compare"),
                                                        QDir::currentPath(),
                                                        tr("Images (*.jpg *.png *.bmp)"));

        QDir file = QFileInfo(fileName).absoluteDir();

        if(fileName.toStdString() != "")
        {
            QString image = fileName.split( "/" ).back();
            QString image_path = file.absolutePath() + "/" + image;
            QString xml = "hist_"+ QString("%1").arg(this->imageID +1, 6, 10, QChar('0')) + ".xml";
            QString xml_path = dir.absolutePath() + "/" + this->HistFolder+"/"+ xml;

            // Extract HSV and compare.
            Histogram *h = new Histogram(image.toStdString(), image_path.toStdString(), xml_path.toStdString());

            // COMPARE HISTOGRAM

            // PARALLEL CODE
            int i;
            QList<Histogram*> list_hist;
            list_hist = this->list_hist;

            #pragma omp parallel firstprivate(list_hist) shared(h)
            {
                #pragma omp for private(i)
                for(i = 0; i < list_hist.length(); i++)
                    h->compareHistogram(h, list_hist.at(i), 1);

                #pragma omp barrier
            }

            // END PARALLEL CODE

            // SORT TOP 15
            QList<Histogram*> ranking;

            for(i = 0; i < list_hist.length(); i++)
            {
                if(ranking.length() < 15)
                {
                    ranking.push_back(list_hist.at(i));
                }
                else
                {
                    if(list_hist.at(i)->getCompare() > ranking.at(0)->getCompare())
                    {
                        ranking.pop_front();
                        ranking.push_back(list_hist.at(i));
                    }
                }

                qSort(ranking.begin(), ranking.end(), compLess<Histogram>());

            }

            this->edit->append("\nTOP 15:\n");

            QList<QString> imagesToShow;

            for(i = ranking.length() - 1; i >= 0 ; i--)
            {
                QString text = "Image: " + QString::fromStdString(ranking.at(i)->getName()) + " is " + QString::number(ranking.at(i)->getCompare()) + "% similar";
                imagesToShow.append("images/" + QString::fromStdString(ranking.at(i)->getName()));

                this->edit->append(text);
            }

            ShowImages showImages(imagesToShow);
            showImages.setWindowTitle("View Images");
            showImages.exec();
        }

    }
    else
    {
        QMessageBox msgBox;
        QString stringMsg = "No existe BBDD de imágenes para comparar.";

        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText(stringMsg);
        msgBox.exec();
    }
}
Exemplo n.º 11
0
void BFSForest::buildForest() {
	QList<RoadVertexDesc> seeds;
	QList<int> groups;

	QMap<RoadEdgeDesc, bool> visitedEdge;
	QMap<RoadVertexDesc, bool> visitedVertex;

	// ルートとして与えられた頂点について
	for (int i = 0; i < roots.size() / 2; i++) {
		RoadVertexDesc src = roots[i * 2];
		RoadVertexDesc tgt = roots[i * 2 + 1];

		// エッジの取得
		RoadEdgeDesc e_desc = GraphUtil::getEdge(roads, src, tgt);

		// エッジのグループ、seedフラグを設定
		roads->graph[e_desc]->group = i;
		roads->graph[e_desc]->seed = true;

		// 頂点srcが既存のシードと重複している場合
		if (seeds.contains(src)) {
			// 頂点srcをコピーする
			RoadVertex* v = new RoadVertex(roads->graph[src]->pt);
			RoadVertexDesc new_src = boost::add_vertex(roads->graph);
			roads->graph[new_src] = v;

			// 古いエッジを削除
			roads->graph[e_desc]->valid = false;

			// 新しいエッジを追加
			e_desc = GraphUtil::addEdge(roads, new_src, tgt, roads->graph[e_desc]);

			src = new_src;
		}

		// 頂点tgtが既存のシードと重複している場合
		if (seeds.contains(tgt)) {
			// 頂点tgtをコピーする
			RoadVertex* v = new RoadVertex(roads->graph[tgt]->pt);
			RoadVertexDesc new_tgt = boost::add_vertex(roads->graph);
			roads->graph[new_tgt] = v;

			// 古いエッジを削除
			roads->graph[e_desc]->valid = false;

			// 新しいエッジを追加
			e_desc = GraphUtil::addEdge(roads, src, new_tgt, roads->graph[e_desc]);

			tgt = new_tgt;
		}

		// src、tgtが更新されたかも知れないので、おおもとのデータも更新しておく
		roots[i * 2] = src;
		roots[i * 2 + 1] = tgt;

		// シードを登録する
		seeds.push_back(src);
		seeds.push_back(tgt);
		groups.push_back(i);
		groups.push_back(i);

		// ルートエッジ・頂点を訪問済みとマークする
		visitedEdge[e_desc] = true;
		visitedVertex[src] = true;
		visitedVertex[tgt] = true;
	}

	// ルート頂点リストからスタートして、BFSで全頂点を訪問する
	while (!seeds.empty()) {
		RoadVertexDesc parent = seeds.front();
		seeds.pop_front();

		int group = groups.front();
		groups.pop_front();

		std::vector<RoadVertexDesc> children;

		// 隣接ノードリストを先に洗い出す
		std::vector<RoadVertexDesc> nodes;
		std::vector<RoadEdgeDesc> edges;
		RoadOutEdgeIter ei, eend;
		for (boost::tie(ei, eend) = boost::out_edges(parent, roads->graph); ei != eend; ++ei) {
			if (!roads->graph[*ei]->valid) continue;
			if (visitedEdge[*ei]) continue;

			// 隣接ノードを取得
			RoadVertexDesc child = boost::target(*ei, roads->graph);
			if (!roads->graph[child]->valid) continue;

			if (getParent(parent).contains(child)) continue;

			nodes.push_back(child);
			edges.push_back(*ei);

			// 当該エッジを通過したとマークする
			visitedEdge[*ei] = true;
		}

		// 洗い出した隣接ノードに対して、訪問する
		for (int i = 0; i < nodes.size(); i++) {
			RoadVertexDesc child = nodes[i];

			if (visitedVertex.contains(child)) { // 訪問済みの場合
				RoadEdgeDesc orig_e_desc = GraphUtil::getEdge(roads, parent, child);

				// もともとのエッジを無効にする
				roads->graph[orig_e_desc]->valid = false;

				// 対象ノードが訪問済みの場合、対象ノードをコピーして子ノードにする
				RoadVertexDesc child2 = GraphUtil::addVertex(roads, roads->graph[child]);
				roads->graph[child2]->virt = false;

				// エッジ作成
				RoadEdgeDesc e_desc = GraphUtil::addEdge(roads, parent, child2, roads->graph[orig_e_desc]);

				roads->graph[e_desc]->group = group;

				children.push_back(child2);
			} else { // 未訪問の場合
				visitedVertex[child] = true;
				roads->graph[edges[i]]->group = group;

				children.push_back(child);

				seeds.push_back(child);
				groups.push_back(group);
			}
		}

		this->children.insert(parent, children);
	}
}
Exemplo n.º 12
0
  void CacheThread::run()
  {
    while (!p->exit_)
    {
      // Wait until we're told there are images we need to request.
      waiting_mutex_.lock();

      // Next, get all of them and sort them by priority.
      p->unprocessed_mutex_.lock();
      QList<ImagePtr> images = p->unprocessed_.values();
      p->unprocessed_mutex_.unlock();

      qSort(images.begin(), images.end(), ComparePriority);

      // Go through all of them and request them.  Qt's network manager will
      // only handle six simultaneous requests at once, so we use a semaphore
      // to limit ourselves to that many.
      // Each individual image will release the semaphore when it is done loading.
      // Also, only load up to a certain number at a time in this loop.  If there
      // are more left afterward, we'll start over.  This ensures that we
      // concentrate on processing the highest-priority images.
      int count = 0;
      while (!p->exit_ && !images.empty() && count < MAXIMUM_SEQUENTIAL_REQUESTS)
      {
        p->network_request_semaphore_.acquire();

        ImagePtr image = images.front();
        p->unprocessed_mutex_.lock();
        if (!image->Loading() && !image->Failed())
        {
          count++;
          image->SetLoading(true);
          images.pop_front();

          QString uri = image->Uri();
          size_t hash = p->uri_to_hash_map_[uri];
          if (uri.startsWith(QString("file:///")))
          {
            image->InitializeImage();
            QString filepath = uri.replace(QString("file:///"), QString("/"));
            if (!image->GetImage()->load(filepath))
            {
              image->ClearImage();
              image->AddFailure();
            }

            p->unprocessed_.remove(hash);
            p->uri_to_hash_map_.remove(uri);
            image->SetLoading(false);
            p->network_request_semaphore_.release();
          }
          else
          {
            Q_EMIT RequestImage(image->Uri());
          }
        }
        else
        {
          images.pop_front();
        }
        p->unprocessed_mutex_.unlock();

      }
      if (!images.empty())
      {
        waiting_mutex_.unlock();
      }
    }
  }
Exemplo n.º 13
0
Spell Magic::generateSpell(SpellField field)
{
    QList<Position> list;
    QList<ActiveEffect> effects;
    QList<ActiveEffect>::iterator iter;
    ActiveEffect* worker;

    //crating mask for field
    bool **mask = new bool*[field.size.x];
    for (int i = 0; i < field.size.x; ++i){
        mask[i] = new bool[field.size.y];
        for(int n = 0; n < field.size.y; ++n)
            if(field.map[i][n] != Runes::End)
                mask[i][n] = true;
            else
                mask[i][n] = false;
    }

    if(field.mainRune.x > -1 && field.mainRune.y > -1 && field.map[field.mainRune.x][field.mainRune.y] != Runes::End){
        Position current(field.mainRune.x,field.mainRune.y);

        ActiveEffect work;
        Effect effect;
        int cost = 0;

        Rune *mainRune = runes[field.map[current.x][current.y]];
        work.effect = mainRune->combinationEffect(field.map[current.x][current.y]);
        work.coefficient = 1;
        effects.append(work);
        cost += mainRune->getCost();
        mask[current.x][current.y] = false;

        //select next rune
        if(current.x > 0 && mask[current.x-1][current.y]){
            list.append(Position(current.x-1,current.y));
            mask[current.x-1][current.y] = false;
        }
        if(current.x < field.size.x-1 && mask[current.x+1][current.y]){
            list.append(Position(current.x+1,current.y));
            mask[current.x+1][current.y] = false;
        }
        if(current.y > 0 && mask[current.x][current.y-1]){
            list.append(Position(current.x,current.y-1));
            mask[current.x][current.y-1] = false;
        }
        if(current.y < field.size.y-1 && mask[current.x][current.y+1]){
            list.append(Position(current.x,current.y+1));
            mask[current.x][current.y+1] = false;
        }


        while(!list.isEmpty()){
            current = list.first();

            //qDebug() << current.x << " " << current.y;

            list.pop_front();
            effect = mainRune->combinationEffect(field.map[current.x][current.y]);
            bool flag = true;
            for(iter = effects.begin(); iter != effects.end(); iter++){
                if(iter->effect == effect)
                {
                    iter->coefficient++;
                    flag = false;
                    break;
                }
            }
            if(flag){
                work.effect = effect;
                effects.append(work);
            }
            cost += runes[field.map[current.x][current.y]]->getCost();

            //select next rune
            if(current.x > 0&& mask[current.x-1][current.y]){
                list.append(Position(current.x-1,current.y));
                mask[current.x-1][current.y] = false;
            }
            if(current.x < field.size.x-1 && mask[current.x+1][current.y]){
                list.append(Position(current.x+1,current.y));
                mask[current.x+1][current.y] = false;
            }
            if(current.y > 0 && mask[current.x][current.y-1]){
                list.append(Position(current.x,current.y-1));
                mask[current.x][current.y-1] = false;
            }
            if(current.y < field.size.y-1 && mask[current.x][current.y+1]){
                list.append(Position(current.x,current.y+1));
                mask[current.x][current.y+1] = false;
            }

        }
        int size;
        worker = new ActiveEffect[size = effects.size()];
        for(int i = 0; i < size; i++){
            worker[i] = effects.first();
            effects.pop_front();
        }
        return Spell("Success", cost, worker, size);
    }
    return Spell("Error", 1,worker, 0);
}
Exemplo n.º 14
0
void PlotExporter::exportPlot(QwtPlot *plot, const QRectF &zoom)
{
  QSizeF guessedDimensions;
  ExportPlotToImageDialog::Parameters p = m_exportDlg->parameters();

  m_exportDlg->setAspectRatio(plot->size().width() / plot->size().height());

  while (m_exportDlg->exec() == QDialog::Accepted) {
    p = m_exportDlg->parameters();

    QString path;

    if (p.path.length() < 0) {
      QMessageBox::warning(nullptr, QObject::tr("Invalid input"), QObject::tr("Invalid path"));
      continue;
    }
    if (!m_supportedFormats.contains(p.format)) {
      QMessageBox::warning(nullptr, QObject::tr("Invalid input"), QObject::tr("Invalid output format"));
      continue;
    }

    if (p.path.endsWith("." + p.format))
      path = p.path;
    else
      path = p.path + "." + p.format;

    /* Create a temporary QwtPlot to use to write the chart to file */
    QwtPlot exPlot;
    QwtPlotZoomer exPlorZoomer(exPlot.canvas());
    exPlorZoomer.zoom(zoom);

    exPlot.setCanvasBackground(QBrush(Qt::white));
    exPlot.setTitle(p.title);
    exPlot.setAxisTitle(QwtPlot::xBottom, plot->axisTitle(QwtPlot::xBottom));
    exPlot.setAxisTitle(QwtPlot::xTop, plot->axisTitle(QwtPlot::xTop));
    exPlot.setAxisTitle(QwtPlot::yLeft, plot->axisTitle(QwtPlot::yLeft));
    exPlot.setAxisTitle(QwtPlot::yRight, plot->axisTitle(QwtPlot::yRight));
    QwtPlotItemList curves = plot->itemList();

    /* Attach all plots from the GUI plot to the temporary plot
     * Note that this will detach the plots from the GUI plot! */
    QList<qreal> curvePenWidths;
    for (QwtPlotItem *i : curves) {
      QwtPlotCurve *c = dynamic_cast<QwtPlotCurve *>(i);

      if (c != nullptr) {
        QPen p = c->pen();
        qreal w = p.widthF();
        qreal nw;

        curvePenWidths.push_back(w);

        nw = w - 1.0;
        if (nw < 0.0)
          nw = 0.0;

        p.setWidthF(nw);
        c->setPen(p);
      }

      i->attach(&exPlot);
    }

    /* Scale up from millimeters to centimeters*/
    QSizeF dimensionsMM(p.dimensions.width() * 10.0, p.dimensions.height() * 10.0);

    /* Store current properties of the plot as we need to change them for rendering */
    QFont xBottomFont = plot->axisWidget(QwtPlot::xBottom)->font();
    QFont xTopFont = plot->axisWidget(QwtPlot::xTop)->font();
    QFont yLeftFont = plot->axisWidget(QwtPlot::yLeft)->font();
    QFont yRightFont = plot->axisWidget(QwtPlot::yRight)->font();
    QFont xBottomTitleFont = plot->axisTitle(QwtPlot::xBottom).font();
    QFont xTopTitleFont = plot->axisTitle(QwtPlot::xTop).font();
    QFont yLeftTitleFont = plot->axisTitle(QwtPlot::yLeft).font();
    QFont yRightTitleFont = plot->axisTitle(QwtPlot::yRight).font();
    QFont titleFont = plot->title().font();
    const qreal xBottomPenWidth = plot->axisWidget(QwtPlot::xBottom)->scaleDraw()->penWidth() > 0 ? plot->axisWidget(QwtPlot::xBottom)->scaleDraw()->penWidth() : 1.0;
    const qreal xTopPenWidth = plot->axisWidget(QwtPlot::xTop)->scaleDraw()->penWidth() > 0 ? plot->axisWidget(QwtPlot::xTop)->scaleDraw()->penWidth() : 1.0;
    const qreal yLeftPenWidth = plot->axisWidget(QwtPlot::yLeft)->scaleDraw()->penWidth() > 0 ? plot->axisWidget(QwtPlot::yLeft)->scaleDraw()->penWidth() : 1.0;
    const qreal yRightPenWidth = plot->axisWidget(QwtPlot::yRight)->scaleDraw()->penWidth() > 0 ? plot->axisWidget(QwtPlot::yRight)->scaleDraw()->penWidth() : 1.0;

    /* Recalculate sizes by the DPI for every element that needs it */
    const qreal outputInPixels = (static_cast<qreal>(p.dimensions.width()) / 2.54) * p.dpi;
    const qreal scalingRatio = (static_cast<qreal>(qApp->desktop()->logicalDpiX()) / p.dpi) * (outputInPixels / plot->geometry().width());

    const qreal _xBottomPenWidth = floor((xBottomPenWidth * scalingRatio) + 0.45);
    const qreal _xTopPenWidth = floor((xTopPenWidth * scalingRatio) + 0.45);
    const qreal _yLeftPenWidth = floor((yLeftPenWidth * scalingRatio) + 0.45);
    const qreal _yRightPenWidth = floor((yRightPenWidth * scalingRatio) + 0.45);
    xBottomFont.setPointSizeF(p.axisNumbersFontSize * scalingRatio);
    xTopFont.setPointSizeF(p.axisNumbersFontSize * scalingRatio);
    yLeftFont.setPointSizeF(p.axisNumbersFontSize * scalingRatio);
    yRightFont.setPointSizeF(p.axisNumbersFontSize * scalingRatio);
    xBottomTitleFont.setPointSizeF(p.axisTitlesFontSize * scalingRatio);
    xTopTitleFont.setPointSizeF(p.axisTitlesFontSize * scalingRatio);
    yLeftTitleFont.setPointSizeF(p.axisTitlesFontSize * scalingRatio);
    yRightTitleFont.setPointSizeF(p.axisTitlesFontSize * scalingRatio);
    titleFont.setPointSizeF(p.chartTitleFontSize * scalingRatio);
    exPlot.axisWidget(QwtPlot::xBottom)->scaleDraw()->setPenWidth(_xBottomPenWidth);
    exPlot.axisWidget(QwtPlot::xTop)->scaleDraw()->setPenWidth(_xTopPenWidth);
    exPlot.axisWidget(QwtPlot::yLeft)->scaleDraw()->setPenWidth(_yLeftPenWidth);
    exPlot.axisWidget(QwtPlot::yRight)->scaleDraw()->setPenWidth(_yRightPenWidth);

    exPlot.setPalette(m_plotPalette);
    exPlot.axisWidget(QwtPlot::xBottom)->setPalette(m_plotPalette);
    exPlot.axisWidget(QwtPlot::xTop)->setPalette(m_plotPalette);
    exPlot.axisWidget(QwtPlot::yLeft)->setPalette(m_plotPalette);
    exPlot.axisWidget(QwtPlot::yRight)->setPalette(m_plotPalette);
    exPlot.axisWidget(QwtPlot::xBottom)->setFont(xBottomFont);
    exPlot.axisWidget(QwtPlot::xTop)->setFont(xTopFont);
    exPlot.axisWidget(QwtPlot::yLeft)->setFont(yLeftFont);
    exPlot.axisWidget(QwtPlot::yRight)->setFont(yRightFont);
    setAxisTitleFont(&exPlot, QwtPlot::xBottom, xBottomTitleFont);
    setAxisTitleFont(&exPlot, QwtPlot::xTop, xTopTitleFont);
    setAxisTitleFont(&exPlot, QwtPlot::yLeft, yLeftTitleFont);
    setAxisTitleFont(&exPlot, QwtPlot::yRight, yRightTitleFont);
    setTitleFont(&exPlot, titleFont);

    exPlot.replot();

    renderPlotToFile(&exPlot, path, p.format, dimensionsMM, p.dpi);

    /* Reattach the plots back to the GUI plot */
    for (QwtPlotItem *i : curves) {
      QwtPlotCurve *c = dynamic_cast<QwtPlotCurve *>(i);

      if (c != nullptr) {
        QPen p = c->pen();

        if (curvePenWidths.isEmpty())
          break;

        p.setWidthF(curvePenWidths.front());
        curvePenWidths.pop_front();

        c->setPen(p);
      }

      i->attach(plot);
    }

    break; /* Exit the while loop */
  }
}
Exemplo n.º 15
0
void MainWindow::updateCache(QList<int> addr, QList<short> cMem, QList<int> bit, QList<int> hit)
{
    int cL = this->ui->tableWidget->columnCount() - 2;
    int iter = cMem.size() / cL;
    QList<int> back = addr;
    int n = 0;

    if (!addr.isEmpty() && !cMem.isEmpty() && !bit.isEmpty())
    {

        for (int i = 0; i<iter; i++)
        {
            short base = log2(ui->tableWidget->columnCount() - 2);
            int mask = -1 << (base-1);
            int tag = addr[0] & mask;
            QTableWidgetItem *item = new QTableWidgetItem;
            QString num = QString::number(tag, 16);
            item->setText(num);
            this->ui->tableWidget->setItem(i,0,item);

            for (int j = 0; j<cL; j++)
            {
                addr.pop_front();
            }

            for (int k = 0; k< cL; k ++)
            {
                QTableWidgetItem *item2 = new QTableWidgetItem;
                QString num = QString::number(cMem[0], 10);
                item2->setText(num);
                item2->setTextColor(Qt::red);
                if (hit.contains(back[n]))
                {
                    item2->setTextColor(Qt::green);
                }
                this->ui->tableWidget->setItem(i,k+1,item2);
                cMem.pop_front();
                n++;
            }

            QTableWidgetItem *item4 = new QTableWidgetItem;
            item4->setText("0");
            this->ui->tableWidget->setItem(i,cL+1,item4);

            for (int l = 0; l < cL; l ++)
            {
                if (bit[0] > 0)
                {
                    QTableWidgetItem *item3 = new QTableWidgetItem;
                    item3->setText("1");
                    this->ui->tableWidget->setItem(i,cL+1,item3);
                }
                bit.pop_front();
            }
        }
    }
    else
    {
        this->ui->tableWidget->clearContents();
    }
}
Exemplo n.º 16
0
Arquivo: pal.cpp Projeto: Ariki/QGIS
  /**
  * \brief Problem Factory
  * Select features from user's choice layers within
  * a specific bounding box
  * @param nbLayers # wanted layers
  * @param layersFactor layers importance
  * @param layersName layers in problem
  * @param lambda_min west bbox
  * @param phi_min south bbox
  * @param lambda_max east bbox
  * @param phi_max north bbox
  * @param scale the scale
  */
  Problem* Pal::extract( int nbLayers, char **layersName, double *layersFactor, double lambda_min, double phi_min, double lambda_max, double phi_max, double scale, std::ofstream *svgmap )
  {
    Q_UNUSED( svgmap );
    // to store obstacles
    RTree<PointSet*, double, 2, double> *obstacles = new RTree<PointSet*, double, 2, double>();

    Problem *prob = new Problem();

    int i, j;

    double bbx[4];
    double bby[4];

    double amin[2];
    double amax[2];

    int max_p = 0;

    LabelPosition* lp;

    bbx[0] = bbx[3] = amin[0] = prob->bbox[0] = lambda_min;
    bby[0] = bby[1] = amin[1] = prob->bbox[1] = phi_min;
    bbx[1] = bbx[2] = amax[0] = prob->bbox[2] = lambda_max;
    bby[2] = bby[3] = amax[1] = prob->bbox[3] = phi_max;


    prob->scale = scale;
    prob->pal = this;

    LinkedList<Feats*> *fFeats = new LinkedList<Feats*> ( ptrFeatsCompare );

    FeatCallBackCtx *context = new FeatCallBackCtx();
    context->fFeats = fFeats;
    context->scale = scale;
    context->obstacles = obstacles;
    context->candidates = prob->candidates;

    context->bbox_min[0] = amin[0];
    context->bbox_min[1] = amin[1];

    context->bbox_max[0] = amax[0];
    context->bbox_max[1] = amax[1];

#ifdef _EXPORT_MAP_
    context->svgmap = svgmap;
#endif

#ifdef _VERBOSE_
    std::cout <<  nbLayers << "/" << layers->size() << " layers to extract " << std::endl;
    std::cout << "scale is 1:" << scale << std::endl << std::endl;

#endif


    /* First step : extract feature from layers
     *
     * */
    int oldNbft = 0;
    Layer *layer;

    QList<char*> *labLayers = new QList<char*>();

    lyrsMutex->lock();
    for ( i = 0; i < nbLayers; i++ )
    {
      for ( QList<Layer*>::iterator it = layers->begin(); it != layers->end(); ++it ) // iterate on pal->layers
      {
        layer = *it;
        // Only select those who are active and labellable (with scale constraint) or those who are active and which must be treated as obstaclewhich must be treated as obstacle
        if ( layer->active
             && ( layer->obstacle || ( layer->toLabel && layer->isScaleValid( scale ) ) ) )
        {

          // check if this selected layers has been selected by user
          if ( strcmp( layersName[i], layer->name ) == 0 )
          {
            // check for connected features with the same label text and join them
            if ( layer->getMergeConnectedLines() )
              layer->joinConnectedFeatures();

            layer->chopFeaturesAtRepeatDistance();


            context->layer = layer;
            context->priority = layersFactor[i];
            // lookup for feature (and generates candidates list)

#ifdef _EXPORT_MAP_
            *svgmap << "<g inkscape:label=\"" << layer->name << "\"" << std::endl
            <<  "    inkscape:groupmode=\"layer\"" << std::endl
            <<  "    id=\"" << layer->name << "\">" << std::endl << std::endl;
#endif

            context->layer->modMutex->lock();
            context->layer->rtree->Search( amin, amax, extractFeatCallback, ( void* ) context );
            context->layer->modMutex->unlock();

#ifdef _EXPORT_MAP_
            *svgmap  << "</g>" << std::endl << std::endl;
#endif

#ifdef _VERBOSE_
            std::cout << "Layer's name: " << layer->getName() << std::endl;
            std::cout << "     scale range: " << layer->getMinScale() << "->" << layer->getMaxScale() << std::endl;
            std::cout << "     active:" << layer->isToLabel() << std::endl;
            std::cout << "     obstacle:" << layer->isObstacle() << std::endl;
            std::cout << "     toLabel:" << layer->isToLabel() << std::endl;
            std::cout << "     # features: " << layer->getNbFeatures() << std::endl;
            std::cout << "     # extracted features: " << context->fFeats->size() - oldNbft << std::endl;
#endif
            if ( context->fFeats->size() - oldNbft > 0 )
            {
              char *name = new char[strlen( layer->getName() ) +1];
              strcpy( name, layer->getName() );
              labLayers->push_back( name );
            }
            oldNbft = context->fFeats->size();


            break;
          }
        }
      }
    }
    delete context;
    lyrsMutex->unlock();

    prob->nbLabelledLayers = labLayers->size();
    prob->labelledLayersName = new char*[prob->nbLabelledLayers];
    for ( i = 0; i < prob->nbLabelledLayers; i++ )
    {
      prob->labelledLayersName[i] = labLayers->front();
      labLayers->pop_front();
    }

    delete labLayers;

    if ( fFeats->size() == 0 )
    {
#ifdef _VERBOSE_
      std::cout << std::endl << "Empty problem" << std::endl;
#endif
      delete fFeats;
      delete prob;
      delete obstacles;
      return NULL;
    }

    prob->nbft = fFeats->size();
    prob->nblp = 0;
    prob->featNbLp = new int [prob->nbft];
    prob->featStartId = new int [prob->nbft];
    prob->inactiveCost = new double[prob->nbft];

    Feats *feat;

#ifdef _VERBOSE_
    std::cout << "FIRST NBFT : " << prob->nbft << std::endl;
#endif

    // Filtering label positions against obstacles
    amin[0] = amin[1] = -DBL_MAX;
    amax[0] = amax[1] = DBL_MAX;
    FilterContext filterCtx;
    filterCtx.cdtsIndex = prob->candidates;
    filterCtx.scale = prob->scale;
    filterCtx.pal = this;
    obstacles->Search( amin, amax, filteringCallback, ( void* ) &filterCtx );

    if ( isCancelled() )
    {
      delete fFeats;
      delete prob;
      delete obstacles;
      return 0;
    }

    int idlp = 0;
    for ( i = 0; i < prob->nbft; i++ ) /* foreach feature into prob */
    {
      feat = fFeats->pop_front();
#ifdef _DEBUG_FULL_
      std::cout << "Feature:" << feat->feature->getLayer()->getName() << "/" << feat->feature->getUID() << " candidates " << feat->nblp << std::endl;
#endif
      prob->featStartId[i] = idlp;
      prob->inactiveCost[i] = pow( 2, 10 - 10 * feat->priority );

      switch ( feat->feature->getGeosType() )
      {
        case GEOS_POINT:
          max_p = point_p;
          break;
        case GEOS_LINESTRING:
          max_p = line_p;
          break;
        case GEOS_POLYGON:
          max_p = poly_p;
          break;
      }

      // sort candidates by cost, skip less interesting ones, calculate polygon costs (if using polygons)
      max_p = CostCalculator::finalizeCandidatesCosts( feat, max_p, obstacles, bbx, bby );

#ifdef _DEBUG_FULL_
      std::cout << "All costs are set" << std::endl;
#endif
      // only keep the 'max_p' best candidates
      for ( j = max_p; j < feat->nblp; j++ )
      {
        // TODO remove from index
        feat->lPos[j]->removeFromIndex( prob->candidates );
        delete feat->lPos[j];
      }
      feat->nblp = max_p;

      // update problem's # candidate
      prob->featNbLp[i] = feat->nblp;
      prob->nblp += feat->nblp;

      // add all candidates into a rtree (to speed up conflicts searching)
      for ( j = 0; j < feat->nblp; j++, idlp++ )
      {
        lp = feat->lPos[j];
        //lp->insertIntoIndex(prob->candidates);
        lp->setProblemIds( i, idlp ); // bugfix #1 (maxence 10/23/2008)
      }
      fFeats->push_back( feat );
    }

#ifdef _DEBUG_FULL_
    std::cout << "Malloc problem...." << std::endl;
#endif


    idlp = 0;
    int nbOverlaps = 0;
    prob->labelpositions = new LabelPosition*[prob->nblp];
    //prob->feat = new int[prob->nblp];

#ifdef _DEBUG_FULL_
    std::cout << "problem malloc'd" << std::endl;
#endif


    j = 0;
    while ( fFeats->size() > 0 ) // foreach feature
    {
      if ( isCancelled() )
      {
        delete fFeats;
        delete prob;
        delete obstacles;
        return 0;
      }

      feat = fFeats->pop_front();
      for ( i = 0; i < feat->nblp; i++, idlp++ )  // foreach label candidate
      {
        lp = feat->lPos[i];
        lp->resetNumOverlaps();

        // make sure that candidate's cost is less than 1
        lp->validateCost();

        prob->labelpositions[idlp] = lp;
        //prob->feat[idlp] = j;

        lp->getBoundingBox( amin, amax );

        // lookup for overlapping candidate
        prob->candidates->Search( amin, amax, LabelPosition::countOverlapCallback, ( void* ) lp );

        nbOverlaps += lp->getNumOverlaps();
#ifdef _DEBUG_FULL_
        std::cout << "Nb overlap for " << idlp << "/" << prob->nblp - 1 << " : " << lp->getNumOverlaps() << std::endl;
#endif
      }
      j++;
      delete[] feat->lPos;
      delete feat;
    }
    delete fFeats;

    //delete candidates;
    delete obstacles;


    nbOverlaps /= 2;
    prob->all_nblp = prob->nblp;
    prob->nbOverlap = nbOverlaps;


#ifdef _VERBOSE_
    std::cout << "nbOverlap: " << prob->nbOverlap << std::endl;
    std::cerr << scale << "\t"
              << prob->nbft << "\t"
              << prob->nblp << "\t"
              << prob->nbOverlap << "\t";
#endif

    return prob;
  }
Exemplo n.º 17
0
//-----------------------------------------------------------
void OGVisao::configurarObjeto(void)
{
 Visao *visao=dynamic_cast<Visao *>(this->obterObjetoOrigem());
 QPolygonF pol;
 int i, qtd;
 Referencia ref_visao;
 float larg;
 QPen pen;
 OGSubItemObjeto *referencia=NULL;
 QList<QGraphicsItem *> subitens;

 //Configura o título da visão
 titulo->configurarObjeto(visao);

 //Obtém a quantidade de referências na parte SELECT
 qtd=visao->obterNumReferencias(Referencia::SQL_REFER_SELECT);

 //Move o container de referências para origem para ser reposicionado posteriormente
 referencias->moveBy(-referencias->scenePos().x(),
                     -referencias->scenePos().y());
 subitens=referencias->children();

 for(i=0; i < qtd; i++)
 {
  //Obtém uma referência
  ref_visao=visao->obterReferencia(i, Referencia::SQL_REFER_SELECT);

  /* Caso o índice 'i' esteja dentro dos limites de subitens de referência
     reaproveita o item e o reconfigura */
  if(!subitens.isEmpty() && i < subitens.size())
  {
   //Obtém a referência ao subitem na posição 'i'
   referencia=dynamic_cast<OGSubItemObjeto *>(subitens[i]);
   //Move a referência para a origem para reposicionar posteriormente
   referencia->moveBy(-referencia->scenePos().x(),
                      -referencia->scenePos().y());
  }
  //Caso o índice esteja fora da capacidade de subitens, aloca um novo
  else
   referencia=new OGSubItemObjeto;

  //Configura o subitem (referência)
  referencias->removeFromGroup(referencia);
  referencia->configurarObjeto(ref_visao);
  referencia->moveBy(ESP_HORIZONTAL, (i * referencia->boundingRect().height()) + ESP_VERTICAL);
  //Adiciona a referência configurada ao grupo
  referencias->addToGroup(referencia);
 }

 //Remove as referências não utilizadas
 i=subitens.size()-1;
 while(i > qtd-1)
 {
  referencia=dynamic_cast<OGSubItemObjeto *>(subitens[i]);
  referencias->removeFromGroup(referencia);
  delete(referencia);
  i--;
 }

 /* Calcula a maior largura dentre o título e corpo de referências. Esta largura
    é usada como largura uniforme de toda a visão */
 if(referencias->boundingRect().width() > titulo->boundingRect().width())
  larg=referencias->boundingRect().width() + (2 * ESP_HORIZONTAL);
 else
  larg=titulo->boundingRect().width() + (2 * ESP_HORIZONTAL);

 titulo->redimensionarTitulo(larg, titulo->boundingRect().height());

 pol.append(QPointF(0.0f,0.0f));
 pol.append(QPointF(1.0f,0.0f));
 pol.append(QPointF(1.0f,1.0f));
 pol.append(QPointF(0.0f,1.0f));

 //Redimensiona o polígono do corpo de referências
 this->redimensionarPoligono(pol, larg, referencias->boundingRect().height() + (2 * ESP_VERTICAL));

 corpo->setPolygon(pol);
 corpo->setBrush(this->obterEstiloPreenchimento(AtributosParsers::CORPO_VISAO));

 //Define que a borda de visão é traceja
 pen=this->obterEstiloBorda(AtributosParsers::CORPO_VISAO);
 pen.setStyle(Qt::DashLine);

 corpo->setPen(pen);
 corpo->setPos(0, titulo->boundingRect().height()-1);
 referencias->setPos(corpo->pos());

 //Reposiciona os rótulos de aliases para o canto direito da visão
 subitens=referencias->children();
 while(!subitens.isEmpty())
 {
  referencia=dynamic_cast<OGSubItemObjeto *>(subitens.front());
  subitens.pop_front();
  referencia->definirPosXObjetoFilho(3, corpo->boundingRect().width() -
                                     referencia->boundingRect().width() - (2 * ESP_HORIZONTAL));
 }


 //Reposiciona o ícone de proteção da visão na extrema direita do título
 icone_protegido->setPos(titulo->pos().x() + titulo->boundingRect().width() * 0.925f,
                         2 * ESP_VERTICAL);

 /* Define o retângulo de dimensão da visão como sendo o ponto inicial o topLeft() do título
    e a largura sendo a do corpo de referências, já a altura da visão é a soma das alturas
    do elementos que a constitui */
 this->bounding_rect.setTopLeft(titulo->boundingRect().topLeft());
 this->bounding_rect.setWidth(corpo->boundingRect().width());
 this->bounding_rect.setHeight(titulo->boundingRect().height() + corpo->boundingRect().height() - 1);

 ObjetoGrafico::configurarObjeto();
 ObjetoGrafico::configurarSombraObjeto();
 ObjetoGrafico::configurarSelecaoObjeto();
}
Exemplo n.º 18
0
void GraphicalView::configureObject(void)
{
	View *view=dynamic_cast<View *>(this->getSourceObject());
	QPolygonF pol;
	int i, count, count1=0;
	Reference ref;
	QPen pen;
	TableObjectView *graph_ref=nullptr;
	QList<QGraphicsItem *> subitems;
	vector<TableObject *> tab_objs;
	QGraphicsItemGroup *groups[]={ columns, ext_attribs };
	QGraphicsPolygonItem *bodies[]={ body, ext_attribs_body };
  QString attribs[]={ ParsersAttributes::VIEW_BODY, ParsersAttributes::VIEW_EXT_BODY },
          tag_attribs[]={ ParsersAttributes::TABLE_BODY, ParsersAttributes::TABLE_EXT_BODY };
	float width, type_width=0, px=0;
	TableObjectView *col_item=nullptr;
	QList<TableObjectView *> col_items;
	TableObject *tab_obj=nullptr;
  Tag *tag=view->getTag();

	//Configures the view's title
	title->configureObject(view);

	//Gets the reference count on SELECT part of the SQL definition
	count=view->getReferenceCount(Reference::SQL_REFER_SELECT);

	if(count==0)
		count=count1=view->getReferenceCount(Reference::SQL_VIEW_DEFINITION);

	//Moves the references group to the origin to be moved latter
	columns->moveBy(-columns->scenePos().x(),
										 -columns->scenePos().y());

	subitems=columns->childItems();

	for(i=0; i < count; i++)
	{
		if(count1==0)
			ref=view->getReference(i, Reference::SQL_REFER_SELECT);
		else
			ref=view->getReference(i, Reference::SQL_VIEW_DEFINITION);

		//Reuses the subitem if it was allocated before
		if(!subitems.isEmpty() && i < subitems.size())
		{
			graph_ref=dynamic_cast<TableObjectView *>(subitems[i]);

			//Moves the reference to the origin to be moved latter
			graph_ref->moveBy(-graph_ref->scenePos().x(),
												-graph_ref->scenePos().y());
		}
		else
			graph_ref=new TableObjectView;

		columns->removeFromGroup(graph_ref);
		graph_ref->configureObject(ref);
		graph_ref->moveBy(HORIZ_SPACING, (i * graph_ref->boundingRect().height()) + VERT_SPACING);
		columns->addToGroup(graph_ref);
	}

	//Destroy the graphical references not used
	i=subitems.size()-1;
	while(i > count-1)
	{
		graph_ref=dynamic_cast<TableObjectView *>(subitems[i]);
		columns->removeFromGroup(graph_ref);
		delete(graph_ref);
		i--;
	}

	tab_objs.assign(view->getObjectList(OBJ_RULE)->begin(),
									view->getObjectList(OBJ_RULE)->end());
	tab_objs.insert(tab_objs.end(),
									view->getObjectList(OBJ_TRIGGER)->begin(),
									view->getObjectList(OBJ_TRIGGER)->end());

	ext_attribs->setVisible(!tab_objs.empty() && !hide_ext_attribs);
	ext_attribs_body->setVisible(!tab_objs.empty() && !hide_ext_attribs);

	if(!tab_objs.empty())
	{
		count=tab_objs.size();

		//Gets the subitems of the current group
		subitems=ext_attribs->childItems();
		ext_attribs->moveBy(-ext_attribs->scenePos().x(),
												-ext_attribs->scenePos().y());
		for(i=0; i < count; i++)
		{
			tab_obj=tab_objs.at(i);

			//Reusing the subitem if it was allocated before
			if(!subitems.isEmpty() && i < subitems.size())
			{
				col_item=dynamic_cast<TableObjectView *>(subitems[i]);
				col_item->setSourceObject(tab_obj);
				col_item->configureObject();
				col_item->moveBy(-col_item->scenePos().x(),
												 -col_item->scenePos().y());
			}
			else
				col_item=new TableObjectView(tab_obj);

			//Configures the item and set its position
			col_item->configureObject();
			col_item->moveBy(HORIZ_SPACING, (i * col_item->boundingRect().height()) + VERT_SPACING);

			/* Calculates the width of the name + type of the object. This is used to align all
			the constraint labels on table */
			width=col_item->getChildObject(0)->boundingRect().width() +
						col_item->getChildObject(1)->boundingRect().width() + (3 * HORIZ_SPACING);
			if(px < width)  px=width;

			//Gets the maximum width of the column type label to align all at same horizontal position
			if(type_width < col_item->getChildObject(2)->boundingRect().width())
				type_width=col_item->getChildObject(2)->boundingRect().width() + (3 * HORIZ_SPACING);

			col_items.push_back(col_item);
		}

		//Destroy the unused items
		i=subitems.size()-1;
		while(i > count-1)
		{
			col_item=dynamic_cast<TableObjectView *>(subitems[i]);
			ext_attribs->removeFromGroup(col_item);
			delete(col_item);
			i--;
		}

		//Set all items position
		while(!col_items.isEmpty())
		{
			col_item=dynamic_cast<TableObjectView *>(col_items.front());
			ext_attribs->removeFromGroup(col_item);
			col_items.pop_front();

			//Positioning the type label
			col_item->setChildObjectXPos(2, px);

			//Positioning the constraints label
			col_item->setChildObjectXPos(3, px + type_width);
			ext_attribs->addToGroup(col_item);
		}
	}

	/* Calculating the maximum width between the title, columns and extended attributes.
		This width is used to set the uniform width of table */
	if(!columns->childItems().isEmpty() &&
		 (columns->boundingRect().width() > title->boundingRect().width() &&
			((hide_ext_attribs || (columns->boundingRect().width() > ext_attribs->boundingRect().width())))))
		width=columns->boundingRect().width() + (2 * HORIZ_SPACING);
	else if(!ext_attribs->childItems().isEmpty() &&  !hide_ext_attribs &&
					(ext_attribs->boundingRect().width() > title->boundingRect().width() &&
					 ext_attribs->boundingRect().width() > columns->boundingRect().width()))
		width=ext_attribs->boundingRect().width() + (2 * HORIZ_SPACING);
	else
		width=title->boundingRect().width() + (2 * HORIZ_SPACING);

	//Resizes the title using the new width
	title->resizeTitle(width, title->boundingRect().height());

	pol.clear();
	pol.append(QPointF(0.0f,0.0f));
	pol.append(QPointF(1.0f,0.0f));
	pol.append(QPointF(1.0f,1.0f));
	pol.append(QPointF(0.0f,1.0f));

	//Resizes the columns/extended attributes using the new width
	for(int idx=0; idx < 2; idx++)
	{
		this->resizePolygon(pol, width, groups[idx]->boundingRect().height() + (2 * VERT_SPACING));
		bodies[idx]->setPolygon(pol);

    pen=this->getBorderStyle(attribs[idx]);
    pen.setStyle(Qt::DashLine);

    if(!tag)
      bodies[idx]->setBrush(this->getFillStyle(attribs[idx]));
    else
    {
      bodies[idx]->setBrush(tag->getFillStyle(tag_attribs[idx]));
      pen.setColor(tag->getElementColor(tag_attribs[idx], Tag::BORDER_COLOR));
    }

		bodies[idx]->setPen(pen);

		if(idx==0)
			bodies[idx]->setPos(title->pos().x(), title->boundingRect().height()-1);
		else
			bodies[idx]->setPos(title->pos().x(),
													title->boundingRect().height() +
													bodies[0]->boundingRect().height() - 2);
		groups[idx]->setPos(bodies[idx]->pos());

		subitems=groups[idx]->childItems();
		while(!subitems.isEmpty())
		{
			col_item=dynamic_cast<TableObjectView *>(subitems.front());
			subitems.pop_front();
			col_item->setChildObjectXPos(3, width -
																	 col_item->boundingRect().width() - (2 * HORIZ_SPACING) - 1);
		}
	}

	this->bounding_rect.setTopLeft(title->boundingRect().topLeft());
	this->bounding_rect.setWidth(title->boundingRect().width());

	if(!ext_attribs->isVisible())
		this->bounding_rect.setHeight(title->boundingRect().height() +
																	body->boundingRect().height() - 1);
	else
		this->bounding_rect.setHeight(title->boundingRect().height() +
																	body->boundingRect().height() +
																	ext_attribs_body->boundingRect().height() -2);

	//Set the protected icon position to the top-right on the title
	protected_icon->setPos(title->pos().x() + title->boundingRect().width() * 0.90f,
												 2 * VERT_SPACING);

	BaseObjectView::__configureObject();
	BaseObjectView::configureObjectShadow();
	BaseObjectView::configureObjectSelection();

	this->table_tooltip=Utf8String::create(view->getName(true)) +
											" (" + view->getTypeName() + ") \n" +
                      QString("Id: %1\n").arg(view->getObjectId()) +
											TableObjectView::CONSTR_DELIM_START +
											trUtf8("Connected rels: %1").arg(this->getConnectRelsCount()) +
											TableObjectView::CONSTR_DELIM_END;

	this->setToolTip(this->table_tooltip);
  configureTag();
}
Exemplo n.º 19
0
void DVGui::MsgBoxInPopup(MsgType type, const QString &text)
{
	// this function must be called by the main thread only
	// (only the main thread should access directly the GUI)
	// (note: working thread can and should call MsgBox(type,text) instead; see tmsgcore.h)

	Q_ASSERT(QApplication::instance()->thread() == QThread::currentThread());

	// a working thread can trigger a call to this function (by the main thread) also when a popup is already open
	// therefore we need a messageQueue
	// note: no mutex are needed because only the main thread call this function
	static QList<QPair<MsgType, QString>> messageQueue;
	static bool popupIsOpen = false;

	messageQueue.append(qMakePair(type, text));
	if (popupIsOpen)
		return;
	popupIsOpen = true;

	Dialog dialog(0, true);

	dialog.setWindowFlags(dialog.windowFlags() | Qt::WindowStaysOnTopHint);
	dialog.setAlignment(Qt::AlignLeft);
	QLabel *mainTextLabel = new QLabel("", &dialog);
	mainTextLabel->setMinimumWidth(400);
	QLabel *iconLabel = new QLabel(&dialog);

	QHBoxLayout *mainLayout = new QHBoxLayout;
	mainLayout->addWidget(iconLabel);
	mainLayout->addStretch();
	mainLayout->addWidget(mainTextLabel);
	mainLayout->addStretch();
	dialog.addLayout(mainLayout);

	// ButtonGroup: is used only to retrieve the clicked button
	QButtonGroup *buttonGroup = new QButtonGroup(&dialog);
	QPushButton *button = new QPushButton(QPushButton::tr("OK"), &dialog);
	button->setDefault(true);
	dialog.addButtonBarWidget(button);
	buttonGroup->addButton(button, 1);
	QObject::connect(buttonGroup, SIGNAL(buttonPressed(int)), &dialog, SLOT(done(int)));

	while (!messageQueue.empty()) {
		MsgType type1 = messageQueue.first().first;
		QString text1 = messageQueue.first().second;
		messageQueue.pop_front();

		mainTextLabel->setText(text1);

		QString msgBoxTitle = getMsgBoxTitle(type1);
		dialog.setWindowTitle(msgBoxTitle);

		QPixmap iconPixmap = getMsgBoxPixmap(type1);
		if (!iconPixmap.isNull()) {
			iconLabel->setPixmap(iconPixmap);
			iconLabel->setVisible(true);
		} else {
			iconLabel->setVisible(false);
		}

		dialog.raise();
		dialog.exec();

	} // loop: open the next dialog in the queue
	popupIsOpen = false;
}
Exemplo n.º 20
0
qint64 Dialog::countSize(QString filePath)
{
    qint64 fileSize = 0;
    QList<QString> fileList;
    QFileInfo fileInfo(filePath);
    QString strTopDir;
    if(fileInfo.isDir()) {//文件夹加入堆栈
        m_bFolder = true;
        if (filePath.contains('/'))
        {
            QStringList strList = filePath.split("/");
            int iSize = strList.size();
            strTopDir = strList.at(iSize-1);
        }
        else if(filePath.contains('\\'))
        {
            QStringList strList = filePath.split("\\");
            int iSize = strList.size();
            strTopDir = strList.at(iSize-1);
        }
            fileList.push_back(filePath);
    } else {//如果是文件的话就取文件的特特征码,文件特征码用文件的创建,最后的修改时间字符串和文件的路径取MD5
            m_bFolder = false;
            m_fileList.push_front(filePath);
            fileSize = fileInfo.size();
            QString createTime = fileInfo.created().toString();
            QString modifiedTime = fileInfo.lastModified().toString();
            QString checkString = createTime + modifiedTime;
            checkString += filePath;
            //m_fileCheck = MD5String(checkString.toLocal8Bit().data());
    }

    while(!fileList.isEmpty()){//判断堆栈中是否有文件夹
            QString filePath = fileList.value(0);//取堆栈的顶部位置
            QDir dir(filePath);//文件夹信息
            dir.setFilter(QDir::Dirs|QDir::Files|QDir::Hidden|QDir::System);
            dir.setSorting(QDir::DirsFirst);
            QFileInfoList list = dir.entryInfoList();//去得文件夹的文件信息
            QFileInfoList::iterator iter;
            if (2 == list.size())
            {
                qDebug() << "empty dir : " << filePath;
                m_emptyFolderList.push_back(filePath);
            }
            for(iter=list.begin(); iter!=list.end(); iter++) {//遍历文件夹内部
                    //m_stopMutex.lock();
//                    if(m_bStop) {
//                            m_stopMutex.unlock();
//                            return -1;
//                    }
                   // m_stopMutex.unlock();
                    //qDebug() << "filename : " << iter->fileName();
                    if(iter->fileName() == "." || iter->fileName() == "..") {
                            continue;
                    }
                    if(iter->isDir()) {//如果为文件夹的话加入到堆栈
                            fileList.push_back(iter->filePath());
                    } else {//如果是文件的话,取到文件的大小,并且把文件加入到发送list中
                            fileSize += iter->size();
                            //QString str
                            m_fileList.push_front(iter->filePath());
                    }
            }
            fileList.pop_front();//堆栈顶部的元素已经处理完毕,出堆栈
    }
//    if(m_fileCheck.size() == 0) {//文件夹的特征码是文件的所有路径取MD5
//            QString checkString;
//            QList<QString>::iterator iter;
//            for(iter=m_fileList.begin(); iter!=m_fileList.end(); iter++) {
//                    checkString += (*iter);
//            }
//            m_fileCheck = MD5String(checkString.toLocal8Bit().data());
//    }

    qDebug() << "file or director size : " << fileSize;
    return fileSize;
}
void QmitkMatchPointRegistrationManipulator::CheckInputs()
{
  if (!m_activeManipulation)
  {
  QList<mitk::DataNode::Pointer> dataNodes = this->GetDataManagerSelection();
  this->m_autoMoving = false;
  this->m_autoTarget = false;
  this->m_SelectedMovingNode = NULL;
  this->m_SelectedTargetNode = NULL;
  this->m_SelectedPreRegNode = NULL;
  this->m_SelectedPreReg = NULL;

  if (dataNodes.size() > 0)
  {
    //test if auto select works
    if (mitk::MITKRegistrationHelper::IsRegNode(dataNodes[0]))
    {
      mitk::DataNode::Pointer regNode = dataNodes[0];
      dataNodes.pop_front();

      mitk::MAPRegistrationWrapper* regWrapper = dynamic_cast<mitk::MAPRegistrationWrapper*>(regNode->GetData());
      if (regWrapper)
      {
        this->m_SelectedPreReg = dynamic_cast<const MAPRegistrationType*>(regWrapper->GetRegistration());
      }

      if (this->m_SelectedPreReg.IsNotNull())
      {
        this->m_SelectedPreRegNode = regNode;

        mitk::BaseProperty* uidProp = m_SelectedPreRegNode->GetData()->GetProperty(mitk::Prop_RegAlgMovingData);

        if (uidProp)
        {
          //search for the moving node
          mitk::NodePredicateDataProperty::Pointer predicate = mitk::NodePredicateDataProperty::New(mitk::Prop_UID,
            uidProp);
          this->m_SelectedMovingNode = this->GetDataStorage()->GetNode(predicate);
          this->m_autoMoving = this->m_SelectedMovingNode.IsNotNull();
        }

        uidProp = m_SelectedPreRegNode->GetData()->GetProperty(mitk::Prop_RegAlgTargetData);

        if (uidProp)
        {
          //search for the target node
          mitk::NodePredicateDataProperty::Pointer predicate = mitk::NodePredicateDataProperty::New(mitk::Prop_UID,
            uidProp);
          this->m_SelectedTargetNode = this->GetDataStorage()->GetNode(predicate);
          this->m_autoTarget = this->m_SelectedTargetNode.IsNotNull();
        }
      }
    }

    //if still nodes are selected -> ignore possible auto select
    if (!dataNodes.empty())
    {
      mitk::Image* inputImage = dynamic_cast<mitk::Image*>(dataNodes[0]->GetData());

      if (inputImage)
      {
        this->m_SelectedMovingNode = dataNodes[0];
        this->m_autoMoving = false;
        dataNodes.pop_front();
      }
    }

    if (!dataNodes.empty())
    {
      mitk::Image* inputImage = dynamic_cast<mitk::Image*>(dataNodes[0]->GetData());

      if (inputImage)
      {
        this->m_SelectedTargetNode = dataNodes[0];
        this->m_autoTarget = false;
        dataNodes.pop_front();
      }
    }
  }
  }
}
Exemplo n.º 22
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    // Initialize SDL and SDL_sound.
    if (!audio::initialize()) {
        QMessageBox::critical(0, QObject::tr("Error"),
                QObject::tr("Unable to initialize SDL and/or SDL_sound."));
        exit(1);
    }

    try {
        bool takeAlong;

        // Attempt to connect to the database.
#ifndef OSX_APP_BUNDLE
        if (!DBController::instance()->connect("experiment.sql")) {
#else
        const QString path = app.applicationDirPath();
        app.addLibraryPath(QString("%1/../Resources/plugins").arg(path));
        QString fileName = QString("%1/../Resources/experiment.sql").arg(path);
        if (!DBController::instance()->connect(fileName.toStdString())) {
#endif
            QMessageBox::critical(0,
                                  QObject::tr("Error"),
                                  QObject::tr("Couldn't open the database!"));
            return 1;
        }

        // Parse the command-line arguments, but remove the first argument
        // beforehand because it is only the application's executable name.
        QList<QString> args = app.arguments();
        if (!args.empty()) args.pop_front();
        parseCmdLine(args, &takeAlong);

        // Let the user choose a participant.
        ChooseParticipantDlg cpDlg;
        if (QDialog::Accepted != cpDlg.exec() || !cpDlg.getParticipantID())
            return 0;

        // Now that the user has successfully chosen a participant, go on
        // and show the main window.
        MainWindow mw(cpDlg.getParticipantID(), takeAlong);
        mw.show();
        mw.raise();

        // Let Qt do the main loop.
        app.exec();

    } catch (exception &ex) {
        QMessageBox::critical(0, QObject::tr("Error"), ex.what());
        return 1;

    } catch (...) {
        QMessageBox::critical(0, QObject::tr("Error"),
                              QObject::tr("An unknown error occured!"));
        return 1;
    }

    // Disconnect from the database.
    DBController::instance()->disconnect();

    // Perform a clean shutdown of SDL and SDL_sound.
    audio::shutdown();

    return 0;
}