<commit_before>/*************************************************************************
 *
 *  $RCSfile: NameContainer.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2004-11-16 10:48:06 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _NAMECONTAINER_HXX
#define _NAMECONTAINER_HXX

#include <cppuhelper/implbase1.hxx>
#include <map>

#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/container/NoSuchElementException.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <com/sun/star/lang/WrappedTargetException.hpp>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/uno/Type.hxx>

typedef cppu::WeakImplHelper1<
    com::sun::star::container::XNameContainer
> NameContainer_t;

template<class T>
class NameContainer : public NameContainer_t
{
protected:
    typedef std::map<rtl::OUString,T> map_t;
    map_t maItems;

    bool hasItems()
    {
        return ! maItems.empty();
    }

    typename map_t::const_iterator findItem( const rtl::OUString& rName )
    {
        return maItems.find( rName );
    }

    bool hasItem( const rtl::OUString& rName )
    {
        return findItem( rName ) != maItems.end();
    }

    T getItem( const rtl::OUString& rName )
    {
        OSL_ENSURE( hasItem( rName ), "can't get non-existant item" );
        return maItems[ rName ];
    }

    void replace( const rtl::OUString& rName,
                  const T& aElement )
    {
        OSL_ENSURE( hasItem( rName ), "unknown item" );
        maItems[ rName ] = aElement;
    }

    void insert( const rtl::OUString& rName,
                 const T& aElement )
    {
        OSL_ENSURE( ! hasItem( rName ), "item already in set" );
        maItems[ rName ] = aElement;
    }

    void remove( const rtl::OUString& rName )
    {
        OSL_ENSURE( hasItem( rName ), "item not in set" );
        maItems.erase( rName );
    }

public:

    NameContainer() {}
    virtual ~NameContainer() {}

    //
    // methods for XElementAccess
    //

    virtual com::sun::star::uno::Type SAL_CALL getElementType()
        throw( com::sun::star::uno::RuntimeException )
    {
        return getCppuType( static_cast<T*>( NULL ) );
    }

    virtual sal_Bool SAL_CALL hasElements()
        throw( com::sun::star::uno::RuntimeException )
    {
        return hasItems();
    }

    //
    // methods for XNameAccess (inherits XElementAccess)
    //

    virtual com::sun::star::uno::Any SAL_CALL getByName(
        const rtl::OUString& rName )
        throw( com::sun::star::container::NoSuchElementException,
               com::sun::star::lang::WrappedTargetException,
               com::sun::star::uno::RuntimeException )
    {
        typename map_t::const_iterator aIter = findItem( rName );
        if( aIter == maItems.end() )
            throw com::sun::star::container::NoSuchElementException();
        else
            return com::sun::star::uno::makeAny( aIter->second );
    }

    virtual com::sun::star::uno::Sequence<rtl::OUString> SAL_CALL getElementNames()
        throw( com::sun::star::uno::RuntimeException )
    {
        com::sun::star::uno::Sequence<rtl::OUString> aSequence( maItems.size() );
        typename map_t::const_iterator aIter = maItems.begin();
        rtl::OUString* pStrings = aSequence.getArray();
        while( aIter != maItems.end() )
        {
            *pStrings = aIter->first;
            ++aIter;
            ++pStrings;
        }
        OSL_ENSURE( pStrings == aSequence.getArray() + aSequence.getLength(),
                    "sequence not of right size; possible buffer overflow" );
        return aSequence;
    }

    virtual sal_Bool SAL_CALL hasByName(
        const rtl::OUString& rName )
        throw( com::sun::star::uno::RuntimeException )
    {
        return hasItem( rName );
    }

    //
    // methods for XNameReplace (inherits XNameAccess)
    //

    virtual void SAL_CALL replaceByName(
        const rtl::OUString& rName,
        const com::sun::star::uno::Any& aElement )
        throw( com::sun::star::lang::IllegalArgumentException,
               com::sun::star::container::NoSuchElementException,
               com::sun::star::lang::WrappedTargetException,
               com::sun::star::uno::RuntimeException)
    {
        T aItem;
        if( aElement >>= aItem )
            if( hasByName( rName ) )
                replace( rName, aItem );
            else
                throw com::sun::star::container::NoSuchElementException();
        else
            throw com::sun::star::lang::IllegalArgumentException();
    }

    //
    // methods for XNameContainer (inherits XNameReplace)
    //

    virtual void SAL_CALL insertByName(
        const rtl::OUString& rName,
        const com::sun::star::uno::Any& aElement )
        throw( com::sun::star::lang::IllegalArgumentException,
               com::sun::star::container::ElementExistException,
               com::sun::star::lang::WrappedTargetException,
               com::sun::star::uno::RuntimeException )
    {
        T aItem;
        if( aElement >>= aItem )
            if( ! hasByName( rName ) )
                insert( rName, aItem );
            else
                throw com::sun::star::container::ElementExistException();
        else
            throw com::sun::star::lang::IllegalArgumentException();
    }

    virtual void SAL_CALL removeByName(
        const rtl::OUString& rName )
        throw( com::sun::star::container::NoSuchElementException,
               com::sun::star::lang::WrappedTargetException,
               com::sun::star::uno::RuntimeException)
    {
        if( hasByName( rName ) )
            remove( rName );
        else
            throw com::sun::star::container::NoSuchElementException();
    }

};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.90); FILE MERGED 2005/09/05 13:50:53 rt 1.2.90.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: NameContainer.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 23:13:30 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#ifndef _NAMECONTAINER_HXX
#define _NAMECONTAINER_HXX

#include <cppuhelper/implbase1.hxx>
#include <map>

#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/container/NoSuchElementException.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <com/sun/star/lang/WrappedTargetException.hpp>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/uno/Type.hxx>

typedef cppu::WeakImplHelper1<
    com::sun::star::container::XNameContainer
> NameContainer_t;

template<class T>
class NameContainer : public NameContainer_t
{
protected:
    typedef std::map<rtl::OUString,T> map_t;
    map_t maItems;

    bool hasItems()
    {
        return ! maItems.empty();
    }

    typename map_t::const_iterator findItem( const rtl::OUString& rName )
    {
        return maItems.find( rName );
    }

    bool hasItem( const rtl::OUString& rName )
    {
        return findItem( rName ) != maItems.end();
    }

    T getItem( const rtl::OUString& rName )
    {
        OSL_ENSURE( hasItem( rName ), "can't get non-existant item" );
        return maItems[ rName ];
    }

    void replace( const rtl::OUString& rName,
                  const T& aElement )
    {
        OSL_ENSURE( hasItem( rName ), "unknown item" );
        maItems[ rName ] = aElement;
    }

    void insert( const rtl::OUString& rName,
                 const T& aElement )
    {
        OSL_ENSURE( ! hasItem( rName ), "item already in set" );
        maItems[ rName ] = aElement;
    }

    void remove( const rtl::OUString& rName )
    {
        OSL_ENSURE( hasItem( rName ), "item not in set" );
        maItems.erase( rName );
    }

public:

    NameContainer() {}
    virtual ~NameContainer() {}

    //
    // methods for XElementAccess
    //

    virtual com::sun::star::uno::Type SAL_CALL getElementType()
        throw( com::sun::star::uno::RuntimeException )
    {
        return getCppuType( static_cast<T*>( NULL ) );
    }

    virtual sal_Bool SAL_CALL hasElements()
        throw( com::sun::star::uno::RuntimeException )
    {
        return hasItems();
    }

    //
    // methods for XNameAccess (inherits XElementAccess)
    //

    virtual com::sun::star::uno::Any SAL_CALL getByName(
        const rtl::OUString& rName )
        throw( com::sun::star::container::NoSuchElementException,
               com::sun::star::lang::WrappedTargetException,
               com::sun::star::uno::RuntimeException )
    {
        typename map_t::const_iterator aIter = findItem( rName );
        if( aIter == maItems.end() )
            throw com::sun::star::container::NoSuchElementException();
        else
            return com::sun::star::uno::makeAny( aIter->second );
    }

    virtual com::sun::star::uno::Sequence<rtl::OUString> SAL_CALL getElementNames()
        throw( com::sun::star::uno::RuntimeException )
    {
        com::sun::star::uno::Sequence<rtl::OUString> aSequence( maItems.size() );
        typename map_t::const_iterator aIter = maItems.begin();
        rtl::OUString* pStrings = aSequence.getArray();
        while( aIter != maItems.end() )
        {
            *pStrings = aIter->first;
            ++aIter;
            ++pStrings;
        }
        OSL_ENSURE( pStrings == aSequence.getArray() + aSequence.getLength(),
                    "sequence not of right size; possible buffer overflow" );
        return aSequence;
    }

    virtual sal_Bool SAL_CALL hasByName(
        const rtl::OUString& rName )
        throw( com::sun::star::uno::RuntimeException )
    {
        return hasItem( rName );
    }

    //
    // methods for XNameReplace (inherits XNameAccess)
    //

    virtual void SAL_CALL replaceByName(
        const rtl::OUString& rName,
        const com::sun::star::uno::Any& aElement )
        throw( com::sun::star::lang::IllegalArgumentException,
               com::sun::star::container::NoSuchElementException,
               com::sun::star::lang::WrappedTargetException,
               com::sun::star::uno::RuntimeException)
    {
        T aItem;
        if( aElement >>= aItem )
            if( hasByName( rName ) )
                replace( rName, aItem );
            else
                throw com::sun::star::container::NoSuchElementException();
        else
            throw com::sun::star::lang::IllegalArgumentException();
    }

    //
    // methods for XNameContainer (inherits XNameReplace)
    //

    virtual void SAL_CALL insertByName(
        const rtl::OUString& rName,
        const com::sun::star::uno::Any& aElement )
        throw( com::sun::star::lang::IllegalArgumentException,
               com::sun::star::container::ElementExistException,
               com::sun::star::lang::WrappedTargetException,
               com::sun::star::uno::RuntimeException )
    {
        T aItem;
        if( aElement >>= aItem )
            if( ! hasByName( rName ) )
                insert( rName, aItem );
            else
                throw com::sun::star::container::ElementExistException();
        else
            throw com::sun::star::lang::IllegalArgumentException();
    }

    virtual void SAL_CALL removeByName(
        const rtl::OUString& rName )
        throw( com::sun::star::container::NoSuchElementException,
               com::sun::star::lang::WrappedTargetException,
               com::sun::star::uno::RuntimeException)
    {
        if( hasByName( rName ) )
            remove( rName );
        else
            throw com::sun::star::container::NoSuchElementException();
    }

};

#endif
<|endoftext|>


<commit_before>#include <vector>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <fstream>
#include "overlapgraph.h"

#define VERTEX_INACTIVE 0
#define VERTEX_ACTIVE 1
#define VERTEX_ELIMINATED -1
#define FUZZ 10

using namespace std;

OverlapGraph::OverlapGraph(std::vector<std::string> readvector, std::vector<overlap> overlapvector)
{
	reads = readvector;
	overlaps = overlapvector;
}

void OverlapGraph::initialize()
{
	graph.resize(reads.size());
	reducedGraph.resize(reads.size());
	nonContainedReads.resize(reads.size());
	nonContainedReads.assign(reads.size(), 1);

	for(int i=0;i<overlaps.size();i++)
	{
		overlap o = overlaps[i];

		//removing contained reads
		if(o.ahg > 0 & o.bhg > 0)
			graph[o.read1].push_back(o);
		else if (o.ahg < 0 & o.bhg < 0)
			graph[o.read2].push_back(o);
		else if (o.ahg > 0 & o.bhg < 0)
			nonContainedReads[o.read2] = 0;
		else if (o.ahg < 0 & o.bhg>0)
			nonContainedReads[o.read1] = 0;
	}
}

void OverlapGraph::runUnitigging()
{
	int N = reads.size();

	initialize();

	int *vertexstatus = (int *)malloc(N*sizeof(int));
	memset(vertexstatus, VERTEX_INACTIVE, N*sizeof(int));
	vector< vector<bool> > reduceflags(N);

	for (int i = 0; i < N; i++)
		for (int j = 0; j < graph[i].size(); j++)
			reduceflags[i].push_back(false);

	for (int I = 0; I < N; I++)
	{
		if (graph[I].size() == 0)
			continue;

		for (int j = 0; j < graph[I].size(); j++)
			vertexstatus[graph[I][j].read2] = VERTEX_ACTIVE;

		int longest = 0;
		for (int j = 0; j < graph[I].size(); j++)
		{
			if (graph[I][j].bhg > longest)
				longest = graph[I][j].bhg;
		}

		longest += FUZZ;
		cout << longest << endl;

		for (int j = 0; j < graph[I].size(); j++)
		{
			if (vertexstatus[graph[I][j].read2] == VERTEX_ACTIVE)
			{
				int x = graph[I][j].read2;
				for (int k = 0; k < graph[x].size(); k++)
				{
					if (graph[I][j].bhg + graph[x][k].bhg <= longest)
					{
						if (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)
							vertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;
					}
				}
			}
		}

		for (int j = 0; j < graph[I].size(); j++)
		{
			int x = graph[I][j].read2;
			for (int k = 0; k < graph[x].size(); k++)
			{
				if (graph[x][k].bhg < FUZZ)
				{
					if (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)
						vertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;
				}
			}
		}

		for (int j = 0; j < graph[I].size(); j++)
		{
			if (vertexstatus[graph[I][j].read2] == VERTEX_ELIMINATED)
			{
				reduceflags[I][j] = true;
			}
			vertexstatus[graph[I][j].read2] == VERTEX_INACTIVE;
		}
	}

	for(int i=0;i<graph.size();i++)
    {
        for(int j=0;j<graph[i].size();j++)
        {
			if (!reduceflags[i][j] & nonContainedReads[graph[i][j].read1] & nonContainedReads[graph[i][j].read2]){
				// Add edge to the reduced graph
				reducedGraph[i].push_back(graph[i][j]);
				cout << graph[i][j].read1 << " -> " << graph[i][j].read2 << endl;
			}
        }
    }
	uniqueJoinCollapsing();

	free(vertexstatus);
	return;
}

void OverlapGraph::printLayouts()
{
	ofstream output("layouts.afg");
	int *offsets = (int *)malloc(reads.size()*sizeof(int));
	memset(offsets, 0, reads.size()*sizeof(int));

	for (int i = 0; i < reads.size(); i++)
	{
		for (int j = 0; j < graph[i].size(); j++)
		{
			overlap o = graph[i][j];
		}
	}
}

void OverlapGraph::uniqueJoinCollapsing(){

	reducedGraphVertexReferenceCounter.assign(reducedGraph.size(), 0);

	// Calculate references to vertexes
	for (int i = 0; i < reducedGraph.size(); i++){
		for (int j = 0; j < reducedGraph[i].size(); j++){
			reducedGraphVertexReferenceCounter[reducedGraph[i][j].read2]++;
		}
	}

	// Find first "juncture" vertex
	int startingVertex = 0;
	bool startingVertexFound = false;
	while (startingVertex < reducedGraph.size()){
		if (reducedGraph[startingVertex].size() > 0){
			startingVertexFound = true;
			break;
		}
		startingVertex++;
	}
	if (startingVertexFound){
		calculateChunks(startingVertex);
	}
}

void OverlapGraph::calculateChunks(int chunkStartingVertexId){

	int currentVertexId = chunkStartingVertexId;

	if (vertexAlreadyInChunk(currentVertexId)){
		return;
	}

	// create new chunk
	Chunk chunk;

	while (true){
		if (reducedGraphVertexReferenceCounter[currentVertexId] > 1 && currentVertexId != chunkStartingVertexId){
			// special case: juncture vertex (not part of our chunk)
			calculateChunks(currentVertexId);
			break;
		}

		chunk.members.push_back(currentVertexId);

		if (reducedGraph[currentVertexId].size() < 1){
			// dead end
			break;
		}

		if (reducedGraph[currentVertexId].size() > 1){
			// juncture point - each path vertex represents a new chunk start
			for (int i = 0; i < reducedGraph[currentVertexId].size(); i++){
				calculateChunks(reducedGraph[currentVertexId][i].read2);
			}
			break;
		}

		currentVertexId = reducedGraph[currentVertexId][0].read2;
	}
	collapsedReducedGraph.push_back(chunk);

	return;
}

bool OverlapGraph::vertexAlreadyInChunk(int vertexId){
	for (int i = 0; i < collapsedReducedGraph.size(); ++i){
		for (int j = 0; j < collapsedReducedGraph[i].members.size(); ++j){
			if (vertexId == collapsedReducedGraph[i].members[j]){
				return true;
			}
		}
	}
	return false;
}<commit_msg>implemented<commit_after>#include <vector>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <fstream>
#include "overlapgraph.h"

#define VERTEX_INACTIVE 0
#define VERTEX_ACTIVE 1
#define VERTEX_ELIMINATED -1
#define FUZZ 10

using namespace std;

OverlapGraph::OverlapGraph(std::vector<std::string> readvector, std::vector<overlap> overlapvector)
{
	reads = readvector;
	overlaps = overlapvector;
}

void OverlapGraph::initialize()
{
	graph.resize(reads.size());
	reducedGraph.resize(reads.size());
	nonContainedReads.resize(reads.size());
	nonContainedReads.assign(reads.size(), 1);

	for(int i=0;i<overlaps.size();i++)
	{
		overlap o = overlaps[i];

		//removing contained reads
		if(o.ahg > 0 & o.bhg > 0)
			graph[o.read1].push_back(o);
		else if (o.ahg < 0 & o.bhg < 0)
			graph[o.read2].push_back(o);
		else if (o.ahg > 0 & o.bhg < 0)
			nonContainedReads[o.read2] = 0;
		else if (o.ahg < 0 & o.bhg>0)
			nonContainedReads[o.read1] = 0;
	}
}

void OverlapGraph::runUnitigging()
{
	int N = reads.size();

	initialize();

	int *vertexstatus = (int *)malloc(N*sizeof(int));
	memset(vertexstatus, VERTEX_INACTIVE, N*sizeof(int));
	vector< vector<bool> > reduceflags(N);

	for (int i = 0; i < N; i++)
		for (int j = 0; j < graph[i].size(); j++)
			reduceflags[i].push_back(false);

	for (int I = 0; I < N; I++)
	{
		if (graph[I].size() == 0)
			continue;

		for (int j = 0; j < graph[I].size(); j++)
			vertexstatus[graph[I][j].read2] = VERTEX_ACTIVE;

		int longest = 0;
		for (int j = 0; j < graph[I].size(); j++)
		{
			if (graph[I][j].bhg > longest)
				longest = graph[I][j].bhg;
		}

		longest += FUZZ;
		cout << longest << endl;

		for (int j = 0; j < graph[I].size(); j++)
		{
			if (vertexstatus[graph[I][j].read2] == VERTEX_ACTIVE)
			{
				int x = graph[I][j].read2;
				for (int k = 0; k < graph[x].size(); k++)
				{
					if (graph[I][j].bhg + graph[x][k].bhg <= longest)
					{
						if (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)
							vertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;
					}
				}
			}
		}

		for (int j = 0; j < graph[I].size(); j++)
		{
			int x = graph[I][j].read2;
			for (int k = 0; k < graph[x].size(); k++)
			{
				if (graph[x][k].bhg < FUZZ)
				{
					if (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)
						vertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;
				}
			}
		}

		for (int j = 0; j < graph[I].size(); j++)
		{
			if (vertexstatus[graph[I][j].read2] == VERTEX_ELIMINATED)
			{
				reduceflags[I][j] = true;
			}
			vertexstatus[graph[I][j].read2] == VERTEX_INACTIVE;
		}
	}

	for(int i=0;i<graph.size();i++)
    {
        for(int j=0;j<graph[i].size();j++)
        {
			if (!reduceflags[i][j] & nonContainedReads[graph[i][j].read1] & nonContainedReads[graph[i][j].read2]){
				// Add edge to the reduced graph
				reducedGraph[i].push_back(graph[i][j]);
				cout << graph[i][j].read1 << " -> " << graph[i][j].read2 << endl;
			}
        }
    }
	uniqueJoinCollapsing();

	free(vertexstatus);
	return;
}

void OverlapGraph::printLayouts()
{
	ofstream output("layouts.afg");
	int *offsets = (int *)malloc(reads.size()*sizeof(int));
	memset(offsets, 0, reads.size()*sizeof(int));

	for (int i = 0; i < reads.size(); i++)
	{
		for (int j = 0; j < graph[i].size(); j++)
		{
			overlap o = graph[i][j];
			if (nonContainedReads[o.read1] & nonContainedReads[o.read2]) {
				offsets[o.read2] = offsets[o.read1] + o.ahg;
			}
		}
	}
}

void OverlapGraph::uniqueJoinCollapsing(){

	reducedGraphVertexReferenceCounter.assign(reducedGraph.size(), 0);

	// Calculate references to vertexes
	for (int i = 0; i < reducedGraph.size(); i++){
		for (int j = 0; j < reducedGraph[i].size(); j++){
			reducedGraphVertexReferenceCounter[reducedGraph[i][j].read2]++;
		}
	}

	// Find first "juncture" vertex
	int startingVertex = 0;
	bool startingVertexFound = false;
	while (startingVertex < reducedGraph.size()){
		if (reducedGraph[startingVertex].size() > 0){
			startingVertexFound = true;
			break;
		}
		startingVertex++;
	}
	if (startingVertexFound){
		calculateChunks(startingVertex);
	}
}

void OverlapGraph::calculateChunks(int chunkStartingVertexId){

	int currentVertexId = chunkStartingVertexId;

	if (vertexAlreadyInChunk(currentVertexId)){
		return;
	}

	// create new chunk
	Chunk chunk;

	while (true){
		if (reducedGraphVertexReferenceCounter[currentVertexId] > 1 && currentVertexId != chunkStartingVertexId){
			// special case: juncture vertex (not part of our chunk)
			calculateChunks(currentVertexId);
			break;
		}

		chunk.members.push_back(currentVertexId);

		if (reducedGraph[currentVertexId].size() < 1){
			// dead end
			break;
		}

		if (reducedGraph[currentVertexId].size() > 1){
			// juncture point - each path vertex represents a new chunk start
			for (int i = 0; i < reducedGraph[currentVertexId].size(); i++){
				calculateChunks(reducedGraph[currentVertexId][i].read2);
			}
			break;
		}

		currentVertexId = reducedGraph[currentVertexId][0].read2;
	}
	collapsedReducedGraph.push_back(chunk);

	return;
}

bool OverlapGraph::vertexAlreadyInChunk(int vertexId){
	for (int i = 0; i < collapsedReducedGraph.size(); ++i){
		for (int j = 0; j < collapsedReducedGraph[i].members.size(); ++j){
			if (vertexId == collapsedReducedGraph[i].members[j]){
				return true;
			}
		}
	}
	return false;
}<|endoftext|>


<commit_before>/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
/*
 * Copyright (c) 2008  litl, LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include <config.h>
#include <string.h>
#include <stdlib.h>
#include <locale.h>

#include <gjs/gjs.h>
#include <gjs/coverage.h>

static char **include_path = NULL;
static char **coverage_paths = NULL;
static char *coverage_output_path = NULL;
static char *command = NULL;

static GOptionEntry entries[] = {
    { "command", 'c', 0, G_OPTION_ARG_STRING, &command, "Program passed in as a string", "COMMAND" },
    { "coverage-path", 'C', 0, G_OPTION_ARG_STRING_ARRAY, &coverage_paths, "Add the directory DIR to the list of directories to generate coverage info for", "DIR" },
    { "coverage-output", 0, 0, G_OPTION_ARG_STRING, &coverage_output_path, "Write coverage output to a directory DIR. This option is mandatory when using --coverage-path", "DIR", },
    { "include-path", 'I', 0, G_OPTION_ARG_STRING_ARRAY, &include_path, "Add the directory DIR to the list of directories to search for js files.", "DIR" },
    { NULL }
};

G_GNUC_NORETURN
static void
print_help (GOptionContext *context,
            gboolean        main_help)
{
  gchar *help;

  help = g_option_context_get_help (context, main_help, NULL);
  g_print ("%s", help);
  g_free (help);

  exit (0);
}

int
main(int argc, char **argv)
{
    GOptionContext *context;
    GError *error = NULL;
    GjsContext *js_context;
    GjsCoverage *coverage = NULL;
    char *script;
    const char *filename;
    const char *program_name;
    gsize len;
    int code;

    context = g_option_context_new(NULL);

    /* pass unknown through to the JS script */
    g_option_context_set_ignore_unknown_options(context, TRUE);
    g_option_context_set_help_enabled(context, FALSE);

    g_option_context_add_main_entries(context, entries, NULL);
    if (!g_option_context_parse(context, &argc, &argv, &error))
        g_error("option parsing failed: %s", error->message);

    if (argc >= 2) {
        if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)
            print_help(context, TRUE);
        else if (strcmp(argv[1], "--help-all") == 0)
            print_help(context, FALSE);
    }

    g_option_context_free (context);

    setlocale(LC_ALL, "");

    if (command != NULL) {
        script = command;
        len = strlen(script);
        filename = "<command line>";
        program_name = argv[0];
    } else if (argc <= 1) {
        script = g_strdup("const Console = imports.console; Console.interact();");
        len = strlen(script);
        filename = "<stdin>";
        program_name = argv[0];
    } else /*if (argc >= 2)*/ {
        error = NULL;
        if (!g_file_get_contents(argv[1], &script, &len, &error)) {
            g_printerr("%s\n", error->message);
            exit(1);
        }
        filename = argv[1];
        program_name = argv[1];
        argc--;
        argv++;
    }

    js_context = (GjsContext*) g_object_new(GJS_TYPE_CONTEXT,
                                            "search-path", include_path,
                                            "program-name", program_name,
                                            NULL);

    if (coverage_paths) {
        if (!coverage_output_path)
            g_error("--coverage-output is required when taking coverage statistics");

        coverage = gjs_coverage_new((const gchar **) coverage_paths,
                                    js_context);
    }

    /* prepare command line arguments */
    if (!gjs_context_define_string_array(js_context, "ARGV",
                                         argc - 1, (const char**)argv + 1,
                                         &error)) {
        code = 1;
        g_printerr("Failed to defined ARGV: %s", error->message);
        g_clear_error(&error);
        goto out;
    }

    /* evaluate the script */
    if (!gjs_context_eval(js_context, script, len,
                          filename, &code, &error)) {
        code = 1;
        g_printerr("%s\n", error->message);
        g_clear_error(&error);
        goto out;
    }

 out:

    /* Probably doesn't make sense to write statistics on failure */
    if (coverage && code == 0)
        gjs_coverage_write_statistics(coverage,
                                      coverage_output_path);

    g_object_unref(js_context);
    g_free(script);
    exit(code);
}
<commit_msg>console: Fix documentation for --coverage-path<commit_after>/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
/*
 * Copyright (c) 2008  litl, LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include <config.h>
#include <string.h>
#include <stdlib.h>
#include <locale.h>

#include <gjs/gjs.h>
#include <gjs/coverage.h>

static char **include_path = NULL;
static char **coverage_paths = NULL;
static char *coverage_output_path = NULL;
static char *command = NULL;

static GOptionEntry entries[] = {
    { "command", 'c', 0, G_OPTION_ARG_STRING, &command, "Program passed in as a string", "COMMAND" },
    { "coverage-path", 'C', 0, G_OPTION_ARG_STRING_ARRAY, &coverage_paths, "Add the filename FILE to the list of files to generate coverage info for", "FILE" },
    { "coverage-output", 0, 0, G_OPTION_ARG_STRING, &coverage_output_path, "Write coverage output to a directory DIR. This option is mandatory when using --coverage-path", "DIR", },
    { "include-path", 'I', 0, G_OPTION_ARG_STRING_ARRAY, &include_path, "Add the directory DIR to the list of directories to search for js files.", "DIR" },
    { NULL }
};

G_GNUC_NORETURN
static void
print_help (GOptionContext *context,
            gboolean        main_help)
{
  gchar *help;

  help = g_option_context_get_help (context, main_help, NULL);
  g_print ("%s", help);
  g_free (help);

  exit (0);
}

int
main(int argc, char **argv)
{
    GOptionContext *context;
    GError *error = NULL;
    GjsContext *js_context;
    GjsCoverage *coverage = NULL;
    char *script;
    const char *filename;
    const char *program_name;
    gsize len;
    int code;

    context = g_option_context_new(NULL);

    /* pass unknown through to the JS script */
    g_option_context_set_ignore_unknown_options(context, TRUE);
    g_option_context_set_help_enabled(context, FALSE);

    g_option_context_add_main_entries(context, entries, NULL);
    if (!g_option_context_parse(context, &argc, &argv, &error))
        g_error("option parsing failed: %s", error->message);

    if (argc >= 2) {
        if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)
            print_help(context, TRUE);
        else if (strcmp(argv[1], "--help-all") == 0)
            print_help(context, FALSE);
    }

    g_option_context_free (context);

    setlocale(LC_ALL, "");

    if (command != NULL) {
        script = command;
        len = strlen(script);
        filename = "<command line>";
        program_name = argv[0];
    } else if (argc <= 1) {
        script = g_strdup("const Console = imports.console; Console.interact();");
        len = strlen(script);
        filename = "<stdin>";
        program_name = argv[0];
    } else /*if (argc >= 2)*/ {
        error = NULL;
        if (!g_file_get_contents(argv[1], &script, &len, &error)) {
            g_printerr("%s\n", error->message);
            exit(1);
        }
        filename = argv[1];
        program_name = argv[1];
        argc--;
        argv++;
    }

    js_context = (GjsContext*) g_object_new(GJS_TYPE_CONTEXT,
                                            "search-path", include_path,
                                            "program-name", program_name,
                                            NULL);

    if (coverage_paths) {
        if (!coverage_output_path)
            g_error("--coverage-output is required when taking coverage statistics");

        coverage = gjs_coverage_new((const gchar **) coverage_paths,
                                    js_context);
    }

    /* prepare command line arguments */
    if (!gjs_context_define_string_array(js_context, "ARGV",
                                         argc - 1, (const char**)argv + 1,
                                         &error)) {
        code = 1;
        g_printerr("Failed to defined ARGV: %s", error->message);
        g_clear_error(&error);
        goto out;
    }

    /* evaluate the script */
    if (!gjs_context_eval(js_context, script, len,
                          filename, &code, &error)) {
        code = 1;
        g_printerr("%s\n", error->message);
        g_clear_error(&error);
        goto out;
    }

 out:

    /* Probably doesn't make sense to write statistics on failure */
    if (coverage && code == 0)
        gjs_coverage_write_statistics(coverage,
                                      coverage_output_path);

    g_object_unref(js_context);
    g_free(script);
    exit(code);
}
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use these files except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

#include "pch.h"

#include "CanvasControl.h"
#include "CanvasDevice.h"
#include "CanvasImageSource.h"

namespace canvas
{
    using namespace Microsoft::WRL::Wrappers;
    using namespace ABI::Windows::UI::Xaml;
    using namespace ABI::Windows::UI::Xaml::Media;

    IFACEMETHODIMP CanvasCreatingResourcesEventArgsFactory::Create(
        ICanvasDevice* device,
        ICanvasCreatingResourcesEventArgs** createResourcesArgs)
    {
        return ExceptionBoundary(
            [&]()
        {
            CheckAndClearOutPointer(createResourcesArgs);

            auto newCanvasCreatingResourcesEventArgs = Make<CanvasCreatingResourcesEventArgs>(device);

            ThrowIfFailed(newCanvasCreatingResourcesEventArgs.CopyTo(createResourcesArgs));
        });
    }

    CanvasCreatingResourcesEventArgs::CanvasCreatingResourcesEventArgs(ICanvasDevice* device)
        : m_device(device)
    {}

    IFACEMETHODIMP CanvasCreatingResourcesEventArgs::get_Device(ICanvasDevice** value)
    {
        return ExceptionBoundary(
            [&]()
        {
            CheckAndClearOutPointer(value);
            ComPtr<ICanvasDevice> device = m_device.EnsureNotClosed();
            ThrowIfFailed(device.CopyTo(value));
        });
    }

    IFACEMETHODIMP CanvasDrawingEventArgsFactory::Create(
        ICanvasDrawingSession* drawingSession,
        ICanvasDrawingEventArgs** drawEventArgs)
    {
        return ExceptionBoundary(
            [&]()
            {
                CheckAndClearOutPointer(drawEventArgs);

                auto newCanvasDrawingEventArgs = Make<CanvasDrawingEventArgs>(drawingSession);

                ThrowIfFailed(newCanvasDrawingEventArgs.CopyTo(drawEventArgs));
            });
    }

    CanvasDrawingEventArgs::CanvasDrawingEventArgs(ICanvasDrawingSession* drawingSession)
        : m_drawingSession(drawingSession)
    {}

    IFACEMETHODIMP CanvasDrawingEventArgs::get_DrawingSession(ICanvasDrawingSession** value)
    {
        return ExceptionBoundary(
            [&]()
            {
                CheckAndClearOutPointer(value);
                ComPtr<ICanvasDrawingSession> drawingSession = m_drawingSession.EnsureNotClosed();
                ThrowIfFailed(drawingSession.CopyTo(value));
            });
    }

    class CanvasControlAdapter : public ICanvasControlAdapter
    {
        ComPtr<IUserControlFactory> m_userControlFactory;
        ComPtr<IActivationFactory> m_canvasDeviceFactory;
        ComPtr<ICompositionTargetStatics> m_compositionTargetStatics;
        ComPtr<ICanvasImageSourceFactory> m_canvasImageSourceFactory;
        ComPtr<IActivationFactory> m_imageControlFactory;

    public:
        CanvasControlAdapter()
        {
            auto& module = Module<InProc>::GetModule();

            ThrowIfFailed(GetActivationFactory(
                HStringReference(RuntimeClass_Windows_UI_Xaml_Controls_UserControl).Get(),
                &m_userControlFactory));

            ThrowIfFailed(module.GetActivationFactory(
                HStringReference(RuntimeClass_Microsoft_Graphics_Canvas_CanvasDevice).Get(),
                &m_canvasDeviceFactory));

            ThrowIfFailed(GetActivationFactory(
                HStringReference(RuntimeClass_Windows_UI_Xaml_Media_CompositionTarget).Get(),
                &m_compositionTargetStatics));

            ComPtr<IActivationFactory> imageSourceActivationFactory;
            ThrowIfFailed(module.GetActivationFactory(
                HStringReference(RuntimeClass_Microsoft_Graphics_Canvas_CanvasImageSource).Get(),
                &imageSourceActivationFactory));
            ThrowIfFailed(imageSourceActivationFactory.As(&m_canvasImageSourceFactory));

            ThrowIfFailed(GetActivationFactory(
                HStringReference(RuntimeClass_Windows_UI_Xaml_Controls_Image).Get(),
                &m_imageControlFactory));
        }

        virtual std::pair<ComPtr<IInspectable>, ComPtr<IUserControl>> CreateUserControl(IInspectable* canvasControl) override
        {
            ComPtr<IInspectable> userControlInspectable;
            ComPtr<IUserControl> userControl;

            ThrowIfFailed(m_userControlFactory->CreateInstance(
                canvasControl,
                &userControlInspectable,
                &userControl));

            return std::make_pair(userControlInspectable, userControl);
        }

        virtual ComPtr<ICanvasDevice> CreateCanvasDevice() override
        {
            ComPtr<IInspectable> inspectableDevice;
            ThrowIfFailed(m_canvasDeviceFactory->ActivateInstance(&inspectableDevice));

            ComPtr<ICanvasDevice> device;
            ThrowIfFailed(inspectableDevice.As(&device));

            return device;
        }

        virtual EventRegistrationToken AddCompositionRenderingCallback(IEventHandler<IInspectable*>* handler) override
        {
            EventRegistrationToken token;
            ThrowIfFailed(m_compositionTargetStatics->add_Rendering(handler, &token));
            return token;
        }

        virtual void RemoveCompositionRenderingCallback(EventRegistrationToken token) override
        {
            ThrowIfFailed(m_compositionTargetStatics->remove_Rendering(token));
        }

        virtual ComPtr<ICanvasImageSource> CreateCanvasImageSource(ICanvasDevice* device, int width, int height) override
        {
            ComPtr<ICanvasImageSource> imageSource;
            ThrowIfFailed(m_canvasImageSourceFactory->Create(device, width, height, &imageSource));
            return imageSource;
        }

        virtual ComPtr<IImage> CreateImageControl() override
        {
            ComPtr<IInspectable> inspectableImage;
            ThrowIfFailed(m_imageControlFactory->ActivateInstance(&inspectableImage));

            ComPtr<IImage> image;
            ThrowIfFailed(inspectableImage.As(&image));

            return image;
        }
    };

    class CanvasControlFactory : public ActivationFactory<>
    {
        std::shared_ptr<CanvasControlAdapter> m_adapter;

    public:
        CanvasControlFactory()
            : m_adapter(std::make_shared<CanvasControlAdapter>())
        {
        }

        IFACEMETHODIMP ActivateInstance(IInspectable** obj) override
        {
            return ExceptionBoundary(
                [&]()
                {
                    using canvas::CanvasControl;
                    CheckAndClearOutPointer(obj);

                    auto control = Make<CanvasControl>(m_adapter);
                    CheckMakeResult(control);

                    ThrowIfFailed(control.CopyTo(obj));
                });
        }
    };

    CanvasControl::CanvasControl(std::shared_ptr<ICanvasControlAdapter> adapter)
        : m_adapter(adapter)
        , m_canvasDevice(m_adapter->CreateCanvasDevice())
        , m_drawNeeded(false)
        , m_isLoaded(false)
        , m_currentWidth(0)
        , m_currentHeight(0)
    {
        CreateBaseClass();
        CreateImageControl();
        RegisterEventHandlers();
    }

    void CanvasControl::CreateBaseClass()
    {
        auto base = m_adapter->CreateUserControl(static_cast<ICanvasControl*>(this));
        ThrowIfFailed(SetComposableBasePointers(base.first.Get(), base.second.Get()));
    }

    void CanvasControl::CreateImageControl()
    {
        m_imageControl = m_adapter->CreateImageControl();

        //
        // Set the stretch mode to None; this will prevent the control from
        // resizing itself when we change its source.  Instead we allow the
        // layout to pick the control size and we ensure that we set the source
        // to an appropriately sized CanvasImageSource.
        //
        ThrowIfFailed(m_imageControl->put_Stretch(ABI::Windows::UI::Xaml::Media::Stretch_None));

        //
        // Set the image control as the content of this control.
        //
        ComPtr<IUIElement> imageAsUIElement;
        ThrowIfFailed(m_imageControl.As(&imageAsUIElement));

        ComPtr<IUserControl> thisAsUserControl;
        ThrowIfFailed(GetComposableBase().As(&thisAsUserControl));
        thisAsUserControl->put_Content(imageAsUIElement.Get());
    }

    void CanvasControl::RegisterEventHandlers()
    {
        using namespace ABI::Windows::UI::Xaml::Controls;
        using namespace Windows::Foundation;

        ComPtr<IFrameworkElement> thisAsFrameworkElement;
        ThrowIfFailed(GetComposableBase().As(&thisAsFrameworkElement));

        // Register for Loaded event
        auto onLoadedFn = Callback<IRoutedEventHandler>(this, &CanvasControl::OnLoaded);
        EventRegistrationToken loadedToken{};

        ThrowIfFailed(thisAsFrameworkElement->add_Loaded(
            onLoadedFn.Get(),
            &loadedToken));

        //  Register for SizeChanged event
        auto onSizeChangedFn = Callback<ISizeChangedEventHandler>(this, &CanvasControl::OnSizeChanged);
        EventRegistrationToken sizeChangedToken{};

        ThrowIfFailed(thisAsFrameworkElement->add_SizeChanged(
            onSizeChangedFn.Get(),
            &sizeChangedToken));
    }

    void CanvasControl::EnsureSizeDependentResources()
    {
        // CanvasControl should always have a device
        assert(m_canvasDevice);

        // It is illegal to call get_actualWidth/Height before Loaded.
        assert(m_isLoaded);

        ComPtr<IFrameworkElement> thisAsFrameworkElement;
        ThrowIfFailed(GetComposableBase().As(&thisAsFrameworkElement));

        double actualWidth, actualHeight;
        ThrowIfFailed(thisAsFrameworkElement->get_ActualWidth(&actualWidth));
        ThrowIfFailed(thisAsFrameworkElement->get_ActualHeight(&actualHeight));

        assert(actualWidth <= static_cast<double>(INT_MAX));
        assert(actualHeight <= static_cast<double>(INT_MAX));

        auto width = static_cast<int>(actualWidth);
        auto height = static_cast<int>(actualHeight);

        //
        // TODO #1769: unit test for resizing behavior.
        //
        if (m_canvasImageSource)
        {
            // If we already have an image source that's the right size we don't
            // need to do anything.
            if (width == m_currentWidth && height == m_currentHeight)
                return;
        }

        m_canvasImageSource = m_adapter->CreateCanvasImageSource(
            m_canvasDevice.Get(),
            width,
            height);

        m_currentWidth = width;
        m_currentHeight = height;

        //
        // Set this new image source on the image control
        //
        ComPtr<IImageSource> baseImageSource;
        ThrowIfFailed(m_canvasImageSource.As(&baseImageSource));
        ThrowIfFailed(m_imageControl->put_Source(baseImageSource.Get()));

        //
        // TODO #1849: this shouldn't be done just because we created the
        // control.  Figure out the right places to do this (eg before drawing
        // for the first time, after device lost; ensure callback called when
        // adding a new handler, even if first draw has already happened etc.)
        //
        // Notify the application-defined resource creation callback.
        //
        if (!m_createResourcesEventList.IsEmpty())
        {
            ComPtr<CanvasCreatingResourcesEventArgs> createResourcesArgs = Make<CanvasCreatingResourcesEventArgs>(m_canvasDevice.Get());
            m_createResourcesEventList.FireAll(this, createResourcesArgs.Get());
        }

    }

    HRESULT CanvasControl::OnLoaded(IInspectable* sender, IRoutedEventArgs* args)
    {
        return ExceptionBoundary(
            [&]()
            {
                m_isLoaded = true;
                InvalidateImpl();
            });
    }

    HRESULT CanvasControl::OnSizeChanged(IInspectable* sender, ISizeChangedEventArgs* args)
    {
        return ExceptionBoundary(
            [&]()
            {
                //
                // OnSizeChanged can get called multiple times.  We only want to
                // invalidate if it represents a size change from what the
                // control was last set to.
                //
                ABI::Windows::Foundation::Size newSize{};
                ThrowIfFailed(args->get_NewSize(&newSize));

                auto newWidth = static_cast<int>(newSize.Width);
                auto newHeight = static_cast<int>(newSize.Height);

                if (newWidth == m_currentWidth && newHeight == m_currentHeight)
                    return;

                InvalidateImpl();
            });
    }

    IFACEMETHODIMP CanvasControl::add_CreatingResources(
        ABI::Windows::Foundation::ITypedEventHandler<ABI::Microsoft::Graphics::Canvas::CanvasControl*, ABI::Microsoft::Graphics::Canvas::CanvasCreatingResourcesEventArgs*>* value,
        EventRegistrationToken *token)
    {
        return ExceptionBoundary(
            [&]()
            {
                *token = m_createResourcesEventList.Add(value);
            });
    }

    IFACEMETHODIMP CanvasControl::remove_CreatingResources(
        EventRegistrationToken token)
    {
        return ExceptionBoundary(
            [&]()
            {
                m_createResourcesEventList.Remove(token);
            });
    }

    IFACEMETHODIMP CanvasControl::add_Drawing(
        ABI::Windows::Foundation::ITypedEventHandler<ABI::Microsoft::Graphics::Canvas::CanvasControl*, ABI::Microsoft::Graphics::Canvas::CanvasDrawingEventArgs*>* value,
        EventRegistrationToken* token)
    {
        return ExceptionBoundary(
            [&]()
            {
                *token = m_drawEventList.Add(value);
            });
    }

    IFACEMETHODIMP CanvasControl::remove_Drawing(
        EventRegistrationToken token)
    {
        return ExceptionBoundary(
            [&]()
            {
                m_drawEventList.Remove(token);
            });
    }

    HRESULT CanvasControl::OnRenderCallback(IInspectable *pSender, IInspectable *pArgs)
    {
        return ExceptionBoundary(
            [&]()
            {
                m_drawNeeded = false;
                m_adapter->RemoveCompositionRenderingCallback(m_renderingEventToken);

                EnsureSizeDependentResources();

                ComPtr<ICanvasDrawingSession> drawingSession;
                ThrowIfFailed(m_canvasImageSource->CreateDrawingSession(&drawingSession));
                ComPtr<CanvasDrawingEventArgs> drawEventArgs = Make<CanvasDrawingEventArgs>(drawingSession.Get());

                m_drawEventList.FireAll(this, drawEventArgs.Get());

                ComPtr<IClosable> drawingSessionClosable;
                ThrowIfFailed(drawingSession.As(&drawingSessionClosable));
                ThrowIfFailed(drawingSessionClosable->Close()); // Device removal should be handled here.
            });
    }

    IFACEMETHODIMP CanvasControl::Invalidate()
    {
        return ExceptionBoundary(
            [&]()
            {
                InvalidateImpl();
            });
    }

    void CanvasControl::InvalidateImpl()
    {
        //
        // TODO #1771: Invalidate() could be called from any thread, so we need to
        // have some lock protecting m_DrawNeeded and adding/removing the
        // rendering event.
        //

        if (m_drawNeeded)
            return;

        m_drawNeeded = true;
        ComPtr<IEventHandler<IInspectable*>> renderingEventHandler = Callback<IEventHandler<IInspectable*>, CanvasControl>(this, &CanvasControl::OnRenderCallback);
        m_renderingEventToken = m_adapter->AddCompositionRenderingCallback(renderingEventHandler.Get());
    }

    IFACEMETHODIMP CanvasControl::MeasureOverride(
        ABI::Windows::Foundation::Size availableSize,
        ABI::Windows::Foundation::Size* returnValue)
    {
        return ExceptionBoundary(
            [&]()
            {
                //
                // MeasureOverride must call Measure on its children (in this
                // case this is just the image control).
                //
                ComPtr<IUIElement> imageOverrides;
                ThrowIfFailed(m_imageControl.As(&imageOverrides));
                ThrowIfFailed(imageOverrides->Measure(availableSize));

                //
                // However, we ignore how they respond and reply that we're
                // happy to be sized however the layout engine wants to size us.
                //
                *returnValue = ABI::Windows::Foundation::Size{};
            });
    }

    IFACEMETHODIMP CanvasControl::ArrangeOverride(
        ABI::Windows::Foundation::Size finalSize,
        ABI::Windows::Foundation::Size* returnValue)
    {
        return ExceptionBoundary(
            [&]()
            {
                //
                // Allow base class to handle this
                //
                ComPtr<IFrameworkElementOverrides> base;
                ThrowIfFailed(GetComposableBase().As(&base));
                ThrowIfFailed(base->ArrangeOverride(finalSize, returnValue));
            });
    }

    IFACEMETHODIMP CanvasControl::OnApplyTemplate()
    {
        return ExceptionBoundary(
            [&]()
            {
                //
                // Allow base class to handle this
                //
                ComPtr<IFrameworkElementOverrides> base;
                ThrowIfFailed(GetComposableBase().As(&base));
                ThrowIfFailed(base->OnApplyTemplate());
            });
    }

    ActivatableClassWithFactory(CanvasCreatingResourcesEventArgs, CanvasCreatingResourcesEventArgsFactory);
    ActivatableClassWithFactory(CanvasDrawingEventArgs, CanvasDrawingEventArgsFactory);
    ActivatableClassWithFactory(CanvasControl, CanvasControlFactory);
}
<commit_msg>CanvasControl - handle getting SizeChanged before we've loaded.<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use these files except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

#include "pch.h"

#include "CanvasControl.h"
#include "CanvasDevice.h"
#include "CanvasImageSource.h"

namespace canvas
{
    using namespace Microsoft::WRL::Wrappers;
    using namespace ABI::Windows::UI::Xaml;
    using namespace ABI::Windows::UI::Xaml::Media;

    IFACEMETHODIMP CanvasCreatingResourcesEventArgsFactory::Create(
        ICanvasDevice* device,
        ICanvasCreatingResourcesEventArgs** createResourcesArgs)
    {
        return ExceptionBoundary(
            [&]()
        {
            CheckAndClearOutPointer(createResourcesArgs);

            auto newCanvasCreatingResourcesEventArgs = Make<CanvasCreatingResourcesEventArgs>(device);

            ThrowIfFailed(newCanvasCreatingResourcesEventArgs.CopyTo(createResourcesArgs));
        });
    }

    CanvasCreatingResourcesEventArgs::CanvasCreatingResourcesEventArgs(ICanvasDevice* device)
        : m_device(device)
    {}

    IFACEMETHODIMP CanvasCreatingResourcesEventArgs::get_Device(ICanvasDevice** value)
    {
        return ExceptionBoundary(
            [&]()
        {
            CheckAndClearOutPointer(value);
            ComPtr<ICanvasDevice> device = m_device.EnsureNotClosed();
            ThrowIfFailed(device.CopyTo(value));
        });
    }

    IFACEMETHODIMP CanvasDrawingEventArgsFactory::Create(
        ICanvasDrawingSession* drawingSession,
        ICanvasDrawingEventArgs** drawEventArgs)
    {
        return ExceptionBoundary(
            [&]()
            {
                CheckAndClearOutPointer(drawEventArgs);

                auto newCanvasDrawingEventArgs = Make<CanvasDrawingEventArgs>(drawingSession);

                ThrowIfFailed(newCanvasDrawingEventArgs.CopyTo(drawEventArgs));
            });
    }

    CanvasDrawingEventArgs::CanvasDrawingEventArgs(ICanvasDrawingSession* drawingSession)
        : m_drawingSession(drawingSession)
    {}

    IFACEMETHODIMP CanvasDrawingEventArgs::get_DrawingSession(ICanvasDrawingSession** value)
    {
        return ExceptionBoundary(
            [&]()
            {
                CheckAndClearOutPointer(value);
                ComPtr<ICanvasDrawingSession> drawingSession = m_drawingSession.EnsureNotClosed();
                ThrowIfFailed(drawingSession.CopyTo(value));
            });
    }

    class CanvasControlAdapter : public ICanvasControlAdapter
    {
        ComPtr<IUserControlFactory> m_userControlFactory;
        ComPtr<IActivationFactory> m_canvasDeviceFactory;
        ComPtr<ICompositionTargetStatics> m_compositionTargetStatics;
        ComPtr<ICanvasImageSourceFactory> m_canvasImageSourceFactory;
        ComPtr<IActivationFactory> m_imageControlFactory;

    public:
        CanvasControlAdapter()
        {
            auto& module = Module<InProc>::GetModule();

            ThrowIfFailed(GetActivationFactory(
                HStringReference(RuntimeClass_Windows_UI_Xaml_Controls_UserControl).Get(),
                &m_userControlFactory));

            ThrowIfFailed(module.GetActivationFactory(
                HStringReference(RuntimeClass_Microsoft_Graphics_Canvas_CanvasDevice).Get(),
                &m_canvasDeviceFactory));

            ThrowIfFailed(GetActivationFactory(
                HStringReference(RuntimeClass_Windows_UI_Xaml_Media_CompositionTarget).Get(),
                &m_compositionTargetStatics));

            ComPtr<IActivationFactory> imageSourceActivationFactory;
            ThrowIfFailed(module.GetActivationFactory(
                HStringReference(RuntimeClass_Microsoft_Graphics_Canvas_CanvasImageSource).Get(),
                &imageSourceActivationFactory));
            ThrowIfFailed(imageSourceActivationFactory.As(&m_canvasImageSourceFactory));

            ThrowIfFailed(GetActivationFactory(
                HStringReference(RuntimeClass_Windows_UI_Xaml_Controls_Image).Get(),
                &m_imageControlFactory));
        }

        virtual std::pair<ComPtr<IInspectable>, ComPtr<IUserControl>> CreateUserControl(IInspectable* canvasControl) override
        {
            ComPtr<IInspectable> userControlInspectable;
            ComPtr<IUserControl> userControl;

            ThrowIfFailed(m_userControlFactory->CreateInstance(
                canvasControl,
                &userControlInspectable,
                &userControl));

            return std::make_pair(userControlInspectable, userControl);
        }

        virtual ComPtr<ICanvasDevice> CreateCanvasDevice() override
        {
            ComPtr<IInspectable> inspectableDevice;
            ThrowIfFailed(m_canvasDeviceFactory->ActivateInstance(&inspectableDevice));

            ComPtr<ICanvasDevice> device;
            ThrowIfFailed(inspectableDevice.As(&device));

            return device;
        }

        virtual EventRegistrationToken AddCompositionRenderingCallback(IEventHandler<IInspectable*>* handler) override
        {
            EventRegistrationToken token;
            ThrowIfFailed(m_compositionTargetStatics->add_Rendering(handler, &token));
            return token;
        }

        virtual void RemoveCompositionRenderingCallback(EventRegistrationToken token) override
        {
            ThrowIfFailed(m_compositionTargetStatics->remove_Rendering(token));
        }

        virtual ComPtr<ICanvasImageSource> CreateCanvasImageSource(ICanvasDevice* device, int width, int height) override
        {
            ComPtr<ICanvasImageSource> imageSource;
            ThrowIfFailed(m_canvasImageSourceFactory->Create(device, width, height, &imageSource));
            return imageSource;
        }

        virtual ComPtr<IImage> CreateImageControl() override
        {
            ComPtr<IInspectable> inspectableImage;
            ThrowIfFailed(m_imageControlFactory->ActivateInstance(&inspectableImage));

            ComPtr<IImage> image;
            ThrowIfFailed(inspectableImage.As(&image));

            return image;
        }
    };

    class CanvasControlFactory : public ActivationFactory<>
    {
        std::shared_ptr<CanvasControlAdapter> m_adapter;

    public:
        CanvasControlFactory()
            : m_adapter(std::make_shared<CanvasControlAdapter>())
        {
        }

        IFACEMETHODIMP ActivateInstance(IInspectable** obj) override
        {
            return ExceptionBoundary(
                [&]()
                {
                    using canvas::CanvasControl;
                    CheckAndClearOutPointer(obj);

                    auto control = Make<CanvasControl>(m_adapter);
                    CheckMakeResult(control);

                    ThrowIfFailed(control.CopyTo(obj));
                });
        }
    };

    CanvasControl::CanvasControl(std::shared_ptr<ICanvasControlAdapter> adapter)
        : m_adapter(adapter)
        , m_canvasDevice(m_adapter->CreateCanvasDevice())
        , m_drawNeeded(false)
        , m_isLoaded(false)
        , m_currentWidth(0)
        , m_currentHeight(0)
    {
        CreateBaseClass();
        CreateImageControl();
        RegisterEventHandlers();
    }

    void CanvasControl::CreateBaseClass()
    {
        auto base = m_adapter->CreateUserControl(static_cast<ICanvasControl*>(this));
        ThrowIfFailed(SetComposableBasePointers(base.first.Get(), base.second.Get()));
    }

    void CanvasControl::CreateImageControl()
    {
        m_imageControl = m_adapter->CreateImageControl();

        //
        // Set the stretch mode to None; this will prevent the control from
        // resizing itself when we change its source.  Instead we allow the
        // layout to pick the control size and we ensure that we set the source
        // to an appropriately sized CanvasImageSource.
        //
        ThrowIfFailed(m_imageControl->put_Stretch(ABI::Windows::UI::Xaml::Media::Stretch_None));

        //
        // Set the image control as the content of this control.
        //
        ComPtr<IUIElement> imageAsUIElement;
        ThrowIfFailed(m_imageControl.As(&imageAsUIElement));

        ComPtr<IUserControl> thisAsUserControl;
        ThrowIfFailed(GetComposableBase().As(&thisAsUserControl));
        thisAsUserControl->put_Content(imageAsUIElement.Get());
    }

    void CanvasControl::RegisterEventHandlers()
    {
        using namespace ABI::Windows::UI::Xaml::Controls;
        using namespace Windows::Foundation;

        ComPtr<IFrameworkElement> thisAsFrameworkElement;
        ThrowIfFailed(GetComposableBase().As(&thisAsFrameworkElement));

        // Register for Loaded event
        auto onLoadedFn = Callback<IRoutedEventHandler>(this, &CanvasControl::OnLoaded);
        EventRegistrationToken loadedToken{};

        ThrowIfFailed(thisAsFrameworkElement->add_Loaded(
            onLoadedFn.Get(),
            &loadedToken));

        //  Register for SizeChanged event
        auto onSizeChangedFn = Callback<ISizeChangedEventHandler>(this, &CanvasControl::OnSizeChanged);
        EventRegistrationToken sizeChangedToken{};

        ThrowIfFailed(thisAsFrameworkElement->add_SizeChanged(
            onSizeChangedFn.Get(),
            &sizeChangedToken));
    }

    void CanvasControl::EnsureSizeDependentResources()
    {
        // CanvasControl should always have a device
        assert(m_canvasDevice);

        // It is illegal to call get_actualWidth/Height before Loaded.
        assert(m_isLoaded);

        ComPtr<IFrameworkElement> thisAsFrameworkElement;
        ThrowIfFailed(GetComposableBase().As(&thisAsFrameworkElement));

        double actualWidth, actualHeight;
        ThrowIfFailed(thisAsFrameworkElement->get_ActualWidth(&actualWidth));
        ThrowIfFailed(thisAsFrameworkElement->get_ActualHeight(&actualHeight));

        assert(actualWidth <= static_cast<double>(INT_MAX));
        assert(actualHeight <= static_cast<double>(INT_MAX));

        auto width = static_cast<int>(actualWidth);
        auto height = static_cast<int>(actualHeight);

        //
        // TODO #1769: unit test for resizing behavior.
        //
        if (m_canvasImageSource)
        {
            // If we already have an image source that's the right size we don't
            // need to do anything.
            if (width == m_currentWidth && height == m_currentHeight)
                return;
        }

        m_canvasImageSource = m_adapter->CreateCanvasImageSource(
            m_canvasDevice.Get(),
            width,
            height);

        m_currentWidth = width;
        m_currentHeight = height;

        //
        // Set this new image source on the image control
        //
        ComPtr<IImageSource> baseImageSource;
        ThrowIfFailed(m_canvasImageSource.As(&baseImageSource));
        ThrowIfFailed(m_imageControl->put_Source(baseImageSource.Get()));

        //
        // TODO #1849: this shouldn't be done just because we created the
        // control.  Figure out the right places to do this (eg before drawing
        // for the first time, after device lost; ensure callback called when
        // adding a new handler, even if first draw has already happened etc.)
        //
        // Notify the application-defined resource creation callback.
        //
        if (!m_createResourcesEventList.IsEmpty())
        {
            ComPtr<CanvasCreatingResourcesEventArgs> createResourcesArgs = Make<CanvasCreatingResourcesEventArgs>(m_canvasDevice.Get());
            m_createResourcesEventList.FireAll(this, createResourcesArgs.Get());
        }

    }

    HRESULT CanvasControl::OnLoaded(IInspectable* sender, IRoutedEventArgs* args)
    {
        return ExceptionBoundary(
            [&]()
            {
                m_isLoaded = true;
                InvalidateImpl();
            });
    }

    HRESULT CanvasControl::OnSizeChanged(IInspectable* sender, ISizeChangedEventArgs* args)
    {
        return ExceptionBoundary(
            [&]()
            {
                //
                // If we get a size changed before we've loaded then we don't do
                // anything.
                //
                if (!m_isLoaded)
                    return;

                //
                // OnSizeChanged can get called multiple times.  We only want to
                // invalidate if it represents a size change from what the
                // control was last set to.
                //
                ABI::Windows::Foundation::Size newSize{};
                ThrowIfFailed(args->get_NewSize(&newSize));

                auto newWidth = static_cast<int>(newSize.Width);
                auto newHeight = static_cast<int>(newSize.Height);

                if (newWidth == m_currentWidth && newHeight == m_currentHeight)
                    return;

                InvalidateImpl();
            });
    }

    IFACEMETHODIMP CanvasControl::add_CreatingResources(
        ABI::Windows::Foundation::ITypedEventHandler<ABI::Microsoft::Graphics::Canvas::CanvasControl*, ABI::Microsoft::Graphics::Canvas::CanvasCreatingResourcesEventArgs*>* value,
        EventRegistrationToken *token)
    {
        return ExceptionBoundary(
            [&]()
            {
                *token = m_createResourcesEventList.Add(value);
            });
    }

    IFACEMETHODIMP CanvasControl::remove_CreatingResources(
        EventRegistrationToken token)
    {
        return ExceptionBoundary(
            [&]()
            {
                m_createResourcesEventList.Remove(token);
            });
    }

    IFACEMETHODIMP CanvasControl::add_Drawing(
        ABI::Windows::Foundation::ITypedEventHandler<ABI::Microsoft::Graphics::Canvas::CanvasControl*, ABI::Microsoft::Graphics::Canvas::CanvasDrawingEventArgs*>* value,
        EventRegistrationToken* token)
    {
        return ExceptionBoundary(
            [&]()
            {
                *token = m_drawEventList.Add(value);
            });
    }

    IFACEMETHODIMP CanvasControl::remove_Drawing(
        EventRegistrationToken token)
    {
        return ExceptionBoundary(
            [&]()
            {
                m_drawEventList.Remove(token);
            });
    }

    HRESULT CanvasControl::OnRenderCallback(IInspectable *pSender, IInspectable *pArgs)
    {
        return ExceptionBoundary(
            [&]()
            {
                m_drawNeeded = false;
                m_adapter->RemoveCompositionRenderingCallback(m_renderingEventToken);

                EnsureSizeDependentResources();

                ComPtr<ICanvasDrawingSession> drawingSession;
                ThrowIfFailed(m_canvasImageSource->CreateDrawingSession(&drawingSession));
                ComPtr<CanvasDrawingEventArgs> drawEventArgs = Make<CanvasDrawingEventArgs>(drawingSession.Get());

                m_drawEventList.FireAll(this, drawEventArgs.Get());

                ComPtr<IClosable> drawingSessionClosable;
                ThrowIfFailed(drawingSession.As(&drawingSessionClosable));
                ThrowIfFailed(drawingSessionClosable->Close()); // Device removal should be handled here.
            });
    }

    IFACEMETHODIMP CanvasControl::Invalidate()
    {
        return ExceptionBoundary(
            [&]()
            {
                InvalidateImpl();
            });
    }

    void CanvasControl::InvalidateImpl()
    {
        //
        // TODO #1771: Invalidate() could be called from any thread, so we need to
        // have some lock protecting m_DrawNeeded and adding/removing the
        // rendering event.
        //

        if (m_drawNeeded)
            return;

        m_drawNeeded = true;
        ComPtr<IEventHandler<IInspectable*>> renderingEventHandler = Callback<IEventHandler<IInspectable*>, CanvasControl>(this, &CanvasControl::OnRenderCallback);
        m_renderingEventToken = m_adapter->AddCompositionRenderingCallback(renderingEventHandler.Get());
    }

    IFACEMETHODIMP CanvasControl::MeasureOverride(
        ABI::Windows::Foundation::Size availableSize,
        ABI::Windows::Foundation::Size* returnValue)
    {
        return ExceptionBoundary(
            [&]()
            {
                //
                // MeasureOverride must call Measure on its children (in this
                // case this is just the image control).
                //
                ComPtr<IUIElement> imageOverrides;
                ThrowIfFailed(m_imageControl.As(&imageOverrides));
                ThrowIfFailed(imageOverrides->Measure(availableSize));

                //
                // However, we ignore how they respond and reply that we're
                // happy to be sized however the layout engine wants to size us.
                //
                *returnValue = ABI::Windows::Foundation::Size{};
            });
    }

    IFACEMETHODIMP CanvasControl::ArrangeOverride(
        ABI::Windows::Foundation::Size finalSize,
        ABI::Windows::Foundation::Size* returnValue)
    {
        return ExceptionBoundary(
            [&]()
            {
                //
                // Allow base class to handle this
                //
                ComPtr<IFrameworkElementOverrides> base;
                ThrowIfFailed(GetComposableBase().As(&base));
                ThrowIfFailed(base->ArrangeOverride(finalSize, returnValue));
            });
    }

    IFACEMETHODIMP CanvasControl::OnApplyTemplate()
    {
        return ExceptionBoundary(
            [&]()
            {
                //
                // Allow base class to handle this
                //
                ComPtr<IFrameworkElementOverrides> base;
                ThrowIfFailed(GetComposableBase().As(&base));
                ThrowIfFailed(base->OnApplyTemplate());
            });
    }

    ActivatableClassWithFactory(CanvasCreatingResourcesEventArgs, CanvasCreatingResourcesEventArgsFactory);
    ActivatableClassWithFactory(CanvasDrawingEventArgs, CanvasDrawingEventArgsFactory);
    ActivatableClassWithFactory(CanvasControl, CanvasControlFactory);
}
<|endoftext|>


<commit_before>/*
 *  reader.hpp
 *  ChessPlusPlus
 *
 *  Created by Ronak Gajrawala on 12/26/13.
 *  Copyright (c) 2013 Ronak Gajrawala. All rights reserved.
 */

#ifndef ChessPlusPlus_reader_hpp
#define ChessPlusPlus_reader_hpp

/***********
 * @todo Create the board reader, next move / last move.
 ***********/

/**
 * The Reader class.
 * The main starting page or menu is created and handled here.
 */
class Reader {
    sf::RenderWindow Window; /**< The window of the menu. */
    sf::Font Font; /**< The font that the text on the menu will use (sansation.ttf). */
    sf::Event Event; /**< Any window events. */
    sf::Vector2u Mouse; /**< Mouse coordinates. */
    sf::Image Icon; /**< The icon for the window */

    sf::Text PlayerTurn, /**< Stores who's turn it is. */
             LastMove; /**< Stores the last move. */
    sf::Sprite Sprite; /**< The Sprite that will load the board and pieces. */

    sf::RectangleShape NextButton; /**< The button that says "Next". */
    sf::Text NextBtnText; /**< Text for the Next Button. */
    sf::RectangleShape GoBackButton; /**< The button that says "Back". */
    sf::Text GoBackBtnText; /**< Text for the Go-Back Button. */

    File::Information FileInfo; /**< File information necessary for the replay. */
    Board8 Board; /**< The board we will be replaying. */
public:

    /**
     * Creates the menu and other important parts of the start page.
     */
    void Initialize(void);

    /**
     * Main loop for the start page.
     * Initializes, runs / loops, and cleans up.
     */
    void Main(void);

    /**
     * Event handler for window events.
     */
    void OnEvent(void);

    /**
     * Event handler for mouse moves.
     * @see OnEvent
     */
    void OnMouseMove(void);

    /**
     * Event handler for key presses.
     * @see OnEvent
     */
    void OnKeyPressed(void);

    /**
     * Handler for mouse button releases.
     * @see OnEvent
     */
    void OnMouseButtonReleased(void);

    /**
     * Draws pieces and chessboard onto screen.
     */
    void Display(void);
} Reader;

////////// SOURCE //////////

void Reader::Initialize(void) {
    this->Window.create(sf::VideoMode(900, 640), "ChessPlusPlus - Reader", sf::Style::Close);
    this->Window.setFramerateLimit(10);

    if(!this->Icon.loadFromFile(GetResource("white_knight.png"))) {
        exit(EXIT_FAILURE);
    }
    this->Window.setIcon(this->Icon.getSize().x, this->Icon.getSize().y, this->Icon.getPixelsPtr());

    if(!this->Font.loadFromFile(GetResource("sansation.ttf"))) {
        exit(EXIT_FAILURE);
    }

    File.Read(&this->FileInfo);
    File.CreateBoardFromFile("default.chessconf", &this->Board);

    this->NextButton.setFillColor(sf::Color::Yellow);
    this->NextButton.setSize(sf::Vector2f(240.0, 50.0));
    this->NextButton.setPosition(650.0, 520.0);

    this->NextBtnText.setColor(sf::Color::Blue);
    this->NextBtnText.setCharacterSize(40);
    this->NextBtnText.setPosition(722.0, 520.0);
    this->NextBtnText.setFont(this->Font);
    this->NextBtnText.setString("Next");

    this->GoBackButton.setFillColor(sf::Color::Yellow);
    this->GoBackButton.setSize(sf::Vector2f(240.0, 50.0));
    this->GoBackButton.setPosition(650.0, 580.0);

    this->GoBackBtnText.setColor(sf::Color::Blue);
    this->GoBackBtnText.setCharacterSize(40);
    this->GoBackBtnText.setPosition(722.0, 580.0);
    this->GoBackBtnText.setFont(this->Font);
    this->GoBackBtnText.setString("Back");
}

void Reader::OnMouseMove(void) {
    this->Mouse.x = Event.mouseMove.x;
    this->Mouse.y = Event.mouseMove.y;
}

void Reader::OnKeyPressed(void) {
    if(((this->Event.key.code is sf::Keyboard::W or this->Event.key.code is sf::Keyboard::C) and this->Event.key.control) or ((this->Event.key.code is sf::Keyboard::W or this->Event.key.code is sf::Keyboard::C) and this->Event.key.alt)) {
        this->Window.close();
    }
}

void Reader::OnMouseButtonReleased(void) {
    if(Utils.Contains(this->Mouse.x, this->Mouse.y, this->NextButton.getPosition().x, this->NextButton.getPosition().y, this->NextButton.getSize().x, this->NextButton.getSize().y)) {
        // Next
    } else if(Utils.Contains(this->Mouse.x, this->Mouse.y, this->GoBackButton.getPosition().x, this->GoBackButton.getPosition().y, this->GoBackButton.getSize().x, this->GoBackButton.getSize().y)) {
        // Back
    } else {

    }
}

void Reader::OnEvent(void) {
    switch(this->Event.type) {
        case sf::Event::Closed: this->Window.close();
        case sf::Event::KeyPressed: this->OnKeyPressed(); break;
        case sf::Event::MouseMoved: this->OnMouseMove(); break;
        case sf::Event::MouseButtonReleased: this->OnMouseButtonReleased(); break;
        default: break;
    }
}

void Reader::Main(void) {
    this->Initialize();
    while(this->Window.isOpen()) {
        this->Window.clear(sf::Color::Black);

        while(this->Window.pollEvent(this->Event)) {
            this->OnEvent();
        }

        this->Display();
    }
}

void Reader::Display(void) {
    this->Sprite.setTexture(Textures.ChessBoard);
    this->Sprite.setPosition(0.0, 0.0);
    this->Window.draw(this->Sprite);

    for(int y = 0; y < 8; y++) {
        for(int x = 0; x < 8; x++) {
            bool isNotEmpty = true;

            switch(this->Board.at(y).at(x)) {
                case Pieces::Empty: isNotEmpty = false; break;
                case Pieces::Black_Pawn: this->Sprite.setTexture(Textures.Black.Pawn); break;
                case Pieces::Black_Rook: this->Sprite.setTexture(Textures.Black.Rook); break;
                case Pieces::Black_Knight: this->Sprite.setTexture(Textures.Black.Knight); break;
                case Pieces::Black_Bishop: this->Sprite.setTexture(Textures.Black.Bishop); break;
                case Pieces::Black_Queen: this->Sprite.setTexture(Textures.Black.Queen); break;
                case Pieces::Black_King: this->Sprite.setTexture(Textures.Black.King); break;
                case Pieces::White_Pawn: this->Sprite.setTexture(Textures.White.Pawn); break;
                case Pieces::White_Rook: this->Sprite.setTexture(Textures.White.Rook); break;
                case Pieces::White_Knight: this->Sprite.setTexture(Textures.White.Knight); break;
                case Pieces::White_Bishop: this->Sprite.setTexture(Textures.White.Bishop); break;
                case Pieces::White_Queen: this->Sprite.setTexture(Textures.White.Queen); break;
                case Pieces::White_King: this->Sprite.setTexture(Textures.White.King); break;
            }

            if(isNotEmpty) {
                this->Sprite.setPosition(float(x * 80), float(y * 80));
                this->Window.draw(this->Sprite);
            }
        }
    }

    this->Window.draw(this->PlayerTurn);
    this->Window.draw(this->LastMove);
    this->Window.draw(this->GoBackButton);
    this->Window.draw(this->NextButton);
    this->Window.draw(this->GoBackBtnText);
    this->Window.draw(this->NextBtnText);

    this->Window.display();
}

#endif
<commit_msg>Update reader.hpp<commit_after>/*
 *  reader.hpp
 *  SimpleChess
 *
 *  Created by Ronak Gajrawala on 12/26/13.
 *  Copyright (c) 2013 Ronak Gajrawala. All rights reserved.
 */

#ifndef SimpleChess_reader_hpp
#define SimpleChess_reader_hpp

/***********
 * @todo Create the board reader, next move / last move.
 ***********/

/**
 * The Reader class.
 * The main starting page or menu is created and handled here.
 */
class Reader {
    sf::RenderWindow Window; /**< The window of the menu. */
    sf::Font Font; /**< The font that the text on the menu will use (sansation.ttf). */
    sf::Event Event; /**< Any window events. */
    sf::Vector2u Mouse; /**< Mouse coordinates. */
    sf::Image Icon; /**< The icon for the window */

    sf::Text PlayerTurn, /**< Stores who's turn it is. */
             LastMove; /**< Stores the last move. */
    sf::Sprite Sprite; /**< The Sprite that will load the board and pieces. */

    sf::RectangleShape NextButton; /**< The button that says "Next". */
    sf::Text NextBtnText; /**< Text for the Next Button. */
    sf::RectangleShape GoBackButton; /**< The button that says "Back". */
    sf::Text GoBackBtnText; /**< Text for the Go-Back Button. */

    File::Information FileInfo; /**< File information necessary for the replay. */
    Board8 Board; /**< The board we will be replaying. */
public:

    /**
     * Creates the menu and other important parts of the start page.
     */
    void Initialize(void);

    /**
     * Main loop for the start page.
     * Initializes, runs / loops, and cleans up.
     */
    void Main(void);

    /**
     * Event handler for window events.
     */
    void OnEvent(void);

    /**
     * Event handler for mouse moves.
     * @see OnEvent
     */
    void OnMouseMove(void);

    /**
     * Event handler for key presses.
     * @see OnEvent
     */
    void OnKeyPressed(void);

    /**
     * Handler for mouse button releases.
     * @see OnEvent
     */
    void OnMouseButtonReleased(void);

    /**
     * Draws pieces and chessboard onto screen.
     */
    void Display(void);
} Reader;

////////// SOURCE //////////

void Reader::Initialize(void) {
    this->Window.create(sf::VideoMode(900, 640), "SimpleChess - Reader", sf::Style::Close);
    this->Window.setFramerateLimit(10);

    if(!this->Icon.loadFromFile(GetResource("white_knight.png"))) {
        exit(EXIT_FAILURE);
    }
    this->Window.setIcon(this->Icon.getSize().x, this->Icon.getSize().y, this->Icon.getPixelsPtr());

    if(!this->Font.loadFromFile(GetResource("sansation.ttf"))) {
        exit(EXIT_FAILURE);
    }

    File.Read(&this->FileInfo);
    File.CreateBoardFromFile("default.chessconf", &this->Board);

    this->NextButton.setFillColor(sf::Color::Yellow);
    this->NextButton.setSize(sf::Vector2f(240.0, 50.0));
    this->NextButton.setPosition(650.0, 520.0);

    this->NextBtnText.setColor(sf::Color::Blue);
    this->NextBtnText.setCharacterSize(40);
    this->NextBtnText.setPosition(722.0, 520.0);
    this->NextBtnText.setFont(this->Font);
    this->NextBtnText.setString("Next");

    this->GoBackButton.setFillColor(sf::Color::Yellow);
    this->GoBackButton.setSize(sf::Vector2f(240.0, 50.0));
    this->GoBackButton.setPosition(650.0, 580.0);

    this->GoBackBtnText.setColor(sf::Color::Blue);
    this->GoBackBtnText.setCharacterSize(40);
    this->GoBackBtnText.setPosition(722.0, 580.0);
    this->GoBackBtnText.setFont(this->Font);
    this->GoBackBtnText.setString("Back");
}

void Reader::OnMouseMove(void) {
    this->Mouse.x = Event.mouseMove.x;
    this->Mouse.y = Event.mouseMove.y;
}

void Reader::OnKeyPressed(void) {
    if(((this->Event.key.code is sf::Keyboard::W or this->Event.key.code is sf::Keyboard::C) and this->Event.key.control) or ((this->Event.key.code is sf::Keyboard::W or this->Event.key.code is sf::Keyboard::C) and this->Event.key.alt)) {
        this->Window.close();
    }
}

void Reader::OnMouseButtonReleased(void) {
    if(Utils.Contains(this->Mouse.x, this->Mouse.y, this->NextButton.getPosition().x, this->NextButton.getPosition().y, this->NextButton.getSize().x, this->NextButton.getSize().y)) {
        // Next
    } else if(Utils.Contains(this->Mouse.x, this->Mouse.y, this->GoBackButton.getPosition().x, this->GoBackButton.getPosition().y, this->GoBackButton.getSize().x, this->GoBackButton.getSize().y)) {
        // Back
    } else {

    }
}

void Reader::OnEvent(void) {
    switch(this->Event.type) {
        case sf::Event::Closed: this->Window.close();
        case sf::Event::KeyPressed: this->OnKeyPressed(); break;
        case sf::Event::MouseMoved: this->OnMouseMove(); break;
        case sf::Event::MouseButtonReleased: this->OnMouseButtonReleased(); break;
        default: break;
    }
}

void Reader::Main(void) {
    this->Initialize();
    while(this->Window.isOpen()) {
        this->Window.clear(sf::Color::Black);

        while(this->Window.pollEvent(this->Event)) {
            this->OnEvent();
        }

        this->Display();
    }
}

void Reader::Display(void) {
    this->Sprite.setTexture(Textures.ChessBoard);
    this->Sprite.setPosition(0.0, 0.0);
    this->Window.draw(this->Sprite);

    for(int y = 0; y < 8; y++) {
        for(int x = 0; x < 8; x++) {
            bool isNotEmpty = true;

            switch(this->Board.at(y).at(x)) {
                case Pieces::Empty: isNotEmpty = false; break;
                case Pieces::Black_Pawn: this->Sprite.setTexture(Textures.Black.Pawn); break;
                case Pieces::Black_Rook: this->Sprite.setTexture(Textures.Black.Rook); break;
                case Pieces::Black_Knight: this->Sprite.setTexture(Textures.Black.Knight); break;
                case Pieces::Black_Bishop: this->Sprite.setTexture(Textures.Black.Bishop); break;
                case Pieces::Black_Queen: this->Sprite.setTexture(Textures.Black.Queen); break;
                case Pieces::Black_King: this->Sprite.setTexture(Textures.Black.King); break;
                case Pieces::White_Pawn: this->Sprite.setTexture(Textures.White.Pawn); break;
                case Pieces::White_Rook: this->Sprite.setTexture(Textures.White.Rook); break;
                case Pieces::White_Knight: this->Sprite.setTexture(Textures.White.Knight); break;
                case Pieces::White_Bishop: this->Sprite.setTexture(Textures.White.Bishop); break;
                case Pieces::White_Queen: this->Sprite.setTexture(Textures.White.Queen); break;
                case Pieces::White_King: this->Sprite.setTexture(Textures.White.King); break;
            }

            if(isNotEmpty) {
                this->Sprite.setPosition(float(x * 80), float(y * 80));
                this->Window.draw(this->Sprite);
            }
        }
    }

    this->Window.draw(this->PlayerTurn);
    this->Window.draw(this->LastMove);
    this->Window.draw(this->GoBackButton);
    this->Window.draw(this->NextButton);
    this->Window.draw(this->GoBackBtnText);
    this->Window.draw(this->NextBtnText);

    this->Window.display();
}

#endif
<|endoftext|>


<commit_before>bool sjAlignSplit(uint a1,uint aLength,Parameters* P, uint &a1D, uint &aLengthD, uint &a1A, uint &aLengthA, uint &isj) {
    uint sj1=(a1-P->sjGstart)%P->sjdbLength;
    if (sj1<P->sjdbOverhang && sj1+aLength>P->sjdbOverhang) {//align crosses the junctions
        isj=(a1-P->sjGstart)/P->sjdbLength;
        aLengthD=P->sjdbOverhang-sj1;
        aLengthA=aLength-aLengthD;
        a1D=P->sjDstart[isj]+sj1;
        a1A=P->sjAstart[isj];
        return true;
    } else {
        return false;
    };
};
<commit_msg>include "IncludeDefine.h" and "Parameters.h" in serviceFuns.cpp<commit_after>#include "IncludeDefine.h"
#include "Parameters.h"

bool sjAlignSplit(uint a1,uint aLength,Parameters* P, uint &a1D, uint &aLengthD, uint &a1A, uint &aLengthA, uint &isj) {
    uint sj1=(a1-P->sjGstart)%P->sjdbLength;
    if (sj1<P->sjdbOverhang && sj1+aLength>P->sjdbOverhang) {//align crosses the junctions
        isj=(a1-P->sjGstart)/P->sjdbLength;
        aLengthD=P->sjdbOverhang-sj1;
        aLengthA=aLength-aLengthD;
        a1D=P->sjDstart[isj]+sj1;
        a1A=P->sjAstart[isj];
        return true;
    } else {
        return false;
    };
};
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling -I%p | FileCheck %s

// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here

// PR #96277
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Value.h"
#include <stdio.h>
gCling->declare("int print() { printf(\"print is run.\\n\"); return 1; }");
cling::Value V;
gCling->process("int a = print();",&V);
//CHECK: print is run.
gCling->process("a", &V);
//CHECK: (int) 1
gCling->process("a;", &V);
//CHECK-NOT: print is run.
// End PR #96277
// PR #98146
gCling->process("\"Root\"", &V);
// CHECK: (const char [5]) "Root"
V
// CHECK: (cling::Value &) boxes [(const char [5]) "Root"]
// End PR #98146

.rawInput 1
typedef enum {k1 = 0, k2} enumName;
enumName var = k1;
.rawInput 0
var
// CHECK: (enumName) (k1) : ({{(unsigned )?}}int) 0
const enumName constVar = (enumName) 1 // k2 is invisible!
// CHECK: (const enumName) (k2) : ({{(unsigned )?}}int) 1
<commit_msg>Add test for ROOT-8036.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling -I%p | FileCheck %s

// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here

// PR #96277
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Value.h"
#include <stdio.h>
gCling->declare("int print() { printf(\"print is run.\\n\"); return 1; }");
cling::Value V;
gCling->process("int a = print();",&V);
//CHECK: print is run.
gCling->process("a", &V);
//CHECK: (int) 1
gCling->process("a;", &V);
//CHECK-NOT: print is run.
// End PR #96277
// PR #98146
gCling->process("\"Root\"", &V);
// CHECK: (const char [5]) "Root"
V
// CHECK: (cling::Value &) boxes [(const char [5]) "Root"]
// End PR #98146

.rawInput 1
typedef enum {k1 = 0, k2} enumName;
enumName var = k1;
.rawInput 0
var
// CHECK: (enumName) (k1) : ({{(unsigned )?}}int) 0
const enumName constVar = (enumName) 1 // k2 is invisible!
// CHECK: (const enumName) (k2) : ({{(unsigned )?}}int) 1

// ROOT-8036: check that library symbols do not override interpreter symbols
int step = 10 // CHECK: (int) 10
step // CHECK: (int) 10
<|endoftext|>