<commit_before>/*
 *  Copyright 2007-2011 Adrian Thurston <thurston@complang.org>
 */

/*  This file is part of Colm.
 *
 *  Colm is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  Colm 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Colm; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "parsedata.h"
#include "parsetree.h"
#include "input.h"
#include "fsmrun.h"
#include "debug.h"

#include <iostream>
using std::cerr;
using std::endl;

SourceFuncs patternFuncs;
SourceFuncs replFuncs;

/*
 * Pattern
 */

SourceStream *newInputStreamPattern( Pattern *pattern )
{
	SourceStream *is = (SourceStream*)malloc(sizeof(SourceStream));
	memset( is, 0, sizeof(SourceStream) );
	is->handlesLine = true;
	is->pattern = pattern;
	is->patItem = pattern->list->head;
	is->funcs = &patternFuncs;
	return is;
}

LangEl *inputStreamPatternGetLangEl( SourceStream *is, long *bindId, char **data, long *length )
{
	LangEl *klangEl = is->patItem->factor->langEl;
	*bindId = is->patItem->bindId;
	*data = 0;
	*length = 0;
	is->line = is->patItem->loc.line;

	is->patItem = is->patItem->next;
	is->offset = 0;
	return klangEl;
}

int inputStreamPatternGetData( SourceStream *is, int skip, char *dest, int length, int *copied )
{
	if ( is->patItem == 0 )
		return INPUT_EOD;

	if ( is->patItem->type == PatternItem::FactorType )
		return INPUT_LANG_EL;

	if ( is->offset == 0 )
		is->line = is->patItem->loc.line;

	assert ( is->patItem->type == PatternItem::InputText );
	int available = is->patItem->data.length() - ( is->offset + skip );

	if ( available == 0 && is->patItem->next == 0 )
		return INPUT_EOD;

	if ( available < length )
		length = available;

	memcpy( dest, is->patItem->data.data + is->offset, length );

//	is->offset += length;
//
//	if ( is->offset == is->patItem->data.length() ) {
//		/* Read up to the end of the data. Advance the
//		 * pattern item. */
//		is->patItem = is->patItem->next;
//		is->offset = 0;
//	}

	*copied = length;
	return INPUT_DATA;
}

void inputStreamPatternBackup( SourceStream *is )
{
	if ( is->patItem == 0 )
		is->patItem = is->pattern->list->tail;
	else
		is->patItem = is->patItem->prev;
}

void inputStreamPatternPushBackBuf( SourceStream *is, RunBuf *runBuf )
{
	char *data = runBuf->data + runBuf->offset;
	long length = runBuf->length;

	if ( length == 0 )
		return;

	/* While pushing back past the current pattern item start. */
	while ( length > is->offset ) {
		length -= is->offset;
		if ( is->offset > 0 )
			assert( memcmp( is->patItem->data, data-length, is->offset ) == 0 );
		inputStreamPatternBackup( is );
		is->offset = is->patItem->data.length();
	}

	is->offset -= length;
	assert( memcmp( &is->patItem->data[is->offset], data, length ) == 0 );
}

void inputStreamPatternUndoConsumeLangEl( SourceStream *is )
{
	inputStreamPatternBackup( is );
	is->offset = is->patItem->data.length();
}

int inputStreamPatternConsumeData( SourceStream *is, int length )
{
	debug( REALM_INPUT, "consuming %ld bytes\n", length );

	is->offset += length;
	if ( is->offset == is->patItem->data.length() ) {
		/* Read up to the end of the data. Advance the
		 * pattern item. */
		is->patItem = is->patItem->next;
		is->offset = 0;
	}

	return length;
}

int inputStreamPatternUndoConsumeData( SourceStream *is, const char *data, int length )
{
	is->offset -= length;
	return length;
}

extern "C" void initPatternFuncs()
{
	memset( &patternFuncs, 0, sizeof(SourceFuncs) );

	patternFuncs.getData = &inputStreamPatternGetData;
	patternFuncs.consumeData = &inputStreamPatternConsumeData;
	patternFuncs.undoConsumeData = &inputStreamPatternUndoConsumeData;

	patternFuncs.consumeLangEl = &inputStreamPatternGetLangEl;
	patternFuncs.undoConsumeLangEl = &inputStreamPatternUndoConsumeLangEl;
}

/*
 * Replacement
 */

SourceStream *newInputStreamRepl( Replacement *replacement )
{
	SourceStream *is = (SourceStream*)malloc(sizeof(SourceStream));
	memset( is, 0, sizeof(SourceStream) );
	is->handlesLine = true;
	is->replacement = replacement;
	is->replItem = replacement->list->head;
	is->funcs = &replFuncs;
	return is;
}

LangEl *inputStreamReplGetLangEl( SourceStream *is, long *bindId, char **data, long *length )
{
	LangEl *klangEl = is->replItem->type == ReplItem::ExprType ?
			is->replItem->langEl : is->replItem->factor->langEl;
	*bindId = is->replItem->bindId;

	*data = 0;
	*length = 0;
	is->line = is->replItem->loc.line;

	if ( is->replItem->type == ReplItem::FactorType ) {
		if ( is->replItem->factor->typeRef->pdaLiteral != 0 ) {
			bool unusedCI;
			prepareLitString( is->replItem->data, unusedCI,
					is->replItem->factor->typeRef->pdaLiteral->token.data,
					is->replItem->factor->typeRef->pdaLiteral->token.loc );

			*data = is->replItem->data;
			*length = is->replItem->data.length();
		}
	}

	is->replItem = is->replItem->next;
	is->offset = 0;
	return klangEl;
}

int inputStreamReplGetData( SourceStream *is, int offset, char *dest, int length, int *copied )
{
	if ( is->replItem == 0 )
		return INPUT_EOD;

	if ( is->replItem->type == ReplItem::ExprType || is->replItem->type == ReplItem::FactorType )
		return INPUT_LANG_EL;

	if ( is->offset == 0 )
		is->line = is->replItem->loc.line;

	assert ( is->replItem->type == ReplItem::InputText );
	int available = is->replItem->data.length() - is->offset - offset;

	if ( available == 0 && is->replItem->next == 0 )
		return INPUT_EOD;

	if ( available < length )
		length = available;

	memcpy( dest, is->replItem->data.data+is->offset, length );

//	is->offset += length;
//
//	if ( is->offset == is->replItem->data.length() ) {
//		/* Read up to the end of the data. Advance the
//		 * replacement item. */
//		is->replItem = is->replItem->next;
//		is->offset = 0;
//	}

	*copied = length;
	return INPUT_DATA;
}

void inputStreamReplBackup( SourceStream *is )
{
	if ( is->replItem == 0 )
		is->replItem = is->replacement->list->tail;
	else
		is->replItem = is->replItem->prev;
}

void inputStreamReplPushBackBuf( SourceStream *is, RunBuf *runBuf )
{
	char *data = runBuf->data + runBuf->offset;
	long length = runBuf->length;

	if ( colm_log_parse ) {
		cerr << "push back data: ";
		cerr.write( data, length );
		cerr << endl;
	}

	if ( length == 0 )
		return;

	/* While pushing back past the current pattern item start. */
	while ( length > is->offset ) {
		length -= is->offset;
		if ( is->offset > 0 )
			assert( memcmp( is->replItem->data, data-length, is->offset ) == 0 );
		inputStreamReplBackup( is );
		is->offset = is->replItem->data.length();
	}

	is->offset -= length;
	assert( memcmp( &is->replItem->data[is->offset], data, length ) == 0 );
}

void inputStreamReplUndoConsumeLangEl( SourceStream *is )
{
	inputStreamReplBackup( is );
	is->offset = is->replItem->data.length();
}

int inputStreamReplConsumeData( SourceStream *is, int length )
{
	is->offset += length;

	if ( is->offset == is->replItem->data.length() ) {
		/* Read up to the end of the data. Advance the
		 * pattern item. */
		is->replItem = is->replItem->next;
		is->offset = 0;
	}

	return length;
}

int inputStreamReplUndoConsumeData( SourceStream *is, const char *data, int length )
{
	is->offset -= length;
	return length;
}

extern "C" void initReplFuncs()
{
	memset( &replFuncs, 0, sizeof(SourceFuncs) );

	replFuncs.getData = &inputStreamReplGetData;
	replFuncs.consumeData = &inputStreamReplConsumeData;
	replFuncs.undoConsumeData = &inputStreamReplUndoConsumeData;

	replFuncs.consumeLangEl = &inputStreamReplGetLangEl;
	replFuncs.undoConsumeLangEl = &inputStreamReplUndoConsumeLangEl;
}

Kid *sendNamedLangEl( Program *prg, Tree **sp, PdaRun *pdaRun, FsmRun *fsmRun, InputStream *inputStream )
{
	/* All three set by consumeLangEl. */
	long bindId;
	char *data;
	long length;

	LangEl *klangEl = consumeLangEl( inputStream, &bindId, &data, &length );
	if ( klangEl->termDup != 0 )
		klangEl = klangEl->termDup;

	#ifdef COLM_LOG_PARSE
	if ( colm_log_parse ) {
		cerr << "named langEl: " << prg->rtd->lelInfo[klangEl->id].name << endl;
	}
	#endif

	/* Copy the token data. */
	Head *tokdata = 0;
	if ( data != 0 )
		tokdata = stringAllocFull( prg, data, length );

	Kid *input = makeTokenWithData( prg, pdaRun, fsmRun, inputStream, klangEl->id, tokdata, true, bindId );

	incrementSteps( pdaRun );

	return input;
}

void initBindings( PdaRun *pdaRun )
{
	/* Bindings are indexed at 1. Need a no-binding. */
	pdaRun->bindings = new Bindings;
	pdaRun->bindings->push(0);
}

void makeTokenPushBinding( PdaRun *pdaRun, int bindId, Tree *tree )
{
	/* If the item is bound then store it in the bindings array. */
	if ( bindId > 0 ) {
		pdaRun->bindings->push( tree );
		treeUpref( tree );
	}
}

void unbind( Program *prg, Tree **sp, PdaRun *pdaRun, Tree *tree )
{
	Tree *lastBound = pdaRun->bindings->top();
	if ( lastBound == tree ) {
		pdaRun->bindings->pop();
		treeDownref( prg, sp, tree );
	}
}

<commit_msg>Work on the compile time input streams. refs #341<commit_after>/*
 *  Copyright 2007-2011 Adrian Thurston <thurston@complang.org>
 */

/*  This file is part of Colm.
 *
 *  Colm is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  Colm 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Colm; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "parsedata.h"
#include "parsetree.h"
#include "input.h"
#include "fsmrun.h"
#include "debug.h"

#include <iostream>
using std::cerr;
using std::endl;

SourceFuncs patternFuncs;
SourceFuncs replFuncs;

/*
 * Pattern
 */

SourceStream *newInputStreamPattern( Pattern *pattern )
{
	SourceStream *is = (SourceStream*)malloc(sizeof(SourceStream));
	memset( is, 0, sizeof(SourceStream) );
	is->handlesLine = true;
	is->pattern = pattern;
	is->patItem = pattern->list->head;
	is->funcs = &patternFuncs;
	return is;
}

LangEl *inputStreamPatternGetLangEl( SourceStream *is, long *bindId, char **data, long *length )
{
	LangEl *klangEl = is->patItem->factor->langEl;
	*bindId = is->patItem->bindId;
	*data = 0;
	*length = 0;
	is->line = is->patItem->loc.line;

	is->patItem = is->patItem->next;
	is->offset = 0;
	return klangEl;
}

int inputStreamPatternGetData( SourceStream *is, int skip, char *dest, int length, int *copied )
{
	*copied = 0;

	PatternItem *buf = is->patItem;
	int offset = is->offset;

	while ( true ) {
		if ( buf == 0 )
			return INPUT_EOD;

		if ( buf->type == PatternItem::FactorType )
			return INPUT_LANG_EL;

		if ( offset == 0 )
			is->line = buf->loc.line;

		assert ( buf->type == PatternItem::InputText );
		int available = buf->data.length() - ( offset + skip );

		if ( available == 0 && buf->next == 0 )
			return INPUT_EOD;

		if ( available > 0 ) {
			if ( available < length )
				length = available;

			memcpy( dest, buf->data.data + offset, length );
			*copied += length;
			break;
		}

		buf = buf->next;
		offset = 0;
	}

	return INPUT_DATA;
}

void inputStreamPatternBackup( SourceStream *is )
{
	if ( is->patItem == 0 )
		is->patItem = is->pattern->list->tail;
	else
		is->patItem = is->patItem->prev;
}

void inputStreamPatternPushBackBuf( SourceStream *is, RunBuf *runBuf )
{
	char *data = runBuf->data + runBuf->offset;
	long length = runBuf->length;

	if ( length == 0 )
		return;

	/* While pushing back past the current pattern item start. */
	while ( length > is->offset ) {
		length -= is->offset;
		if ( is->offset > 0 )
			assert( memcmp( is->patItem->data, data-length, is->offset ) == 0 );
		inputStreamPatternBackup( is );
		is->offset = is->patItem->data.length();
	}

	is->offset -= length;
	assert( memcmp( &is->patItem->data[is->offset], data, length ) == 0 );
}

void inputStreamPatternUndoConsumeLangEl( SourceStream *is )
{
	inputStreamPatternBackup( is );
	is->offset = is->patItem->data.length();
}

int inputStreamPatternConsumeData( SourceStream *is, int length )
{
	debug( REALM_INPUT, "consuming %ld bytes\n", length );

	is->offset += length;
	if ( is->offset == is->patItem->data.length() ) {
		/* Read up to the end of the data. Advance the
		 * pattern item. */
		is->patItem = is->patItem->next;
		is->offset = 0;
	}

	return length;
}

int inputStreamPatternUndoConsumeData( SourceStream *is, const char *data, int length )
{
	is->offset -= length;
	return length;
}

extern "C" void initPatternFuncs()
{
	memset( &patternFuncs, 0, sizeof(SourceFuncs) );

	patternFuncs.getData = &inputStreamPatternGetData;
	patternFuncs.consumeData = &inputStreamPatternConsumeData;
	patternFuncs.undoConsumeData = &inputStreamPatternUndoConsumeData;

	patternFuncs.consumeLangEl = &inputStreamPatternGetLangEl;
	patternFuncs.undoConsumeLangEl = &inputStreamPatternUndoConsumeLangEl;
}

/*
 * Replacement
 */

SourceStream *newInputStreamRepl( Replacement *replacement )
{
	SourceStream *is = (SourceStream*)malloc(sizeof(SourceStream));
	memset( is, 0, sizeof(SourceStream) );
	is->handlesLine = true;
	is->replacement = replacement;
	is->replItem = replacement->list->head;
	is->funcs = &replFuncs;
	return is;
}

LangEl *inputStreamReplGetLangEl( SourceStream *is, long *bindId, char **data, long *length )
{
	LangEl *klangEl = is->replItem->type == ReplItem::ExprType ?
			is->replItem->langEl : is->replItem->factor->langEl;
	*bindId = is->replItem->bindId;

	*data = 0;
	*length = 0;
	is->line = is->replItem->loc.line;

	if ( is->replItem->type == ReplItem::FactorType ) {
		if ( is->replItem->factor->typeRef->pdaLiteral != 0 ) {
			bool unusedCI;
			prepareLitString( is->replItem->data, unusedCI,
					is->replItem->factor->typeRef->pdaLiteral->token.data,
					is->replItem->factor->typeRef->pdaLiteral->token.loc );

			*data = is->replItem->data;
			*length = is->replItem->data.length();
		}
	}

	is->replItem = is->replItem->next;
	is->offset = 0;
	return klangEl;
}

int inputStreamReplGetData( SourceStream *is, int skip, char *dest, int length, int *copied )
{
	*copied = 0;

	ReplItem *buf = is->replItem;
	int offset = is->offset;

	while ( true ) {
		if ( buf == 0 )
			return INPUT_EOD;

		if ( buf->type == ReplItem::ExprType || buf->type == ReplItem::FactorType )
			return INPUT_LANG_EL;

		if ( offset == 0 )
			is->line = buf->loc.line;

		assert ( buf->type == ReplItem::InputText );
		int available = buf->data.length() - ( offset + skip ) ;

		if ( available == 0 && buf->next == 0 )
			return INPUT_EOD;

		if ( available > 0 ) {
			if ( available < length )
				length = available;

			memcpy( dest, buf->data.data + offset, length );
			*copied += length;
			break;
		}

		buf = buf->next;
		offset = 0;
	}

	return INPUT_DATA;
}

void inputStreamReplBackup( SourceStream *is )
{
	if ( is->replItem == 0 )
		is->replItem = is->replacement->list->tail;
	else
		is->replItem = is->replItem->prev;
}

void inputStreamReplPushBackBuf( SourceStream *is, RunBuf *runBuf )
{
	char *data = runBuf->data + runBuf->offset;
	long length = runBuf->length;

	if ( colm_log_parse ) {
		cerr << "push back data: ";
		cerr.write( data, length );
		cerr << endl;
	}

	if ( length == 0 )
		return;

	/* While pushing back past the current pattern item start. */
	while ( length > is->offset ) {
		length -= is->offset;
		if ( is->offset > 0 )
			assert( memcmp( is->replItem->data, data-length, is->offset ) == 0 );
		inputStreamReplBackup( is );
		is->offset = is->replItem->data.length();
	}

	is->offset -= length;
	assert( memcmp( &is->replItem->data[is->offset], data, length ) == 0 );
}

void inputStreamReplUndoConsumeLangEl( SourceStream *is )
{
	inputStreamReplBackup( is );
	is->offset = is->replItem->data.length();
}

int inputStreamReplConsumeData( SourceStream *is, int length )
{
	is->offset += length;

	if ( is->offset == is->replItem->data.length() ) {
		/* Read up to the end of the data. Advance the
		 * pattern item. */
		is->replItem = is->replItem->next;
		is->offset = 0;
	}

	return length;
}

int inputStreamReplUndoConsumeData( SourceStream *is, const char *data, int length )
{
	is->offset -= length;
	return length;
}

extern "C" void initReplFuncs()
{
	memset( &replFuncs, 0, sizeof(SourceFuncs) );

	replFuncs.getData = &inputStreamReplGetData;
	replFuncs.consumeData = &inputStreamReplConsumeData;
	replFuncs.undoConsumeData = &inputStreamReplUndoConsumeData;

	replFuncs.consumeLangEl = &inputStreamReplGetLangEl;
	replFuncs.undoConsumeLangEl = &inputStreamReplUndoConsumeLangEl;
}

Kid *sendNamedLangEl( Program *prg, Tree **sp, PdaRun *pdaRun, FsmRun *fsmRun, InputStream *inputStream )
{
	/* All three set by consumeLangEl. */
	long bindId;
	char *data;
	long length;

	LangEl *klangEl = consumeLangEl( inputStream, &bindId, &data, &length );
	if ( klangEl->termDup != 0 )
		klangEl = klangEl->termDup;

	#ifdef COLM_LOG_PARSE
	if ( colm_log_parse ) {
		cerr << "named langEl: " << prg->rtd->lelInfo[klangEl->id].name << endl;
	}
	#endif

	/* Copy the token data. */
	Head *tokdata = 0;
	if ( data != 0 )
		tokdata = stringAllocFull( prg, data, length );

	Kid *input = makeTokenWithData( prg, pdaRun, fsmRun, inputStream, klangEl->id, tokdata, true, bindId );

	incrementSteps( pdaRun );

	return input;
}

void initBindings( PdaRun *pdaRun )
{
	/* Bindings are indexed at 1. Need a no-binding. */
	pdaRun->bindings = new Bindings;
	pdaRun->bindings->push(0);
}

void makeTokenPushBinding( PdaRun *pdaRun, int bindId, Tree *tree )
{
	/* If the item is bound then store it in the bindings array. */
	if ( bindId > 0 ) {
		pdaRun->bindings->push( tree );
		treeUpref( tree );
	}
}

void unbind( Program *prg, Tree **sp, PdaRun *pdaRun, Tree *tree )
{
	Tree *lastBound = pdaRun->bindings->top();
	if ( lastBound == tree ) {
		pdaRun->bindings->pop();
		treeDownref( prg, sp, tree );
	}
}

<|endoftext|>


<commit_before>#include "Format_ostream.h"
#include <cmath>
#include <iostream>

struct Vector2D {
    float x;
    float y;
};

template <>
struct fmtxx::FormatValue<Vector2D>
{
    auto operator()(Writer& w, FormatSpec const& spec, Vector2D const& value) const
    {
        if (spec.conv == 'p' || spec.conv == 'P')
        {
            auto r   = std::hypot(value.x, value.y);
            auto phi = std::atan2(value.y, value.x);

            return fmtxx::format(w, "(r={:.3g}, phi={:.3g})", r, phi);
        }

        return fmtxx::format(w, "({}, {})", value.x, value.y);
    }
};

int main()
{
    Vector2D vec { 3.0, 4.0 };

    fmtxx::format(std::cout, "{}\n", vec);
        // "(3, 4)"
    fmtxx::format(std::cout, "{:p}\n", vec);
        // "(r=5, phi=0.927)"
}
<commit_msg>Fix gcc 6.3 compilation<commit_after>#include "Format_ostream.h"
#include <cmath>
#include <iostream>

struct Vector2D {
    float x;
    float y;
};

namespace fmtxx
{
    template <>
    struct FormatValue<Vector2D>
    {
        auto operator()(Writer& w, FormatSpec const& spec, Vector2D const& value) const
        {
            if (spec.conv == 'p' || spec.conv == 'P')
            {
                auto r   = std::hypot(value.x, value.y);
                auto phi = std::atan2(value.y, value.x);

                return fmtxx::format(w, "(r={:.3g}, phi={:.3g})", r, phi);
            }

            return fmtxx::format(w, "({}, {})", value.x, value.y);
        }
    };
}

int main()
{
    Vector2D vec { 3.0, 4.0 };

    fmtxx::format(std::cout, "{}\n", vec);
        // "(3, 4)"
    fmtxx::format(std::cout, "{:p}\n", vec);
        // "(r=5, phi=0.927)"
}
<|endoftext|>


<commit_before>/*
 * Util.cpp -- some utilities
 *
 * Copyright (c) 2011, 2012, 2013 David Demelier <markand@malikania.fr>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <cerrno>
#include <cstring>
#include <sstream>

#if defined(_WIN32)
#  include <sys/timeb.h>
#  include <direct.h>
#  include <windows.h>
#  include <shlobj.h>

#  define _MKDIR(p, x)	::_mkdir(p)
#else
#  include <sys/time.h>
#  include <libgen.h>

// This is libxdg-basedir
#  include <basedir.h>

#  define _MKDIR(p, x)	::mkdir(p, x)
#endif

#include <sys/stat.h>

#include "Util.h"

namespace irccd
{

/* --------------------------------------------------------
 * ErrorException class
 * -------------------------------------------------------- */

Util::ErrorException::ErrorException()
{
}

Util::ErrorException::ErrorException(const std::string &error)
	: m_error(error)
{
}

Util::ErrorException::~ErrorException() throw()
{
}

const char * Util::ErrorException::what() const throw()
{
	return m_error.c_str();
}

/* --------------------------------------------------------
 * Util class (private functions)
 * -------------------------------------------------------- */

std::string Util::pathBase(const std::string &append)
{
	std::ostringstream oss;

#if defined(_WIN32)
	char exepath[512];
	std::string base;
	size_t pos;

	/*
	 * Window is more complicated case as we don't know in advance
	 * where irccd is installed, so we get the current process path
	 * and removes its bin/ suffix.
	 */
	GetModuleFileNameA(NULL, exepath, sizeof (exepath));
	base = Util::dirName(exepath);
	pos = base.find("bin");
	if (pos != std::string::npos)
		base.erase(pos);

	oss << base << "\\";
#else
	oss << PREFIX << "/";
#endif

	oss << append;

	return oss.str();
}

std::string Util::pathUser(const std::string &append)
{
	std::ostringstream oss;

#if defined(_WIN32)
	char path[MAX_PATH];

	if (SHGetFolderPathA(NULL, CSIDL_PROFILE, NULL, 0, path) != S_OK)
		oss << "";
	else {
		oss << path;
		oss << "\\irccd";
	}
#else
	xdgHandle handle;

	if ((xdgInitHandle(&handle)) == nullptr) {
		const char *home = getenv("HOME");

		if (home != nullptr)
			oss << home;

		// append default path.
		oss << "/.config/irccd";
	} else {
		oss << xdgConfigHome(&handle);
		oss << "/irccd";
	}

	xdgWipeHandle(&handle);
#endif

	oss << append;

	return oss.str();
}

/* --------------------------------------------------------
 * Util class (public functions)
 * -------------------------------------------------------- */

#if defined(_WIN32)
	const char Util::DIR_SEP = '\\';
#else
	const char Util::DIR_SEP = '/';
#endif

std::string Util::baseName(const std::string &path)
{
#if defined(_WIN32) || defined(_MSC_VER)
	std::string copy = path;
	size_t pos;

	pos = copy.find_last_of('\\');
	if (pos == std::string::npos)
		pos = copy.find_last_of('/');

	if (pos == std::string::npos)
		return copy;

	return copy.substr(pos + 1);
#else
	char *copy = strdup(path.c_str());
	std::string ret;

	if (copy == NULL)
		return "";

	ret = std::string(::basename(copy));
	free(copy);

	return ret;
#endif
}

bool Util::findConfig(const std::string &name, ConfigFinder func)
{
	std::ostringstream oss;
	std::string path;

	// 1. Always user first
	oss << configUser();
	oss << name;
	path = oss.str();

	if (func(path))
		return true;

	// 2. System config
	oss.str("");
	oss << configSystem();
	oss << name;
	path = oss.str();

	if (func(path))
		return true;

	return false;
}

std::string Util::dirName(const std::string &file)
{
#if defined(_WIN32) || defined(_MSC_VER)
	std::string copy = file;
	std::size_t pos;

	pos = copy.find_last_of('\\');
	if (pos == std::string::npos)
		pos = copy.find_last_of('/');

	if (pos == std::string::npos)
		return copy;

	return copy.substr(0, pos);
#else
	char *copy = strdup(file.c_str());
	std::string ret;

	if (copy == NULL)
		return "";

	ret = std::string(::dirname(copy));
	free(copy);

	return ret;
#endif
}

bool Util::exist(const std::string &path)
{
	struct stat st;

	return (stat(path.c_str(), &st) != -1);
}

std::string Util::getHome()
{
#if defined(_WIN32)
	char path[MAX_PATH];

	if (SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, path) != S_OK)
		return "";

	return std::string(path);
#else
	return std::string(getenv("HOME"));
#endif
}

uint64_t Util::getTicks()
{
#if defined(_WIN32) || defined(_MSC_VER)
	_timeb tp;

	_ftime(&tp);

	return tp.time * 1000LL + tp.millitm;
#else
        struct timeval tp;

        gettimeofday(&tp, NULL);

        return tp.tv_sec * 1000LL + tp.tv_usec / 1000;
#endif
}

void Util::mkdir(const std::string &dir, int mode)
{
	std::ostringstream oss;

	oss << "mkdir: ";

	for (size_t i = 0; i < dir.length(); ++i) {
		if (dir[i] != '/')
			continue;

		std::string part = dir.substr(0, i);
		if (part.length() <= 0 || exist(part))
			continue;

		if (_MKDIR(part.c_str(), mode) == -1) {
			oss << part << ": " << strerror(errno);
			throw Util::ErrorException(oss.str());
		}
	}

	// Last part
	if (_MKDIR(dir.c_str(), mode) == -1) {
		oss << dir << ": " << strerror(errno);
		throw Util::ErrorException(oss.str());
	}
}

std::string Util::pluginDirectory()
{
	/*
	 * Under unix, we store local plugins under the same directory
	 * as the config, plus /plugins suffix, so it's usually:
	 *
	 * ~/.config/irccd/plugins.
	 *
	 * On windows, it reside inside the user home like :
	 * C:\Users\Simone\irccd\plugins
	 */
	std::ostringstream oss;

	oss << configUser();

#if defined(_WIN32)
	oss << "plugins\\";
#else
	oss << "plugins/";
#endif

	return oss.str();
}

std::vector<std::string> Util::split(const std::string &list,
				     const std::string &delimiter,
				     int max)
{
	std::vector<std::string> result;
	size_t next = -1, current;
	int count = 1;
	bool finished = false;

	do {
		std::string val;

		current = next + 1;
		next = list.find_first_of(delimiter, current);

		// split max, get until the end
		if (max >= 0 && count++ >= max) {
			val = list.substr(current, std::string::npos);
			finished = true;
		} else {
			val = list.substr(current, next - current);
			finished = next == std::string::npos;
		}

		result.push_back(val);
	} while (!finished);

	return result;
}

void Util::usleep(int msec)
{
#if defined(_WIN32)
	Sleep(msec);
#else
	::usleep(msec * 1000);
#endif
}

} // !irccd
<commit_msg>Fix segfault<commit_after>/*
 * Util.cpp -- some utilities
 *
 * Copyright (c) 2011, 2012, 2013 David Demelier <markand@malikania.fr>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <cerrno>
#include <cstring>
#include <sstream>

#if defined(_WIN32)
#  include <sys/timeb.h>
#  include <direct.h>
#  include <windows.h>
#  include <shlobj.h>

#  define _MKDIR(p, x)	::_mkdir(p)
#else
#  include <sys/time.h>
#  include <libgen.h>

// This is libxdg-basedir
#  include <basedir.h>

#  define _MKDIR(p, x)	::mkdir(p, x)
#endif

#include <sys/stat.h>

#include "Util.h"

namespace irccd
{

/* --------------------------------------------------------
 * ErrorException class
 * -------------------------------------------------------- */

Util::ErrorException::ErrorException()
{
}

Util::ErrorException::ErrorException(const std::string &error)
	: m_error(error)
{
}

Util::ErrorException::~ErrorException() throw()
{
}

const char * Util::ErrorException::what() const throw()
{
	return m_error.c_str();
}

/* --------------------------------------------------------
 * Util class (private functions)
 * -------------------------------------------------------- */

std::string Util::pathBase(const std::string &append)
{
	std::ostringstream oss;

#if defined(_WIN32)
	char exepath[512];
	std::string base;
	size_t pos;

	/*
	 * Window is more complicated case as we don't know in advance
	 * where irccd is installed, so we get the current process path
	 * and removes its bin/ suffix.
	 */
	GetModuleFileNameA(NULL, exepath, sizeof (exepath));
	base = Util::dirName(exepath);
	pos = base.find("bin");
	if (pos != std::string::npos)
		base.erase(pos);

	oss << base << "\\";
#else
	oss << PREFIX << "/";
#endif

	oss << append;

	return oss.str();
}

std::string Util::pathUser(const std::string &append)
{
	std::ostringstream oss;

#if defined(_WIN32)
	char path[MAX_PATH];

	if (SHGetFolderPathA(NULL, CSIDL_PROFILE, NULL, 0, path) != S_OK)
		oss << "";
	else {
		oss << path;
		oss << "\\irccd";
	}
#else
	xdgHandle handle;

	if ((xdgInitHandle(&handle)) == nullptr) {
		const char *home = getenv("HOME");

		if (home != nullptr)
			oss << home;

		// append default path.
		oss << "/.config/irccd";

		xdgWipeHandle(&handle);
	} else {
		oss << xdgConfigHome(&handle);
		oss << "/irccd";
	}

#endif

	oss << append;

	return oss.str();
}

/* --------------------------------------------------------
 * Util class (public functions)
 * -------------------------------------------------------- */

#if defined(_WIN32)
	const char Util::DIR_SEP = '\\';
#else
	const char Util::DIR_SEP = '/';
#endif

std::string Util::baseName(const std::string &path)
{
#if defined(_WIN32) || defined(_MSC_VER)
	std::string copy = path;
	size_t pos;

	pos = copy.find_last_of('\\');
	if (pos == std::string::npos)
		pos = copy.find_last_of('/');

	if (pos == std::string::npos)
		return copy;

	return copy.substr(pos + 1);
#else
	char *copy = strdup(path.c_str());
	std::string ret;

	if (copy == NULL)
		return "";

	ret = std::string(::basename(copy));
	free(copy);

	return ret;
#endif
}

bool Util::findConfig(const std::string &name, ConfigFinder func)
{
	std::ostringstream oss;
	std::string path;

	// 1. Always user first
	oss << configUser();
	oss << name;
	path = oss.str();

	if (func(path))
		return true;

	// 2. System config
	oss.str("");
	oss << configSystem();
	oss << name;
	path = oss.str();

	if (func(path))
		return true;

	return false;
}

std::string Util::dirName(const std::string &file)
{
#if defined(_WIN32) || defined(_MSC_VER)
	std::string copy = file;
	std::size_t pos;

	pos = copy.find_last_of('\\');
	if (pos == std::string::npos)
		pos = copy.find_last_of('/');

	if (pos == std::string::npos)
		return copy;

	return copy.substr(0, pos);
#else
	char *copy = strdup(file.c_str());
	std::string ret;

	if (copy == NULL)
		return "";

	ret = std::string(::dirname(copy));
	free(copy);

	return ret;
#endif
}

bool Util::exist(const std::string &path)
{
	struct stat st;

	return (stat(path.c_str(), &st) != -1);
}

std::string Util::getHome()
{
#if defined(_WIN32)
	char path[MAX_PATH];

	if (SHGetFolderPathA(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, path) != S_OK)
		return "";

	return std::string(path);
#else
	return std::string(getenv("HOME"));
#endif
}

uint64_t Util::getTicks()
{
#if defined(_WIN32) || defined(_MSC_VER)
	_timeb tp;

	_ftime(&tp);

	return tp.time * 1000LL + tp.millitm;
#else
        struct timeval tp;

        gettimeofday(&tp, NULL);

        return tp.tv_sec * 1000LL + tp.tv_usec / 1000;
#endif
}

void Util::mkdir(const std::string &dir, int mode)
{
	std::ostringstream oss;

	oss << "mkdir: ";

	for (size_t i = 0; i < dir.length(); ++i) {
		if (dir[i] != '/')
			continue;

		std::string part = dir.substr(0, i);
		if (part.length() <= 0 || exist(part))
			continue;

		if (_MKDIR(part.c_str(), mode) == -1) {
			oss << part << ": " << strerror(errno);
			throw Util::ErrorException(oss.str());
		}
	}

	// Last part
	if (_MKDIR(dir.c_str(), mode) == -1) {
		oss << dir << ": " << strerror(errno);
		throw Util::ErrorException(oss.str());
	}
}

std::string Util::pluginDirectory()
{
	/*
	 * Under unix, we store local plugins under the same directory
	 * as the config, plus /plugins suffix, so it's usually:
	 *
	 * ~/.config/irccd/plugins.
	 *
	 * On windows, it reside inside the user home like :
	 * C:\Users\Simone\irccd\plugins
	 */
	std::ostringstream oss;

	oss << configUser();

#if defined(_WIN32)
	oss << "plugins\\";
#else
	oss << "plugins/";
#endif

	return oss.str();
}

std::vector<std::string> Util::split(const std::string &list,
				     const std::string &delimiter,
				     int max)
{
	std::vector<std::string> result;
	size_t next = -1, current;
	int count = 1;
	bool finished = false;

	do {
		std::string val;

		current = next + 1;
		next = list.find_first_of(delimiter, current);

		// split max, get until the end
		if (max >= 0 && count++ >= max) {
			val = list.substr(current, std::string::npos);
			finished = true;
		} else {
			val = list.substr(current, next - current);
			finished = next == std::string::npos;
		}

		result.push_back(val);
	} while (!finished);

	return result;
}

void Util::usleep(int msec)
{
#if defined(_WIN32)
	Sleep(msec);
#else
	::usleep(msec * 1000);
#endif
}

} // !irccd
<|endoftext|>


<commit_before>//===-- Mangler.cpp - Self-contained c/asm llvm name mangler --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Unified name mangler for CWriter and assembly backends.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/Mangler.h"
#include "llvm/Module.h"
#include "llvm/Type.h"
#include "llvm/ADT/StringExtras.h"
using namespace llvm;

static char HexDigit(int V) {
  return V < 10 ? V+'0' : V+'A'-10;
}

static std::string MangleLetter(unsigned char C) {
  return std::string("_")+HexDigit(C >> 4) + HexDigit(C & 15) + "_";
}

/// makeNameProper - We don't want identifier names non-C-identifier characters
/// in them, so mangle them as appropriate.
///
std::string Mangler::makeNameProper(const std::string &X, const char *Prefix) {
  std::string Result;

  // If X does not start with (char)1, add the prefix.
  std::string::const_iterator I = X.begin();
  if (*I != 1)
    Result = Prefix;
  else
    ++I;  // Skip over the marker.

  // Mangle the first letter specially, don't allow numbers...
  if (*I >= '0' && *I <= '9')
    Result += MangleLetter(*I++);

  for (std::string::const_iterator E = X.end(); I != E; ++I)
    if ((*I < 'a' || *I > 'z') && (*I < 'A' || *I > 'Z') &&
        (*I < '0' || *I > '9') && *I != '_')
      Result += MangleLetter(*I);
    else
      Result += *I;
  return Result;
}

/// getTypeID - Return a unique ID for the specified LLVM type.
///
unsigned Mangler::getTypeID(const Type *Ty) {
  unsigned &E = TypeMap[Ty];
  if (E == 0) E = ++TypeCounter;
  return E;
}

std::string Mangler::getValueName(const Value *V) {
  // Check to see whether we've already named V.
  ValueMap::iterator VI = Memo.find(V);
  if (VI != Memo.end()) {
    return VI->second; // Return the old name for V.
  }

  std::string name;
  if (V->hasName()) { // Print out the label if it exists...
    // Name mangling occurs as follows:
    // - If V is an intrinsic function, do not change name at all
    // - If V is not a global, mangling always occurs.
    // - Otherwise, mangling occurs when any of the following are true:
    //   1) V has internal linkage
    //   2) V's name would collide if it is not mangled.
    //
    const GlobalValue* gv = dyn_cast<GlobalValue>(V);
    if (gv && isa<Function>(gv) && cast<Function>(gv)->getIntrinsicID()) {
      name = gv->getName(); // Is an intrinsic function
    } else if (gv && !gv->hasInternalLinkage() && !MangledGlobals.count(gv)) {
      name = makeNameProper(gv->getName(), Prefix);
    } else {
      // Non-global, or global with internal linkage / colliding name
      // -> mangle.
      unsigned TypeUniqueID = getTypeID(V->getType());
      name = "l" + utostr(TypeUniqueID) + "_" + makeNameProper(V->getName());
    }
  } else {
    name = "ltmp_" + utostr(Count++) + "_" + utostr(getTypeID(V->getType()));
  }

  Memo[V] = name;
  return name;
}

void Mangler::InsertName(GlobalValue *GV,
                         std::map<std::string, GlobalValue*> &Names) {
  if (!GV->hasName()) {   // We must mangle unnamed globals.
    MangledGlobals.insert(GV);
    return;
  }

  // Figure out if this is already used.
  GlobalValue *&ExistingValue = Names[GV->getName()];
  if (!ExistingValue) {
    ExistingValue = GV;
  } else {
    // If GV is external but the existing one is static, mangle the existing one
    if (GV->hasExternalLinkage() && !ExistingValue->hasExternalLinkage()) {
      MangledGlobals.insert(ExistingValue);
      ExistingValue = GV;
    } else {
      // Otherwise, mangle GV
      MangledGlobals.insert(GV);
    }
  }
}

Mangler::Mangler(Module &m, const char *prefix)
  : M(m), Prefix(prefix), TypeCounter(0), Count(0) {
  // Calculate which global values have names that will collide when we throw
  // away type information.
  std::map<std::string, GlobalValue*> Names;
  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
    InsertName(I, Names);
  for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
    InsertName(I, Names);
}
<commit_msg>Allow $<commit_after>//===-- Mangler.cpp - Self-contained c/asm llvm name mangler --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Unified name mangler for CWriter and assembly backends.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/Mangler.h"
#include "llvm/Module.h"
#include "llvm/Type.h"
#include "llvm/ADT/StringExtras.h"
using namespace llvm;

static char HexDigit(int V) {
  return V < 10 ? V+'0' : V+'A'-10;
}

static std::string MangleLetter(unsigned char C) {
  return std::string("_")+HexDigit(C >> 4) + HexDigit(C & 15) + "_";
}

/// makeNameProper - We don't want identifier names non-C-identifier characters
/// in them, so mangle them as appropriate.
///
std::string Mangler::makeNameProper(const std::string &X, const char *Prefix) {
  std::string Result;

  // If X does not start with (char)1, add the prefix.
  std::string::const_iterator I = X.begin();
  if (*I != 1)
    Result = Prefix;
  else
    ++I;  // Skip over the marker.

  // Mangle the first letter specially, don't allow numbers...
  if (*I >= '0' && *I <= '9')
    Result += MangleLetter(*I++);

  for (std::string::const_iterator E = X.end(); I != E; ++I)
    if ((*I < 'a' || *I > 'z') && (*I < 'A' || *I > 'Z') &&
        (*I < '0' || *I > '9') && *I != '_' && *I != '$')
      Result += MangleLetter(*I);
    else
      Result += *I;
  return Result;
}

/// getTypeID - Return a unique ID for the specified LLVM type.
///
unsigned Mangler::getTypeID(const Type *Ty) {
  unsigned &E = TypeMap[Ty];
  if (E == 0) E = ++TypeCounter;
  return E;
}

std::string Mangler::getValueName(const Value *V) {
  // Check to see whether we've already named V.
  ValueMap::iterator VI = Memo.find(V);
  if (VI != Memo.end()) {
    return VI->second; // Return the old name for V.
  }

  std::string name;
  if (V->hasName()) { // Print out the label if it exists...
    // Name mangling occurs as follows:
    // - If V is an intrinsic function, do not change name at all
    // - If V is not a global, mangling always occurs.
    // - Otherwise, mangling occurs when any of the following are true:
    //   1) V has internal linkage
    //   2) V's name would collide if it is not mangled.
    //
    const GlobalValue* gv = dyn_cast<GlobalValue>(V);
    if (gv && isa<Function>(gv) && cast<Function>(gv)->getIntrinsicID()) {
      name = gv->getName(); // Is an intrinsic function
    } else if (gv && !gv->hasInternalLinkage() && !MangledGlobals.count(gv)) {
      name = makeNameProper(gv->getName(), Prefix);
    } else {
      // Non-global, or global with internal linkage / colliding name
      // -> mangle.
      unsigned TypeUniqueID = getTypeID(V->getType());
      name = "l" + utostr(TypeUniqueID) + "_" + makeNameProper(V->getName());
    }
  } else {
    name = "ltmp_" + utostr(Count++) + "_" + utostr(getTypeID(V->getType()));
  }

  Memo[V] = name;
  return name;
}

void Mangler::InsertName(GlobalValue *GV,
                         std::map<std::string, GlobalValue*> &Names) {
  if (!GV->hasName()) {   // We must mangle unnamed globals.
    MangledGlobals.insert(GV);
    return;
  }

  // Figure out if this is already used.
  GlobalValue *&ExistingValue = Names[GV->getName()];
  if (!ExistingValue) {
    ExistingValue = GV;
  } else {
    // If GV is external but the existing one is static, mangle the existing one
    if (GV->hasExternalLinkage() && !ExistingValue->hasExternalLinkage()) {
      MangledGlobals.insert(ExistingValue);
      ExistingValue = GV;
    } else {
      // Otherwise, mangle GV
      MangledGlobals.insert(GV);
    }
  }
}

Mangler::Mangler(Module &m, const char *prefix)
  : M(m), Prefix(prefix), TypeCounter(0), Count(0) {
  // Calculate which global values have names that will collide when we throw
  // away type information.
  std::map<std::string, GlobalValue*> Names;
  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
    InsertName(I, Names);
  for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
    InsertName(I, Names);
}
<|endoftext|>


<commit_before><commit_msg>Proper face assignment for half-edge data structure<commit_after><|endoftext|>


<commit_before>#include "castconverthelpers.h"

int DicomFileConverterScalar( const std::string &inputPixelComponentType,
	const std::string &outputPixelComponentType, const std::string &inputDirectoryName,
	const std::string &outputFileName, int inputDimension )
{
	/** Support for 3D images. */
	if ( inputDimension == 3 )
	{
		/** From unsigned char to something else. */
		callCorrectReadDicomWriterMacro( unsigned char, unsigned char );
		callCorrectReadDicomWriterMacro( unsigned char, char );
		callCorrectReadDicomWriterMacro( unsigned char, unsigned short );
		callCorrectReadDicomWriterMacro( unsigned char, short );
		callCorrectReadDicomWriterMacro( unsigned char, unsigned int );
		callCorrectReadDicomWriterMacro( unsigned char, int );
		callCorrectReadDicomWriterMacro( unsigned char, unsigned long );
		callCorrectReadDicomWriterMacro( unsigned char, long );
		callCorrectReadDicomWriterMacro( unsigned char, float );
		callCorrectReadDicomWriterMacro( unsigned char, double );

		/** From char to something else. */
		callCorrectReadDicomWriterMacro( char, unsigned char );
		callCorrectReadDicomWriterMacro( char, char );
		callCorrectReadDicomWriterMacro( char, unsigned short );
		callCorrectReadDicomWriterMacro( char, short );
		callCorrectReadDicomWriterMacro( char, unsigned int );
		callCorrectReadDicomWriterMacro( char, int );
		callCorrectReadDicomWriterMacro( char, unsigned long );
		callCorrectReadDicomWriterMacro( char, long );
		callCorrectReadDicomWriterMacro( char, float );
		callCorrectReadDicomWriterMacro( char, double );

		/** From unsigned short to something else. */
		callCorrectReadDicomWriterMacro( unsigned short, unsigned char );
		callCorrectReadDicomWriterMacro( unsigned short, char );
		callCorrectReadDicomWriterMacro( unsigned short, unsigned short );
		callCorrectReadDicomWriterMacro( unsigned short, short );
		callCorrectReadDicomWriterMacro( unsigned short, unsigned int );
		callCorrectReadDicomWriterMacro( unsigned short, int );
		callCorrectReadDicomWriterMacro( unsigned short, unsigned long );
		callCorrectReadDicomWriterMacro( unsigned short, long );
		callCorrectReadDicomWriterMacro( unsigned short, float );
		callCorrectReadDicomWriterMacro( unsigned short, double );

		/** From short to something else. */
		callCorrectReadDicomWriterMacro( short, unsigned char );
		callCorrectReadDicomWriterMacro( short, char );
		callCorrectReadDicomWriterMacro( short, unsigned short );
		callCorrectReadDicomWriterMacro( short, short );
		callCorrectReadDicomWriterMacro( short, unsigned int );
		callCorrectReadDicomWriterMacro( short, int );
		callCorrectReadDicomWriterMacro( short, unsigned long );
		callCorrectReadDicomWriterMacro( short, long );
		callCorrectReadDicomWriterMacro( short, float );
		callCorrectReadDicomWriterMacro( short, double );

		/** From unsigned int to something else. */
		callCorrectReadDicomWriterMacro( unsigned int, unsigned char );
		callCorrectReadDicomWriterMacro( unsigned int, char );
		callCorrectReadDicomWriterMacro( unsigned int, unsigned short );
		callCorrectReadDicomWriterMacro( unsigned int, short );
		callCorrectReadDicomWriterMacro( unsigned int, unsigned int );
		callCorrectReadDicomWriterMacro( unsigned int, int );
		callCorrectReadDicomWriterMacro( unsigned int, unsigned long );
		callCorrectReadDicomWriterMacro( unsigned int, long );
		callCorrectReadDicomWriterMacro( unsigned int, float );
		callCorrectReadDicomWriterMacro( unsigned int, double );

		/** From int to something else. */
		callCorrectReadDicomWriterMacro( int, unsigned char );
		callCorrectReadDicomWriterMacro( int, char );
		callCorrectReadDicomWriterMacro( int, unsigned short );
		callCorrectReadDicomWriterMacro( int, short );
		callCorrectReadDicomWriterMacro( int, unsigned int );
		callCorrectReadDicomWriterMacro( int, int );
		callCorrectReadDicomWriterMacro( int, unsigned long );
		callCorrectReadDicomWriterMacro( int, long );
		callCorrectReadDicomWriterMacro( int, float );
		callCorrectReadDicomWriterMacro( int, double );

		/** From float to something else. *
		callCorrectReadDicomWriterMacro( float, unsigned char );
		callCorrectReadDicomWriterMacro( float, char );
		callCorrectReadDicomWriterMacro( float, unsigned short );
		callCorrectReadDicomWriterMacro( float, short );
		callCorrectReadDicomWriterMacro( float, unsigned int );
		callCorrectReadDicomWriterMacro( float, int );
		callCorrectReadDicomWriterMacro( float, unsigned long );
		callCorrectReadDicomWriterMacro( float, long );
		callCorrectReadDicomWriterMacro( float, float );
		callCorrectReadDicomWriterMacro( float, double );

		/ * * From double to something else. */
		callCorrectReadDicomWriterMacro( double, unsigned char );
		callCorrectReadDicomWriterMacro( double, char );
		callCorrectReadDicomWriterMacro( double, unsigned short );
		callCorrectReadDicomWriterMacro( double, short );
		callCorrectReadDicomWriterMacro( double, unsigned int );
		callCorrectReadDicomWriterMacro( double, int );
		callCorrectReadDicomWriterMacro( double, unsigned long );
		callCorrectReadDicomWriterMacro( double, long );
		callCorrectReadDicomWriterMacro( double, float );
		callCorrectReadDicomWriterMacro( double, double );
	}
	else
	{
		std::cerr << "Dimension equals " << inputDimension << ", which is not supported." << std::endl;
		std::cerr << "Only 3D images are supported." << std::endl;
		return 1;
	} // end if over inputDimension

	/** Return a value. */
	return 0;

} // end support for SCALAR pixel type
<commit_msg>MS:<commit_after>#include "castconverthelpers.h"

int DicomFileConverterScalar( const std::string &inputPixelComponentType,
	const std::string &outputPixelComponentType, const std::string &inputDirectoryName,
	const std::string &outputFileName, int inputDimension )
{
	/** Support for 3D images. */
	if ( inputDimension == 3 )
	{
		/** From unsigned char to something else. */
		callCorrectReadDicomWriterMacro( unsigned char, unsigned char );
		callCorrectReadDicomWriterMacro( unsigned char, char );
		callCorrectReadDicomWriterMacro( unsigned char, unsigned short );
		callCorrectReadDicomWriterMacro( unsigned char, short );
		callCorrectReadDicomWriterMacro( unsigned char, unsigned int );
		callCorrectReadDicomWriterMacro( unsigned char, int );
		callCorrectReadDicomWriterMacro( unsigned char, unsigned long );
		callCorrectReadDicomWriterMacro( unsigned char, long );
		callCorrectReadDicomWriterMacro( unsigned char, float );
		callCorrectReadDicomWriterMacro( unsigned char, double );

		/** From char to something else. */
		callCorrectReadDicomWriterMacro( char, unsigned char );
		callCorrectReadDicomWriterMacro( char, char );
		callCorrectReadDicomWriterMacro( char, unsigned short );
		callCorrectReadDicomWriterMacro( char, short );
		callCorrectReadDicomWriterMacro( char, unsigned int );
		callCorrectReadDicomWriterMacro( char, int );
		callCorrectReadDicomWriterMacro( char, unsigned long );
		callCorrectReadDicomWriterMacro( char, long );
		callCorrectReadDicomWriterMacro( char, float );
		callCorrectReadDicomWriterMacro( char, double );

		/** From unsigned short to something else. */
		callCorrectReadDicomWriterMacro( unsigned short, unsigned char );
		callCorrectReadDicomWriterMacro( unsigned short, char );
		callCorrectReadDicomWriterMacro( unsigned short, unsigned short );
		callCorrectReadDicomWriterMacro( unsigned short, short );
		callCorrectReadDicomWriterMacro( unsigned short, unsigned int );
		callCorrectReadDicomWriterMacro( unsigned short, int );
		callCorrectReadDicomWriterMacro( unsigned short, unsigned long );
		callCorrectReadDicomWriterMacro( unsigned short, long );
		callCorrectReadDicomWriterMacro( unsigned short, float );
		callCorrectReadDicomWriterMacro( unsigned short, double );

		/** From short to something else. */
		callCorrectReadDicomWriterMacro( short, unsigned char );
		callCorrectReadDicomWriterMacro( short, char );
		callCorrectReadDicomWriterMacro( short, unsigned short );
		callCorrectReadDicomWriterMacro( short, short );
		callCorrectReadDicomWriterMacro( short, unsigned int );
		callCorrectReadDicomWriterMacro( short, int );
		callCorrectReadDicomWriterMacro( short, unsigned long );
		callCorrectReadDicomWriterMacro( short, long );
		callCorrectReadDicomWriterMacro( short, float );
		callCorrectReadDicomWriterMacro( short, double );

		/** From unsigned int to something else. */
		callCorrectReadDicomWriterMacro( unsigned int, unsigned char );
		callCorrectReadDicomWriterMacro( unsigned int, char );
		callCorrectReadDicomWriterMacro( unsigned int, unsigned short );
		callCorrectReadDicomWriterMacro( unsigned int, short );
		callCorrectReadDicomWriterMacro( unsigned int, unsigned int );
		callCorrectReadDicomWriterMacro( unsigned int, int );
		callCorrectReadDicomWriterMacro( unsigned int, unsigned long );
		callCorrectReadDicomWriterMacro( unsigned int, long );
		callCorrectReadDicomWriterMacro( unsigned int, float );
		callCorrectReadDicomWriterMacro( unsigned int, double );

		/** From int to something else. */
		callCorrectReadDicomWriterMacro( int, unsigned char );
		callCorrectReadDicomWriterMacro( int, char );
		callCorrectReadDicomWriterMacro( int, unsigned short );
		callCorrectReadDicomWriterMacro( int, short );
		callCorrectReadDicomWriterMacro( int, unsigned int );
		callCorrectReadDicomWriterMacro( int, int );
		callCorrectReadDicomWriterMacro( int, unsigned long );
		callCorrectReadDicomWriterMacro( int, long );
		callCorrectReadDicomWriterMacro( int, float );
		callCorrectReadDicomWriterMacro( int, double );

		/** From float to something else. */
		callCorrectReadDicomWriterMacro( float, unsigned char );
		callCorrectReadDicomWriterMacro( float, char );
		callCorrectReadDicomWriterMacro( float, unsigned short );
		callCorrectReadDicomWriterMacro( float, short );
		callCorrectReadDicomWriterMacro( float, unsigned int );
		callCorrectReadDicomWriterMacro( float, int );
		callCorrectReadDicomWriterMacro( float, unsigned long );
		callCorrectReadDicomWriterMacro( float, long );
		callCorrectReadDicomWriterMacro( float, float );
		callCorrectReadDicomWriterMacro( float, double );

		/** From double to something else. */
		callCorrectReadDicomWriterMacro( double, unsigned char );
		callCorrectReadDicomWriterMacro( double, char );
		callCorrectReadDicomWriterMacro( double, unsigned short );
		callCorrectReadDicomWriterMacro( double, short );
		callCorrectReadDicomWriterMacro( double, unsigned int );
		callCorrectReadDicomWriterMacro( double, int );
		callCorrectReadDicomWriterMacro( double, unsigned long );
		callCorrectReadDicomWriterMacro( double, long );
		callCorrectReadDicomWriterMacro( double, float );
		callCorrectReadDicomWriterMacro( double, double );
	}
	else
	{
		std::cerr << "Dimension equals " << inputDimension << ", which is not supported." << std::endl;
		std::cerr << "Only 3D images are supported." << std::endl;
		return 1;
	} // end if over inputDimension

	/** Return a value. */
	return 0;

} // end support for SCALAR pixel type
<|endoftext|>


<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2019 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "clientmodel.h"

#include "bantablemodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "peertablemodel.h"

#include "chainparams.h"
#include "checkpoints.h"
#include "clientversion.h"
#include "main.h"
#include "masternode-sync.h"
#include "masternodeman.h"
#include "net.h"
#include "netbase.h"
#include "guiinterface.h"
#include "util.h"

#include <stdint.h>

#include <QDateTime>
#include <QDebug>
#include <QTimer>

static const int64_t nClientStartupTime = GetTime();
// Last tip update notification
static int64_t nLastBlockTipUpdateNotification = 0;

ClientModel::ClientModel(OptionsModel* optionsModel, QObject* parent) : QObject(parent),
                                                                        optionsModel(optionsModel),
                                                                        peerTableModel(0),
                                                                        banTableModel(0),
                                                                        cacheTip(nullptr),
                                                                        cachedMasternodeCountString(""),
                                                                        cachedReindexing(0), cachedImporting(0),
                                                                        numBlocksAtStartup(-1), pollTimer(0)
{
    peerTableModel = new PeerTableModel(this);
    banTableModel = new BanTableModel(this);
    pollTimer = new QTimer(this);
    connect(pollTimer, &QTimer::timeout, this, &ClientModel::updateTimer);
    pollTimer->start(MODEL_UPDATE_DELAY);

    pollMnTimer = new QTimer(this);
    connect(pollMnTimer, &QTimer::timeout, this, &ClientModel::updateMnTimer);
    // no need to update as frequent as data for balances/txes/blocks
    pollMnTimer->start(MODEL_UPDATE_DELAY * 4);

    subscribeToCoreSignals();
}

ClientModel::~ClientModel()
{
    unsubscribeFromCoreSignals();
}

int ClientModel::getNumConnections(unsigned int flags) const
{
    LOCK(cs_vNodes);
    if (flags == CONNECTIONS_ALL) // Shortcut if we want total
        return vNodes.size();

    int nNum = 0;
    for (CNode* pnode : vNodes)
        if (flags & (pnode->fInbound ? CONNECTIONS_IN : CONNECTIONS_OUT))
            nNum++;

    return nNum;
}

QString ClientModel::getMasternodeCountString() const
{
    int ipv4 = 0, ipv6 = 0, onion = 0;
    mnodeman.CountNetworks(ActiveProtocol(), ipv4, ipv6, onion);
    int nUnknown = mnodeman.size() - ipv4 - ipv6 - onion;
    if(nUnknown < 0) nUnknown = 0;
    return tr("Total: %1 (IPv4: %2 / IPv6: %3 / Tor: %4 / Unknown: %5)").arg(QString::number((int)mnodeman.size())).arg(QString::number((int)ipv4)).arg(QString::number((int)ipv6)).arg(QString::number((int)onion)).arg(QString::number((int)nUnknown));
}

int ClientModel::getNumBlocks()
{
    if (!cacheTip) {
        cacheTip = WITH_LOCK(cs_main, return chainActive.Tip(););
    }

    return cacheTip ? cacheTip->nHeight : 0;
}

int ClientModel::getNumBlocksAtStartup()
{
    if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks();
    return numBlocksAtStartup;
}

quint64 ClientModel::getTotalBytesRecv() const
{
    return CNode::GetTotalBytesRecv();
}

quint64 ClientModel::getTotalBytesSent() const
{
    return CNode::GetTotalBytesSent();
}

QDateTime ClientModel::getLastBlockDate() const
{
    const int nTime = (cacheTip == nullptr ? Params().GenesisBlock().GetBlockTime() : cacheTip->GetBlockTime());
    return QDateTime::fromTime_t(nTime);
}

QString ClientModel::getLastBlockHash() const
{
    const uint256& nHash = (cacheTip == nullptr ? Params().GenesisBlock().GetHash() : cacheTip->GetBlockHash());
    return QString::fromStdString(nHash.GetHex());
}

double ClientModel::getVerificationProgress() const
{
    return Checkpoints::GuessVerificationProgress(cacheTip);
}

void ClientModel::updateTimer()
{
    // Get required lock upfront. This avoids the GUI from getting stuck on
    // periodical polls if the core is holding the locks for a longer time -
    // for example, during a wallet rescan.
    Q_EMIT bytesChanged(getTotalBytesRecv(), getTotalBytesSent());
}

void ClientModel::updateMnTimer()
{
    // Get required lock upfront. This avoids the GUI from getting stuck on
    // periodical polls if the core is holding the locks for a longer time -
    // for example, during a wallet rescan.
    TRY_LOCK(cs_main, lockMain);
    if (!lockMain)
        return;
    QString newMasternodeCountString = getMasternodeCountString();

    if (cachedMasternodeCountString != newMasternodeCountString) {
        cachedMasternodeCountString = newMasternodeCountString;

        Q_EMIT strMasternodesChanged(cachedMasternodeCountString);
    }
}

void ClientModel::updateNumConnections(int numConnections)
{
    Q_EMIT numConnectionsChanged(numConnections);
}

void ClientModel::updateAlert()
{
    Q_EMIT alertsChanged(getStatusBarWarnings());
}

bool ClientModel::inInitialBlockDownload() const
{
    return cachedInitialSync;
}

enum BlockSource ClientModel::getBlockSource() const
{
    if (fReindex)
        return BLOCK_SOURCE_REINDEX;
    else if (fImporting)
        return BLOCK_SOURCE_DISK;
    else if (getNumConnections() > 0)
        return BLOCK_SOURCE_NETWORK;

    return BLOCK_SOURCE_NONE;
}

QString ClientModel::getStatusBarWarnings() const
{
    return QString::fromStdString(GetWarnings("statusbar"));
}

OptionsModel* ClientModel::getOptionsModel()
{
    return optionsModel;
}

PeerTableModel* ClientModel::getPeerTableModel()
{
    return peerTableModel;
}

BanTableModel *ClientModel::getBanTableModel()
{
    return banTableModel;
}

QString ClientModel::formatFullVersion() const
{
    return QString::fromStdString(FormatFullVersion());
}

QString ClientModel::formatBuildDate() const
{
    return QString::fromStdString(CLIENT_DATE);
}

bool ClientModel::isReleaseVersion() const
{
    return CLIENT_VERSION_IS_RELEASE;
}

QString ClientModel::clientName() const
{
    return QString::fromStdString(CLIENT_NAME);
}

QString ClientModel::formatClientStartupTime() const
{
    return QDateTime::fromTime_t(nClientStartupTime).toString();
}

QString ClientModel::dataDir() const
{
    return GUIUtil::boostPathToQString(GetDataDir());
}

void ClientModel::updateBanlist()
{
    banTableModel->refresh();
}

static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CBlockIndex *pIndex)
{
    // lock free async UI updates in case we have a new block tip
    // during initial sync, only update the UI if the last update
    // was > 1000ms (MODEL_UPDATE_DELAY) ago
    int64_t now = 0;
    if (initialSync)
        now = GetTimeMillis();

    // if we are in-sync, update the UI regardless of last update time
    if (!initialSync || now - nLastBlockTipUpdateNotification > MODEL_UPDATE_DELAY) {
        //pass a async signal to the UI thread
        clientmodel->setCacheTip(pIndex);
        clientmodel->setCacheImporting(fImporting);
        clientmodel->setCacheReindexing(fReindex);
        clientmodel->setCacheInitialSync(initialSync);
        Q_EMIT clientmodel->numBlocksChanged(pIndex->nHeight);
        nLastBlockTipUpdateNotification = now;
    }
}

// Handlers for core signals
static void ShowProgress(ClientModel* clientmodel, const std::string& title, int nProgress)
{
    // emits signal "showProgress"
    QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection,
        Q_ARG(QString, QString::fromStdString(title)),
        Q_ARG(int, nProgress));
}

static void NotifyNumConnectionsChanged(ClientModel* clientmodel, int newNumConnections)
{
    // Too noisy: qDebug() << "NotifyNumConnectionsChanged : " + QString::number(newNumConnections);
    QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection,
        Q_ARG(int, newNumConnections));
}

static void NotifyAlertChanged(ClientModel* clientmodel)
{
    qDebug() << "NotifyAlertChanged";
    QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection);
}

static void BannedListChanged(ClientModel *clientmodel)
{
    qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__);
    QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection);
}

void ClientModel::subscribeToCoreSignals()
{
    // Connect signals to client
    uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
    uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this));
    uiInterface.BannedListChanged.connect(boost::bind(BannedListChanged, this));
    uiInterface.NotifyBlockTip.connect(boost::bind(BlockTipChanged, this, _1, _2));
}

void ClientModel::unsubscribeFromCoreSignals()
{
    // Disconnect signals from client
    uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
    uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this));
    uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this));
    uiInterface.NotifyBlockTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2));
}

bool ClientModel::getTorInfo(std::string& ip_port) const
{
    proxyType onion;
    if (GetProxy((Network) 3, onion) && IsReachable((Network) 3)) {
        {
            LOCK(cs_mapLocalHost);
            for (const std::pair<const CNetAddr, LocalServiceInfo>& item : mapLocalHost) {
                if (item.first.IsTor()) {
                     CService addrOnion = CService(item.first.ToString(), item.second.nPort);
                     ip_port = addrOnion.ToStringIPPort();
                     return true;
                }
            }
        }
    }
    return false;
}
<commit_msg>[GUI] Update MNs GUI count every 40 seconds.<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2019 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "clientmodel.h"

#include "bantablemodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "peertablemodel.h"

#include "chainparams.h"
#include "checkpoints.h"
#include "clientversion.h"
#include "main.h"
#include "masternode-sync.h"
#include "masternodeman.h"
#include "net.h"
#include "netbase.h"
#include "guiinterface.h"
#include "util.h"

#include <stdint.h>

#include <QDateTime>
#include <QDebug>
#include <QTimer>

static const int64_t nClientStartupTime = GetTime();
// Last tip update notification
static int64_t nLastBlockTipUpdateNotification = 0;

ClientModel::ClientModel(OptionsModel* optionsModel, QObject* parent) : QObject(parent),
                                                                        optionsModel(optionsModel),
                                                                        peerTableModel(0),
                                                                        banTableModel(0),
                                                                        cacheTip(nullptr),
                                                                        cachedMasternodeCountString(""),
                                                                        cachedReindexing(0), cachedImporting(0),
                                                                        numBlocksAtStartup(-1), pollTimer(0)
{
    peerTableModel = new PeerTableModel(this);
    banTableModel = new BanTableModel(this);
    pollTimer = new QTimer(this);
    connect(pollTimer, &QTimer::timeout, this, &ClientModel::updateTimer);
    pollTimer->start(MODEL_UPDATE_DELAY);

    pollMnTimer = new QTimer(this);
    connect(pollMnTimer, &QTimer::timeout, this, &ClientModel::updateMnTimer);
    // no need to update as frequent as data for balances/txes/blocks
    pollMnTimer->start(MODEL_UPDATE_DELAY * 40);

    subscribeToCoreSignals();
}

ClientModel::~ClientModel()
{
    unsubscribeFromCoreSignals();
}

int ClientModel::getNumConnections(unsigned int flags) const
{
    LOCK(cs_vNodes);
    if (flags == CONNECTIONS_ALL) // Shortcut if we want total
        return vNodes.size();

    int nNum = 0;
    for (CNode* pnode : vNodes)
        if (flags & (pnode->fInbound ? CONNECTIONS_IN : CONNECTIONS_OUT))
            nNum++;

    return nNum;
}

QString ClientModel::getMasternodeCountString() const
{
    int ipv4 = 0, ipv6 = 0, onion = 0;
    mnodeman.CountNetworks(ActiveProtocol(), ipv4, ipv6, onion);
    int nUnknown = mnodeman.size() - ipv4 - ipv6 - onion;
    if(nUnknown < 0) nUnknown = 0;
    return tr("Total: %1 (IPv4: %2 / IPv6: %3 / Tor: %4 / Unknown: %5)").arg(QString::number((int)mnodeman.size())).arg(QString::number((int)ipv4)).arg(QString::number((int)ipv6)).arg(QString::number((int)onion)).arg(QString::number((int)nUnknown));
}

int ClientModel::getNumBlocks()
{
    if (!cacheTip) {
        cacheTip = WITH_LOCK(cs_main, return chainActive.Tip(););
    }

    return cacheTip ? cacheTip->nHeight : 0;
}

int ClientModel::getNumBlocksAtStartup()
{
    if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks();
    return numBlocksAtStartup;
}

quint64 ClientModel::getTotalBytesRecv() const
{
    return CNode::GetTotalBytesRecv();
}

quint64 ClientModel::getTotalBytesSent() const
{
    return CNode::GetTotalBytesSent();
}

QDateTime ClientModel::getLastBlockDate() const
{
    const int nTime = (cacheTip == nullptr ? Params().GenesisBlock().GetBlockTime() : cacheTip->GetBlockTime());
    return QDateTime::fromTime_t(nTime);
}

QString ClientModel::getLastBlockHash() const
{
    const uint256& nHash = (cacheTip == nullptr ? Params().GenesisBlock().GetHash() : cacheTip->GetBlockHash());
    return QString::fromStdString(nHash.GetHex());
}

double ClientModel::getVerificationProgress() const
{
    return Checkpoints::GuessVerificationProgress(cacheTip);
}

void ClientModel::updateTimer()
{
    // Get required lock upfront. This avoids the GUI from getting stuck on
    // periodical polls if the core is holding the locks for a longer time -
    // for example, during a wallet rescan.
    Q_EMIT bytesChanged(getTotalBytesRecv(), getTotalBytesSent());
}

void ClientModel::updateMnTimer()
{
    // Get required lock upfront. This avoids the GUI from getting stuck on
    // periodical polls if the core is holding the locks for a longer time -
    // for example, during a wallet rescan.
    TRY_LOCK(cs_main, lockMain);
    if (!lockMain)
        return;
    QString newMasternodeCountString = getMasternodeCountString();

    if (cachedMasternodeCountString != newMasternodeCountString) {
        cachedMasternodeCountString = newMasternodeCountString;

        Q_EMIT strMasternodesChanged(cachedMasternodeCountString);
    }
}

void ClientModel::updateNumConnections(int numConnections)
{
    Q_EMIT numConnectionsChanged(numConnections);
}

void ClientModel::updateAlert()
{
    Q_EMIT alertsChanged(getStatusBarWarnings());
}

bool ClientModel::inInitialBlockDownload() const
{
    return cachedInitialSync;
}

enum BlockSource ClientModel::getBlockSource() const
{
    if (fReindex)
        return BLOCK_SOURCE_REINDEX;
    else if (fImporting)
        return BLOCK_SOURCE_DISK;
    else if (getNumConnections() > 0)
        return BLOCK_SOURCE_NETWORK;

    return BLOCK_SOURCE_NONE;
}

QString ClientModel::getStatusBarWarnings() const
{
    return QString::fromStdString(GetWarnings("statusbar"));
}

OptionsModel* ClientModel::getOptionsModel()
{
    return optionsModel;
}

PeerTableModel* ClientModel::getPeerTableModel()
{
    return peerTableModel;
}

BanTableModel *ClientModel::getBanTableModel()
{
    return banTableModel;
}

QString ClientModel::formatFullVersion() const
{
    return QString::fromStdString(FormatFullVersion());
}

QString ClientModel::formatBuildDate() const
{
    return QString::fromStdString(CLIENT_DATE);
}

bool ClientModel::isReleaseVersion() const
{
    return CLIENT_VERSION_IS_RELEASE;
}

QString ClientModel::clientName() const
{
    return QString::fromStdString(CLIENT_NAME);
}

QString ClientModel::formatClientStartupTime() const
{
    return QDateTime::fromTime_t(nClientStartupTime).toString();
}

QString ClientModel::dataDir() const
{
    return GUIUtil::boostPathToQString(GetDataDir());
}

void ClientModel::updateBanlist()
{
    banTableModel->refresh();
}

static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CBlockIndex *pIndex)
{
    // lock free async UI updates in case we have a new block tip
    // during initial sync, only update the UI if the last update
    // was > 1000ms (MODEL_UPDATE_DELAY) ago
    int64_t now = 0;
    if (initialSync)
        now = GetTimeMillis();

    // if we are in-sync, update the UI regardless of last update time
    if (!initialSync || now - nLastBlockTipUpdateNotification > MODEL_UPDATE_DELAY) {
        //pass a async signal to the UI thread
        clientmodel->setCacheTip(pIndex);
        clientmodel->setCacheImporting(fImporting);
        clientmodel->setCacheReindexing(fReindex);
        clientmodel->setCacheInitialSync(initialSync);
        Q_EMIT clientmodel->numBlocksChanged(pIndex->nHeight);
        nLastBlockTipUpdateNotification = now;
    }
}

// Handlers for core signals
static void ShowProgress(ClientModel* clientmodel, const std::string& title, int nProgress)
{
    // emits signal "showProgress"
    QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection,
        Q_ARG(QString, QString::fromStdString(title)),
        Q_ARG(int, nProgress));
}

static void NotifyNumConnectionsChanged(ClientModel* clientmodel, int newNumConnections)
{
    // Too noisy: qDebug() << "NotifyNumConnectionsChanged : " + QString::number(newNumConnections);
    QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection,
        Q_ARG(int, newNumConnections));
}

static void NotifyAlertChanged(ClientModel* clientmodel)
{
    qDebug() << "NotifyAlertChanged";
    QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection);
}

static void BannedListChanged(ClientModel *clientmodel)
{
    qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__);
    QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection);
}

void ClientModel::subscribeToCoreSignals()
{
    // Connect signals to client
    uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
    uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this));
    uiInterface.BannedListChanged.connect(boost::bind(BannedListChanged, this));
    uiInterface.NotifyBlockTip.connect(boost::bind(BlockTipChanged, this, _1, _2));
}

void ClientModel::unsubscribeFromCoreSignals()
{
    // Disconnect signals from client
    uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
    uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1));
    uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this));
    uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this));
    uiInterface.NotifyBlockTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2));
}

bool ClientModel::getTorInfo(std::string& ip_port) const
{
    proxyType onion;
    if (GetProxy((Network) 3, onion) && IsReachable((Network) 3)) {
        {
            LOCK(cs_mapLocalHost);
            for (const std::pair<const CNetAddr, LocalServiceInfo>& item : mapLocalHost) {
                if (item.first.IsTor()) {
                     CService addrOnion = CService(item.first.ToString(), item.second.nPort);
                     ip_port = addrOnion.ToStringIPPort();
                     return true;
                }
            }
        }
    }
    return false;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/version.hpp>
#if defined(WIN32) && BOOST_VERSION == 104900
#define BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME
#define BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME
#endif

#include "qtipcserver.h"
#include "guiconstants.h"
#include "ui_interface.h"
#include "util.h"

#include <boost/algorithm/string/predicate.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/version.hpp>

#if defined(WIN32) && (!defined(BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME) || !defined(BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME) || BOOST_VERSION < 104900)
#warning Compiling without BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME and BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME uncommented in boost/interprocess/detail/tmp_dir_helpers.hpp or using a boost version before 1.49 may have unintended results see svn.boost.org/trac/boost/ticket/5392
#endif

using namespace boost;
using namespace boost::interprocess;
using namespace boost::posix_time;

#if defined MAC_OSX || defined __FreeBSD__
// URI handling not implemented on OSX yet

void ipcScanRelay(int argc, char *argv[]) { }
void ipcInit(int argc, char *argv[]) { }

#else

static void ipcThread2(void* pArg);

static bool ipcScanCmd(int argc, char *argv[], bool fRelay)
{
    // Check for URI in argv
    bool fSent = false;
    for (int i = 1; i < argc; i++)
    {
        if (boost::algorithm::istarts_with(argv[i], "FuelCoin:"))
        {
            const char *strURI = argv[i];
            try {
                boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
                if (mq.try_send(strURI, strlen(strURI), 0))
                    fSent = true;
                else if (fRelay)
                    break;
            }
            catch (boost::interprocess::interprocess_exception &ex) {
                // don't log the "file not found" exception, because that's normal for
                // the first start of the first instance
                if (ex.get_error_code() != boost::interprocess::not_found_error || !fRelay)
                {
                    printf("main() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what());
                    break;
                }
            }
        }
    }
    return fSent;
}

void ipcScanRelay(int argc, char *argv[])
{
    if (ipcScanCmd(argc, argv, true))
        exit(0);
}

static void ipcThread(void* pArg)
{
    // Make this thread recognisable as the GUI-IPC thread
    RenameThread("FuelCoin-gui-ipc");

    try
    {
        ipcThread2(pArg);
    }
    catch (std::exception& e) {
        PrintExceptionContinue(&e, "ipcThread()");
    } catch (...) {
        PrintExceptionContinue(NULL, "ipcThread()");
    }
    printf("ipcThread exited\n");
}

static void ipcThread2(void* pArg)
{
    printf("ipcThread started\n");

    message_queue* mq = (message_queue*)pArg;
    char buffer[MAX_URI_LENGTH + 1] = "";
    size_t nSize = 0;
    unsigned int nPriority = 0;

    while (true)
    {
        ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(100);
        if (mq->timed_receive(&buffer, sizeof(buffer), nSize, nPriority, d))
        {
            uiInterface.ThreadSafeHandleURI(std::string(buffer, nSize));
            MilliSleep(1000);
        }

        if (fShutdown)
            break;
    }

    // Remove message queue
    message_queue::remove(BITCOINURI_QUEUE_NAME);
    // Cleanup allocated memory
    delete mq;
}

void ipcInit(int argc, char *argv[])
{
    message_queue* mq = NULL;
    char buffer[MAX_URI_LENGTH + 1] = "";
    size_t nSize = 0;
    unsigned int nPriority = 0;

    try {
        mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, MAX_URI_LENGTH);

        // Make sure we don't lose any bitcoin: URIs
        for (int i = 0; i < 2; i++)
        {
            ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(1);
            if (mq->timed_receive(&buffer, sizeof(buffer), nSize, nPriority, d))
            {
                uiInterface.ThreadSafeHandleURI(std::string(buffer, nSize));
            }
            else
                break;
        }

        // Make sure only one bitcoin instance is listening
        message_queue::remove(BITCOINURI_QUEUE_NAME);
        delete mq;

        mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, MAX_URI_LENGTH);
    }
    catch (interprocess_exception &ex) {
        printf("ipcInit() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what());
        return;
    }

    if (!NewThread(ipcThread, mq))
    {
        delete mq;
        return;
    }

    ipcScanCmd(argc, argv, false);
}

#endif
<commit_msg>Update qtipcserver.cpp<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <boost/version.hpp>
#if defined(WIN32) && BOOST_VERSION == 104900
#define BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME
#define BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME
#endif

#include "qtipcserver.h"
#include "guiconstants.h"
#include "ui_interface.h"
#include "util.h"

#include <boost/algorithm/string/predicate.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/version.hpp>

#if defined(WIN32) && (!defined(BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME) || !defined(BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME) || BOOST_VERSION < 104900)
#warning Compiling without BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME and BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME uncommented in boost/interprocess/detail/tmp_dir_helpers.hpp or using a boost version before 1.49 may have unintended results see svn.boost.org/trac/boost/ticket/5392
#endif

using namespace boost;
using namespace boost::interprocess;
using namespace boost::posix_time;

#if defined MAC_OSX || defined __FreeBSD__
// URI handling not implemented on OSX yet

void ipcScanRelay(int argc, char *argv[]) { }
void ipcInit(int argc, char *argv[]) { }

#else

static void ipcThread2(void* pArg);

static bool ipcScanCmd(int argc, char *argv[], bool fRelay)
{
    // Check for URI in argv
    bool fSent = false;
    for (int i = 1; i < argc; i++)
    {
        if (boost::algorithm::istarts_with(argv[i], "Fuelcoin:"))
        {
            const char *strURI = argv[i];
            try {
                boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
                if (mq.try_send(strURI, strlen(strURI), 0))
                    fSent = true;
                else if (fRelay)
                    break;
            }
            catch (boost::interprocess::interprocess_exception &ex) {
                // don't log the "file not found" exception, because that's normal for
                // the first start of the first instance
                if (ex.get_error_code() != boost::interprocess::not_found_error || !fRelay)
                {
                    printf("main() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what());
                    break;
                }
            }
        }
    }
    return fSent;
}

void ipcScanRelay(int argc, char *argv[])
{
    if (ipcScanCmd(argc, argv, true))
        exit(0);
}

static void ipcThread(void* pArg)
{
    // Make this thread recognisable as the GUI-IPC thread
    RenameThread("Fuelcoin-gui-ipc");

    try
    {
        ipcThread2(pArg);
    }
    catch (std::exception& e) {
        PrintExceptionContinue(&e, "ipcThread()");
    } catch (...) {
        PrintExceptionContinue(NULL, "ipcThread()");
    }
    printf("ipcThread exited\n");
}

static void ipcThread2(void* pArg)
{
    printf("ipcThread started\n");

    message_queue* mq = (message_queue*)pArg;
    char buffer[MAX_URI_LENGTH + 1] = "";
    size_t nSize = 0;
    unsigned int nPriority = 0;

    while (true)
    {
        ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(100);
        if (mq->timed_receive(&buffer, sizeof(buffer), nSize, nPriority, d))
        {
            uiInterface.ThreadSafeHandleURI(std::string(buffer, nSize));
            MilliSleep(1000);
        }

        if (fShutdown)
            break;
    }

    // Remove message queue
    message_queue::remove(BITCOINURI_QUEUE_NAME);
    // Cleanup allocated memory
    delete mq;
}

void ipcInit(int argc, char *argv[])
{
    message_queue* mq = NULL;
    char buffer[MAX_URI_LENGTH + 1] = "";
    size_t nSize = 0;
    unsigned int nPriority = 0;

    try {
        mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, MAX_URI_LENGTH);

        // Make sure we don't lose any bitcoin: URIs
        for (int i = 0; i < 2; i++)
        {
            ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(1);
            if (mq->timed_receive(&buffer, sizeof(buffer), nSize, nPriority, d))
            {
                uiInterface.ThreadSafeHandleURI(std::string(buffer, nSize));
            }
            else
                break;
        }

        // Make sure only one bitcoin instance is listening
        message_queue::remove(BITCOINURI_QUEUE_NAME);
        delete mq;

        mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, MAX_URI_LENGTH);
    }
    catch (interprocess_exception &ex) {
        printf("ipcInit() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what());
        return;
    }

    if (!NewThread(ipcThread, mq))
    {
        delete mq;
        return;
    }

    ipcScanCmd(argc, argv, false);
}

#endif
<|endoftext|>


<commit_before>#include "duisettingsmainpage.h"

#include <QtDebug>

#include <duilinearlayout.h>
#include <duilabel.h>
#include <duipannableviewport.h>

#include "duimaincategory.h"
#include "duidescriptioncomponent.h"
#include "pages.h"

static const QString componentTexts[] = {
    DuiSettingsMainPage::tr("Personalization"), /* <- title */
    DuiSettingsMainPage::tr("Personalize the device with e.g. "
                            "profile, themes, fonts, "
                            "home screen, language etc."),
    DuiSettingsMainPage::tr("Connectivity"), /* <- title */
    DuiSettingsMainPage::tr("Adjust connections of e.g. "
                            ""
                            "Internet connection, Bluetooth, GPS etc."),
    DuiSettingsMainPage::tr("Display"), /* <- title */
    DuiSettingsMainPage::tr("Adjust display appearance with e.g. "
                            "Light "
                            "sensor, brightness etc."),
    DuiSettingsMainPage::tr("Sound"), /* <- title */
    DuiSettingsMainPage::tr("Adjust tones for e.g. "
                            ""
                            "Message alert, email "
                            "alert etc."),
    DuiSettingsMainPage::tr("Call"), /* <- title */
    DuiSettingsMainPage::tr("Adjust settings with e.g. "
                            ""
                            "call waiting, automatic redial etc."),
    DuiSettingsMainPage::tr("Date & Time"), /* <- title */
    DuiSettingsMainPage::tr("Adjust Date & Time with e.g. "
                            ""
                            "time format and timezone."),
    DuiSettingsMainPage::tr("Security"), /* <- title */
    DuiSettingsMainPage::tr("Adjust phone security settings with e.g. "
                            "passcode, privacy lock"
                            " etc."),
    DuiSettingsMainPage::tr("Device system"), /* <- title */
    DuiSettingsMainPage::tr("View "
                            "memory information and "
                            "backup / restore "
                            "data."),
    DuiSettingsMainPage::tr("Account"), /* <- title */
    DuiSettingsMainPage::tr("Create your own service accounts in e.g. "
                            "Ovi, Google, Yahooo "
                            "etc. and adjust settings for "
                            "existing accounts,"),
    DuiSettingsMainPage::tr("Application"), /* <- title */
    DuiSettingsMainPage::tr("Adjust settings for each application e.g. "
                            "Browser, Messaging, "
                            "Calendar etc."),
    QString()
};

static const QString resetSettingsTitle = DuiSettingsMainPage::tr(
                                                "Reset settings");
static const QString resetSettingsDescription = DuiSettingsMainPage::tr(
                                  "Reset network settings; Delete all media "
                                  "and data or reset all settings without "
                                  "deleting all media and data.");

static const QString settingsTitle = DuiSettingsMainPage::tr("Settings");

DuiSettingsMainPage::DuiSettingsMainPage()
{
}

void DuiSettingsMainPage::createContent()
{
    DuiSettingsPage::createContent();
    DuiLinearLayout* mainLayout = new DuiLinearLayout(Qt::Vertical);

    DuiLabel* title = new DuiLabel(settingsTitle);
    title->setAlignment(Qt::AlignCenter);
    title->setMaximumHeight(30);
    mainLayout->addItem(title);

    m_Category = new DuiMainCategory(settingsTitle);
    Q_ASSERT (sizeof (componentTexts) / sizeof(QString) % 4 == 1);
    for (int i=0; true; i+=4){
        QString title = componentTexts[i];
        if (title.isNull()) break;

        DuiDescriptionComponent *compo1 = new DuiDescriptionComponent(
                m_Category, title);
        compo1->setDescription(componentTexts[i+1]);
        compo1->setSubPageId(Pages::ACCOUNTS);
        connect(compo1, SIGNAL(openSubPage(Pages::Id)),
                this, SIGNAL(openSubPage(Pages::Id)));

        title = componentTexts[i+2];
        DuiDescriptionComponent *compo2 = new DuiDescriptionComponent(
                m_Category, title);
        compo2->setDescription(componentTexts[i+3]);
        m_Category->add(compo1, compo2);
    }

    // reset settings:
    DuiDescriptionComponent *resetSettings = new DuiDescriptionComponent(
            m_Category, resetSettingsTitle);
    resetSettings->setDescription(resetSettingsDescription);
    resetSettings->setFullRowSize ();
    m_Category->add(resetSettings);

    connect (m_DesktopViewport,
             SIGNAL(sizeChanged(const QSizeF &, const QSizeF &)),
             this, SLOT(onSizeChanged(const QSizeF &, const QSizeF &)));
    m_DesktopViewport->setWidget(m_Category);

    mainLayout->addItem(m_DesktopViewport);

    setLayout(mainLayout);
}

/* This function is responsible for keeping the width of the panned widget
   and its viewport the same. */
void DuiSettingsMainPage::onSizeChanged(const QSizeF & pannedWidgetSize,
                                    const QSizeF & pannableViewportSize)
{
    int width = pannableViewportSize.width();
    if (pannedWidgetSize.width() != width){
        m_Category->setMinimumSize(width, -1);
        m_Category->setMaximumSize(width, -1);
    }
}

<commit_msg>Title is restored.<commit_after>#include "duisettingsmainpage.h"

#include <QtDebug>

#include <duilinearlayout.h>
#include <duilabel.h>
#include <duipannableviewport.h>

#include "duimaincategory.h"
#include "duidescriptioncomponent.h"
#include "pages.h"

static const QString componentTexts[] = {
    DuiSettingsMainPage::tr("Personalization"), /* <- title */
    DuiSettingsMainPage::tr("
Personalize the device with e.g. "
                            "profile, themes, fonts, "
                            "home screen, language etc.
"),
    DuiSettingsMainPage::tr("Connectivity"), /* <- title */
    DuiSettingsMainPage::tr("
Adjust connections of e.g. "
                            ""
                            "Internet connection, Bluetooth, GPS etc.
"),
    DuiSettingsMainPage::tr("Display"), /* <- title */
    DuiSettingsMainPage::tr("
Adjust display appearance with e.g. "
                            "Light "
                            "sensor, brightness etc.
"),
    DuiSettingsMainPage::tr("Sound"), /* <- title */
    DuiSettingsMainPage::tr("
Adjust tones for e.g. "
                            ""
                            "Message alert, email "
                            "alert etc.
"),
    DuiSettingsMainPage::tr("Call"), /* <- title */
    DuiSettingsMainPage::tr("
Adjust settings with e.g. "
                            ""
                            "call waiting, automatic redial etc.
"),
    DuiSettingsMainPage::tr("Date & Time"), /* <- title */
    DuiSettingsMainPage::tr("
Adjust Date & Time with e.g. "
                            ""
                            "time format and timezone.
"),
    DuiSettingsMainPage::tr("Security"), /* <- title */
    DuiSettingsMainPage::tr("
Adjust phone security settings with e.g. "
                            "passcode, privacy lock"
                            " etc.
"),
    DuiSettingsMainPage::tr("Device system"), /* <- title */
    DuiSettingsMainPage::tr("
View "
                            "memory information and "
                            "backup / restore "
                            "data.
"),
    DuiSettingsMainPage::tr("Account"), /* <- title */
    DuiSettingsMainPage::tr("
Create your own service accounts in e.g. "
                            "Ovi, Google, Yahooo "
                            "etc. and adjust settings for "
                            "existing accounts,
"),
    DuiSettingsMainPage::tr("Application"), /* <- title */
    DuiSettingsMainPage::tr("
Adjust settings for each application e.g. "
                            "Browser, Messaging, "
                            "Calendar etc.
"),
    QString()
};

static const QString resetSettingsTitle = DuiSettingsMainPage::tr(
                                                "Reset settings");
static const QString resetSettingsDescription = DuiSettingsMainPage::tr(
                                  "Reset network settings; Delete all media "
                                  "and data or reset all settings without "
                                  "deleting all media and data.");

static const QString settingsTitle = DuiSettingsMainPage::tr("Settings");

DuiSettingsMainPage::DuiSettingsMainPage()
{
}

void DuiSettingsMainPage::createContent()
{
    DuiSettingsPage::createContent();
    DuiLinearLayout* mainLayout = new DuiLinearLayout(Qt::Vertical);

    DuiLabel* title = new DuiLabel();
    title->setText(settingsTitle);
    title->setAlignment(Qt::AlignCenter);
    title->setMaximumHeight(30);
    mainLayout->addItem(title);

    m_Category = new DuiMainCategory(settingsTitle);
    Q_ASSERT (sizeof (componentTexts) / sizeof(QString) % 4 == 1);
    for (int i=0; true; i+=4){
        QString title = componentTexts[i];
        if (title.isNull()) break;

        DuiDescriptionComponent *compo1 = new DuiDescriptionComponent(
                m_Category, title);
        compo1->setDescription(componentTexts[i+1]);
        compo1->setSubPageId(Pages::ACCOUNTS);
        connect(compo1, SIGNAL(openSubPage(Pages::Id)),
                this, SIGNAL(openSubPage(Pages::Id)));

        title = componentTexts[i+2];
        DuiDescriptionComponent *compo2 = new DuiDescriptionComponent(
                m_Category, title);
        compo2->setDescription(componentTexts[i+3]);
        m_Category->add(compo1, compo2);
    }

    // reset settings:
    DuiDescriptionComponent *resetSettings = new DuiDescriptionComponent(
            m_Category, resetSettingsTitle);
    resetSettings->setDescription(resetSettingsDescription);
    resetSettings->setFullRowSize ();
    m_Category->add(resetSettings);

    connect (m_DesktopViewport,
             SIGNAL(sizeChanged(const QSizeF &, const QSizeF &)),
             this, SLOT(onSizeChanged(const QSizeF &, const QSizeF &)));
    m_DesktopViewport->setWidget(m_Category);

    mainLayout->addItem(m_DesktopViewport);

    setLayout(mainLayout);
}

/* This function is responsible for keeping the width of the panned widget
   and its viewport the same. */
void DuiSettingsMainPage::onSizeChanged(const QSizeF & pannedWidgetSize,
                                    const QSizeF & pannableViewportSize)
{
    int width = pannableViewportSize.width();
    if (pannedWidgetSize.width() != width){
        m_Category->setMinimumSize(width, -1);
        m_Category->setMaximumSize(width, -1);
    }
}

<|endoftext|>