<commit_before>/*
    Kopete Yahoo Protocol
    Handles logging into to the Yahoo service

    Copyright (c) 2004 Duncan Mac-Vicar P. <duncan@kde.org>

    Copyright (c) 2005 André Duffeck <andre.duffeck@kdemail.net>

    Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This library is free software; you can redistribute it and/or         *
    * modify it under the terms of the GNU Lesser General Public            *
    * License as published by the Free Software Foundation; either          *
    * version 2 of the License, or (at your option) any later version.      *
    *                                                                       *
    *************************************************************************
*/

#include <string>

#include "ymsgtransfer.h"
#include "yahootypes.h"
#include "kdebug.h"

#include <qdatastream.h>
#include <qmap.h>
#include <qstring.h>
#include <qstringlist.h>

using namespace Yahoo;

class YMSGTransferPrivate
{
public:
	int yflag;
	int version;
	int packetLength;
	Yahoo::Service service;
	Yahoo::Status status;
	unsigned int id;
	ParamList data;
	bool valid;
};

YMSGTransfer::YMSGTransfer()
{
	d = new YMSGTransferPrivate;
	d->valid = true;
	d->id = 0;
	d-> status = Yahoo::StatusAvailable;
}

YMSGTransfer::YMSGTransfer(Yahoo::Service service)
{
	d = new YMSGTransferPrivate;
	d->valid = true;
	d->service = service;
	d->id = 0;
	d->status = Yahoo::StatusAvailable;
}

YMSGTransfer::YMSGTransfer(Yahoo::Service service, Yahoo::Status status)
{
	d = new YMSGTransferPrivate;
	d->valid = true;
	d->service = service;
	d->id = 0;
	d->status = status;
}

YMSGTransfer::~YMSGTransfer()
{
	delete d;
}

Transfer::TransferType YMSGTransfer::type()
{
	return Transfer::YMSGTransfer;
}

bool YMSGTransfer::isValid()
{
	return d->valid;
}

Yahoo::Service YMSGTransfer::service() const
{
	return d->service;
}

void YMSGTransfer::setService(Yahoo::Service service)
{
	d->service = service;
}

Yahoo::Status YMSGTransfer::status()
{
	return d->status;
}

void YMSGTransfer::setStatus(Yahoo::Status status)
{
	d->status = status;
}

unsigned int YMSGTransfer::id()
{
	return d->id;
}

void YMSGTransfer::setId(unsigned int id)
{
	d->id = id;
}

int YMSGTransfer::packetLength()
{
	return d->packetLength;
}

void YMSGTransfer::setPacketLength(int len)
{
	d->packetLength = len;
}

ParamList YMSGTransfer::paramList()
{
	return d->data;
}

int YMSGTransfer::paramCount( int index )
{
	int cnt = 0;
	for (ParamList::ConstIterator it = d->data.begin(); it !=  d->data.end(); ++it)
	{
		if( (*it).first == index )
			cnt++;
	}
	return cnt;
}

QByteArray YMSGTransfer::nthParam( int index, int occurence )
{
	int cnt = 0;
	for (ParamList::ConstIterator it = d->data.begin(); it !=  d->data.end(); ++it)
	{
		if( (*it).first == index && cnt++ == occurence)
			return (*it).second;
	}
	return QByteArray();
}

QByteArray YMSGTransfer::nthParamSeparated( int index, int occurence, int separator )
{

	int cnt = -1;
	for (ParamList::ConstIterator it = d->data.begin(); it !=  d->data.end(); ++it)
	{
		if( (*it).first == separator )
			cnt++;
		if( (*it).first == index && cnt == occurence)
			return (*it).second;
	}
	return QByteArray();
}

QByteArray YMSGTransfer::firstParam( int index )
{
	for (ParamList::ConstIterator it = d->data.begin(); it !=  d->data.end(); ++it)
	{
		if( (*it).first == index )
			return (*it).second;
	}
	return QByteArray();
}

void YMSGTransfer::setParam(int index, const QByteArray &data)
{
	d->data.append( Param( index, data ) );
}

void YMSGTransfer::setParam( int index, int data )
{
	d->data.append( Param( index, QString::number( data ).toLocal8Bit() ) );
}

int YMSGTransfer::length()
{
	int len = 0;
	for (ParamList::ConstIterator it = d->data.begin(); it !=  d->data.end(); ++it)
	{
		len += QString::number( (*it).first ).length();
		len += 2;
		len += (*it).second.length();
		len += 2;
	}
	return len;
}

QByteArray YMSGTransfer::serialize()
{
	/*
	<------- 4B -------><------- 4B -------><---2B--->
	+-------------------+-------------------+---------+
	|   Y   M   S   G   |      version      | pkt_len |
	+---------+---------+---------+---------+---------+
	| service |      status       |    session_id     |
	+---------+-------------------+-------------------+
	|                                                 |
	:                    D A T A                      :
	/                   0 - 65535*                   |
	+-------------------------------------------------+
	*/

	int pos = 0;
	QStringList::ConstIterator listIt = 0;
	QByteArray buffer;
	QDataStream stream( &buffer, QIODevice::WriteOnly );

	stream << (Q_INT8)'Y' << (Q_INT8)'M' << (Q_INT8)'S' << (Q_INT8)'G';
	if( d->service == Yahoo::ServicePictureUpload )
		stream << (Q_INT16)0x0e00;
	else
		stream << (Q_INT16)0x000e;
	stream << (Q_INT16)0x0000;
	if( d->service == Yahoo::ServicePictureUpload ||
		d->service == Yahoo::ServiceFileTransfer )
		stream << (Q_INT16)(length()+4);
	else
		stream << (Q_INT16)length();
	stream << (Q_INT16)d->service;
	stream << (Q_INT32)d->status;
	stream << (Q_INT32)d->id;
 	for (ParamList::ConstIterator it = d->data.begin(); it !=  d->data.end(); ++it)
	{
 		kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << " Serializing key " << (*it).first << " value " << (*it).second << endl;
		stream.writeRawData ( QString::number( (*it).first ).toLocal8Bit(), QString::number( (*it).first ).length() );
		stream << (Q_INT8)0xc0 << (Q_INT8)0x80;
		stream.writeRawData( (*it).second, (*it).second.length() );
		stream << (Q_INT8)0xc0 << (Q_INT8)0x80;
	}
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << " pos=" << pos << " (packet size)" << buffer << endl;
	return buffer;
}

<commit_msg>YMSGVersion++<commit_after>/*
    Kopete Yahoo Protocol
    Handles logging into to the Yahoo service

    Copyright (c) 2004 Duncan Mac-Vicar P. <duncan@kde.org>

    Copyright (c) 2005 André Duffeck <andre.duffeck@kdemail.net>

    Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This library is free software; you can redistribute it and/or         *
    * modify it under the terms of the GNU Lesser General Public            *
    * License as published by the Free Software Foundation; either          *
    * version 2 of the License, or (at your option) any later version.      *
    *                                                                       *
    *************************************************************************
*/

#include <string>

#include "ymsgtransfer.h"
#include "yahootypes.h"
#include "kdebug.h"

#include <qdatastream.h>
#include <qmap.h>
#include <qstring.h>
#include <qstringlist.h>

using namespace Yahoo;

class YMSGTransferPrivate
{
public:
	int yflag;
	int version;
	int packetLength;
	Yahoo::Service service;
	Yahoo::Status status;
	unsigned int id;
	ParamList data;
	bool valid;
};

YMSGTransfer::YMSGTransfer()
{
	d = new YMSGTransferPrivate;
	d->valid = true;
	d->id = 0;
	d-> status = Yahoo::StatusAvailable;
}

YMSGTransfer::YMSGTransfer(Yahoo::Service service)
{
	d = new YMSGTransferPrivate;
	d->valid = true;
	d->service = service;
	d->id = 0;
	d->status = Yahoo::StatusAvailable;
}

YMSGTransfer::YMSGTransfer(Yahoo::Service service, Yahoo::Status status)
{
	d = new YMSGTransferPrivate;
	d->valid = true;
	d->service = service;
	d->id = 0;
	d->status = status;
}

YMSGTransfer::~YMSGTransfer()
{
	delete d;
}

Transfer::TransferType YMSGTransfer::type()
{
	return Transfer::YMSGTransfer;
}

bool YMSGTransfer::isValid()
{
	return d->valid;
}

Yahoo::Service YMSGTransfer::service() const
{
	return d->service;
}

void YMSGTransfer::setService(Yahoo::Service service)
{
	d->service = service;
}

Yahoo::Status YMSGTransfer::status()
{
	return d->status;
}

void YMSGTransfer::setStatus(Yahoo::Status status)
{
	d->status = status;
}

unsigned int YMSGTransfer::id()
{
	return d->id;
}

void YMSGTransfer::setId(unsigned int id)
{
	d->id = id;
}

int YMSGTransfer::packetLength()
{
	return d->packetLength;
}

void YMSGTransfer::setPacketLength(int len)
{
	d->packetLength = len;
}

ParamList YMSGTransfer::paramList()
{
	return d->data;
}

int YMSGTransfer::paramCount( int index )
{
	int cnt = 0;
	for (ParamList::ConstIterator it = d->data.begin(); it !=  d->data.end(); ++it)
	{
		if( (*it).first == index )
			cnt++;
	}
	return cnt;
}

QByteArray YMSGTransfer::nthParam( int index, int occurence )
{
	int cnt = 0;
	for (ParamList::ConstIterator it = d->data.begin(); it !=  d->data.end(); ++it)
	{
		if( (*it).first == index && cnt++ == occurence)
			return (*it).second;
	}
	return QByteArray();
}

QByteArray YMSGTransfer::nthParamSeparated( int index, int occurence, int separator )
{

	int cnt = -1;
	for (ParamList::ConstIterator it = d->data.begin(); it !=  d->data.end(); ++it)
	{
		if( (*it).first == separator )
			cnt++;
		if( (*it).first == index && cnt == occurence)
			return (*it).second;
	}
	return QByteArray();
}

QByteArray YMSGTransfer::firstParam( int index )
{
	for (ParamList::ConstIterator it = d->data.begin(); it !=  d->data.end(); ++it)
	{
		if( (*it).first == index )
			return (*it).second;
	}
	return QByteArray();
}

void YMSGTransfer::setParam(int index, const QByteArray &data)
{
	d->data.append( Param( index, data ) );
}

void YMSGTransfer::setParam( int index, int data )
{
	d->data.append( Param( index, QString::number( data ).toLocal8Bit() ) );
}

int YMSGTransfer::length()
{
	int len = 0;
	for (ParamList::ConstIterator it = d->data.begin(); it !=  d->data.end(); ++it)
	{
		len += QString::number( (*it).first ).length();
		len += 2;
		len += (*it).second.length();
		len += 2;
	}
	return len;
}

QByteArray YMSGTransfer::serialize()
{
	/*
	<------- 4B -------><------- 4B -------><---2B--->
	+-------------------+-------------------+---------+
	|   Y   M   S   G   |      version      | pkt_len |
	+---------+---------+---------+---------+---------+
	| service |      status       |    session_id     |
	+---------+-------------------+-------------------+
	|                                                 |
	:                    D A T A                      :
	/                   0 - 65535*                   |
	+-------------------------------------------------+
	*/

	int pos = 0;
	QStringList::ConstIterator listIt = 0;
	QByteArray buffer;
	QDataStream stream( &buffer, QIODevice::WriteOnly );

	stream << (Q_INT8)'Y' << (Q_INT8)'M' << (Q_INT8)'S' << (Q_INT8)'G';
	if( d->service == Yahoo::ServicePictureUpload )
		stream << (Q_INT16)0x0f00;
	else
		stream << (Q_INT16)0x000f;
	stream << (Q_INT16)0x0000;
	if( d->service == Yahoo::ServicePictureUpload ||
		d->service == Yahoo::ServiceFileTransfer )
		stream << (Q_INT16)(length()+4);
	else
		stream << (Q_INT16)length();
	stream << (Q_INT16)d->service;
	stream << (Q_INT32)d->status;
	stream << (Q_INT32)d->id;
 	for (ParamList::ConstIterator it = d->data.begin(); it !=  d->data.end(); ++it)
	{
 		kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << " Serializing key " << (*it).first << " value " << (*it).second << endl;
		stream.writeRawData ( QString::number( (*it).first ).toLocal8Bit(), QString::number( (*it).first ).length() );
		stream << (Q_INT8)0xc0 << (Q_INT8)0x80;
		stream.writeRawData( (*it).second, (*it).second.length() );
		stream << (Q_INT8)0xc0 << (Q_INT8)0x80;
	}
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << " pos=" << pos << " (packet size)" << buffer << endl;
	return buffer;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PageMasterPropHdl.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 14:46:02 $
 *
 *  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 _XMLOFF_PAGEMASTERPROPHDL_HXX_
#define _XMLOFF_PAGEMASTERPROPHDL_HXX_

#ifndef _XMLOFF_PROPERTYHANDLERBASE_HXX
#include "xmlprhdl.hxx"
#endif

#ifndef _RTL_USTRING_
#include <rtl/ustring.hxx>
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif

//______________________________________________________________________________
// property handler for style:page-usage (style::PageStyleLayout)

class XMLPMPropHdl_PageStyleLayout : public XMLPropertyHandler
{
public:
    virtual                 ~XMLPMPropHdl_PageStyleLayout();
    virtual bool            equals(
                                const ::com::sun::star::uno::Any& rAny1,
                                const ::com::sun::star::uno::Any& rAny2
                                ) const;
    virtual sal_Bool        importXML(
                                const ::rtl::OUString& rStrImpValue,
                                ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
    virtual sal_Bool        exportXML(
                                ::rtl::OUString& rStrExpValue,
                                const ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
};

//______________________________________________________________________________
// property handler for style:num-format (style::NumberingType)

class XMLPMPropHdl_NumFormat : public XMLPropertyHandler
{
public:
    virtual                 ~XMLPMPropHdl_NumFormat();
    virtual sal_Bool        importXML(
                                const ::rtl::OUString& rStrImpValue,
                                ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
    virtual sal_Bool        exportXML(
                                ::rtl::OUString& rStrExpValue,
                                const ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
};

//______________________________________________________________________________
// property handler for style:num-letter-sync (style::NumberingType)

class XMLPMPropHdl_NumLetterSync : public XMLPropertyHandler
{
public:
    virtual                 ~XMLPMPropHdl_NumLetterSync();
    virtual sal_Bool        importXML(
                                const ::rtl::OUString& rStrImpValue,
                                ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
    virtual sal_Bool        exportXML(
                                ::rtl::OUString& rStrExpValue,
                                const ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
};

//______________________________________________________________________________
// property handler for style:paper-tray-number

class XMLPMPropHdl_PaperTrayNumber : public XMLPropertyHandler
{
public:
    virtual                 ~XMLPMPropHdl_PaperTrayNumber();
    virtual sal_Bool        importXML(
                                const ::rtl::OUString& rStrImpValue,
                                ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
    virtual sal_Bool        exportXML(
                                ::rtl::OUString& rStrExpValue,
                                const ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
};

//______________________________________________________________________________
// property handler for style:print

class XMLPMPropHdl_Print : public XMLPropertyHandler
{
protected:
    ::rtl::OUString         sAttrValue;

public:
                            XMLPMPropHdl_Print( enum ::xmloff::token::XMLTokenEnum eValue );
    virtual                 ~XMLPMPropHdl_Print();

    virtual sal_Bool        importXML(
                                const ::rtl::OUString& rStrImpValue,
                                ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
    virtual sal_Bool        exportXML(
                                ::rtl::OUString& rStrExpValue,
                                const ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
};

//______________________________________________________________________________
// property handler for style:table-centering

class XMLPMPropHdl_CenterHorizontal : public XMLPropertyHandler
{
public:
    virtual                 ~XMLPMPropHdl_CenterHorizontal();
    virtual sal_Bool        importXML(
                                const ::rtl::OUString& rStrImpValue,
                                ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
    virtual sal_Bool        exportXML(
                                ::rtl::OUString& rStrExpValue,
                                const ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
};

class XMLPMPropHdl_CenterVertical : public XMLPropertyHandler
{
public:
    virtual                 ~XMLPMPropHdl_CenterVertical();
    virtual sal_Bool        importXML(
                                const ::rtl::OUString& rStrImpValue,
                                ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
    virtual sal_Bool        exportXML(
                                ::rtl::OUString& rStrExpValue,
                                const ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
};

#endif

<commit_msg>INTEGRATION: CWS vgbugs07 (1.8.114); FILE MERGED 2007/06/04 13:23:29 vg 1.8.114.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PageMasterPropHdl.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 15:27:37 $
 *
 *  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 _XMLOFF_PAGEMASTERPROPHDL_HXX_
#define _XMLOFF_PAGEMASTERPROPHDL_HXX_

#ifndef _XMLOFF_PROPERTYHANDLERBASE_HXX
#include <xmloff/xmlprhdl.hxx>
#endif

#ifndef _RTL_USTRING_
#include <rtl/ustring.hxx>
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif

//______________________________________________________________________________
// property handler for style:page-usage (style::PageStyleLayout)

class XMLPMPropHdl_PageStyleLayout : public XMLPropertyHandler
{
public:
    virtual                 ~XMLPMPropHdl_PageStyleLayout();
    virtual bool            equals(
                                const ::com::sun::star::uno::Any& rAny1,
                                const ::com::sun::star::uno::Any& rAny2
                                ) const;
    virtual sal_Bool        importXML(
                                const ::rtl::OUString& rStrImpValue,
                                ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
    virtual sal_Bool        exportXML(
                                ::rtl::OUString& rStrExpValue,
                                const ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
};

//______________________________________________________________________________
// property handler for style:num-format (style::NumberingType)

class XMLPMPropHdl_NumFormat : public XMLPropertyHandler
{
public:
    virtual                 ~XMLPMPropHdl_NumFormat();
    virtual sal_Bool        importXML(
                                const ::rtl::OUString& rStrImpValue,
                                ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
    virtual sal_Bool        exportXML(
                                ::rtl::OUString& rStrExpValue,
                                const ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
};

//______________________________________________________________________________
// property handler for style:num-letter-sync (style::NumberingType)

class XMLPMPropHdl_NumLetterSync : public XMLPropertyHandler
{
public:
    virtual                 ~XMLPMPropHdl_NumLetterSync();
    virtual sal_Bool        importXML(
                                const ::rtl::OUString& rStrImpValue,
                                ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
    virtual sal_Bool        exportXML(
                                ::rtl::OUString& rStrExpValue,
                                const ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
};

//______________________________________________________________________________
// property handler for style:paper-tray-number

class XMLPMPropHdl_PaperTrayNumber : public XMLPropertyHandler
{
public:
    virtual                 ~XMLPMPropHdl_PaperTrayNumber();
    virtual sal_Bool        importXML(
                                const ::rtl::OUString& rStrImpValue,
                                ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
    virtual sal_Bool        exportXML(
                                ::rtl::OUString& rStrExpValue,
                                const ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
};

//______________________________________________________________________________
// property handler for style:print

class XMLPMPropHdl_Print : public XMLPropertyHandler
{
protected:
    ::rtl::OUString         sAttrValue;

public:
                            XMLPMPropHdl_Print( enum ::xmloff::token::XMLTokenEnum eValue );
    virtual                 ~XMLPMPropHdl_Print();

    virtual sal_Bool        importXML(
                                const ::rtl::OUString& rStrImpValue,
                                ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
    virtual sal_Bool        exportXML(
                                ::rtl::OUString& rStrExpValue,
                                const ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
};

//______________________________________________________________________________
// property handler for style:table-centering

class XMLPMPropHdl_CenterHorizontal : public XMLPropertyHandler
{
public:
    virtual                 ~XMLPMPropHdl_CenterHorizontal();
    virtual sal_Bool        importXML(
                                const ::rtl::OUString& rStrImpValue,
                                ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
    virtual sal_Bool        exportXML(
                                ::rtl::OUString& rStrExpValue,
                                const ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
};

class XMLPMPropHdl_CenterVertical : public XMLPropertyHandler
{
public:
    virtual                 ~XMLPMPropHdl_CenterVertical();
    virtual sal_Bool        importXML(
                                const ::rtl::OUString& rStrImpValue,
                                ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
    virtual sal_Bool        exportXML(
                                ::rtl::OUString& rStrExpValue,
                                const ::com::sun::star::uno::Any& rValue,
                                const SvXMLUnitConverter& rUnitConverter
                                ) const;
};

#endif

<|endoftext|>


<commit_before>//
// Created by Miguel Rentes on 19/01/2017.
//

#include "STL.h"

int main(void) {
    unsigned int number_elements;
    unsigned int number_queries;
    unsigned int element;
    cin >> number_elements;
    vector <unsigned int> elements;
    for (int i = 0; i < number_elements; i++) {
        if (cin >> element) {
            elements.push_back(element);
        }
    }
    cin >> number_queries;
    std::vector<unsigned int>::iterator it;
    for (int i = 0; i < number_queries; i++) {
        cin >> element;
        it = find(elements.begin(), elements.end(), element);
        if (it != elements.end() || *it == element) {
            cout << "Yes " << it - elements.begin() + 1 << endl;
        }
        else {
            it = lower_bound(elements.begin(), elements.end(), element);
            cout << "No " << it - elements.begin() + 1 << endl;
        }
    }

    return EXIT_SUCCESS;
}<commit_msg>Refactors solution for the Lower Bound-STL challenge.<commit_after>//
// Created by Miguel Rentes on 19/01/2017.
//

#include "STL.h"

int main(void) {
    unsigned int number_elements;
    unsigned int number_queries;
    unsigned int element;
    vector <unsigned int> elements;
    vector<unsigned int>::iterator it;
    cin >> number_elements;
    for (int i = 0; i < number_elements; i++) {
        if (cin >> element) {
            elements.push_back(element);
        }
    }
    cin >> number_queries;
    for (int i = 0; i < number_queries; i++) {
        cin >> element;
        it = find(elements.begin(), elements.end(), element);
        if (it != elements.end() || *it == element) {
            cout << "Yes " << it - elements.begin() + 1 << endl;
        }
        else {
            it = lower_bound(elements.begin(), elements.end(), element);
            cout << "No " << it - elements.begin() + 1 << endl;
        }
    }

    return EXIT_SUCCESS;
}<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of GIMPACT Library.

For the latest info, see http://gimpact.sourceforge.net/

Copyright (c) 2006 Francisco Leon. C.C. 80087371.
email: projectileman@yahoo.com

 This library is free software; you can redistribute it and/or
 modify it under the terms of EITHER:
   (1) The GNU Lesser General Public License as published by the Free
       Software Foundation; either version 2.1 of the License, or (at
       your option) any later version. The text of the GNU Lesser
       General Public License is included with this library in the
       file GIMPACT-LICENSE-LGPL.TXT.
   (2) The BSD-style license that is included with this library in
       the file GIMPACT-LICENSE-BSD.TXT.

 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 files
 GIMPACT-LICENSE-LGPL.TXT and GIMPACT-LICENSE-BSD.TXT for more details.

-----------------------------------------------------------------------------
*/

#include "GIMPACT/gim_math.h"
#include "stdlib.h"
#include "time.h"

GREAL gim_inv_sqrt(GREAL f)
{
    GREAL r;
    GIM_INV_SQRT(f,r);
    return r;
}

GREAL gim_sqrt(GREAL f)
{
    GREAL r;
    GIM_SQRT(f,r);
    return r;
}

//!Initializes mathematical functions
void gim_init_math()
{
    srand(time(0));
}

//! Generates an unit random
GREAL gim_unit_random()
{
    GREAL rn = rand();
    rn/=(GREAL)RAND_MAX;
    return rn;
}
<commit_msg>Fix for int assigned to float without cast warning.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of GIMPACT Library.

For the latest info, see http://gimpact.sourceforge.net/

Copyright (c) 2006 Francisco Leon. C.C. 80087371.
email: projectileman@yahoo.com

 This library is free software; you can redistribute it and/or
 modify it under the terms of EITHER:
   (1) The GNU Lesser General Public License as published by the Free
       Software Foundation; either version 2.1 of the License, or (at
       your option) any later version. The text of the GNU Lesser
       General Public License is included with this library in the
       file GIMPACT-LICENSE-LGPL.TXT.
   (2) The BSD-style license that is included with this library in
       the file GIMPACT-LICENSE-BSD.TXT.

 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 files
 GIMPACT-LICENSE-LGPL.TXT and GIMPACT-LICENSE-BSD.TXT for more details.

-----------------------------------------------------------------------------
*/

#include "GIMPACT/gim_math.h"
#include "stdlib.h"
#include "time.h"

GREAL gim_inv_sqrt(GREAL f)
{
    GREAL r;
    GIM_INV_SQRT(f,r);
    return r;
}

GREAL gim_sqrt(GREAL f)
{
    GREAL r;
    GIM_SQRT(f,r);
    return r;
}

//!Initializes mathematical functions
void gim_init_math()
{
    srand(time(0));
}

//! Generates an unit random
GREAL gim_unit_random()
{
    GREAL rn = static_cast< GREAL >( rand() );
    rn/=(GREAL)RAND_MAX;
    return rn;
}
<|endoftext|>


<commit_before>#include "GLDisplayList.h"
#include "GL.h"
#include <errors.h>
#include <stdio.h>

using namespace GLDraw;

static int gNumDisplayLists = 0;

GLDisplayList::GLDisplayList(int _count)
  :count(_count)
{}

GLDisplayList::~GLDisplayList()
{
  erase();
}

bool GLDisplayList::isCompiled() const
{
  return id != NULL;
}

void GLDisplayList::beginCompile(int index)
{
  if(id == NULL) {
    id = new int;
    *id = glGenLists(count);
    gNumDisplayLists += count;
    if(gNumDisplayLists > 3000)
      printf("Warning, compiling new OpenGL display list id %d, total number %d\n",*id,gNumDisplayLists);
  }
  glNewList(*id+index,GL_COMPILE);
}

void GLDisplayList::endCompile()
{
  if(id == NULL) return;
  //printf("End compile,  list %d\n",*id);
  glEndList();
}

void GLDisplayList::call(int index) const
{
  if(id == NULL) return;
  //printf("Calling list %d\n",*id+index);
  glCallList(*id+index);
}

void GLDisplayList::callAll() const
{
  if(id == NULL) return;
  for(int i=0;i<count;i++)
    glCallList(*id+i);
}

void GLDisplayList::erase()
{
  if(id && id.getRefCount()==1) {
    //printf("Erasing OpenGL display list %d\n",*id);
    glDeleteLists(*id,count);
    gNumDisplayLists -= count;
  }
  //else if(id)
    //printf("Not yet erasing OpenGL display list %d has ref count %d\n",*id,id.getRefCount());

  id=NULL;
}
<commit_msg>Some graphics cards have a big problem with creating lots of display lists... now this will keep a set of previously deleted display lists<commit_after>#include "GLDisplayList.h"
#include "GL.h"
#include <errors.h>
#include <stdio.h>
#include <vector>

using namespace GLDraw;

static int gNumDisplayLists = 0;
const static int MAX_STALE_DISPLAY_LISTS = 100;

class DisplayListManager
{
public:
  DisplayListManager();
  ~DisplayListManager();
  int Allocate(int count=1);
  void Deallocate(int id,int count=1);

  std::vector<int> freedDisplayLists;
  std::vector<int> freedDisplayListCounts;
};

DisplayListManager::DisplayListManager()
{}

DisplayListManager::~DisplayListManager()
{
  for(size_t i=0;i<freedDisplayLists.size();i++) {
    glDeleteLists(freedDisplayLists[i],freedDisplayListCounts[i]);
    gNumDisplayLists -= freedDisplayListCounts[i];
  }
}

int DisplayListManager::Allocate(int count)
{
  for(size_t i=0;i<freedDisplayLists.size();i++) {
    if(freedDisplayListCounts[i] == count) {
      int id = freedDisplayLists[i];
      freedDisplayLists[i] = freedDisplayLists.back();
      freedDisplayListCounts[i] = freedDisplayListCounts.back();
      freedDisplayLists.resize(freedDisplayLists.size()-1);
      freedDisplayListCounts.resize(freedDisplayListCounts.size()-1);
      return id;
    }
  }
  int id = glGenLists(count);
  gNumDisplayLists += count;
  if(gNumDisplayLists > 3000)
    printf("Warning, compiling new OpenGL display list id %d, total number %d\n",id,gNumDisplayLists);
  return id;
}

void DisplayListManager::Deallocate(int id,int count)
{
  if(freedDisplayLists.size() >= MAX_STALE_DISPLAY_LISTS) {
    glDeleteLists(id,count);
    gNumDisplayLists -= count;
  }
  else {
    freedDisplayLists.push_back(id);
    freedDisplayListCounts.push_back(count);
  }
}

static DisplayListManager gDisplayListManager;

GLDisplayList::GLDisplayList(int _count)
  :count(_count)
{}

GLDisplayList::~GLDisplayList()
{
  erase();
}

bool GLDisplayList::isCompiled() const
{
  return id != NULL;
}

void GLDisplayList::beginCompile(int index)
{
  if(id == NULL) {
    id = new int;
    *id = gDisplayListManager.Allocate(count);
  }
  glNewList(*id+index,GL_COMPILE);
}

void GLDisplayList::endCompile()
{
  if(id == NULL) return;
  //printf("End compile,  list %d\n",*id);
  glEndList();
}

void GLDisplayList::call(int index) const
{
  if(id == NULL) return;
  //printf("Calling list %d\n",*id+index);
  glCallList(*id+index);
}

void GLDisplayList::callAll() const
{
  if(id == NULL) return;
  for(int i=0;i<count;i++)
    glCallList(*id+i);
}

void GLDisplayList::erase()
{
  if(id && id.getRefCount()==1) {
    //printf("Erasing OpenGL display list %d\n",*id);
    gDisplayListManager.Deallocate(*id,count);
  }
  //else if(id)
    //printf("Not yet erasing OpenGL display list %d has ref count %d\n",*id,id.getRefCount());

  id=NULL;
}
<|endoftext|>


<commit_before>//
// Created by Dennis Goldfarb on 1/3/17.
//

#include <iostream>
#include <fstream>
#include <random>
#include <algorithm>

#include <OpenMS/CHEMISTRY/Element.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/CHEMISTRY/ResidueDB.h>
#include <OpenMS/CHEMISTRY/ElementDB.h>

#include "FASTAParser.h"

static const ElementDB* elementDB = ElementDB::getInstance();
static const OpenMS::ResidueDB* residueDB = OpenMS::ResidueDB::getInstance();

static std::string AMINO_ACIDS = "ADEFGHIKLNPQRSTVWYCM";
static std::string AMINO_ACIDS_NO_SULFUR = "ADEFGHIKLNPQRSTVWY";
static std::string AMINO_ACIDS_SULFUR = "CM";

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis_AA(0,1);

std::ofstream* openOutputFiles(std::string base_path, int max_depth)
{
    // create all output files and write header to each
    std::ofstream* outfiles = new std::ofstream[max_depth];
    for (int precursor_isotope = 0; precursor_isotope < max_depth; ++precursor_isotope)
    {
        std::string filename = "Precursor" + std::to_string(precursor_isotope) + ".tab";

        outfiles[precursor_isotope].open(base_path + filename);
        outfiles[precursor_isotope] << "probability" << "\tprecursor.mass" << std::endl;
    }

    return outfiles;
}

void closeOutputFiles(std::ofstream* outfiles, int max_depth)
{
    // close all output files
    for (int precursor_isotope = 0; precursor_isotope < max_depth; ++precursor_isotope)
    {
        outfiles[precursor_isotope].close();
    }
    delete[] outfiles;
}

void write_distribution(const OpenMS::AASequence &p, std::ofstream* outfiles, int max_depth, bool mono)
{
    OpenMS::EmpiricalFormula precursor_ef = p.getFormula();
    OpenMS::IsotopeDistribution precursor_id = precursor_ef.getIsotopeDistribution(0);

    for (int precursor_isotope = 0; precursor_isotope < max_depth && precursor_isotope < precursor_id.size(); ++precursor_isotope)
    {
        double mass = mono ? precursor_ef.getMonoWeight() : precursor_ef.getAverageWeight();

        outfiles[precursor_isotope] << precursor_id.getContainer()[precursor_isotope].second << "\t" << mass << std::endl;
    }
}

void proteome_isotopic_distributions(std::string base_path, std::string fasta_path, float max_mass, int num_sulfurs, int max_depth, bool mono)
{
    std::ofstream* outfiles = openOutputFiles(base_path, max_depth);

    FASTAParser parser(fasta_path, max_mass, 1, 100);
    for (auto itr = parser.begin(); itr != parser.end(); ++itr)
    {
        if (num_sulfurs < 0 || itr->getFormula().getNumberOf(elementDB->getElement("Sulfur")) == num_sulfurs)
        {
            write_distribution(*itr, outfiles, max_depth, mono);
        }
    }

    closeOutputFiles(outfiles, max_depth);
}

OpenMS::AASequence create_random_peptide_sequence(int peptide_length, std::vector<double> aa2prob, int num_sulfurs)
{
    OpenMS::AASequence random_peptide;

    if (num_sulfurs < 0)
    {
        for (int aa_index = 0; aa_index < peptide_length; ++aa_index)
        {
            double rand = dis_AA(gen);
            int index = std::lower_bound(aa2prob.begin(), aa2prob.end(), rand) - aa2prob.begin();
            random_peptide += residueDB->getResidue(AMINO_ACIDS[index]);
        }
    }
    else
    {
        // for insertion of sulfur containing amino acids
        for (int i = 0; i < num_sulfurs; ++i)
        {
            random_peptide += residueDB->getResidue(AMINO_ACIDS_SULFUR[0]);
        }

        // random amino acid insertion (non Sulfur and Selenium amino acids)
        for (int aa_index = 0; aa_index < peptide_length; ++aa_index)
        {
            double rand = dis_AA(gen);
            int index = std::lower_bound(aa2prob.begin(), aa2prob.end(), rand) - aa2prob.begin() - 1;
            random_peptide += residueDB->getResidue(AMINO_ACIDS_NO_SULFUR[index]);
        }
    }

    return random_peptide;
}

std::map<char, double> getAAProbabilities(std::string fasta_path, bool sulfur)
{
    std::map<char, double> aa2prob;
    for (char aa : AMINO_ACIDS)
    {
        aa2prob[aa] = 0.0;
    }

    std::vector<FASTAFile::FASTAEntry> proteins;
    FASTAFile().load(fasta_path, proteins);

    int count = 0;
    for (Size i = 0; i < proteins.size(); ++i)
    {
        for (int j = 0; j < proteins[i].sequence.size(); ++j)
        {
            char aa = proteins[i].sequence[j];
            if ((sulfur && AMINO_ACIDS.find(aa) != -1) || (!sulfur && AMINO_ACIDS_NO_SULFUR.find(aa) != -1))
            {
                aa2prob[aa]++;
                count++;
            }
        }
    }

    for (auto &aa : aa2prob)
    {
        aa.second /= count;
    }

    return aa2prob;
}

std::vector<double> calcPrefixSum(std::map<char, double> aa2prob, bool sulfur)
{
    std::string AAs = sulfur ? AMINO_ACIDS : AMINO_ACIDS_NO_SULFUR;
    std::vector<double> prefixSum;

    prefixSum.push_back(0d);

    for (int i = 0; i < AAs.size(); ++i)
    {
        prefixSum.push_back(aa2prob[AAs[i]] + prefixSum[i]);
    }

    return prefixSum;
}

void sample_isotopic_distributions(std::string base_path, std::string fasta_path, float max_mass, int num_sulfurs, int max_depth, bool mono)
{

    std::vector<double> aa2prob = calcPrefixSum(getAAProbabilities(fasta_path, num_sulfurs == -1), num_sulfurs == -1);

    std::ofstream* outfiles = openOutputFiles(base_path, max_depth);

    int max_length = max_mass/100;

    for (int peptide_length = 0; peptide_length <= max_length; ++peptide_length)
    {
        for (int sample = 0; sample < 100; ++sample)
        {
            OpenMS::AASequence random_sequence = create_random_peptide_sequence(peptide_length, aa2prob, num_sulfurs);

            if (random_sequence.size() > 0 && random_sequence.getMonoWeight() <= max_mass)
            {
                write_distribution(random_sequence, outfiles, max_depth, mono);
            }
        }
    }

    closeOutputFiles(outfiles, max_depth);
}

void usage()
{
    std::cout << "GenerateTrainingData fasta_path out_path max_mass num_samples S max_depth mono" << std::endl;
    std::cout << "fasta_path: The path to the fasta file to train the splines on." << std::endl;
    std::cout << "out_path: The path to the directory that will store the training data, e.g. ~/data/" << std::endl;
    std::cout << "max_mass: maximum mass allowed for sampled peptides, e.g. 8500" << std::endl;
    std::cout << "S: number of sulfurs that should be in the fragment ion. Use -1 for all (e.g. 0,1,2..)" << std::endl;
    std::cout << "max_depth: The number of isotopes to generate training data for, e.g. 3 = M0,M1,M2" << std::endl;
    std::cout << "mono: should monoisotopic masses be used or average? 1=mono, 0=average" << std::endl;
    std::cout << std::endl;
}

int main(int argc, const char ** argv)
{
    if (argc != 7)
    {
        usage();
        return 0;
    }

    std::string fasta_path = argv[1];
    std::string out_path = argv[2];
    float max_mass = atof(argv[3]);
    int S = atoi(argv[4]);
    int max_depth = atoi(argv[5]);
    bool mono = strncmp(argv[6], "1", 1) == 0 ? true : false;

    //proteome_isotopic_distributions(out_path, fasta_path, max_mass, S, max_depth, mono);
    sample_isotopic_distributions(out_path, fasta_path, max_mass, S, max_depth, mono);

    return 0;
}<commit_msg>added stochastic peptide sampling<commit_after>//
// Created by Dennis Goldfarb on 1/3/17.
//

#include <iostream>
#include <fstream>
#include <random>
#include <algorithm>

#include <OpenMS/CHEMISTRY/Element.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/CHEMISTRY/ResidueDB.h>
#include <OpenMS/CHEMISTRY/ElementDB.h>

#include "FASTAParser.h"

static const ElementDB* elementDB = ElementDB::getInstance();
static const OpenMS::ResidueDB* residueDB = OpenMS::ResidueDB::getInstance();

static std::string AMINO_ACIDS = "ADEFGHIKLNPQRSTVWYCM";
static std::string AMINO_ACIDS_NO_SULFUR = "ADEFGHIKLNPQRSTVWY";
static std::string AMINO_ACIDS_SULFUR = "CM";

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis_AA(0,1);

std::ofstream* openOutputFiles(std::string base_path, int max_depth)
{
    // create all output files and write header to each
    std::ofstream* outfiles = new std::ofstream[max_depth];
    for (int precursor_isotope = 0; precursor_isotope < max_depth; ++precursor_isotope)
    {
        std::string filename = "Precursor" + std::to_string(precursor_isotope) + ".tab";

        outfiles[precursor_isotope].open(base_path + filename);
        outfiles[precursor_isotope] << "probability" << "\tprecursor.mass" << std::endl;
    }

    return outfiles;
}

void closeOutputFiles(std::ofstream* outfiles, int max_depth)
{
    // close all output files
    for (int precursor_isotope = 0; precursor_isotope < max_depth; ++precursor_isotope)
    {
        outfiles[precursor_isotope].close();
    }
    delete[] outfiles;
}

void write_distribution(const OpenMS::AASequence &p, std::ofstream* outfiles, int max_depth, bool mono)
{
    OpenMS::EmpiricalFormula precursor_ef = p.getFormula();
    OpenMS::IsotopeDistribution precursor_id = precursor_ef.getIsotopeDistribution(0);

    for (int precursor_isotope = 0; precursor_isotope < max_depth && precursor_isotope < precursor_id.size(); ++precursor_isotope)
    {
        double mass = mono ? precursor_ef.getMonoWeight() : precursor_ef.getAverageWeight();

        outfiles[precursor_isotope] << precursor_id.getContainer()[precursor_isotope].second << "\t" << mass << std::endl;
    }
}

void proteome_isotopic_distributions(std::string base_path, std::string fasta_path, float max_mass, int num_sulfurs, int max_depth, bool mono)
{
    std::ofstream* outfiles = openOutputFiles(base_path, max_depth);

    FASTAParser parser(fasta_path, max_mass, 1, 100);
    for (auto itr = parser.begin(); itr != parser.end(); ++itr)
    {
        if (num_sulfurs < 0 || itr->getFormula().getNumberOf(elementDB->getElement("Sulfur")) == num_sulfurs)
        {
            write_distribution(*itr, outfiles, max_depth, mono);
        }
    }

    closeOutputFiles(outfiles, max_depth);
}

OpenMS::AASequence create_random_peptide_sequence(int peptide_length, std::vector<double> aa2prob, int num_sulfurs)
{
    OpenMS::AASequence random_peptide;

    if (num_sulfurs < 0)
    {
        for (int aa_index = 0; aa_index < peptide_length; ++aa_index)
        {
            double rand = dis_AA(gen);
            int index = std::lower_bound(aa2prob.begin(), aa2prob.end(), rand) - aa2prob.begin();
            random_peptide += residueDB->getResidue(AMINO_ACIDS[index]);
        }
    }
    else
    {
        // for insertion of sulfur containing amino acids
        for (int i = 0; i < num_sulfurs; ++i)
        {
            random_peptide += residueDB->getResidue(AMINO_ACIDS_SULFUR[0]);
        }

        // random amino acid insertion (non Sulfur and Selenium amino acids)
        for (int aa_index = 0; aa_index < peptide_length; ++aa_index)
        {
            double rand = dis_AA(gen);
            int index = std::lower_bound(aa2prob.begin(), aa2prob.end(), rand) - aa2prob.begin() - 1;
            random_peptide += residueDB->getResidue(AMINO_ACIDS_NO_SULFUR[index]);
        }
    }

    return random_peptide;
}

std::map<char, double> getAAProbabilities(std::string fasta_path, bool sulfur)
{
    std::map<char, double> aa2prob;
    for (char aa : AMINO_ACIDS)
    {
        aa2prob[aa] = 0.0;
    }

    std::vector<FASTAFile::FASTAEntry> proteins;
    FASTAFile().load(fasta_path, proteins);

    int count = 0;
    for (Size i = 0; i < proteins.size(); ++i)
    {
        for (int j = 0; j < proteins[i].sequence.size(); ++j)
        {
            char aa = proteins[i].sequence[j];
            if ((sulfur && AMINO_ACIDS.find(aa) != -1) || (!sulfur && AMINO_ACIDS_NO_SULFUR.find(aa) != -1))
            {
                aa2prob[aa]++;
                count++;
            }
        }
    }

    for (auto &aa : aa2prob)
    {
        aa.second /= count;
    }

    return aa2prob;
}

std::vector<double> calcPrefixSum(std::map<char, double> aa2prob, bool sulfur)
{
    std::string AAs = sulfur ? AMINO_ACIDS : AMINO_ACIDS_NO_SULFUR;
    std::vector<double> prefixSum;

    prefixSum.push_back(0);

    for (int i = 0; i < AAs.size(); ++i)
    {
        prefixSum.push_back(aa2prob[AAs[i]] + prefixSum[i]);
    }

    return prefixSum;
}

void sample_isotopic_distributions(std::string base_path, std::string fasta_path, float max_mass, int num_sulfurs, int max_depth, bool mono)
{

    std::vector<double> aa2prob = calcPrefixSum(getAAProbabilities(fasta_path, num_sulfurs == -1), num_sulfurs == -1);

    std::ofstream* outfiles = openOutputFiles(base_path, max_depth);

    int max_length = max_mass/100;

    for (int peptide_length = 0; peptide_length <= max_length; ++peptide_length)
    {
        for (int sample = 0; sample < 100; ++sample)
        {
            OpenMS::AASequence random_sequence = create_random_peptide_sequence(peptide_length, aa2prob, num_sulfurs);

            if (random_sequence.size() > 0 && random_sequence.getMonoWeight() <= max_mass)
            {
                write_distribution(random_sequence, outfiles, max_depth, mono);
            }
        }
    }

    closeOutputFiles(outfiles, max_depth);
}

void usage()
{
    std::cout << "GenerateTrainingData fasta_path out_path max_mass num_samples S max_depth mono" << std::endl;
    std::cout << "fasta_path: The path to the fasta file to train the splines on." << std::endl;
    std::cout << "out_path: The path to the directory that will store the training data, e.g. ~/data/" << std::endl;
    std::cout << "max_mass: maximum mass allowed for sampled peptides, e.g. 8500" << std::endl;
    std::cout << "S: number of sulfurs that should be in the fragment ion. Use -1 for all (e.g. 0,1,2..)" << std::endl;
    std::cout << "max_depth: The number of isotopes to generate training data for, e.g. 3 = M0,M1,M2" << std::endl;
    std::cout << "mono: should monoisotopic masses be used or average? 1=mono, 0=average" << std::endl;
    std::cout << std::endl;
}

int main(int argc, const char ** argv)
{
    if (argc != 7)
    {
        usage();
        return 0;
    }

    std::string fasta_path = argv[1];
    std::string out_path = argv[2];
    float max_mass = atof(argv[3]);
    int S = atoi(argv[4]);
    int max_depth = atoi(argv[5]);
    bool mono = strncmp(argv[6], "1", 1) == 0 ? true : false;

    //proteome_isotopic_distributions(out_path, fasta_path, max_mass, S, max_depth, mono);
    sample_isotopic_distributions(out_path, fasta_path, max_mass, S, max_depth, mono);

    return 0;
}<|endoftext|>


<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)
  #include <Riostream.h>

  #include "AliRun.h"
  #include "AliRunLoader.h"
  #include "AliLoader.h"
  #include "AliTPC.h"

  #include "TStopwatch.h"
#endif

extern AliRun *gAlice;

Int_t AliTPCHits2Digits(Int_t nev=5) {
  // Connect the Root Galice file containing Geometry, Kine and Hits
  if (gAlice) {
     delete gAlice->GetRunLoader();
     delete gAlice;//if everything was OK here it is already NULL
     gAlice = 0x0;
  }

  AliRunLoader *rl = AliRunLoader::Open("galice.root","Event","update");
  if (!rl) {
    cerr<<"Can't load RunLoader from "<<endl;
    return 1;
  }

  // Get AliRun object from file or create it if not on file

  rl->LoadgAlice();

  gAlice = rl->GetAliRun();
  if (!gAlice) {
    cerr<<"AliTPCHits2Digits.C : AliRun object not found on file\n";
    return 2;
  }

  AliTPC *TPC = (AliTPC*)gAlice->GetDetector("TPC");
  AliLoader * tpcl = rl->GetLoader("TPCLoader");
  if ((TPC == 0x0) || (tpcl == 0x0)) {
    cerr<<"AliTPCHits2Digits.C : Can not find TPC or TPCLoader\n";
    delete rl;
    return 3;
  }
  tpcl->LoadHits("READ");
  tpcl->LoadDigits("recreate");

  TStopwatch timer;
  timer.Start();

 // uncomment below lines to set sectors active
 // Int_t sec[10]={0,1,2,3,4,5,6,7,8,9};
 // TPC->SetActiveSectors(sec,10);

  for (Int_t i=0; i<nev; i++){
    printf("Processing event %d \n",i);
    rl->GetEvent(i);
    TPC->SetActiveSectors(); // all sectors set active
    TPC->Hits2Digits(i);
  }

  delete rl;

  timer.Stop();
  timer.Print();

  return 0;
}

<commit_msg>Protecting if the events are not there<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)
  #include <Riostream.h>

  #include "AliRun.h"
  #include "AliRunLoader.h"
  #include "AliLoader.h"
  #include "AliTPC.h"

  #include "TStopwatch.h"
#endif

extern AliRun *gAlice;

Int_t AliTPCHits2Digits(Int_t nev=5) {
  // Connect the Root Galice file containing Geometry, Kine and Hits
  if (gAlice) {
     delete gAlice->GetRunLoader();
     delete gAlice;//if everything was OK here it is already NULL
     gAlice = 0x0;
  }

  AliRunLoader *rl = AliRunLoader::Open("galice.root","Event","update");
  if (!rl) {
    cerr<<"Can't load RunLoader from "<<endl;
    return 1;
  }

  // Get AliRun object from file or create it if not on file

  rl->LoadgAlice();

  gAlice = rl->GetAliRun();
  if (!gAlice) {
    cerr<<"AliTPCHits2Digits.C : AliRun object not found on file\n";
    return 2;
  }

  AliTPC *TPC = (AliTPC*)gAlice->GetDetector("TPC");
  AliLoader * tpcl = rl->GetLoader("TPCLoader");
  if ((TPC == 0x0) || (tpcl == 0x0)) {
    cerr<<"AliTPCHits2Digits.C : Can not find TPC or TPCLoader\n";
    delete rl;
    return 3;
  }
  tpcl->LoadHits("READ");
  tpcl->LoadDigits("recreate");

  TStopwatch timer;
  timer.Start();

 // uncomment below lines to set sectors active
 // Int_t sec[10]={0,1,2,3,4,5,6,7,8,9};
 // TPC->SetActiveSectors(sec,10);

  for (Int_t i=0; i<nev; i++){
    printf("Processing event %d \n",i);
    if(rl->GetEvent(i)) break;
    TPC->SetActiveSectors(); // all sectors set active
    TPC->Hits2Digits(i);
  }

  delete rl;

  timer.Stop();
  timer.Print();

  return 0;
}

<|endoftext|>


<commit_before>
#include "stdafx.h"
#include "gameview.h"

#include "config/config.h"
#include "tig/tig_mouse.h"

GameView::GameView(MainWindow &mainWindow, gfx::RenderingDevice &device, int width, int height)
    : mMainWindow(mainWindow), mDevice(device), mWidth(width), mHeight(height),
      mResizeListener(device.AddResizeListener(
          [this](int w, int h) { this->Resize(w, h); })),

	mCamera(std::make_shared<gfx::WorldCamera>()) {
	mCamera->SetScreenSize((float) width, (float) height);

	auto &backBufferSize = device.GetBackBufferSize();
	Resize(backBufferSize.width, backBufferSize.height);

	mainWindow.SetMouseMoveHandler([this](int x, int y, int wheelDelta) {
		// Map to game view
		auto pos = MapToScene(x, y);
		x = pos.x;
		y = pos.y;

		// Account for a resized screen
		if (x < 0 || y < 0 || x >= mWidth || y >= mHeight)
		{
			if (config.windowed)
			{
				if ((x > -7 && x < mWidth + 7 && x > -7 && y < mHeight + 7))
				{
					if (x < 0)
						x = 0;
					else if (x > mWidth)
						x = mWidth;
					if (y < 0)
						y = 0;
					else if (y > mHeight)
						y = mHeight;
					mouseFuncs.MouseOutsideWndSet(false);
					mouseFuncs.SetPos(x, y, wheelDelta);
					return;
				}
				else
				{
					mouseFuncs.MouseOutsideWndSet(true);
				}
			}
			else
			{
				logger->info("Mouse outside resized window: x: {}, y: {}, wheel: {}", x, y, wheelDelta);
			}

			return;
		}
		mouseFuncs.MouseOutsideWndSet(false);
		mouseFuncs.SetPos(x, y, wheelDelta);
	});

  if (!gameView) {
	  gameView = this;
  }
}

GameView::~GameView() {
	mMainWindow.SetMouseMoveHandler(nullptr);

	if (gameView == this) {
		gameView = nullptr;
	}
}

XMINT2 GameView::MapToScene(int x, int y) const
{
	// Move it into the scene rectangle coordinate space
	auto localX = x - mSceneRect.x;
	auto localY = y - mSceneRect.y;

	// Scale it to the coordinate system that was used to render the scene
	localX = floor(localX / mSceneScale);
	localY = floor(localY / mSceneScale);

	return{ (int) localX, (int) localY };
}

XMINT2 GameView::MapFromScene(int x, int y) const{

	auto localX = x * mSceneScale;
	auto localY = y * mSceneScale;

	// move it into the scene rectangle coordinate space
	localX += mSceneRect.x+1;
	localY += mSceneRect.y+1;

	return{ (int)localX, (int)localY };
}

XMFLOAT3 GameView::GetScreenCenterInWorld3d()
{
	return mCamera->ScreenToWorld(
		mCamera->GetScreenWidth() * 0.5f,
		mCamera->GetScreenHeight() * 0.5f
	);
}

void GameView::Resize(int width, int height)
{
	auto widthFactor = (float) width / (float)mWidth;
	auto heightFactor = (float) height / (float)mHeight;
	mSceneScale = std::min<float>(widthFactor, heightFactor);

	// Calculate the rectangle on the back buffer where the scene will
	// be stretched to
	auto drawWidth = mSceneScale * mWidth;
	auto drawHeight = mSceneScale * mHeight;
	auto drawX = ((float) width - drawWidth) / 2;
	auto drawY = ((float) height - drawHeight) / 2;
	mSceneRect = XMFLOAT4(drawX, drawY, drawWidth, drawHeight);

}

// TODO: See if this can just be replaced by the proper version used below
// This is equivalent to 10029570
XMFLOAT2 GameView::ScreenToTileLegacy(int x, int y) {

	auto translation = mCamera->GetTranslation();

	auto tmpX = (x - translation.x) * 20 / INCH_PER_TILE; // * 0.70710677
	auto tmpY = (y - translation.y) / 0.7f * 20 / INCH_PER_TILE; // * 1.0101526 originally

	return {
		tmpY - tmpX - INCH_PER_HALFTILE,
		tmpY + tmpX - INCH_PER_HALFTILE
	};

}

LocAndOffsets GameView::ScreenToTile(int screenX, int screenY) {

	auto translation = mCamera->GetTranslation();

	auto tmpX = (int)((screenX - translation.x) / 2);
	auto tmpY = (int)(((screenY - translation.y) / 2) / 0.7f);

	auto unrotatedX = tmpY - tmpX;
	auto unrotatedY = tmpY + tmpX;

	// Convert to tiles
	LocAndOffsets result;
	result.location.locx = unrotatedX / 20;
	result.location.locy = unrotatedY / 20;

	// Convert to offset within tile
	result.off_x = ((unrotatedX % 20) / 20.0f - 0.5f) * INCH_PER_TILE;
	result.off_y = ((unrotatedY % 20) / 20.0f - 0.5f) * INCH_PER_TILE;

	return result;
}

// replaces 10028EC0
XMFLOAT3 GameView::TileToWorld(locXY tilePos)
{
	auto result = XMFLOAT3();
	result.x = (float)((tilePos.locy - tilePos.locx - 1) * 20);
	result.y = (float)((tilePos.locy + tilePos.locx) * 14);
	result.z = 0;

	return result;
}

GameView *gameView;
<commit_msg>gameview fixed copy paste bug x>-7<commit_after>
#include "stdafx.h"
#include "gameview.h"

#include "config/config.h"
#include "tig/tig_mouse.h"

GameView::GameView(MainWindow &mainWindow, gfx::RenderingDevice &device, int width, int height)
    : mMainWindow(mainWindow), mDevice(device), mWidth(width), mHeight(height),
      mResizeListener(device.AddResizeListener(
          [this](int w, int h) { this->Resize(w, h); })),

	mCamera(std::make_shared<gfx::WorldCamera>()) {
	mCamera->SetScreenSize((float) width, (float) height);

	auto &backBufferSize = device.GetBackBufferSize();
	Resize(backBufferSize.width, backBufferSize.height);

	mainWindow.SetMouseMoveHandler([this](int x, int y, int wheelDelta) {
		// Map to game view
		auto pos = MapToScene(x, y);
		x = pos.x;
		y = pos.y;

		// Account for a resized screen
		if (x < 0 || y < 0 || x >= mWidth || y >= mHeight)
		{
			if (config.windowed)
			{
				if ((x > -7 && x < mWidth + 7 && y > -7 && y < mHeight + 7))
				{
					if (x < 0)
						x = 0;
					else if (x > mWidth)
						x = mWidth;
					if (y < 0)
						y = 0;
					else if (y > mHeight)
						y = mHeight;
					mouseFuncs.MouseOutsideWndSet(false);
					mouseFuncs.SetPos(x, y, wheelDelta);
					return;
				}
				else
				{
					mouseFuncs.MouseOutsideWndSet(true);
				}
			}
			else
			{
				logger->info("Mouse outside resized window: x: {}, y: {}, wheel: {}", x, y, wheelDelta);
			}

			return;
		}
		mouseFuncs.MouseOutsideWndSet(false);
		mouseFuncs.SetPos(x, y, wheelDelta);
	});

  if (!gameView) {
	  gameView = this;
  }
}

GameView::~GameView() {
	mMainWindow.SetMouseMoveHandler(nullptr);

	if (gameView == this) {
		gameView = nullptr;
	}
}

XMINT2 GameView::MapToScene(int x, int y) const
{
	// Move it into the scene rectangle coordinate space
	auto localX = x - mSceneRect.x;
	auto localY = y - mSceneRect.y;

	// Scale it to the coordinate system that was used to render the scene
	localX = floor(localX / mSceneScale);
	localY = floor(localY / mSceneScale);

	return{ (int) localX, (int) localY };
}

XMINT2 GameView::MapFromScene(int x, int y) const{

	auto localX = x * mSceneScale;
	auto localY = y * mSceneScale;

	// move it into the scene rectangle coordinate space
	localX += mSceneRect.x+1;
	localY += mSceneRect.y+1;

	return{ (int)localX, (int)localY };
}

XMFLOAT3 GameView::GetScreenCenterInWorld3d()
{
	return mCamera->ScreenToWorld(
		mCamera->GetScreenWidth() * 0.5f,
		mCamera->GetScreenHeight() * 0.5f
	);
}

void GameView::Resize(int width, int height)
{
	auto widthFactor = (float) width / (float)mWidth;
	auto heightFactor = (float) height / (float)mHeight;
	mSceneScale = std::min<float>(widthFactor, heightFactor);

	// Calculate the rectangle on the back buffer where the scene will
	// be stretched to
	auto drawWidth = mSceneScale * mWidth;
	auto drawHeight = mSceneScale * mHeight;
	auto drawX = ((float) width - drawWidth) / 2;
	auto drawY = ((float) height - drawHeight) / 2;
	mSceneRect = XMFLOAT4(drawX, drawY, drawWidth, drawHeight);

}

// TODO: See if this can just be replaced by the proper version used below
// This is equivalent to 10029570
XMFLOAT2 GameView::ScreenToTileLegacy(int x, int y) {

	auto translation = mCamera->GetTranslation();

	auto tmpX = (x - translation.x) * 20 / INCH_PER_TILE; // * 0.70710677
	auto tmpY = (y - translation.y) / 0.7f * 20 / INCH_PER_TILE; // * 1.0101526 originally

	return {
		tmpY - tmpX - INCH_PER_HALFTILE,
		tmpY + tmpX - INCH_PER_HALFTILE
	};

}

LocAndOffsets GameView::ScreenToTile(int screenX, int screenY) {

	auto translation = mCamera->GetTranslation();

	auto tmpX = (int)((screenX - translation.x) / 2);
	auto tmpY = (int)(((screenY - translation.y) / 2) / 0.7f);

	auto unrotatedX = tmpY - tmpX;
	auto unrotatedY = tmpY + tmpX;

	// Convert to tiles
	LocAndOffsets result;
	result.location.locx = unrotatedX / 20;
	result.location.locy = unrotatedY / 20;

	// Convert to offset within tile
	result.off_x = ((unrotatedX % 20) / 20.0f - 0.5f) * INCH_PER_TILE;
	result.off_y = ((unrotatedY % 20) / 20.0f - 0.5f) * INCH_PER_TILE;

	return result;
}

// replaces 10028EC0
XMFLOAT3 GameView::TileToWorld(locXY tilePos)
{
	auto result = XMFLOAT3();
	result.x = (float)((tilePos.locy - tilePos.locx - 1) * 20);
	result.y = (float)((tilePos.locy + tilePos.locx) * 14);
	result.z = 0;

	return result;
}

GameView *gameView;
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   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.
*/

/**
  \file    TiffVolumeConverter.h
  \author  Tom Fogal
           SCI Institute
           University of Utah
*/
#include <cstring>
#include "boost/cstdint.hpp"
#ifndef TUVOK_NO_IO
# include "3rdParty/tiff/tiffio.h"
#else
  struct TIFF;
#endif
#include "TiffVolumeConverter.h"
#include "../StdTuvokDefines.h"
#include "../Controller/Controller.h"
#include "../Basics/SysTools.h"

#ifdef __GNUC__
# define _malloc __attribute__((malloc))
#else
# define _malloc /* nothing */
#endif

static void tv_dimensions(TIFF *, size_t dims[3]);
_malloc static BYTE* tv_read_slice(TIFF *);

TiffVolumeConverter::TiffVolumeConverter()
{
  m_vConverterDesc = "TIFF Volume (Image stack)";
#ifndef TUVOK_NO_IO
  m_vSupportedExt.push_back("OME.TIF");
  m_vSupportedExt.push_back("OME.TIFF");
  m_vSupportedExt.push_back("TIF");
  m_vSupportedExt.push_back("TIFF");
#endif
}

// converts a TiffVolume to a `raw' file.  We'll read through the TIFF
// slice-by-slice, copying each slice to the raw file.
bool
TiffVolumeConverter::ConvertToRAW(const std::string& strSourceFilename,
                                  const std::string& strTempDir,
                                  bool, UINT64& iHeaderSkip,
                                  UINT64& iComponentSize,
                                  UINT64& iComponentCount,
                                  bool& bConvertEndianess, bool& bSigned,
                                  bool& bIsFloat, UINT64VECTOR3& vVolumeSize,
                                  FLOATVECTOR3& vVolumeAspect,
                                  std::string& strTitle,
                                  UVFTables::ElementSemanticTable& eType,
                                  std::string& strIntermediateFile,
                                  bool& bDeleteIntermediateFile)
{
#ifndef TUVOK_NO_IO
  MESSAGE("Attempting to convert TiffVolume: %s", strSourceFilename.c_str());

  TIFF *tif = TIFFOpen(strSourceFilename.c_str(), "r");
  if(tif == NULL) {
    T_ERROR("Could not open %s", strSourceFilename.c_str());
    return false;
  }

  // Get the dimensions of the volume.
  {
    size_t dims[3];
    tv_dimensions(tif, dims);
    vVolumeSize[0] = static_cast<UINT64>(dims[0]);
    vVolumeSize[1] = static_cast<UINT64>(dims[1]);
    vVolumeSize[2] = static_cast<UINT64>(dims[2]);
    MESSAGE("TiffVolume dimensions: %ux%ux%u", static_cast<unsigned>(dims[0]),
                                               static_cast<unsigned>(dims[1]),
                                               static_cast<unsigned>(dims[2]));
    if(dims[2] <= 1) {
      T_ERROR("TIFF is not a volume; use "
              "`Load Dataset from Directory' instead!");
      TIFFClose(tif);
      return false;
    }
  }
  iHeaderSkip = 0;

  // read the number of bits per component from the tiff tag.
  {
    boost::uint16_t bits_per_sample;
    TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits_per_sample);
    iComponentSize = bits_per_sample;
    MESSAGE("%ld bits per component.", iComponentSize);
  }
  // likewise for the number of components / pixel.
  {
    boost::uint16_t components;
    TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &components);
    iComponentCount = components;
    {
      std::ostringstream com;
      com << iComponentCount << " component";
      if(components > 1) { com << "s"; }
      com << ".";
      MESSAGE("%s", com.str().c_str());
    }
  }
  // Libtiff handles the endian issue for us.
  bConvertEndianess = false;

  // Data type/kind: signed or unsigned, floating point or not.
  {
    bSigned = false;
    bIsFloat = false;
    boost::uint16_t sf;
    if(TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &sf) != 0) {
      bSigned = (sf == SAMPLEFORMAT_INT) || (sf == SAMPLEFORMAT_IEEEFP) ||
                (sf == SAMPLEFORMAT_COMPLEXINT);
      bIsFloat = (sf == SAMPLEFORMAT_IEEEFP);
    }
  }
  // Not sure if these are readable/stored in a TIFF.
  vVolumeAspect[0] = 1;
  vVolumeAspect[1] = 1;
  vVolumeAspect[2] = 1;

  strTitle = "TIFF Volume";
  eType = UVFTables::ES_UNDEFINED;

  // Create an intermediate file to hold the data.
  strIntermediateFile = strTempDir +
                        SysTools::GetFilename(strSourceFilename) + ".binary";
  LargeRAWFile binary(strIntermediateFile);
  binary.Create(iComponentSize/8 * iComponentCount * vVolumeSize.volume());
  if(!binary.IsOpen()) {
    T_ERROR("Could not create binary file %s", strIntermediateFile.c_str());

    TIFFClose(tif);
    return false;
  }
  bDeleteIntermediateFile = true;
  // Populate the intermediate file.  We'll do this slice-by-slice, which isn't
  // exactly kosher for this library -- a slice could technically be larger
  // than INCORESIZE.  But it won't be.
  do {
    BYTE* slice = tv_read_slice(tif);
    if(slice) {
      // assuming 8-bit monochrome data here, which might not always be valid.
      binary.WriteRAW(static_cast<unsigned char*>(slice),
                      vVolumeSize[0]*vVolumeSize[1]*sizeof(BYTE));
      _TIFFfree(slice);
    } else {
      binary.Close();
      binary.Delete();
      TIFFClose(tif);
      return false;
    }
  } while(TIFFReadDirectory(tif));
  binary.Close();

  TIFFClose(tif);
  return true;
#else
  T_ERROR("Tuvok was not built with IO support!");
  return false;
#endif
}

// unimplemented!
bool
TiffVolumeConverter::ConvertToNative(const std::string&,
                                     const std::string&,
                                     UINT64, UINT64,
                                     UINT64, bool,
                                     bool,
                                     UINT64VECTOR3,
                                     FLOATVECTOR3,
                                     bool)
{
  return false;
}

// Reads the dimensions of the TIFF volume.  X and Y come from the dimensions
// of the first image in the stack: we assume that this stays constant
// throughout the volume.  Z comes from the number of images in the stack.
static void
tv_dimensions(TIFF *tif, size_t dims[3])
{
#ifndef TUVOK_NO_IO
  UINT32 x,y;
  size_t z=0;

  TIFFSetDirectory(tif, 0);
  TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &x);
  // tiff calls the height "length" for some reason.
  TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &y);
  do {
    ++z;
  } while(TIFFReadDirectory(tif));
  TIFFSetDirectory(tif, 0);

  dims[0] = x;
  dims[1] = y;
  dims[2] = z;
#endif
}

_malloc static BYTE*
tv_read_slice(TIFF *tif)
{
#ifdef TUVOK_NO_IO
  return NULL;
#else
  BYTE *slice;
  UINT32 width;
  UINT32 height;
  boost::uint16_t bpp;
  TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
  TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);
  TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bpp);
  MESSAGE("Reading %ux%u TIFF slice.", width, height);

  const size_t slice_sz = width*height*(bpp/8) * sizeof(BYTE);
  slice = static_cast<BYTE*>(_TIFFmalloc(slice_sz));
  if(slice == NULL) {
    T_ERROR("TIFFmalloc failed.");
    return NULL;
  }

  const tstrip_t n_strips = TIFFNumberOfStrips(tif);
  {
    BYTE *data = slice;
    tdata_t buf = static_cast<tdata_t>(_TIFFmalloc(TIFFStripSize(tif)));
    // strips shouldn't be bigger than slices.
    assert(static_cast<size_t>(TIFFStripSize(tif)) <= slice_sz);
    for(tstrip_t s=0; s < n_strips; ++s) {
      tsize_t n_bytes;
      n_bytes = TIFFReadEncodedStrip(tif, s, buf, static_cast<tsize_t>(-1));
      std::memcpy(data, buf, n_bytes);
      data += n_bytes;
    }
    _TIFFfree(buf);
  }

  return slice;
#endif
}
<commit_msg>tiff: Progress information while reading slices.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   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.
*/

/**
  \file    TiffVolumeConverter.h
  \author  Tom Fogal
           SCI Institute
           University of Utah
*/
#include <cstring>
#include "boost/cstdint.hpp"
#ifndef TUVOK_NO_IO
# include "3rdParty/tiff/tiffio.h"
#else
  struct TIFF;
#endif
#include "TiffVolumeConverter.h"
#include "../StdTuvokDefines.h"
#include "../Controller/Controller.h"
#include "../Basics/SysTools.h"

#ifdef __GNUC__
# define _malloc __attribute__((malloc))
#else
# define _malloc /* nothing */
#endif

static void tv_dimensions(TIFF *, size_t dims[3]);
_malloc static BYTE* tv_read_slice(TIFF *);

TiffVolumeConverter::TiffVolumeConverter()
{
  m_vConverterDesc = "TIFF Volume (Image stack)";
#ifndef TUVOK_NO_IO
  m_vSupportedExt.push_back("OME.TIF");
  m_vSupportedExt.push_back("OME.TIFF");
  m_vSupportedExt.push_back("TIF");
  m_vSupportedExt.push_back("TIFF");
#endif
}

// converts a TiffVolume to a `raw' file.  We'll read through the TIFF
// slice-by-slice, copying each slice to the raw file.
bool
TiffVolumeConverter::ConvertToRAW(const std::string& strSourceFilename,
                                  const std::string& strTempDir,
                                  bool, UINT64& iHeaderSkip,
                                  UINT64& iComponentSize,
                                  UINT64& iComponentCount,
                                  bool& bConvertEndianess, bool& bSigned,
                                  bool& bIsFloat, UINT64VECTOR3& vVolumeSize,
                                  FLOATVECTOR3& vVolumeAspect,
                                  std::string& strTitle,
                                  UVFTables::ElementSemanticTable& eType,
                                  std::string& strIntermediateFile,
                                  bool& bDeleteIntermediateFile)
{
#ifndef TUVOK_NO_IO
  MESSAGE("Attempting to convert TiffVolume: %s", strSourceFilename.c_str());

  TIFF *tif = TIFFOpen(strSourceFilename.c_str(), "r");
  if(tif == NULL) {
    T_ERROR("Could not open %s", strSourceFilename.c_str());
    return false;
  }

  // Get the dimensions of the volume.
  {
    size_t dims[3];
    tv_dimensions(tif, dims);
    vVolumeSize[0] = static_cast<UINT64>(dims[0]);
    vVolumeSize[1] = static_cast<UINT64>(dims[1]);
    vVolumeSize[2] = static_cast<UINT64>(dims[2]);
    MESSAGE("TiffVolume dimensions: %ux%ux%u", static_cast<unsigned>(dims[0]),
                                               static_cast<unsigned>(dims[1]),
                                               static_cast<unsigned>(dims[2]));
    if(dims[2] <= 1) {
      T_ERROR("TIFF is not a volume; use "
              "`Load Dataset from Directory' instead!");
      TIFFClose(tif);
      return false;
    }
  }
  iHeaderSkip = 0;

  // read the number of bits per component from the tiff tag.
  {
    boost::uint16_t bits_per_sample;
    TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits_per_sample);
    iComponentSize = bits_per_sample;
    MESSAGE("%ld bits per component.", iComponentSize);
  }
  // likewise for the number of components / pixel.
  {
    boost::uint16_t components;
    TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &components);
    iComponentCount = components;
    {
      std::ostringstream com;
      com << iComponentCount << " component";
      if(components > 1) { com << "s"; }
      com << ".";
      MESSAGE("%s", com.str().c_str());
    }
  }
  // Libtiff handles the endian issue for us.
  bConvertEndianess = false;

  // Data type/kind: signed or unsigned, floating point or not.
  {
    bSigned = false;
    bIsFloat = false;
    boost::uint16_t sf;
    if(TIFFGetField(tif, TIFFTAG_SAMPLEFORMAT, &sf) != 0) {
      bSigned = (sf == SAMPLEFORMAT_INT) || (sf == SAMPLEFORMAT_IEEEFP) ||
                (sf == SAMPLEFORMAT_COMPLEXINT);
      bIsFloat = (sf == SAMPLEFORMAT_IEEEFP);
    }
  }
  // Not sure if these are readable/stored in a TIFF.
  vVolumeAspect[0] = 1;
  vVolumeAspect[1] = 1;
  vVolumeAspect[2] = 1;

  strTitle = "TIFF Volume";
  eType = UVFTables::ES_UNDEFINED;

  // Create an intermediate file to hold the data.
  strIntermediateFile = strTempDir +
                        SysTools::GetFilename(strSourceFilename) + ".binary";
  LargeRAWFile binary(strIntermediateFile);
  binary.Create(iComponentSize/8 * iComponentCount * vVolumeSize.volume());
  if(!binary.IsOpen()) {
    T_ERROR("Could not create binary file %s", strIntermediateFile.c_str());

    TIFFClose(tif);
    return false;
  }
  bDeleteIntermediateFile = true;
  // Populate the intermediate file.  We'll do this slice-by-slice, which isn't
  // exactly kosher for this library -- a slice could technically be larger
  // than INCORESIZE.  But it won't be.
  unsigned slice_idx=0;
  do {
    MESSAGE("Reading %llux%llu TIFF slice %u of %llu",
            vVolumeSize[0], vVolumeSize[1], slice_idx++, vVolumeSize[2]-1);
    BYTE* slice = tv_read_slice(tif);
    if(slice) {
      // assuming 8-bit monochrome data here, which might not always be valid.
      binary.WriteRAW(static_cast<unsigned char*>(slice),
                      vVolumeSize[0]*vVolumeSize[1]*sizeof(BYTE));
      _TIFFfree(slice);
    } else {
      binary.Close();
      binary.Delete();
      TIFFClose(tif);
      return false;
    }
  } while(TIFFReadDirectory(tif));
  binary.Close();

  TIFFClose(tif);
  return true;
#else
  T_ERROR("Tuvok was not built with IO support!");
  return false;
#endif
}

// unimplemented!
bool
TiffVolumeConverter::ConvertToNative(const std::string&,
                                     const std::string&,
                                     UINT64, UINT64,
                                     UINT64, bool,
                                     bool,
                                     UINT64VECTOR3,
                                     FLOATVECTOR3,
                                     bool)
{
  return false;
}

// Reads the dimensions of the TIFF volume.  X and Y come from the dimensions
// of the first image in the stack: we assume that this stays constant
// throughout the volume.  Z comes from the number of images in the stack.
static void
tv_dimensions(TIFF *tif, size_t dims[3])
{
#ifndef TUVOK_NO_IO
  UINT32 x,y;
  size_t z=0;

  TIFFSetDirectory(tif, 0);
  TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &x);
  // tiff calls the height "length" for some reason.
  TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &y);
  do {
    ++z;
  } while(TIFFReadDirectory(tif));
  TIFFSetDirectory(tif, 0);

  dims[0] = x;
  dims[1] = y;
  dims[2] = z;
#endif
}

_malloc static BYTE*
tv_read_slice(TIFF *tif)
{
#ifdef TUVOK_NO_IO
  return NULL;
#else
  BYTE *slice;
  UINT32 width;
  UINT32 height;
  boost::uint16_t bpp;
  TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width);
  TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height);
  TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bpp);

  const size_t slice_sz = width*height*(bpp/8) * sizeof(BYTE);
  slice = static_cast<BYTE*>(_TIFFmalloc(slice_sz));
  if(slice == NULL) {
    T_ERROR("TIFFmalloc failed.");
    return NULL;
  }

  const tstrip_t n_strips = TIFFNumberOfStrips(tif);
  {
    BYTE *data = slice;
    tdata_t buf = static_cast<tdata_t>(_TIFFmalloc(TIFFStripSize(tif)));
    // strips shouldn't be bigger than slices.
    assert(static_cast<size_t>(TIFFStripSize(tif)) <= slice_sz);
    for(tstrip_t s=0; s < n_strips; ++s) {
      tsize_t n_bytes;
      n_bytes = TIFFReadEncodedStrip(tif, s, buf, static_cast<tsize_t>(-1));
      std::memcpy(data, buf, n_bytes);
      data += n_bytes;
    }
    _TIFFfree(buf);
  }

  return slice;
#endif
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/ntp/new_tab_page_handler.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/memory/scoped_ptr.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/default_apps_trial.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/ui/webui/ntp/new_tab_ui.h"
#include "chrome/browser/web_resource/notification_promo.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/notification_service.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"

static const int kIntroDisplayMax = 10;

// The URL of a knowledge-base article about the new NTP.
static const char kNTP4IntroURL[] =
  "http://www.google.com/support/chrome/bin/answer.py?answer=95451";

WebUIMessageHandler* NewTabPageHandler::Attach(WebUI* web_ui) {
  // Record an open of the NTP with its default page type.
  PrefService* prefs = Profile::FromWebUI(web_ui)->GetPrefs();
  int shown_page_type = prefs->GetInteger(prefs::kNTPShownPage) >>
      kPageIdOffset;
  UMA_HISTOGRAM_ENUMERATION("NewTabPage.DefaultPageType",
                            shown_page_type, kHistogramEnumerationMax);

  static bool default_apps_trial_exists =
      base::FieldTrialList::TrialExists(kDefaultAppsTrial_Name);
  if (default_apps_trial_exists) {
    UMA_HISTOGRAM_ENUMERATION(
        base::FieldTrial::MakeName("NewTabPage.DefaultPageType",
                                   kDefaultAppsTrial_Name),
        shown_page_type, kHistogramEnumerationMax);
  }

  return WebUIMessageHandler::Attach(web_ui);
}

void NewTabPageHandler::RegisterMessages() {
  web_ui()->RegisterMessageCallback("closeNotificationPromo",
      base::Bind(&NewTabPageHandler::HandleCloseNotificationPromo,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("notificationPromoViewed",
      base::Bind(&NewTabPageHandler::HandleNotificationPromoViewed,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("pageSelected",
      base::Bind(&NewTabPageHandler::HandlePageSelected,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("introMessageDismissed",
      base::Bind(&NewTabPageHandler::HandleIntroMessageDismissed,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("introMessageSeen",
      base::Bind(&NewTabPageHandler::HandleIntroMessageSeen,
                 base::Unretained(this)));
}

void NewTabPageHandler::HandleCloseNotificationPromo(const ListValue* args) {
  scoped_refptr<NotificationPromo> notification_promo =
      NotificationPromo::Create(Profile::FromWebUI(web_ui()), NULL);
  notification_promo->HandleClosed();
  Notify(chrome::NOTIFICATION_PROMO_RESOURCE_STATE_CHANGED);
}

void NewTabPageHandler::HandleNotificationPromoViewed(const ListValue* args) {
  scoped_refptr<NotificationPromo> notification_promo =
      NotificationPromo::Create(Profile::FromWebUI(web_ui_), NULL);
  if (notification_promo->HandleViewed())
    Notify(chrome::NOTIFICATION_PROMO_RESOURCE_STATE_CHANGED);
}

void NewTabPageHandler::HandlePageSelected(const ListValue* args) {
  double page_id_double;
  CHECK(args->GetDouble(0, &page_id_double));
  int page_id = static_cast<int>(page_id_double);

  double index_double;
  CHECK(args->GetDouble(1, &index_double));
  int index = static_cast<int>(index_double);

  PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs();
  prefs->SetInteger(prefs::kNTPShownPage, page_id | index);

  int shown_page_type = page_id >> kPageIdOffset;
  UMA_HISTOGRAM_ENUMERATION("NewTabPage.SelectedPageType",
                            shown_page_type, kHistogramEnumerationMax);

  static bool default_apps_trial_exists =
      base::FieldTrialList::TrialExists(kDefaultAppsTrial_Name);
  if (default_apps_trial_exists) {
    UMA_HISTOGRAM_ENUMERATION(
        base::FieldTrial::MakeName("NewTabPage.SelectedPageType",
                                   kDefaultAppsTrial_Name),
        shown_page_type, kHistogramEnumerationMax);
  }
}

void NewTabPageHandler::HandleIntroMessageDismissed(const ListValue* args) {
  PrefService* prefs = g_browser_process->local_state();
  prefs->SetInteger(prefs::kNTP4IntroDisplayCount, kIntroDisplayMax + 1);
  Notify(chrome::NTP4_INTRO_PREF_CHANGED);
}

void NewTabPageHandler::HandleIntroMessageSeen(const ListValue* args) {
  PrefService* prefs = g_browser_process->local_state();
  int intro_displays = prefs->GetInteger(prefs::kNTP4IntroDisplayCount);
  prefs->SetInteger(prefs::kNTP4IntroDisplayCount, intro_displays + 1);
  Notify(chrome::NTP4_INTRO_PREF_CHANGED);
}

// static
void NewTabPageHandler::RegisterUserPrefs(PrefService* prefs) {
  // TODO(estade): should be syncable.
  prefs->RegisterIntegerPref(prefs::kNTPShownPage, APPS_PAGE_ID,
                             PrefService::UNSYNCABLE_PREF);
}

// static
void NewTabPageHandler::RegisterPrefs(PrefService* prefs) {
  prefs->RegisterIntegerPref(prefs::kNTP4IntroDisplayCount, 0,
                             PrefService::UNSYNCABLE_PREF);
}

// static
void NewTabPageHandler::GetLocalizedValues(Profile* profile,
                                           DictionaryValue* values) {
  values->SetInteger("most_visited_page_id", MOST_VISITED_PAGE_ID);
  values->SetInteger("apps_page_id", APPS_PAGE_ID);

  PrefService* prefs = profile->GetPrefs();
  int shown_page = prefs->GetInteger(prefs::kNTPShownPage);
  values->SetInteger("shown_page_type", shown_page & ~INDEX_MASK);
  values->SetInteger("shown_page_index", shown_page & INDEX_MASK);

  PrefService* local_state = g_browser_process->local_state();
  int intro_displays = local_state->GetInteger(prefs::kNTP4IntroDisplayCount);
  // This preference used to exist in profile, so check the profile if it has
  // not been set in local state yet.
  if (!intro_displays) {
    prefs->RegisterIntegerPref(prefs::kNTP4IntroDisplayCount, 0,
                               PrefService::UNSYNCABLE_PREF);
    intro_displays = prefs->GetInteger(prefs::kNTP4IntroDisplayCount);
    if (intro_displays)
      local_state->SetInteger(prefs::kNTP4IntroDisplayCount, intro_displays);
  }
  if (intro_displays <= kIntroDisplayMax) {
    values->SetString("ntp4_intro_message",
                      l10n_util::GetStringUTF16(IDS_NTP4_INTRO_MESSAGE));
    values->SetString("ntp4_intro_url", kNTP4IntroURL);
    values->SetString("learn_more",
                      l10n_util::GetStringUTF16(IDS_LEARN_MORE));
  }
}

// static
void NewTabPageHandler::DismissIntroMessage(PrefService* prefs) {
  prefs->SetInteger(prefs::kNTP4IntroDisplayCount, kIntroDisplayMax + 1);
  // No need to send notification to update resource cache, because this method
  // is only called during startup before the ntp resource cache is constructed.
}

void NewTabPageHandler::Notify(chrome::NotificationType notification_type) {
  content::NotificationService* service =
      content::NotificationService::current();
  service->Notify(notification_type,
                  content::Source<NewTabPageHandler>(this),
                  content::NotificationService::NoDetails());
}
<commit_msg>ntp: add more UMA to prove existing UMA is sane.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/ntp/new_tab_page_handler.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/memory/scoped_ptr.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/default_apps_trial.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/ui/webui/ntp/new_tab_ui.h"
#include "chrome/browser/web_resource/notification_promo.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/notification_service.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"

static const int kIntroDisplayMax = 10;

// The URL of a knowledge-base article about the new NTP.
static const char kNTP4IntroURL[] =
  "http://www.google.com/support/chrome/bin/answer.py?answer=95451";

WebUIMessageHandler* NewTabPageHandler::Attach(WebUI* web_ui) {
  // Record an open of the NTP with its default page type.
  PrefService* prefs = Profile::FromWebUI(web_ui)->GetPrefs();
  int shown_page_type = prefs->GetInteger(prefs::kNTPShownPage) >>
      kPageIdOffset;
  UMA_HISTOGRAM_ENUMERATION("NewTabPage.DefaultPageType",
                            shown_page_type, kHistogramEnumerationMax);

  static bool default_apps_trial_exists =
      base::FieldTrialList::TrialExists(kDefaultAppsTrial_Name);
  if (default_apps_trial_exists) {
    UMA_HISTOGRAM_ENUMERATION(
        base::FieldTrial::MakeName("NewTabPage.DefaultPageType",
                                   kDefaultAppsTrial_Name),
        shown_page_type, kHistogramEnumerationMax);
  }

  return WebUIMessageHandler::Attach(web_ui);
}

void NewTabPageHandler::RegisterMessages() {
  web_ui()->RegisterMessageCallback("closeNotificationPromo",
      base::Bind(&NewTabPageHandler::HandleCloseNotificationPromo,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("notificationPromoViewed",
      base::Bind(&NewTabPageHandler::HandleNotificationPromoViewed,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("pageSelected",
      base::Bind(&NewTabPageHandler::HandlePageSelected,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("introMessageDismissed",
      base::Bind(&NewTabPageHandler::HandleIntroMessageDismissed,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("introMessageSeen",
      base::Bind(&NewTabPageHandler::HandleIntroMessageSeen,
                 base::Unretained(this)));
}

void NewTabPageHandler::HandleCloseNotificationPromo(const ListValue* args) {
  scoped_refptr<NotificationPromo> notification_promo =
      NotificationPromo::Create(Profile::FromWebUI(web_ui()), NULL);
  notification_promo->HandleClosed();
  Notify(chrome::NOTIFICATION_PROMO_RESOURCE_STATE_CHANGED);
}

void NewTabPageHandler::HandleNotificationPromoViewed(const ListValue* args) {
  scoped_refptr<NotificationPromo> notification_promo =
      NotificationPromo::Create(Profile::FromWebUI(web_ui_), NULL);
  if (notification_promo->HandleViewed())
    Notify(chrome::NOTIFICATION_PROMO_RESOURCE_STATE_CHANGED);
}

void NewTabPageHandler::HandlePageSelected(const ListValue* args) {
  double page_id_double;
  CHECK(args->GetDouble(0, &page_id_double));
  int page_id = static_cast<int>(page_id_double);

  double index_double;
  CHECK(args->GetDouble(1, &index_double));
  int index = static_cast<int>(index_double);

  PrefService* prefs = Profile::FromWebUI(web_ui())->GetPrefs();
  int previous_shown_page =
      prefs->GetInteger(prefs::kNTPShownPage) >> kPageIdOffset;
  UMA_HISTOGRAM_ENUMERATION("NewTabPage.PreviousSelectedPageType",
                            previous_shown_page, kHistogramEnumerationMax);

  prefs->SetInteger(prefs::kNTPShownPage, page_id | index);

  int shown_page_type = page_id >> kPageIdOffset;
  UMA_HISTOGRAM_ENUMERATION("NewTabPage.SelectedPageType",
                            shown_page_type, kHistogramEnumerationMax);

  static bool default_apps_trial_exists =
      base::FieldTrialList::TrialExists(kDefaultAppsTrial_Name);
  if (default_apps_trial_exists) {
    UMA_HISTOGRAM_ENUMERATION(
        base::FieldTrial::MakeName("NewTabPage.SelectedPageType",
                                   kDefaultAppsTrial_Name),
        shown_page_type, kHistogramEnumerationMax);
  }
}

void NewTabPageHandler::HandleIntroMessageDismissed(const ListValue* args) {
  PrefService* prefs = g_browser_process->local_state();
  prefs->SetInteger(prefs::kNTP4IntroDisplayCount, kIntroDisplayMax + 1);
  Notify(chrome::NTP4_INTRO_PREF_CHANGED);
}

void NewTabPageHandler::HandleIntroMessageSeen(const ListValue* args) {
  PrefService* prefs = g_browser_process->local_state();
  int intro_displays = prefs->GetInteger(prefs::kNTP4IntroDisplayCount);
  prefs->SetInteger(prefs::kNTP4IntroDisplayCount, intro_displays + 1);
  Notify(chrome::NTP4_INTRO_PREF_CHANGED);
}

// static
void NewTabPageHandler::RegisterUserPrefs(PrefService* prefs) {
  // TODO(estade): should be syncable.
  prefs->RegisterIntegerPref(prefs::kNTPShownPage, APPS_PAGE_ID,
                             PrefService::UNSYNCABLE_PREF);
}

// static
void NewTabPageHandler::RegisterPrefs(PrefService* prefs) {
  prefs->RegisterIntegerPref(prefs::kNTP4IntroDisplayCount, 0,
                             PrefService::UNSYNCABLE_PREF);
}

// static
void NewTabPageHandler::GetLocalizedValues(Profile* profile,
                                           DictionaryValue* values) {
  values->SetInteger("most_visited_page_id", MOST_VISITED_PAGE_ID);
  values->SetInteger("apps_page_id", APPS_PAGE_ID);

  PrefService* prefs = profile->GetPrefs();
  int shown_page = prefs->GetInteger(prefs::kNTPShownPage);
  values->SetInteger("shown_page_type", shown_page & ~INDEX_MASK);
  values->SetInteger("shown_page_index", shown_page & INDEX_MASK);

  PrefService* local_state = g_browser_process->local_state();
  int intro_displays = local_state->GetInteger(prefs::kNTP4IntroDisplayCount);
  // This preference used to exist in profile, so check the profile if it has
  // not been set in local state yet.
  if (!intro_displays) {
    prefs->RegisterIntegerPref(prefs::kNTP4IntroDisplayCount, 0,
                               PrefService::UNSYNCABLE_PREF);
    intro_displays = prefs->GetInteger(prefs::kNTP4IntroDisplayCount);
    if (intro_displays)
      local_state->SetInteger(prefs::kNTP4IntroDisplayCount, intro_displays);
  }
  if (intro_displays <= kIntroDisplayMax) {
    values->SetString("ntp4_intro_message",
                      l10n_util::GetStringUTF16(IDS_NTP4_INTRO_MESSAGE));
    values->SetString("ntp4_intro_url", kNTP4IntroURL);
    values->SetString("learn_more",
                      l10n_util::GetStringUTF16(IDS_LEARN_MORE));
  }
}

// static
void NewTabPageHandler::DismissIntroMessage(PrefService* prefs) {
  prefs->SetInteger(prefs::kNTP4IntroDisplayCount, kIntroDisplayMax + 1);
  // No need to send notification to update resource cache, because this method
  // is only called during startup before the ntp resource cache is constructed.
}

void NewTabPageHandler::Notify(chrome::NotificationType notification_type) {
  content::NotificationService* service =
      content::NotificationService::current();
  service->Notify(notification_type,
                  content::Source<NewTabPageHandler>(this),
                  content::NotificationService::NoDetails());
}
<|endoftext|>