<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkStandardFileLocations.h"
#include "mitkTestingMacros.h"
#include "mitkPointSetStatisticsCalculator.h"
#include "itkImage.h"
#include "mitkExtendedLabelStatisticsImageFilter.h"
#include "itkDiscreteGaussianImageFilter.h"

#include <itkImageRegionConstIterator.h>
#include <itkImageRegionIterator.h>
#include <itkImageRegionConstIteratorWithIndex.h>
#include <itkImageRegionIteratorWithIndex.h>
//#include <QtCore>

/**
 * \brief Test class for mitkPointSetStatisticsCalculator
 */
class mitkImageStatisticsTextureAnalysisTestClass
{
public:

  typedef itk::Image<unsigned short,3 >ImageType;
  typedef ImageType::Pointer pointerOfImage;

  typedef itk::ExtendedLabelStatisticsImageFilter< ImageType, ImageType > LabelStatisticsFilterType;
  typedef LabelStatisticsFilterType::Pointer labelStatisticsFilterPointer;
  //typedef itk::ImageRegionConstIteratorWithIndex<MaskImageType> MaskImageIteratorType;
  //typedef itk::ImageRegionConstIteratorWithIndex <ImageType> InputImageIndexIteratorType;

  static ImageType::Pointer CreatingTestLabelImage()
  {
    //InputImageIndexIteratorType labelIterator2;
    ImageType::Pointer image = ImageType :: New();
    ImageType::IndexType start;
    ImageType::SizeType size;

    start[0] = 0;
    start[1] = 0;
    start[2] = 0;

    size[0] = 2;
    size[1] = 2;
    size[2] = 2;

    ImageType:: RegionType region;
    region.SetSize( size );
    region.SetIndex( start );

    image->SetRegions(region);
    image->Allocate();
    image->FillBuffer(1.0);

    return image;
  }

  static ImageType::Pointer CreatingTestImage()
  {

    //InputImageIndexIteratorType labelIterator2;
    ImageType::Pointer image = ImageType :: New();
    ImageType::IndexType start;
    ImageType::SizeType size;

    start[0] = 0;
    start[1] = 0;
    start[2] = 0;

    size[0] = 2;
    size[1] = 2;
    size[2] = 2;

    ImageType:: RegionType region;
    region.SetSize( size );
    region.SetIndex( start );

    image->SetRegions(region);
    image->Allocate();
    image->FillBuffer(3.0);

    //for( labelIterator2.GoToBegin(); !labelIterator2.IsAtEnd(); ++labelIterator2)
    // {
    // }

    for(unsigned int r = 0; r < 1; r++)
    {
      for(unsigned int c = 0; c < 2; c++)
      {
        for(unsigned int l = 0; l < 2; l++)
        {
          ImageType::IndexType pixelIndex;
          pixelIndex[0] = r;
          pixelIndex[1] = c;
          pixelIndex[2] = l;

          image->SetPixel(pixelIndex, 2.0);
        }
      }
    }

    return image;
  }

  static LabelStatisticsFilterType::Pointer  TestInstantiation(ImageType::Pointer image, ImageType::Pointer maskImage)
  {
   // typedef itk::ExtendedLabelStatisticsImageFilter< ImageType, ImageType > LabelStatisticsFilterType;
    LabelStatisticsFilterType::Pointer labelStatisticsFilter;
    labelStatisticsFilter = LabelStatisticsFilterType::New();
    labelStatisticsFilter->SetInput( image );
    labelStatisticsFilter->SetLabelInput( maskImage );
    labelStatisticsFilter->SetLabelInput( maskImage );
    labelStatisticsFilter->Update();
    //typename StatisticsFilterType::Pointer statisticsFilter = StatisticsFilterType::New();
   // mitk::PointSetStatisticsCalculator::Pointer myPointSetStatisticsCalculator = mitk::PointSetStatisticsCalculator::New();
   // MITK_TEST_CONDITION_REQUIRED(myPointSetStatisticsCalculator.IsNotNull(),"Testing instantiation with constructor 1.");

    return labelStatisticsFilter;
  }

  static void TestTrueFalse(LabelStatisticsFilterType::Pointer labelStatisticsFilter, double expectedSkewness, double expectedKurtosis)
  {
    // let's create an object of our class
    MITK_TEST_CONDITION(labelStatisticsFilter->GetSkewness( 1 ) == expectedSkewness,"expectedSkewness: " << expectedSkewness << " actual Value: " << labelStatisticsFilter->GetSkewness( 1 ) );
    MITK_TEST_CONDITION(labelStatisticsFilter->GetKurtosis( 1 ) == expectedKurtosis,"expectedKurtosis: " << expectedKurtosis << " actual Value: " << labelStatisticsFilter->GetKurtosis( 1 ) );
  }
};

int mitkImageStatisticsTextureAnalysisTest(int, char* [])
{
  // always start with this!
  MITK_TEST_BEGIN("mitkImageStatisticsTextureAnalysisTest")

  mitkImageStatisticsTextureAnalysisTestClass::pointerOfImage label = mitkImageStatisticsTextureAnalysisTestClass:: CreatingTestLabelImage();
  mitkImageStatisticsTextureAnalysisTestClass::pointerOfImage image = mitkImageStatisticsTextureAnalysisTestClass:: CreatingTestImage();

   itk::ImageFileWriter<mitkImageStatisticsTextureAnalysisTestClass::ImageType>:: Pointer writer1 = itk::ImageFileWriter<mitkImageStatisticsTextureAnalysisTestClass::ImageType>::New();
 // writer->SetImageIO(nrrdImageIO);
  writer1->SetFileName("C:\\Users\\tmueller\\Documents\\TestPics\\SeedsFG_TEST1.nrrd");
  writer1->SetInput(label);
  writer1->Update();

   itk::ImageFileWriter<mitkImageStatisticsTextureAnalysisTestClass::ImageType>:: Pointer writer = itk::ImageFileWriter<mitkImageStatisticsTextureAnalysisTestClass::ImageType>::New();
 // writer->SetImageIO(nrrdImageIO);
  writer->SetFileName("C:\\Users\\tmueller\\Documents\\TestPics\\SeedsFG_TEST2.nrrd");
  writer->SetInput(image);
  writer->Update();

  mitkImageStatisticsTextureAnalysisTestClass::labelStatisticsFilterPointer mitkLabelFilter= mitkImageStatisticsTextureAnalysisTestClass::TestInstantiation( image,label);

  mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(mitkLabelFilter, 0, 1);
 // superImage = CreateSuperImage();
 // superImage1 = CreateSuperImage();
 // superImage2 = CreateSuperImage();
 // superImage3 = CreateSuperImage();

  //mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(superImage, 2334.33, 2332.3);
  //mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(superImage1, 2312334.33, 43434.0);
  //mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(superImage2, 123223.8, 2332.3);
  //mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(superImage3, 2312334.33, 2332.3);

  MITK_TEST_END()
}
<commit_msg>add some new tests for the imageStatisticsCalculator<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkStandardFileLocations.h"
#include "mitkTestingMacros.h"
#include "mitkPointSetStatisticsCalculator.h"
#include "itkImage.h"
#include "mitkExtendedLabelStatisticsImageFilter.h"
#include "mitkExtendedStatisticsImageFilter.h"
#include "itkDiscreteGaussianImageFilter.h"

#include <itkImageRegionConstIterator.h>
#include <itkImageRegionIterator.h>
#include <itkImageRegionConstIteratorWithIndex.h>
#include <itkImageRegionIteratorWithIndex.h>
//#include <QtCore>

/**
 * \brief Test class for mitkPointSetStatisticsCalculator
 */
class mitkImageStatisticsTextureAnalysisTestClass
{
public:

  typedef itk::Image<unsigned short,3 >ImageType;
  typedef ImageType::Pointer pointerOfImage;

  typedef itk::ExtendedLabelStatisticsImageFilter< ImageType, ImageType > LabelStatisticsFilterType;
  typedef LabelStatisticsFilterType::Pointer labelStatisticsFilterPointer;

  typedef itk::ExtendedStatisticsImageFilter< ImageType > StatisticsFilterType;
  typedef StatisticsFilterType::Pointer StatisticsFilterPointer;

  static ImageType::Pointer CreatingTestLabelImage()
  {
    ImageType::Pointer image = ImageType :: New();
    ImageType::IndexType start;
    ImageType::SizeType size;

    start[0] = 0;
    start[1] = 0;
    start[2] = 0;

    size[0] = 100;
    size[1] = 100;
    size[2] = 100;

    ImageType:: RegionType region;
    region.SetSize( size );
    region.SetIndex( start );

    image->SetRegions(region);
    image->Allocate();
    image->FillBuffer(1.0);

    return image;
  }

  static ImageType::Pointer CreatingTestImage()
  {
    ImageType::Pointer image = ImageType :: New();
    ImageType::IndexType start;
    ImageType::SizeType size;

    start[0] = 0;
    start[1] = 0;
    start[2] = 0;

    size[0] = 100;
    size[1] = 100;
    size[2] = 100;

    ImageType:: RegionType region;
    region.SetSize( size );
    region.SetIndex( start );

    image->SetRegions(region);
    image->Allocate();
    image->FillBuffer(3.0);

    for(unsigned int r = 0; r < 50; r++)
    {
      for(unsigned int c = 0; c < 100; c++)
      {
        for(unsigned int l = 0; l < 100; l++)
        {
          ImageType::IndexType pixelIndex;
          pixelIndex[0] = r;
          pixelIndex[1] = c;
          pixelIndex[2] = l;

          image->SetPixel(pixelIndex, 2.0);
        }
      }
    }

    return image;
  }

  static ImageType::Pointer CreatingTestImage2()
  {
    ImageType::Pointer image = ImageType :: New();
    ImageType::IndexType start;
    ImageType::SizeType size;

    start[0] = 0;
    start[1] = 0;
    start[2] = 0;

    size[0] = 100;
    size[1] = 100;
    size[2] = 100;

    ImageType:: RegionType region;
    region.SetSize( size );
    region.SetIndex( start );

    image->SetRegions(region);
    image->Allocate();
    image->FillBuffer(3.0);

    for(unsigned int r = 0; r < 50; r++)
    {
      for(unsigned int c = 0; c < 50; c++)
      {
        for(unsigned int l = 0; l < 100; l++)
        {
          ImageType::IndexType pixelIndex;
          pixelIndex[0] = r;
          pixelIndex[1] = c;
          pixelIndex[2] = l;

          image->SetPixel(pixelIndex, 2.0);
        }
      }
    }

    return image;
  }

  static LabelStatisticsFilterType::Pointer  TestInstantiation(ImageType::Pointer image, ImageType::Pointer maskImage)
  {
    LabelStatisticsFilterType::Pointer labelStatisticsFilter;
    labelStatisticsFilter = LabelStatisticsFilterType::New();
    labelStatisticsFilter->SetInput( image );
    labelStatisticsFilter->SetLabelInput( maskImage );
    labelStatisticsFilter->Update();

    return labelStatisticsFilter;
  }

  static StatisticsFilterType::Pointer  TestInstantiation2(ImageType::Pointer image )
  {
    StatisticsFilterType::Pointer StatisticsFilter;
    StatisticsFilter = StatisticsFilterType::New();
    StatisticsFilter->SetInput( image );
    StatisticsFilter->Update();

    return StatisticsFilter;
  }

  static void TestTrueFalse(LabelStatisticsFilterType::Pointer labelStatisticsFilter, double expectedSkewness, double expectedKurtosis)
  {
    // let's create an object of our class
    bool isSkewsnessLowerlimitCorrect = labelStatisticsFilter->GetSkewness( 1 )- expectedKurtosis+ std::pow(10,-3) <= expectedSkewness;
    bool isSkewsnessUpperlimitCorrect = labelStatisticsFilter->GetSkewness( 1 )+ expectedKurtosis+ std::pow(10,-3) >= expectedSkewness;

    MITK_TEST_CONDITION( isSkewsnessLowerlimitCorrect && isSkewsnessUpperlimitCorrect,"expectedSkewness: " << expectedSkewness << " actual Value: " << labelStatisticsFilter->GetSkewness( 1 ) );

    bool isKurtosisUpperlimitCorrect = labelStatisticsFilter->GetKurtosis( 1 ) <= expectedKurtosis+ std::pow(10,-3);
    bool isKurtosisLowerlimitCorrect = expectedKurtosis- std::pow(10,-3) <= labelStatisticsFilter->GetKurtosis( 1 );

    MITK_TEST_CONDITION( isKurtosisUpperlimitCorrect && isKurtosisLowerlimitCorrect,"expectedKurtosis: " << expectedKurtosis << " actual Value: " << labelStatisticsFilter->GetKurtosis( 1 ) );
  }

  static void TestTrueFalse2(StatisticsFilterType::Pointer StatisticsFilter, double expectedSkewness, double expectedKurtosis)
  {
    // let's create an object of our class
    bool isSkewsnessLowerlimitCorrect = StatisticsFilter->GetSkewness()- expectedKurtosis+ std::pow(10,-3) <= expectedSkewness;
    bool isSkewsnessUpperlimitCorrect = StatisticsFilter->GetSkewness()+ expectedKurtosis+ std::pow(10,-3) >= expectedSkewness;

    MITK_TEST_CONDITION( isSkewsnessLowerlimitCorrect && isSkewsnessUpperlimitCorrect,"expectedSkewness: " << expectedSkewness << " actual Value: " << StatisticsFilter->GetSkewness() );

    bool isKurtosisUpperlimitCorrect = StatisticsFilter->GetKurtosis() <= expectedKurtosis+ std::pow(10,-3);
    bool isKurtosisLowerlimitCorrect = expectedKurtosis- std::pow(10,-3) <= StatisticsFilter->GetKurtosis();

    MITK_TEST_CONDITION( isKurtosisUpperlimitCorrect && isKurtosisLowerlimitCorrect,"expectedKurtosis: " << expectedKurtosis << " actual Value: " << StatisticsFilter->GetKurtosis() );
  }

};

int mitkImageStatisticsTextureAnalysisTest(int, char* [])
{
  // always start with this!
  MITK_TEST_BEGIN("mitkImageStatisticsTextureAnalysisTest")

  mitkImageStatisticsTextureAnalysisTestClass::pointerOfImage label = mitkImageStatisticsTextureAnalysisTestClass:: CreatingTestLabelImage();

  mitkImageStatisticsTextureAnalysisTestClass::pointerOfImage image = mitkImageStatisticsTextureAnalysisTestClass:: CreatingTestImage();
  mitkImageStatisticsTextureAnalysisTestClass::pointerOfImage image2 = mitkImageStatisticsTextureAnalysisTestClass:: CreatingTestImage2();

  mitkImageStatisticsTextureAnalysisTestClass::labelStatisticsFilterPointer mitkLabelFilter= mitkImageStatisticsTextureAnalysisTestClass::TestInstantiation( image,label);
  mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(mitkLabelFilter, 0, 0.999998);

  mitkImageStatisticsTextureAnalysisTestClass::labelStatisticsFilterPointer mitkLabelFilter2= mitkImageStatisticsTextureAnalysisTestClass::TestInstantiation( image2,label);
  mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(mitkLabelFilter2, -1.1547, 2.33333);

  mitkImageStatisticsTextureAnalysisTestClass::StatisticsFilterPointer mitkFilter= mitkImageStatisticsTextureAnalysisTestClass::TestInstantiation2( image);
  mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(mitkLabelFilter, 0, 0.999998);

  mitkImageStatisticsTextureAnalysisTestClass::StatisticsFilterPointer mitkFilter2= mitkImageStatisticsTextureAnalysisTestClass::TestInstantiation2( image2);
  mitkImageStatisticsTextureAnalysisTestClass::TestTrueFalse(mitkLabelFilter2, -1.1547, 2.33333);

  MITK_TEST_END()
}
<|endoftext|>


<commit_before>#include <sstream>
using std::ostringstream;
#include "shared_read_write_remote_classifier.h"
#include "log.h"

namespace HybridProtocol_PPMOSI_SS
{

SharedReadWriteRemoteClassifier::SharedReadWriteRemoteClassifier()
   : Classifier()
   , _saved_mode(Mode::PRIVATE)
{}

SharedReadWriteRemoteClassifier::~SharedReadWriteRemoteClassifier()
{}

Mode::Type
SharedReadWriteRemoteClassifier::getMode(tile_id_t sharer)
{
   return _saved_mode;
}

void
SharedReadWriteRemoteClassifier::updateMode(tile_id_t sender, ShmemMsg* shmem_msg, DirectoryEntry* directory_entry, BufferedReq* buffered_req)
{
   if (_saved_mode == Mode::REMOTE_LINE)
      return;

   if (!IS_BLOCKING_REQ(shmem_msg->getType()))
      return;

   tile_id_t sharer = sender;
   UInt32 num_sharers = directory_entry->getNumSharers();
   DirectoryState::Type dstate = directory_entry->getDirectoryBlockInfo()->getDState();
   ShmemMsg::Type req_type = shmem_msg->getType();

   // For new cache lines
   if (num_sharers == 0)
      return;

   // For private cache lines
   if ( (num_sharers == 1) && (directory_entry->hasSharer(sharer)) )
      return;

   // If state is MODIFIED or OWNED, there has been a write to it, so return in REMOTE mode
   if ( (dstate == DirectoryState::MODIFIED) || (dstate == DirectoryState::OWNED) )
   {
      _saved_mode = Mode::REMOTE_LINE;
      return;
   }

   // Now, line is in SHARED or EXCLUSIVE state
   // For read-only cache lines
   if (req_type == ShmemMsg::UNIFIED_READ_REQ)
      return;

   // Set the line in remote mode
   _saved_mode = Mode::REMOTE_LINE;
}

}
<commit_msg>[adaptive protocol] Updated the shared_read_write_remote classifier<commit_after>#include "shared_read_write_remote_classifier.h"
#include "log.h"

namespace HybridProtocol_PPMOSI_SS
{

SharedReadWriteRemoteClassifier::SharedReadWriteRemoteClassifier()
   : Classifier()
   , _saved_mode(Mode::PRIVATE)
{}

SharedReadWriteRemoteClassifier::~SharedReadWriteRemoteClassifier()
{}

Mode::Type
SharedReadWriteRemoteClassifier::getMode(tile_id_t sharer)
{
   return _saved_mode;
}

void
SharedReadWriteRemoteClassifier::updateMode(tile_id_t sender, ShmemMsg* shmem_msg, DirectoryEntry* directory_entry, BufferedReq* buffered_req)
{
   // Uni-directional classification change from PRIVATE -> REMOTE_LINE, never reverts back
   if (_saved_mode == Mode::REMOTE_LINE)
      return;

   // Special code for WB_REPLY
   if ( (shmem_msg->getType() == ShmemMsg::WB_REPLY) || (shmem_msg->getType() == ShmemMsg::FLUSH_REQ) )
   {
      tile_id_t requester = buffered_req ? buffered_req->getShmemMsg()->getRequester() : INVALID_TILE_ID;
      if ((requester != INVALID_TILE_ID) && shmem_msg->isCacheLineDirty())
      {
         LOG_ASSERT_ERROR(requester != sender, "Requester(%i), Sender(%i)", requester, sender);
         _saved_mode = Mode::REMOTE_LINE;
      }
      return;
   }

   if (!IS_BLOCKING_REQ(shmem_msg->getType()))
      return;

   tile_id_t sharer = sender;
   UInt32 num_sharers = directory_entry->getNumSharers();
   DirectoryState::Type dstate = directory_entry->getDirectoryBlockInfo()->getDState();
   ShmemMsg::Type req_type = shmem_msg->getType();

   // For new cache lines
   if (num_sharers == 0)
      return;

   // For private cache lines
   if ( (num_sharers == 1) && (directory_entry->hasSharer(sharer)) )
      return;

   // If state is MODIFIED or OWNED, there has been a write to it, so return in REMOTE mode
   if ( (dstate == DirectoryState::MODIFIED) || (dstate == DirectoryState::OWNED) )
   {
      _saved_mode = Mode::REMOTE_LINE;
      return;
   }

   // Now, line is in SHARED or EXCLUSIVE state
   // For read-only cache lines
   if (req_type == ShmemMsg::UNIFIED_READ_REQ)
      return;

   // Set the line in remote mode
   _saved_mode = Mode::REMOTE_LINE;
}

}
<|endoftext|>


<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
**    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
**      disclaimer.
**    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
**      following disclaimer in the documentation and/or other materials provided with the distribution.
**    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
**      derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/

#include "VersionControlQuery.h"

#include "../query_framework/QueryRegistry.h"

#include "ModelBase/src/nodes/Node.h"
#include "ModelBase/src/model/TreeManager.h"

#include "FilePersistence/src/simple/SimpleTextFileStore.h"
#include "FilePersistence/src/version_control/GitRepository.h"
#include "FilePersistence/src/version_control/History.h"

#include "ModelBase/src/nodes/Node.h"
#include "OOModel/src/elements/StatementItem.h"

using namespace FilePersistence;

namespace InformationScripting {

const QStringList VersionControlQuery::COUNT_ARGUMENT_NAMES{"c", "count"};
const QStringList VersionControlQuery::NODE_TYPE_ARGUMENT_NAMES{"t", "type"};
const QStringList VersionControlQuery::NODES_ARGUMENTS_NAMES{"nodes"};
const QStringList VersionControlQuery::IN_ARGUMENT_NAMES{"in"};

Optional<TupleSet> VersionControlQuery::executeLinear(TupleSet input)
{
	Model::TreeManager* treeManager = target()->manager();

	// get GitRepository
	QString path{"projects/" + treeManager->name()};
	if (!GitRepository::repositoryExists(path)) return {"No repository found"};

	GitRepository repository{path};
	TupleSet result;

	auto commitIdRange = repository.revisions();
	auto adaptedRangeOptional = commitsToConsider(commitIdRange);
	if (!adaptedRangeOptional)
		return adaptedRangeOptional.errors()[0];
	commitIdRange = adaptedRangeOptional.value();

	QList<Model::Node*> nodesToLookAt;

	bool considerLocalCommitsOnly = arguments_.isArgumentSet(ArgumentParser::LOCAL_SCOPE_ARGUMENT_NAMES[0]) &&
			arguments_.scope(this) == ArgumentParser::Scope::Local;
	if (considerLocalCommitsOnly)
		nodesToLookAt << target();
	else if (arguments_.scope(this) == ArgumentParser::Scope::Input)
		for (const auto& astTuple : input.tuples("ast"))
			nodesToLookAt << static_cast<Model::Node*>(astTuple["ast"]);

	bool outputNodesOnly = arguments_.isArgumentSet(NODES_ARGUMENTS_NAMES[0]);

	auto typeMatcher = Model::SymbolMatcher::guessMatcher(arguments_.argument(NODE_TYPE_ARGUMENT_NAMES[1]));

	for (int i = commitIdRange.size() - 1; i > 0; --i)
	{
		QString oldCommitId = commitIdRange[i];
		QString newCommitId = commitIdRange[i - 1];

		Diff diff = repository.diff(oldCommitId, newCommitId);
		auto changes = diff.changes();

		if (!outputNodesOnly)
			addCommitMetaInformation(result, repository.getCommitInformation(newCommitId));

		for (auto change : changes.values())
		{
			// We ignore structure only changes since a node with a structure only change,
			// has a child which was deleted or added or modified, and this child will appear in the final representation.
			if (change->isFake() || change->onlyStructureChange()) continue;

			auto id = change->nodeId();
			if (auto node = const_cast<Model::Node*>(treeManager->nodeIdMap().node(id)))
			{
				Model::Node* changedNode = nullptr;
				if (auto statement = node->firstAncestorOfType(typeMatcher))
					changedNode = statement;
				else // The node is hopefully higher up in the node hierarchy thus we take it as is.
					changedNode = node;

				auto ancestorIt = std::find_if(nodesToLookAt.begin(), nodesToLookAt.end(), [changedNode](Model::Node* n) {
						return n->isAncestorOf(changedNode);
				});
				if (nodesToLookAt.isEmpty() || ancestorIt != nodesToLookAt.end())
				{
					// If we have input or local node(s) only return the information of the input nodes and not the children:
					if (!nodesToLookAt.isEmpty())
						changedNode = *ancestorIt;

					if (outputNodesOnly)
						result.add({{"ast", changedNode}});
					else
						result.add({"change", {{"id", newCommitId}, {"ast", changedNode}}});
				}
			}
		}
	}

	return result;
}

void VersionControlQuery::registerDefaultQueries()
{
	QueryRegistry::registerQuery<VersionControlQuery>("changes",
		std::vector<ArgumentRule>{{ArgumentRule::AtMostOneOf, {{COUNT_ARGUMENT_NAMES[1], ArgumentValue::IsSet},
												{IN_ARGUMENT_NAMES[0], ArgumentValue::IsSet}}}});
}

VersionControlQuery::VersionControlQuery(Model::Node* target, QStringList args, std::vector<ArgumentRule> argumentRules)
	: LinearQuery{target}, arguments_{{
		{COUNT_ARGUMENT_NAMES, "The amount of revisions to look at", COUNT_ARGUMENT_NAMES[1], "10"},
		{NODE_TYPE_ARGUMENT_NAMES, "The minimum type of the nodes returned", NODE_TYPE_ARGUMENT_NAMES[1], "StatementItem"},
		QCommandLineOption{NODES_ARGUMENTS_NAMES},
		{IN_ARGUMENT_NAMES, "Specific commits to look at, either a single one or a range with ..", IN_ARGUMENT_NAMES[0]}
}, args, true}
{
	for (const auto& rule : argumentRules)
		rule.check(arguments_);
}

void VersionControlQuery::addCommitMetaInformation(TupleSet& ts, const CommitMetaData& metadata)
{
		ts.add({"commit", {{"id", metadata.sha1_},
				  {"message", metadata.message_},
				  {"date", metadata.dateTime_.toString("dd.MM.yyyy hh:mm")},
				  {"commiter", metadata.committer_.name_ + " " + metadata.committer_.eMail_},
				  {"author", metadata.author_.name_ + " " + metadata.author_.eMail_}}});
}

Optional<QList<QString>> VersionControlQuery::commitsToConsider(const QStringList& commitIdRange) const
{
	if (arguments_.isArgumentSet(IN_ARGUMENT_NAMES[0]))
	{
		auto commitRange = arguments_.argument(IN_ARGUMENT_NAMES[0]).split("..");
		QString startCommit = commitRange[0];
		auto startIt = std::find_if(commitIdRange.begin(), commitIdRange.end(), [startCommit](QString sha1) {
				return sha1.startsWith(startCommit);
		});
		if (startIt == commitIdRange.end())
			return {QString{"%1 is not a commit id that exists in this repository."}.arg(startCommit)};

		QStringList::const_iterator endIt;
		if (commitRange.size() > 1)
		{
			QString endCommit = commitRange[1];
			endIt = std::find_if(commitIdRange.begin(), commitIdRange.end(), [endCommit](QString sha1) {
					return sha1.startsWith(endCommit);
			});
			if (endIt == commitIdRange.end())
				return {QString{"%1 is not a commit id that exists in this repository."}.arg(endCommit)};
		}
		else
		{
			endIt = startIt + 1;
		}
		QStringList result;
		// We always need one more than the actual end since we compare on two commits:
		for (auto it = startIt; it != endIt + 1; ++it)
			result.append(*it);
		return result;
	}
	else
	{
		QString countArgument = arguments_.argument(COUNT_ARGUMENT_NAMES[0]);
		bool converts = false;
		const int CHANGE_COUNT = countArgument.toInt(&converts);
		if (converts)
			return commitIdRange.mid(0, std::min(commitIdRange.size(), CHANGE_COUNT + 1));
		else if (countArgument != "all")
			return {"Invalid count argument"};
		else
			return commitIdRange;
	}
}

}
<commit_msg>start work on improving changes query<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
**    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
**      disclaimer.
**    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
**      following disclaimer in the documentation and/or other materials provided with the distribution.
**    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
**      derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/

#include "VersionControlQuery.h"

#include "../query_framework/QueryRegistry.h"

#include "ModelBase/src/nodes/Node.h"
#include "ModelBase/src/model/TreeManager.h"

#include "FilePersistence/src/simple/SimpleTextFileStore.h"
#include "FilePersistence/src/version_control/GitRepository.h"
#include "FilePersistence/src/version_control/History.h"

#include "ModelBase/src/nodes/Node.h"
#include "OOModel/src/elements/StatementItem.h"

using namespace FilePersistence;

namespace InformationScripting {

const QStringList VersionControlQuery::COUNT_ARGUMENT_NAMES{"c", "count"};
const QStringList VersionControlQuery::NODE_TYPE_ARGUMENT_NAMES{"t", "type"};
const QStringList VersionControlQuery::NODES_ARGUMENTS_NAMES{"nodes"};
const QStringList VersionControlQuery::IN_ARGUMENT_NAMES{"in"};

Optional<TupleSet> VersionControlQuery::executeLinear(TupleSet input)
{
	Model::TreeManager* treeManager = target()->manager();

	// get GitRepository
	QString path{"projects/" + treeManager->name()};
	if (!GitRepository::repositoryExists(path)) return {"No repository found"};

	GitRepository repository{path};
	TupleSet result;

	auto commitIdRange = repository.revisions();
	auto adaptedRangeOptional = commitsToConsider(commitIdRange);
	if (!adaptedRangeOptional)
		return adaptedRangeOptional.errors()[0];
	commitIdRange = adaptedRangeOptional.value();

	QList<Model::Node*> nodesToLookAt;

	bool considerLocalCommitsOnly = arguments_.isArgumentSet(ArgumentParser::LOCAL_SCOPE_ARGUMENT_NAMES[0]) &&
			arguments_.scope(this) == ArgumentParser::Scope::Local;
	if (considerLocalCommitsOnly)
		nodesToLookAt << target();
	else if (arguments_.scope(this) == ArgumentParser::Scope::Input)
		for (const auto& astTuple : input.tuples("ast"))
			nodesToLookAt << static_cast<Model::Node*>(astTuple["ast"]);

	bool outputNodesOnly = arguments_.isArgumentSet(NODES_ARGUMENTS_NAMES[0]);

	auto typeMatcher = Model::SymbolMatcher::guessMatcher(arguments_.argument(NODE_TYPE_ARGUMENT_NAMES[1]));

	for (int i = commitIdRange.size() - 1; i > 0; --i)
	{
		QString oldCommitId = commitIdRange[i];
		QString newCommitId = commitIdRange[i - 1];

		Diff diff = repository.diff(oldCommitId, newCommitId);
		auto changes = diff.changes();

		if (!outputNodesOnly)
			addCommitMetaInformation(result, repository.getCommitInformation(newCommitId));

		for (auto change : changes.values())
		{
			// We ignore structure only changes since a node with a structure only change,
			// has a child which was deleted or added or modified, and this child will appear in the final representation.
			if (change->isFake() || change->onlyStructureChange()) continue;

			auto id = change->nodeId();
			if (auto node = const_cast<Model::Node*>(treeManager->nodeIdMap().node(id)))
			{
				Model::Node* changedNode = nullptr;
				if (auto statement = node->firstAncestorOfType(typeMatcher))
					changedNode = statement;
				else // The node is hopefully higher up in the node hierarchy thus we take it as is.
					changedNode = node;

				auto ancestorIt = std::find_if(nodesToLookAt.begin(), nodesToLookAt.end(), [changedNode](Model::Node* n) {
						return n->isAncestorOf(changedNode);
				});
				if (nodesToLookAt.isEmpty() || ancestorIt != nodesToLookAt.end())
				{
					// If we have input or local node(s) only return the information of the input nodes and not the children:
					if (!nodesToLookAt.isEmpty())
						changedNode = *ancestorIt;

					if (outputNodesOnly)
					{
						result.add({{"ast", changedNode}});
						switch (change->type())
						{
							case ChangeType::Deletion:
								result.add({"color", {{"ast", changedNode}, {"color", QString{"red"}}}});
								break;
							case ChangeType::Insertion:
								result.add({"color", {{"ast", changedNode}, {"color", QString{"blue"}}}});
								break;
							case ChangeType::Move:
								result.add({"color", {{"ast", changedNode}, {"color", QString{"yellow"}}}});
								break;
							case ChangeType::Stationary:
								result.add({"color", {{"ast", changedNode}, {"color", QString{"black"}}}});
								break;
							case ChangeType::Unclassified:
								result.add({"color", {{"ast", changedNode}, {"color", QString{"white"}}}});
								break;
						}
					}
					else
						result.add({"change", {{"id", newCommitId}, {"ast", changedNode}}});
				}
			}
		}
	}

	return result;
}

void VersionControlQuery::registerDefaultQueries()
{
	QueryRegistry::registerQuery<VersionControlQuery>("changes",
		std::vector<ArgumentRule>{{ArgumentRule::AtMostOneOf, {{COUNT_ARGUMENT_NAMES[1], ArgumentValue::IsSet},
												{IN_ARGUMENT_NAMES[0], ArgumentValue::IsSet}}}});
}

VersionControlQuery::VersionControlQuery(Model::Node* target, QStringList args, std::vector<ArgumentRule> argumentRules)
	: LinearQuery{target}, arguments_{{
		{COUNT_ARGUMENT_NAMES, "The amount of revisions to look at", COUNT_ARGUMENT_NAMES[1], "10"},
		{NODE_TYPE_ARGUMENT_NAMES, "The minimum type of the nodes returned", NODE_TYPE_ARGUMENT_NAMES[1], "StatementItem"},
		QCommandLineOption{NODES_ARGUMENTS_NAMES},
		{IN_ARGUMENT_NAMES, "Specific commits to look at, either a single one or a range with ..", IN_ARGUMENT_NAMES[0]}
}, args, true}
{
	for (const auto& rule : argumentRules)
		rule.check(arguments_);
}

void VersionControlQuery::addCommitMetaInformation(TupleSet& ts, const CommitMetaData& metadata)
{
		ts.add({"commit", {{"id", metadata.sha1_},
				  {"message", metadata.message_},
				  {"date", metadata.dateTime_.toString("dd.MM.yyyy hh:mm")},
				  {"commiter", metadata.committer_.name_ + " " + metadata.committer_.eMail_},
				  {"author", metadata.author_.name_ + " " + metadata.author_.eMail_}}});
}

Optional<QList<QString>> VersionControlQuery::commitsToConsider(const QStringList& commitIdRange) const
{
	if (arguments_.isArgumentSet(IN_ARGUMENT_NAMES[0]))
	{
		auto commitRange = arguments_.argument(IN_ARGUMENT_NAMES[0]).split("..");
		QString startCommit = commitRange[0];
		auto startIt = std::find_if(commitIdRange.begin(), commitIdRange.end(), [startCommit](QString sha1) {
				return sha1.startsWith(startCommit);
		});
		if (startIt == commitIdRange.end())
			return {QString{"%1 is not a commit id that exists in this repository."}.arg(startCommit)};

		QStringList::const_iterator endIt;
		if (commitRange.size() > 1)
		{
			QString endCommit = commitRange[1];
			endIt = std::find_if(commitIdRange.begin(), commitIdRange.end(), [endCommit](QString sha1) {
					return sha1.startsWith(endCommit);
			});
			if (endIt == commitIdRange.end())
				return {QString{"%1 is not a commit id that exists in this repository."}.arg(endCommit)};
		}
		else
		{
			endIt = startIt + 1;
		}
		QStringList result;
		// We always need one more than the actual end since we compare on two commits:
		for (auto it = startIt; it != endIt + 1; ++it)
			result.append(*it);
		return result;
	}
	else
	{
		QString countArgument = arguments_.argument(COUNT_ARGUMENT_NAMES[0]);
		bool converts = false;
		const int CHANGE_COUNT = countArgument.toInt(&converts);
		if (converts)
			return commitIdRange.mid(0, std::min(commitIdRange.size(), CHANGE_COUNT + 1));
		else if (countArgument != "all")
			return {"Invalid count argument"};
		else
			return commitIdRange;
	}
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: canvasfont.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2004-11-26 17:11:39 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <canvas/debug.hxx>

#ifndef INCLUDED_RTL_MATH_HXX
#include <rtl/math.hxx>
#endif
#ifndef _BGFX_NUMERIC_FTOOLS_HXX
#include <basegfx/numeric/ftools.hxx>
#endif

#ifndef _SV_METRIC_HXX
#include <vcl/metric.hxx>
#endif

#include "outdevprovider.hxx"
#include "canvasfont.hxx"
#include "textlayout.hxx"

using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star;

namespace vclcanvas
{
    CanvasFont::CanvasFont( const rendering::FontRequest&                   rFontRequest,
                            const uno::Sequence< beans::PropertyValue >&    rExtraFontProperties,
                            const geometry::Matrix2D&                       rFontMatrix,
                            const OutDevProviderSharedPtr&                  rDevice ) :
        CanvasFont_Base( m_aMutex ),
        maFont( Font( rFontRequest.FontDescription.FamilyName,
                      rFontRequest.FontDescription.StyleName,
                      Size( 0, ::basegfx::fround(rFontRequest.CellSize) ) ) ),
        maFontRequest( rFontRequest ),
        mpRefDevice( rDevice )
    {
        CHECK_AND_THROW( mpRefDevice.get(),
                         "CanvasFont::CanvasFont(): Invalid ref device" );

        maFont->SetAlign( ALIGN_BASELINE );
        maFont->SetCharSet( (rFontRequest.FontDescription.IsSymbolFont==com::sun::star::util::TriState_YES) ? RTL_TEXTENCODING_SYMBOL : RTL_TEXTENCODING_UNICODE );
        maFont->SetVertical( (rFontRequest.FontDescription.IsVertical==com::sun::star::util::TriState_YES) ? TRUE : FALSE );

        // TODO(F2): improve panose->vclenum conversion
        maFont->SetWeight( static_cast<FontWeight>(rFontRequest.FontDescription.FontDescription.Weight) );
        maFont->SetItalic( (rFontRequest.FontDescription.FontDescription.Letterform<=8) ? ITALIC_NONE : ITALIC_NORMAL );

        // adjust to stretched font
        if( !::rtl::math::approxEqual( rFontMatrix.m00, rFontMatrix.m11) )
        {
            const OutputDevice& rOutDev( mpRefDevice->getOutDev() );
            const Size aSize = rOutDev.GetFontMetric( *maFont ).GetSize();

            const double fDividend( rFontMatrix.m10 + rFontMatrix.m11 );
            double fStretch = (rFontMatrix.m00 + rFontMatrix.m01);

            if( !::basegfx::fTools::equalZero( fDividend) )
                fStretch /= fDividend;

            const long nNewWidth = ::basegfx::fround( aSize.Width() * fStretch );

            maFont->SetWidth( nNewWidth );
        }
    }

    CanvasFont::~CanvasFont()
    {
    }

    void SAL_CALL CanvasFont::disposing()
    {
        tools::LocalGuard aGuard;

        mpRefDevice.reset();
    }

    uno::Reference< rendering::XTextLayout > SAL_CALL  CanvasFont::createTextLayout( const rendering::StringContext& aText, sal_Int8 nDirection, sal_Int64 nRandomSeed ) throw (uno::RuntimeException)
    {
        tools::LocalGuard aGuard;

        if( !mpRefDevice.get() )
            return uno::Reference< rendering::XTextLayout >(); // we're disposed

        return new TextLayout( aText, nDirection, nRandomSeed, ImplRef( this ), mpRefDevice );
    }

    rendering::FontRequest SAL_CALL  CanvasFont::getFontRequest(  ) throw (uno::RuntimeException)
    {
        tools::LocalGuard aGuard;

        return maFontRequest;
    }

    rendering::FontMetrics SAL_CALL  CanvasFont::getFontMetrics(  ) throw (uno::RuntimeException)
    {
        tools::LocalGuard aGuard;

        // TODO(F1)
        return rendering::FontMetrics();
    }

    uno::Sequence< double > SAL_CALL  CanvasFont::getAvailableSizes(  ) throw (uno::RuntimeException)
    {
        tools::LocalGuard aGuard;

        // TODO(F1)
        return uno::Sequence< double >();
    }

    uno::Sequence< beans::PropertyValue > SAL_CALL  CanvasFont::getExtraFontProperties(  ) throw (uno::RuntimeException)
    {
        tools::LocalGuard aGuard;

        // TODO(F1)
        return uno::Sequence< beans::PropertyValue >();
    }

#define SERVICE_NAME "drafts.com.sun.star.rendering.CanvasFont"

    ::rtl::OUString SAL_CALL CanvasFont::getImplementationName() throw( uno::RuntimeException )
    {
        return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( CANVASFONT_IMPLEMENTATION_NAME ) );
    }

    sal_Bool SAL_CALL CanvasFont::supportsService( const ::rtl::OUString& ServiceName ) throw( uno::RuntimeException )
    {
        return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ) );
    }

    uno::Sequence< ::rtl::OUString > SAL_CALL CanvasFont::getSupportedServiceNames()  throw( uno::RuntimeException )
    {
        uno::Sequence< ::rtl::OUString > aRet(1);
        aRet[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );

        return aRet;
    }

    ::Font CanvasFont::getVCLFont() const
    {
        return *maFont;
    }
}
<commit_msg>INTEGRATION: CWS presfixes01 (1.3.10); FILE MERGED 2005/02/16 11:14:06 fs 1.3.10.1: #i42558# drafts.com.sun.star.drawing/rendering/geometry moved to com.sun.star.*<commit_after>/*************************************************************************
 *
 *  $RCSfile: canvasfont.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-10 11:58:22 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <canvas/debug.hxx>

#ifndef INCLUDED_RTL_MATH_HXX
#include <rtl/math.hxx>
#endif
#ifndef _BGFX_NUMERIC_FTOOLS_HXX
#include <basegfx/numeric/ftools.hxx>
#endif

#ifndef _SV_METRIC_HXX
#include <vcl/metric.hxx>
#endif

#include "outdevprovider.hxx"
#include "canvasfont.hxx"
#include "textlayout.hxx"

using namespace ::com::sun::star;

namespace vclcanvas
{
    CanvasFont::CanvasFont( const rendering::FontRequest&                   rFontRequest,
                            const uno::Sequence< beans::PropertyValue >&    rExtraFontProperties,
                            const geometry::Matrix2D&                       rFontMatrix,
                            const OutDevProviderSharedPtr&                  rDevice ) :
        CanvasFont_Base( m_aMutex ),
        maFont( Font( rFontRequest.FontDescription.FamilyName,
                      rFontRequest.FontDescription.StyleName,
                      Size( 0, ::basegfx::fround(rFontRequest.CellSize) ) ) ),
        maFontRequest( rFontRequest ),
        mpRefDevice( rDevice )
    {
        CHECK_AND_THROW( mpRefDevice.get(),
                         "CanvasFont::CanvasFont(): Invalid ref device" );

        maFont->SetAlign( ALIGN_BASELINE );
        maFont->SetCharSet( (rFontRequest.FontDescription.IsSymbolFont==com::sun::star::util::TriState_YES) ? RTL_TEXTENCODING_SYMBOL : RTL_TEXTENCODING_UNICODE );
        maFont->SetVertical( (rFontRequest.FontDescription.IsVertical==com::sun::star::util::TriState_YES) ? TRUE : FALSE );

        // TODO(F2): improve panose->vclenum conversion
        maFont->SetWeight( static_cast<FontWeight>(rFontRequest.FontDescription.FontDescription.Weight) );
        maFont->SetItalic( (rFontRequest.FontDescription.FontDescription.Letterform<=8) ? ITALIC_NONE : ITALIC_NORMAL );

        // adjust to stretched font
        if( !::rtl::math::approxEqual( rFontMatrix.m00, rFontMatrix.m11) )
        {
            const OutputDevice& rOutDev( mpRefDevice->getOutDev() );
            const Size aSize = rOutDev.GetFontMetric( *maFont ).GetSize();

            const double fDividend( rFontMatrix.m10 + rFontMatrix.m11 );
            double fStretch = (rFontMatrix.m00 + rFontMatrix.m01);

            if( !::basegfx::fTools::equalZero( fDividend) )
                fStretch /= fDividend;

            const long nNewWidth = ::basegfx::fround( aSize.Width() * fStretch );

            maFont->SetWidth( nNewWidth );
        }
    }

    CanvasFont::~CanvasFont()
    {
    }

    void SAL_CALL CanvasFont::disposing()
    {
        tools::LocalGuard aGuard;

        mpRefDevice.reset();
    }

    uno::Reference< rendering::XTextLayout > SAL_CALL  CanvasFont::createTextLayout( const rendering::StringContext& aText, sal_Int8 nDirection, sal_Int64 nRandomSeed ) throw (uno::RuntimeException)
    {
        tools::LocalGuard aGuard;

        if( !mpRefDevice.get() )
            return uno::Reference< rendering::XTextLayout >(); // we're disposed

        return new TextLayout( aText, nDirection, nRandomSeed, ImplRef( this ), mpRefDevice );
    }

    rendering::FontRequest SAL_CALL  CanvasFont::getFontRequest(  ) throw (uno::RuntimeException)
    {
        tools::LocalGuard aGuard;

        return maFontRequest;
    }

    rendering::FontMetrics SAL_CALL  CanvasFont::getFontMetrics(  ) throw (uno::RuntimeException)
    {
        tools::LocalGuard aGuard;

        // TODO(F1)
        return rendering::FontMetrics();
    }

    uno::Sequence< double > SAL_CALL  CanvasFont::getAvailableSizes(  ) throw (uno::RuntimeException)
    {
        tools::LocalGuard aGuard;

        // TODO(F1)
        return uno::Sequence< double >();
    }

    uno::Sequence< beans::PropertyValue > SAL_CALL  CanvasFont::getExtraFontProperties(  ) throw (uno::RuntimeException)
    {
        tools::LocalGuard aGuard;

        // TODO(F1)
        return uno::Sequence< beans::PropertyValue >();
    }

#define SERVICE_NAME "com.sun.star.rendering.CanvasFont"

    ::rtl::OUString SAL_CALL CanvasFont::getImplementationName() throw( uno::RuntimeException )
    {
        return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( CANVASFONT_IMPLEMENTATION_NAME ) );
    }

    sal_Bool SAL_CALL CanvasFont::supportsService( const ::rtl::OUString& ServiceName ) throw( uno::RuntimeException )
    {
        return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ) );
    }

    uno::Sequence< ::rtl::OUString > SAL_CALL CanvasFont::getSupportedServiceNames()  throw( uno::RuntimeException )
    {
        uno::Sequence< ::rtl::OUString > aRet(1);
        aRet[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );

        return aRet;
    }

    ::Font CanvasFont::getVCLFont() const
    {
        return *maFont;
    }
}
<|endoftext|>


<commit_before>#include <iostream>

#include "EightQueens.h"

namespace EightQueensProblem
{
	bool EightQueensSolver::eightQueens( bool spotTaken[8][8], int numQueensPositioned )
	{//Does the main line of work by recursively calling itself. spotTaken is an array of bools representing a board (spaces numbered 0...7 in either direction) in which true means a queen is in that spot and false means an empty spot. numQueensPositioned specifies how many queens have already been placed. Returns true if it finds a solution, false if it doesn't.
	}

	bool EightQueensSolver::isLegal( bool chessBoard[8][8] )
	{//Tests the chess board to see if there are any queens in the same row, column or diagonal. chessBoard follows the same design as spotTaken in the eightQueens method. Returns true if no queens are in the same row, column or diagonal or returns false if finds even a single queen in the same row, column or diagonal.
		int count;//Number of queens encountered in a given row/column/diagonal.

		//Check the rows.
		for( int i = 0; i < 8; i++ )
		{
			count = 0;
			for( int j = 0; j < 8; j++ )
			{
				if( chessBoard[j][i] == true )
				{//Found a queen.
					count++;
				}

				if( count > 1 )
				{//If more than one queen has been found on this row, the board isn't legal so return false.
					return false;
				}
			}
		}

		//Check the columns.
		for( int i = 0; i < 8; i++ )
		{
			count = 0;
			for( int j = 0; j < 8; j++ )
			{
				if( chessBoard[i][j] == true )
				{//Found a queen.
					count++;
				}

				if( count > 1 )
				{//If more than one queen has been found on this column, the board isn't legal so return false.
					return false;
				}
			}
		}

		//Check the diagonals.
	}

	static void printBoard( bool chessBoard[8][8] )
	{//Prints out chessBoard to standard output.
		//Go through each element one by one and print - for empty and * for queen.
		for( int i = 0; i < 8; i++ )
		{
			for( int j = 0; j < 8; j++ )
			{
				if( chessBoard[j][i] == true )
				{//Queen space
					std::cout << "*";
				}
				else
				{//Empty space
					std::cout << "-";
				}

				//Print a space after the character, but not if it's the last one since only want spaces between characters.
				if( j < 7 )
				{
					std::cout << " ";
				}
			}

			//Print an endline after the current line.
			std::cout << std::endl;
	}
}
<commit_msg>Did a little bit for the isLegal method.<commit_after>#include <iostream>

#include "EightQueens.h"

namespace EightQueensProblem
{
	bool EightQueensSolver::eightQueens( bool spotTaken[8][8], int numQueensPositioned )
	{//Does the main line of work by recursively calling itself. spotTaken is an array of bools representing a board (spaces numbered 0...7 in either direction) in which true means a queen is in that spot and false means an empty spot. numQueensPositioned specifies how many queens have already been placed. Returns true if it finds a solution, false if it doesn't.
	}

	bool EightQueensSolver::isLegal( bool chessBoard[8][8] )
	{//Tests the chess board to see if there are any queens in the same row, column or diagonal. chessBoard follows the same design as spotTaken in the eightQueens method. Returns true if no queens are in the same row, column or diagonal or returns false if finds even a single queen in the same row, column or diagonal.
		int count;//Number of queens encountered in a given row/column/diagonal.

		//Check the rows.
		for( int i = 0; i < 8; i++ )
		{
			count = 0;
			for( int j = 0; j < 8; j++ )
			{
				if( chessBoard[j][i] == true )
				{//Found a queen.
					count++;
				}

				if( count > 1 )
				{//If more than one queen has been found on this row, the board isn't legal so return false.
					return false;
				}
			}
		}

		//Check the columns.
		for( int i = 0; i < 8; i++ )
		{
			count = 0;
			for( int j = 0; j < 8; j++ )
			{
				if( chessBoard[i][j] == true )
				{//Found a queen.
					count++;
				}

				if( count > 1 )
				{//If more than one queen has been found on this column, the board isn't legal so return false.
					return false;
				}
			}
		}

		//Check the diagonals.
		for( int i
	}

	static void printBoard( bool chessBoard[8][8] )
	{//Prints out chessBoard to standard output.
		//Go through each element one by one and print - for empty and * for queen.
		for( int i = 0; i < 8; i++ )
		{
			for( int j = 0; j < 8; j++ )
			{
				if( chessBoard[j][i] == true )
				{//Queen space
					std::cout << "*";
				}
				else
				{//Empty space
					std::cout << "-";
				}

				//Print a space after the character, but not if it's the last one since only want spaces between characters.
				if( j < 7 )
				{
					std::cout << " ";
				}
			}

			//Print an endline after the current line.
			std::cout << std::endl;
	}
}
<|endoftext|>


<commit_before>#include "window.h"

namespace thirdsengine {
	namespace graphics {

		Window *Window::instance = NULL;

		Window::Window(const char *title, int width, int height) {
			instance = this;

			m_Title = title;
			m_Width = width;
			m_Height = height;
			m_Closed = false;
			if (!init())
			{
				glfwTerminate();
			}

			for (int i = 0; i < MAX_KEYS; i++)
				m_Keys[i] = false;
			for (int i = 0; i < MAX_BUTTONS; i++)
				m_Buttons[i] = false;
		}

		Window::~Window() {
			glfwTerminate();
		}

		bool Window::init() {

			if (!glfwInit()) {
				std::cout << "GLFW could not initialise!" << std::endl;
				return false;
			}

			m_Window = glfwCreateWindow(m_Width, m_Height, m_Title, NULL, NULL);
			if (!m_Window)
			{
				std::cout << "Failed to create window!" << std::endl;
				return false;
			}
			glfwMakeContextCurrent(m_Window);

			if (glewInit() != GLEW_OK) {
				std::cout << "GLEW could not initialise!" << std::endl;
				return false;
			}

			std::cout << "Using OpenGL " << glGetString(GL_VERSION) << std::endl;

			glfwSetWindowSizeCallback(	m_Window, callbackResize);
			glfwSetKeyCallback(			m_Window, callbackKey);
			glfwSetMouseButtonCallback(	m_Window, callbackMouseButton);
			glfwSetCursorPosCallback(	m_Window, callbackMouseMove);

			return true;
		}

		void Window::clear() const
		{
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		}

		void Window::update() {

			glfwPollEvents();

			glfwGetFramebufferSize(m_Window, &m_Width, &m_Height);
			glViewport(0, 0, m_Width, m_Height);

			glfwSwapBuffers(m_Window);
		}

		bool Window::closed() const {
			return glfwWindowShouldClose(m_Window) != 0;
		}

		void Window::callbackResize(GLFWwindow *window, int width, int height) {
			glViewport(0, 0, width, height);
		}

		void Window::callbackKey(GLFWwindow *window, int key, int scancode, int action, int mods) {
			instance->m_Keys[key] = (action != GLFW_RELEASE);
		}

		void Window::callbackMouseButton(GLFWwindow *window, int button, int action, int mods) {
			instance->m_Buttons[button] = (action != GLFW_RELEASE);
		}

		void Window::callbackMouseMove(GLFWwindow *window, double xpos, double ypos) {
			instance->m_MouseX = xpos;
			instance->m_MouseY = ypos;
		}

		bool Window::keyPressed(unsigned int keycode) const {
			if (keycode >= MAX_KEYS) return false;
			return m_Keys[keycode];
		}

		bool Window::mouseButtonPressed(unsigned int button) const {
			if (button >= MAX_BUTTONS) return false;
			return m_Buttons[button];
		}

		double Window::mouseX() const {
			return m_MouseX;
		}

		double Window::mouseY() const {
			return m_MouseY;
		}
	}
}<commit_msg>Catch OpenGL errors<commit_after>#include "window.h"

namespace thirdsengine {
	namespace graphics {

		Window *Window::instance = NULL;

		Window::Window(const char *title, int width, int height) {
			instance = this;

			m_Title = title;
			m_Width = width;
			m_Height = height;
			m_Closed = false;
			if (!init())
			{
				glfwTerminate();
			}

			for (int i = 0; i < MAX_KEYS; i++)
				m_Keys[i] = false;
			for (int i = 0; i < MAX_BUTTONS; i++)
				m_Buttons[i] = false;
		}

		Window::~Window() {
			glfwTerminate();
		}

		bool Window::init() {

			if (!glfwInit()) {
				std::cout << "GLFW could not initialise!" << std::endl;
				return false;
			}

			m_Window = glfwCreateWindow(m_Width, m_Height, m_Title, NULL, NULL);
			if (!m_Window)
			{
				std::cout << "Failed to create window!" << std::endl;
				return false;
			}
			glfwMakeContextCurrent(m_Window);

			if (glewInit() != GLEW_OK) {
				std::cout << "GLEW could not initialise!" << std::endl;
				return false;
			}

			std::cout << "Using OpenGL " << glGetString(GL_VERSION) << std::endl;

			glfwSetWindowSizeCallback(	m_Window, callbackResize);
			glfwSetKeyCallback(			m_Window, callbackKey);
			glfwSetMouseButtonCallback(	m_Window, callbackMouseButton);
			glfwSetCursorPosCallback(	m_Window, callbackMouseMove);

			return true;
		}

		void Window::clear() const
		{
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		}

		void Window::update() {

			GLenum error = glGetError();
			if (error != GL_NO_ERROR)
				std::cout << "OpenGL error code " << error << std::endl;

			glfwPollEvents();

			glfwGetFramebufferSize(m_Window, &m_Width, &m_Height);
			glViewport(0, 0, m_Width, m_Height);

			glfwSwapBuffers(m_Window);
		}

		bool Window::closed() const {
			return glfwWindowShouldClose(m_Window) != 0;
		}

		void Window::callbackResize(GLFWwindow *window, int width, int height) {
			glViewport(0, 0, width, height);
		}

		void Window::callbackKey(GLFWwindow *window, int key, int scancode, int action, int mods) {
			instance->m_Keys[key] = (action != GLFW_RELEASE);
		}

		void Window::callbackMouseButton(GLFWwindow *window, int button, int action, int mods) {
			instance->m_Buttons[button] = (action != GLFW_RELEASE);
		}

		void Window::callbackMouseMove(GLFWwindow *window, double xpos, double ypos) {
			instance->m_MouseX = xpos;
			instance->m_MouseY = ypos;
		}

		bool Window::keyPressed(unsigned int keycode) const {
			if (keycode >= MAX_KEYS) return false;
			return m_Keys[keycode];
		}

		bool Window::mouseButtonPressed(unsigned int button) const {
			if (button >= MAX_BUTTONS) return false;
			return m_Buttons[button];
		}

		double Window::mouseX() const {
			return m_MouseX;
		}

		double Window::mouseY() const {
			return m_MouseY;
		}
	}
}<|endoftext|>


<commit_before>#include "Models_Manager.h"

Models_Manager::Models_Manager()
{
	//TODO more elegant solution, AKA method for creating models
	// triangle game object
	Transform t1 = Transform(
		Vector3(0, 0, 0),
		Vector3(1, 1, 1),
		Quaternion()
	);

	Triangle* triangle = new Triangle(t1, Color::RED);
	triangle->SetProgram(Shader_Manager::GetShader("colorShader"));
	triangle->Create();
	gameModelList["triangle"] = triangle;

	Transform t2 = Transform(
		Vector3(0, 0, 0),
		Vector3(0.5, 0.5, 1),
		Quaternion(1.0, 0.5, 0.5, 0.5)
	);

	Quad* quad = new Quad(t2, Color::RED);
	quad->SetProgram(Shader_Manager::GetShader("colorShader"));
	quad->Create();
	gameModelList["quad"] = quad;
}

Models_Manager::~Models_Manager()
{
	// iterate through map
	for (auto model : gameModelList)
	{
		delete model.second;
	}
	gameModelList.clear();
}

void Models_Manager::DeleteModel(const std::string& gameModelName)
{
	IGameObject* model = gameModelList[gameModelName];
	model->Destroy();
	gameModelList.erase(gameModelName);
}

const IGameObject& Models_Manager::GetModel(const std::string& gameModelName)
{
	return (*gameModelList.at(gameModelName));
}

void Models_Manager::Update()
{
	// iterate through model list and Update
	for (auto model : gameModelList)
	{
		model.second->Update();
	}
}

void Models_Manager::Draw()
{
	// iterate through model list and Draw
	for (auto model : gameModelList)
	{
		model.second->Draw();
	}
}<commit_msg>Demo: Mountain range<commit_after>#include "Models_Manager.h"

Models_Manager::Models_Manager()
{
	Triangle* triangle1 = new Triangle(Transform(
		Vector3(-25, 25, 0),
		Vector3(0.5, 0.5, 1),
		Quaternion()), Color::Darken(Color::GREEN, 0.3));
	triangle1->SetProgram(Shader_Manager::GetShader("colorShader"));
	triangle1->Create();
	gameModelList["triangle1"] = triangle1;

	Triangle* triangle2 = new Triangle(Transform(
		Vector3(25, 25, 50),
		Vector3(1, 1, 1),
		Quaternion()), Color::Darken(Color::GREEN, 0.3));
	triangle2->SetProgram(Shader_Manager::GetShader("colorShader"));
	triangle2->Create();
	gameModelList["triangle2"] = triangle2;

	Quad* quad1 = new Quad(Transform(
		Vector3(0, 0, -100),
		Vector3(2, 0.25, 1),
		Quaternion()), Color::HSV(0.45, 0.60, 0.20));
	quad1->SetProgram(Shader_Manager::GetShader("colorShader"));
	quad1->Create();
	gameModelList["quad1"] = quad1;
}
Models_Manager::~Models_Manager()
{
	// iterate through map
	for (auto model : gameModelList)
	{
		delete model.second;
	}
	gameModelList.clear();
}

void Models_Manager::DeleteModel(const std::string& gameModelName)
{
	IGameObject* model = gameModelList[gameModelName];
	model->Destroy();
	gameModelList.erase(gameModelName);
}

const IGameObject& Models_Manager::GetModel(const std::string& gameModelName)
{
	return (*gameModelList.at(gameModelName));
}

void Models_Manager::Update()
{
	// iterate through model list and Update
	for (auto model : gameModelList)
	{
		model.second->Update();
	}
}

void Models_Manager::Draw()
{
	// iterate through model list and Draw
	for (auto model : gameModelList)
	{
		model.second->Draw();
	}
}<|endoftext|>


<commit_before>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2015 ETH Zurich
 ** All rights reserved.
 **
 ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 ** following conditions are met:
 **
 **    * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 **      following disclaimer.
 **    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 **      following disclaimer in the documentation and/or other materials provided with the distribution.
 **    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
 **      derived from this software without specific prior written permission.
 **
 **
 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/

#include "ClangHelpers.h"

#include "OOModel/src/declarations/Project.h"
#include "OOModel/src/declarations/MetaDefinition.h"

#include "CppExport/src/exporter/CppExporter.h"
#include "CppExport/src/CodeUnit.h"

namespace CppImport {

QString ClangHelpers::spelling(clang::SourceRange sourceRange) const
{
	clang::SourceLocation b = sourceManager_->getSpellingLoc(sourceRange.getBegin());
	clang::SourceLocation e = clang::Lexer::getLocForEndOfToken(sourceManager_->getSpellingLoc(sourceRange.getEnd()), 0,
																					*sourceManager_, preprocessor_->getLangOpts());

	// this can help in preventing an uncaught exception due to questionable input
	//if (sourceManager_->getPresumedLoc(b).getFilename() != sourceManager_->getPresumedLoc(e).getFilename()) return "";

	bool invalid = true;
	auto beginPtr = sourceManager_->getCharacterData(b, &invalid);
	Q_ASSERT(!invalid);

	auto endPtr = sourceManager_->getCharacterData(e, &invalid);
	Q_ASSERT(!invalid);

	auto length = endPtr - beginPtr;
	return 0 < length ? QString::fromStdString(std::string(beginPtr, endPtr - beginPtr)) : "";
}

QString ClangHelpers::unexpandedSpelling(clang::SourceRange range) const
{
	auto result = spelling(getUnexpandedRange(range));
	while (result.startsWith("\\")) result = result.right(result.length() - 1);
	return result.trimmed();
}

clang::SourceRange ClangHelpers::getUnexpandedRange(clang::SourceRange sourceRange) const
{
	auto start = sourceRange.getBegin();
	auto end = sourceRange.getEnd();

	if (// start is a macro location and...
		 start.isMacroID() &&
		 // start was expanded from a macro argument or...
		 (sourceManager_->isMacroArgExpansion(start) ||
		 // start was expanded from a "virtual" macro i.e. it is not written anywhere (identifier concatentation etc.)
		 !sourceManager_->getFileEntryForID(sourceManager_->getFileID(sourceManager_->getSpellingLoc(start)))))
		start = sourceManager_->getImmediateExpansionRange(start).first;

	if (// end is a macro location and...
		 end.isMacroID() &&
		 // end was expanded from a macro argument or...
		 (sourceManager_->isMacroArgExpansion(end) ||
		 // end was expanded from a "virtual" macro i.e. it is not written anywhere (identifier concatentation etc.)
		 !sourceManager_->getFileEntryForID(sourceManager_->getFileID(sourceManager_->getSpellingLoc(end)))))
		end = sourceManager_->getImmediateExpansionRange(end).second;

	return clang::SourceRange{start, end};
}

ClangHelpers::ClangHelpers(OOModel::Project* rootProject, QString rootProjectPath)
	: rootProject_{rootProject}, rootProjectPath_{rootProjectPath} {}

clang::SourceLocation ClangHelpers::immediateMacroLocation(clang::SourceLocation location) const
{
	// this code is an adaptation of clang::lexer::immediateMacroName

	if (location.isMacroID())
		while (true)
		{
			auto fileID = sourceManager_->getFileID(location);
			auto sourceLocationEntry = &sourceManager_->getSLocEntry(fileID);
			if (!sourceLocationEntry->isExpansion()) break;

			auto expansion = sourceLocationEntry->getExpansion();
			location = expansion.getExpansionLocStart();
			if (!expansion.isMacroArgExpansion()) break;

			location = sourceManager_->getImmediateExpansionRange(location).first;
			auto spellingLocation = expansion.getSpellingLoc();
			if (spellingLocation.isFileID())	break;

			auto macroFileID = sourceManager_->getFileID(location);
			if (sourceManager_->isInFileID(spellingLocation, macroFileID))	break;

			location = spellingLocation;
		}

	return location;
}

void ClangHelpers::immediateSpellingHistory(clang::SourceLocation location,
														  QList<clang::SourceLocation>& result) const
{
	result.append(location);

	auto next = sourceManager_->getImmediateSpellingLoc(location);

	if (next != location)
		immediateSpellingHistory(next, result);
}

QList<QString> ClangHelpers::argumentNames(const clang::MacroDirective* definition) const
{
	QList<QString> result;

	for (auto i = definition->getMacroInfo()->arg_begin(); i != definition->getMacroInfo()->arg_end(); i++)
		result.append(QString::fromStdString((*i)->getName().str()));

	return result;
}

void ClangHelpers::deleteNode(Model::Node* node)
{
	QList<Model::Node*> workList{node};
	while (!workList.empty())
	{
		auto current = workList.takeLast();
		workList << current->children();
		envisionToClangMap_.remove(current);
	}

	SAFE_DELETE(node);
}

QStringList ClangHelpers::folderNamesFromPath(QString path)
{
	QStringList result;
	QDir dir{path};
	while (dir.cdUp())
	{
		if (dir.absolutePath() == rootProjectPath_) break;
		result.append(dir.dirName());
	}
	result.removeLast();
	return result;
}

void ClangHelpers::insertDeclarationInFolder(OOModel::Declaration* declaration, clang::SourceLocation location,
															OOModel::Declaration* parentNonFolderDeclaration)
{
	auto inserter = [declaration](auto container)
	{
		if (auto castedDeclaration = DCast<OOModel::Field>(declaration))
			container->fields()->append(castedDeclaration);
		else if (auto castedDeclaration = DCast<OOModel::Class>(declaration))
			container->classes()->append(castedDeclaration);
		else if (auto castedDeclaration = DCast<OOModel::Method>(declaration))
			container->methods()->append(castedDeclaration);
		else if (auto castedDeclaration = DCast<OOModel::MetaDefinition>(declaration))
			container->subDeclarations()->append(castedDeclaration);
	};
	auto folder = folderForLocation(location, parentNonFolderDeclaration);
	if (auto container = DCast<OOModel::Project>(folder)) inserter(container);
	else if (auto container = DCast<OOModel::Module>(folder)) inserter(container);
	else Q_ASSERT(false);
}

QString ClangHelpers::presumedFilenameWithExtension(clang::SourceLocation location) const
{
	auto presumedLocation = sourceManager_->getPresumedLoc(location);
	QDir dir{presumedLocation.getFilename()};
	auto fileName = dir.absolutePath();
	return fileName;
}

QString ClangHelpers::presumedFilenameWithoutExtension(clang::SourceLocation location) const
{
	auto fileName = presumedFilenameWithExtension(location);
	return fileName.left(fileName.lastIndexOf("."));
}

OOModel::Declaration* ClangHelpers::folderForLocation(clang::SourceLocation location,
																		OOModel::Declaration* parentNonFolderDeclaration)
{
	Q_ASSERT(parentNonFolderDeclaration);
	Q_ASSERT(DCast<OOModel::Module>(parentNonFolderDeclaration) || DCast<OOModel::Project>(parentNonFolderDeclaration));

	auto currentFolder = parentNonFolderDeclaration;
	auto presumedLocation = sourceManager()->getPresumedLoc(location);
	auto folderNames = folderNamesFromPath(presumedLocation.getFilename());
	while (!folderNames.empty())
	{
		auto requestedFolderName = folderNames.takeLast();
		auto moduleFound = false;
		Model::TypedList<OOModel::Module>* modules{};
		if (auto currentProject = DCast<OOModel::Project>(currentFolder))
			modules = currentProject->modules();
		else if (auto currentModule = DCast<OOModel::Module>(currentFolder))
			modules = currentModule->modules();

		for (auto childFolder : *modules)
			if (childFolder->name() == requestedFolderName)
			{
				currentFolder = childFolder;
				moduleFound = true;
				break;
			}
		if (!moduleFound)
		{
			auto newFolder = new OOModel::Module{requestedFolderName, OOModel::Module::ModuleKind::Folder};
			if (auto currentProject = DCast<OOModel::Project>(currentFolder))
				currentProject->modules()->append(newFolder);
			else if (auto currentModule = DCast<OOModel::Module>(currentFolder))
				currentModule->modules()->append(newFolder);
			currentFolder = newFolder;
		}
	}

	Q_ASSERT(DCast<OOModel::Module>(currentFolder) || DCast<OOModel::Project>(currentFolder));
	return currentFolder;
}

OOModel::Project* ClangHelpers::projectForLocation(clang::SourceLocation location)
{
	auto presumedLocation = sourceManager()->getPresumedLoc(location);
	auto parentName = projectNameFromPath(presumedLocation.getFilename());
	if (!parentName.isEmpty())
	{
		auto project = projectByName(parentName);
		if (!project)
		{
			project = new OOModel::Project{parentName};
			rootProject_->projects()->append(project);
			projects_.insert(parentName, project);
		}
		return project;
	}
	return rootProject_;
}

QString ClangHelpers::projectNameFromPath(QString path)
{
	QRegularExpression regex{rootProjectPath_ + "/(\\w+)/"};
	auto m = regex.match(QDir{path}.absolutePath());
	if (m.hasMatch())
		return m.captured(1);
	return {};
}

void ClangHelpers::attachDeclarationComments(clang::NamedDecl* namedDecl, Model::Node* receiver) const
{
	if (auto commentForDeclaration = namedDecl->getASTContext().getRawCommentForDeclNoCache(namedDecl))
	{
		auto compositeNode = DCast<Model::CompositeNode>(receiver);
		Q_ASSERT(compositeNode);

		for (Comment* clangComment : comments_)
			if (clangComment->rawComment() == commentForDeclaration && !clangComment->node())
			{
				clangComment->setNode(compositeNode);

				if (compositeNode->comment())
				{
					// This code is here for future reference, but we don't actually support this case at the moment.
					// It would be necessary to check if the lines we are about to attach already exist.
					return;

					auto commentNode = DCast<Comments::CommentNode>(compositeNode->comment());
					Q_ASSERT(commentNode);

					commentNode->appendText(clangComment->text());
				}
				else compositeNode->setComment(new Comments::CommentNode{clangComment->text()});
			}
	}
}

void ClangHelpers::printMacroDefinitionForDebug(const clang::MacroDirective* macroDirective) const
{
	qDebug() << "Macro in: " << presumedFilenameWithExtension(macroDirective->getMacroInfo()->getDefinitionLoc());
	qDebug() << spelling(clang::SourceRange{macroDirective->getMacroInfo()->getDefinitionLoc(),
																  macroDirective->getMacroInfo()->getDefinitionEndLoc()});
}

void ClangHelpers::associateNodeWithPresumedFileLocation(Model::Node* node, clang::SourceLocation location)
{
	auto fullPath = presumedFilenameWithoutExtension(location);
	nodeToFilenameMap_ [node] = fullPath.right(fullPath.size() - rootProjectPath_.size() - 1);
}

void ClangHelpers::associateNodeWithPresumedFileLocation(Model::Node* node, Model::Node* from)
{
	auto it = nodeToFilenameMap_.find(from);
	Q_ASSERT(it != nodeToFilenameMap_.end());
	nodeToFilenameMap_[node] = *it;
}

void ClangHelpers::exportMergeMapToJson(QString filename)
{
	QHash<QString, QString> exportedMap;
	QList<CppExport::CodeUnit*> codeUnits;
	CppExport::CppExporter::units(rootProject_, codeUnits, exportedMap);

	QHash<QString, QString> generatedExportedMap;
	for (auto unit : codeUnits)
	{
		auto nodeFilename = nodeToFilenameMap_[unit->node()];

		if (generatedExportedMap.contains(unit->name()))
		{
			if (generatedExportedMap.value(unit->name()) != nodeFilename)
			{
				qDebug() << unit->name() << "mapped at least twice with different values:";
				qDebug() << "1:   " << nodeFilename;
				qDebug() << "2:   " << generatedExportedMap.value(unit->name());
				Q_ASSERT(false);
			}
		}
		else if (unit->name() != nodeFilename)
			generatedExportedMap.insert(unit->name(), nodeFilename);
	}

	QFile file{filename};
	file.open(QIODevice::WriteOnly | QIODevice::Text);
	QTextStream out{&file};
	out << "{\n";
	out << "\t\"DependencyUnitMergeMap\" :\n";
	out << "\t{\n";
	for (auto it = generatedExportedMap.begin(); it != generatedExportedMap.end(); it++)
		if (it.key() != it.value())
			out << "\t\t\"" << it.key() << "\" : \"" << it.value() << "\",\n";
	out << "\t},\n";
	out << "\t\"SeparateTemplateImplementationSet\" : [ ]\n";
	out << "}";
	file.close();
}

}
<commit_msg>do not automatically generate merge map entries for special code units<commit_after>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2015 ETH Zurich
 ** All rights reserved.
 **
 ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 ** following conditions are met:
 **
 **    * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 **      following disclaimer.
 **    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 **      following disclaimer in the documentation and/or other materials provided with the distribution.
 **    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
 **      derived from this software without specific prior written permission.
 **
 **
 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/

#include "ClangHelpers.h"

#include "OOModel/src/declarations/Project.h"
#include "OOModel/src/declarations/MetaDefinition.h"

#include "CppExport/src/exporter/CppExporter.h"
#include "CppExport/src/CodeUnit.h"

namespace CppImport {

QString ClangHelpers::spelling(clang::SourceRange sourceRange) const
{
	clang::SourceLocation b = sourceManager_->getSpellingLoc(sourceRange.getBegin());
	clang::SourceLocation e = clang::Lexer::getLocForEndOfToken(sourceManager_->getSpellingLoc(sourceRange.getEnd()), 0,
																					*sourceManager_, preprocessor_->getLangOpts());

	// this can help in preventing an uncaught exception due to questionable input
	//if (sourceManager_->getPresumedLoc(b).getFilename() != sourceManager_->getPresumedLoc(e).getFilename()) return "";

	bool invalid = true;
	auto beginPtr = sourceManager_->getCharacterData(b, &invalid);
	Q_ASSERT(!invalid);

	auto endPtr = sourceManager_->getCharacterData(e, &invalid);
	Q_ASSERT(!invalid);

	auto length = endPtr - beginPtr;
	return 0 < length ? QString::fromStdString(std::string(beginPtr, endPtr - beginPtr)) : "";
}

QString ClangHelpers::unexpandedSpelling(clang::SourceRange range) const
{
	auto result = spelling(getUnexpandedRange(range));
	while (result.startsWith("\\")) result = result.right(result.length() - 1);
	return result.trimmed();
}

clang::SourceRange ClangHelpers::getUnexpandedRange(clang::SourceRange sourceRange) const
{
	auto start = sourceRange.getBegin();
	auto end = sourceRange.getEnd();

	if (// start is a macro location and...
		 start.isMacroID() &&
		 // start was expanded from a macro argument or...
		 (sourceManager_->isMacroArgExpansion(start) ||
		 // start was expanded from a "virtual" macro i.e. it is not written anywhere (identifier concatentation etc.)
		 !sourceManager_->getFileEntryForID(sourceManager_->getFileID(sourceManager_->getSpellingLoc(start)))))
		start = sourceManager_->getImmediateExpansionRange(start).first;

	if (// end is a macro location and...
		 end.isMacroID() &&
		 // end was expanded from a macro argument or...
		 (sourceManager_->isMacroArgExpansion(end) ||
		 // end was expanded from a "virtual" macro i.e. it is not written anywhere (identifier concatentation etc.)
		 !sourceManager_->getFileEntryForID(sourceManager_->getFileID(sourceManager_->getSpellingLoc(end)))))
		end = sourceManager_->getImmediateExpansionRange(end).second;

	return clang::SourceRange{start, end};
}

ClangHelpers::ClangHelpers(OOModel::Project* rootProject, QString rootProjectPath)
	: rootProject_{rootProject}, rootProjectPath_{rootProjectPath} {}

clang::SourceLocation ClangHelpers::immediateMacroLocation(clang::SourceLocation location) const
{
	// this code is an adaptation of clang::lexer::immediateMacroName

	if (location.isMacroID())
		while (true)
		{
			auto fileID = sourceManager_->getFileID(location);
			auto sourceLocationEntry = &sourceManager_->getSLocEntry(fileID);
			if (!sourceLocationEntry->isExpansion()) break;

			auto expansion = sourceLocationEntry->getExpansion();
			location = expansion.getExpansionLocStart();
			if (!expansion.isMacroArgExpansion()) break;

			location = sourceManager_->getImmediateExpansionRange(location).first;
			auto spellingLocation = expansion.getSpellingLoc();
			if (spellingLocation.isFileID())	break;

			auto macroFileID = sourceManager_->getFileID(location);
			if (sourceManager_->isInFileID(spellingLocation, macroFileID))	break;

			location = spellingLocation;
		}

	return location;
}

void ClangHelpers::immediateSpellingHistory(clang::SourceLocation location,
														  QList<clang::SourceLocation>& result) const
{
	result.append(location);

	auto next = sourceManager_->getImmediateSpellingLoc(location);

	if (next != location)
		immediateSpellingHistory(next, result);
}

QList<QString> ClangHelpers::argumentNames(const clang::MacroDirective* definition) const
{
	QList<QString> result;

	for (auto i = definition->getMacroInfo()->arg_begin(); i != definition->getMacroInfo()->arg_end(); i++)
		result.append(QString::fromStdString((*i)->getName().str()));

	return result;
}

void ClangHelpers::deleteNode(Model::Node* node)
{
	QList<Model::Node*> workList{node};
	while (!workList.empty())
	{
		auto current = workList.takeLast();
		workList << current->children();
		envisionToClangMap_.remove(current);
	}

	SAFE_DELETE(node);
}

QStringList ClangHelpers::folderNamesFromPath(QString path)
{
	QStringList result;
	QDir dir{path};
	while (dir.cdUp())
	{
		if (dir.absolutePath() == rootProjectPath_) break;
		result.append(dir.dirName());
	}
	result.removeLast();
	return result;
}

void ClangHelpers::insertDeclarationInFolder(OOModel::Declaration* declaration, clang::SourceLocation location,
															OOModel::Declaration* parentNonFolderDeclaration)
{
	auto inserter = [declaration](auto container)
	{
		if (auto castedDeclaration = DCast<OOModel::Field>(declaration))
			container->fields()->append(castedDeclaration);
		else if (auto castedDeclaration = DCast<OOModel::Class>(declaration))
			container->classes()->append(castedDeclaration);
		else if (auto castedDeclaration = DCast<OOModel::Method>(declaration))
			container->methods()->append(castedDeclaration);
		else if (auto castedDeclaration = DCast<OOModel::MetaDefinition>(declaration))
			container->subDeclarations()->append(castedDeclaration);
	};
	auto folder = folderForLocation(location, parentNonFolderDeclaration);
	if (auto container = DCast<OOModel::Project>(folder)) inserter(container);
	else if (auto container = DCast<OOModel::Module>(folder)) inserter(container);
	else Q_ASSERT(false);
}

QString ClangHelpers::presumedFilenameWithExtension(clang::SourceLocation location) const
{
	auto presumedLocation = sourceManager_->getPresumedLoc(location);
	QDir dir{presumedLocation.getFilename()};
	auto fileName = dir.absolutePath();
	return fileName;
}

QString ClangHelpers::presumedFilenameWithoutExtension(clang::SourceLocation location) const
{
	auto fileName = presumedFilenameWithExtension(location);
	return fileName.left(fileName.lastIndexOf("."));
}

OOModel::Declaration* ClangHelpers::folderForLocation(clang::SourceLocation location,
																		OOModel::Declaration* parentNonFolderDeclaration)
{
	Q_ASSERT(parentNonFolderDeclaration);
	Q_ASSERT(DCast<OOModel::Module>(parentNonFolderDeclaration) || DCast<OOModel::Project>(parentNonFolderDeclaration));

	auto currentFolder = parentNonFolderDeclaration;
	auto presumedLocation = sourceManager()->getPresumedLoc(location);
	auto folderNames = folderNamesFromPath(presumedLocation.getFilename());
	while (!folderNames.empty())
	{
		auto requestedFolderName = folderNames.takeLast();
		auto moduleFound = false;
		Model::TypedList<OOModel::Module>* modules{};
		if (auto currentProject = DCast<OOModel::Project>(currentFolder))
			modules = currentProject->modules();
		else if (auto currentModule = DCast<OOModel::Module>(currentFolder))
			modules = currentModule->modules();

		for (auto childFolder : *modules)
			if (childFolder->name() == requestedFolderName)
			{
				currentFolder = childFolder;
				moduleFound = true;
				break;
			}
		if (!moduleFound)
		{
			auto newFolder = new OOModel::Module{requestedFolderName, OOModel::Module::ModuleKind::Folder};
			if (auto currentProject = DCast<OOModel::Project>(currentFolder))
				currentProject->modules()->append(newFolder);
			else if (auto currentModule = DCast<OOModel::Module>(currentFolder))
				currentModule->modules()->append(newFolder);
			currentFolder = newFolder;
		}
	}

	Q_ASSERT(DCast<OOModel::Module>(currentFolder) || DCast<OOModel::Project>(currentFolder));
	return currentFolder;
}

OOModel::Project* ClangHelpers::projectForLocation(clang::SourceLocation location)
{
	auto presumedLocation = sourceManager()->getPresumedLoc(location);
	auto parentName = projectNameFromPath(presumedLocation.getFilename());
	if (!parentName.isEmpty())
	{
		auto project = projectByName(parentName);
		if (!project)
		{
			project = new OOModel::Project{parentName};
			rootProject_->projects()->append(project);
			projects_.insert(parentName, project);
		}
		return project;
	}
	return rootProject_;
}

QString ClangHelpers::projectNameFromPath(QString path)
{
	QRegularExpression regex{rootProjectPath_ + "/(\\w+)/"};
	auto m = regex.match(QDir{path}.absolutePath());
	if (m.hasMatch())
		return m.captured(1);
	return {};
}

void ClangHelpers::attachDeclarationComments(clang::NamedDecl* namedDecl, Model::Node* receiver) const
{
	if (auto commentForDeclaration = namedDecl->getASTContext().getRawCommentForDeclNoCache(namedDecl))
	{
		auto compositeNode = DCast<Model::CompositeNode>(receiver);
		Q_ASSERT(compositeNode);

		for (Comment* clangComment : comments_)
			if (clangComment->rawComment() == commentForDeclaration && !clangComment->node())
			{
				clangComment->setNode(compositeNode);

				if (compositeNode->comment())
				{
					// This code is here for future reference, but we don't actually support this case at the moment.
					// It would be necessary to check if the lines we are about to attach already exist.
					return;

					auto commentNode = DCast<Comments::CommentNode>(compositeNode->comment());
					Q_ASSERT(commentNode);

					commentNode->appendText(clangComment->text());
				}
				else compositeNode->setComment(new Comments::CommentNode{clangComment->text()});
			}
	}
}

void ClangHelpers::printMacroDefinitionForDebug(const clang::MacroDirective* macroDirective) const
{
	qDebug() << "Macro in: " << presumedFilenameWithExtension(macroDirective->getMacroInfo()->getDefinitionLoc());
	qDebug() << spelling(clang::SourceRange{macroDirective->getMacroInfo()->getDefinitionLoc(),
																  macroDirective->getMacroInfo()->getDefinitionEndLoc()});
}

void ClangHelpers::associateNodeWithPresumedFileLocation(Model::Node* node, clang::SourceLocation location)
{
	auto fullPath = presumedFilenameWithoutExtension(location);
	nodeToFilenameMap_ [node] = fullPath.right(fullPath.size() - rootProjectPath_.size() - 1);
}

void ClangHelpers::associateNodeWithPresumedFileLocation(Model::Node* node, Model::Node* from)
{
	auto it = nodeToFilenameMap_.find(from);
	Q_ASSERT(it != nodeToFilenameMap_.end());
	nodeToFilenameMap_[node] = *it;
}

void ClangHelpers::exportMergeMapToJson(QString filename)
{
	QHash<QString, QString> exportedMap;
	QList<CppExport::CodeUnit*> codeUnits;
	CppExport::CppExporter::units(rootProject_, codeUnits, exportedMap);

	QHash<QString, QString> generatedExportedMap;
	for (auto unit : codeUnits)
	{
		// exportedMap contains only the special created code units (like external template instantiations that were
		// inside classes). These special code units should not appear in the exported merge map.
		if (exportedMap.contains(unit->name())) continue;

		auto nodeFilename = nodeToFilenameMap_[unit->node()];

		if (generatedExportedMap.contains(unit->name()))
		{
			if (generatedExportedMap.value(unit->name()) != nodeFilename)
			{
				qDebug() << unit->name() << "mapped at least twice with different values:";
				qDebug() << "1:   " << nodeFilename;
				qDebug() << "2:   " << generatedExportedMap.value(unit->name());
				Q_ASSERT(false);
			}
		}
		else if (unit->name() != nodeFilename)
			generatedExportedMap.insert(unit->name(), nodeFilename);
	}

	QFile file{filename};
	file.open(QIODevice::WriteOnly | QIODevice::Text);
	QTextStream out{&file};
	out << "{\n";
	out << "\t\"DependencyUnitMergeMap\" :\n";
	out << "\t{\n";
	for (auto it = generatedExportedMap.begin(); it != generatedExportedMap.end(); it++)
		if (it.key() != it.value())
			out << "\t\t\"" << it.key() << "\" : \"" << it.value() << "\",\n";
	out << "\t},\n";
	out << "\t\"SeparateTemplateImplementationSet\" : [ ]\n";
	out << "}";
	file.close();
}

}
<|endoftext|>


<commit_before><commit_msg>Bug fixes<commit_after><|endoftext|>


<commit_before>#include "network.h"
#include <QDebug>

Network::Network(QObject *parent) :QObject(parent)
{
    my_socket = new QUdpSocket(this);
    my_socket->bind(QHostAddress::LocalHost, 1337);
    connect(my_socket, SIGNAL(readyRead()),
            this, SLOT(processPendingDatagram()));
}

void Network::sendData(QImage image)
{
    QByteArray q;
    QBuffer buffer(&q);
    buffer.open(QIODevice::WriteOnly);
    image.save(&buffer);
    my_socket->writeDatagram(q, QHostAddress::LocalHost, 1337);
}

void Network::processPendingDatagram()
{

    while (my_socket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(my_socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        my_socket->readDatagram(datagram.data(), datagram.size(),
                                &sender, &senderPort);
        //QImage recv_image((uchar*)datagram.data(), 240, 150, QImage::Format_RGB888);
        QImage recv_image;
        recv_image.loadFromData(datagram, "PNG");

        if (recv_image.isNull())		      // Check if the image was indeed received
                qDebug("The image is null. Something failed.");
        image = recv_image;
   }
    //image = QImage("debug/images/kep.png").scaledToHeight(240).scaledToHeight(150);
}

QImage Network::get_image()
{
    return image;
}

Network::~Network()
{
    delete my_socket;
}
<commit_msg>network working<commit_after>#include "network.h"
#include <QDebug>

Network::Network(QObject *parent) :QObject(parent)
{
    my_socket = new QUdpSocket(this);
    my_socket->bind(QHostAddress::LocalHost, 1337);
    connect(my_socket, SIGNAL(readyRead()),
            this, SLOT(processPendingDatagram()));
}

void Network::sendData(QImage image)
{
    QByteArray q;
    QBuffer buffer(&q);
    buffer.open(QIODevice::WriteOnly);
    image.save(&buffer, "PNG");
    my_socket->writeDatagram(q, QHostAddress::LocalHost, 1337);
}

void Network::processPendingDatagram()
{

    while (my_socket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(my_socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        my_socket->readDatagram(datagram.data(), datagram.size(),
                                &sender, &senderPort);
        //QImage recv_image((uchar*)datagram.data(), 240, 150, QImage::Format_RGB888);
        QImage recv_image;
        if (datagram.isNull())
            qDebug("Ures a bejovo buzi!!");
        else
            qDebug("datagram nem ures");
        recv_image.loadFromData(datagram, "PNG");

        if (recv_image.isNull())		      // Check if the image was indeed received
                qDebug("The image is null. Something failed.");
        image = recv_image;
   }
    //image = QImage("debug/images/kep.png").scaledToHeight(240).scaledToHeight(150);
}

QImage Network::get_image()
{
    return image;
}

Network::~Network()
{
    delete my_socket;
}
<|endoftext|>