<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "decode.hxx"

struct GIFLZWTableEntry
{
    GIFLZWTableEntry*   pPrev;
    GIFLZWTableEntry*   pFirst;
    sal_uInt8               nData;
};

GIFLZWDecompressor::GIFLZWDecompressor(sal_uInt8 cDataSize)
    : pBlockBuf(NULL)
    , nInputBitsBuf(0)
    , nOutBufDataLen(0)
    , nInputBitsBufSize(0)
    , bEOIFound(false)
    , nDataSize(cDataSize)
    , nBlockBufSize(0)
    , nBlockBufPos(0)
{
    pOutBuf = new sal_uInt8[ 4096 ];

    nClearCode = 1 << nDataSize;
    nEOICode = nClearCode + 1;
    nTableSize = nEOICode + 1;
    nCodeSize = nDataSize + 1;
    nOldCode = 0xffff;
    pOutBufData = pOutBuf + 4096;

    pTable = new GIFLZWTableEntry[ 4098 ];

    for (sal_uInt16 i = 0; i < nTableSize; ++i)
    {
        pTable[i].pPrev = NULL;
        pTable[i].pFirst = pTable + i;
        pTable[i].nData = (sal_uInt8) i;
    }

    memset(pTable + nTableSize, 0, sizeof(GIFLZWTableEntry) * (4098 - nTableSize));
}

GIFLZWDecompressor::~GIFLZWDecompressor()
{
    delete[] pOutBuf;
    delete[] pTable;
}

HPBYTE GIFLZWDecompressor::DecompressBlock( HPBYTE pSrc, sal_uInt8 cBufSize,
                                            sal_uLong& rCount, bool& rEOI )
{
    sal_uLong   nTargetSize = 4096;
    sal_uLong   nCount = 0;
    HPBYTE  pTarget = static_cast<HPBYTE>(rtl_allocateMemory( nTargetSize ));
    HPBYTE  pTmpTarget = pTarget;

    nBlockBufSize = cBufSize;
    nBlockBufPos = 0;
    pBlockBuf = pSrc;

    while( ProcessOneCode() )
    {
        nCount += nOutBufDataLen;

        if( nCount > nTargetSize )
        {
            sal_uLong   nNewSize = nTargetSize << 1;
            sal_uLong   nOffset = pTmpTarget - pTarget;
            HPBYTE  pTmp = static_cast<HPBYTE>(rtl_allocateMemory( nNewSize ));

            memcpy( pTmp, pTarget, nTargetSize );
            rtl_freeMemory( pTarget );

            nTargetSize = nNewSize;
            pTmpTarget = ( pTarget = pTmp ) + nOffset;
        }

        memcpy( pTmpTarget, pOutBufData, nOutBufDataLen );
        pTmpTarget += nOutBufDataLen;
        pOutBufData += nOutBufDataLen;
        nOutBufDataLen = 0;

        if ( bEOIFound )
            break;
    }

    rCount = nCount;
    rEOI = bEOIFound;

    return pTarget;
}

bool GIFLZWDecompressor::AddToTable( sal_uInt16 nPrevCode, sal_uInt16 nCodeFirstData )
{
    GIFLZWTableEntry* pE;

    if( nTableSize < 4096 )
    {
        pE = pTable + nTableSize;
        pE->pPrev = pTable + nPrevCode;
        pE->pFirst = pE->pPrev->pFirst;
        GIFLZWTableEntry *pEntry = pTable[nCodeFirstData].pFirst;
        if (!pEntry)
            return false;
        pE->nData = pEntry->nData;
        nTableSize++;

        if ( ( nTableSize == (sal_uInt16) (1 << nCodeSize) ) && ( nTableSize < 4096 ) )
            nCodeSize++;
    }
    return true;
}

bool GIFLZWDecompressor::ProcessOneCode()
{
    GIFLZWTableEntry*   pE;
    sal_uInt16              nCode;
    bool                bRet = false;
    bool                bEndOfBlock = false;

    while( nInputBitsBufSize < nCodeSize )
    {
        if( nBlockBufPos >= nBlockBufSize )
        {
            bEndOfBlock = true;
            break;
        }

        nInputBitsBuf |= ( (sal_uLong) pBlockBuf[ nBlockBufPos++ ] ) << nInputBitsBufSize;
        nInputBitsBufSize += 8;
    }

    if ( !bEndOfBlock )
    {
        // fetch code from input buffer
        nCode = sal::static_int_cast< sal_uInt16 >(
            ( (sal_uInt16) nInputBitsBuf ) & ( ~( 0xffff << nCodeSize ) ));
        nInputBitsBuf >>= nCodeSize;
        nInputBitsBufSize = nInputBitsBufSize - nCodeSize;

        if ( nCode < nClearCode )
        {
            bool bOk = true;
            if ( nOldCode != 0xffff )
                bOk = AddToTable(nOldCode, nCode);
            if (!bOk)
                return false;
        }
        else if ( ( nCode > nEOICode ) && ( nCode <= nTableSize ) )
        {
            if ( nOldCode != 0xffff )
            {
                bool bOk;
                if ( nCode == nTableSize )
                    bOk = AddToTable( nOldCode, nOldCode );
                else
                    bOk = AddToTable( nOldCode, nCode );
                if (!bOk)
                    return false;
            }
        }
        else
        {
            if ( nCode == nClearCode )
            {
                nTableSize = nEOICode + 1;
                nCodeSize = nDataSize + 1;
                nOldCode = 0xffff;
                nOutBufDataLen = 0;
            }
            else
                bEOIFound = true;

            return true;
        }

        nOldCode = nCode;

        if (nCode > 4096)
            return false;

        // write character(/-sequence) of code nCode in the output buffer:
        pE = pTable + nCode;
        do
        {
            if (pOutBufData == pOutBuf) //can't go back past start
                return false;
            nOutBufDataLen++;
            *(--pOutBufData) = pE->nData;
            pE = pE->pPrev;
        }
        while( pE );

        bRet = true;
    }

    return bRet;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>use same limit in ProcessOneCode as AddToTable<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "decode.hxx"

struct GIFLZWTableEntry
{
    GIFLZWTableEntry*   pPrev;
    GIFLZWTableEntry*   pFirst;
    sal_uInt8               nData;
};

GIFLZWDecompressor::GIFLZWDecompressor(sal_uInt8 cDataSize)
    : pBlockBuf(NULL)
    , nInputBitsBuf(0)
    , nOutBufDataLen(0)
    , nInputBitsBufSize(0)
    , bEOIFound(false)
    , nDataSize(cDataSize)
    , nBlockBufSize(0)
    , nBlockBufPos(0)
{
    pOutBuf = new sal_uInt8[ 4096 ];

    nClearCode = 1 << nDataSize;
    nEOICode = nClearCode + 1;
    nTableSize = nEOICode + 1;
    nCodeSize = nDataSize + 1;
    nOldCode = 0xffff;
    pOutBufData = pOutBuf + 4096;

    pTable = new GIFLZWTableEntry[ 4098 ];

    for (sal_uInt16 i = 0; i < nTableSize; ++i)
    {
        pTable[i].pPrev = NULL;
        pTable[i].pFirst = pTable + i;
        pTable[i].nData = (sal_uInt8) i;
    }

    memset(pTable + nTableSize, 0, sizeof(GIFLZWTableEntry) * (4098 - nTableSize));
}

GIFLZWDecompressor::~GIFLZWDecompressor()
{
    delete[] pOutBuf;
    delete[] pTable;
}

HPBYTE GIFLZWDecompressor::DecompressBlock( HPBYTE pSrc, sal_uInt8 cBufSize,
                                            sal_uLong& rCount, bool& rEOI )
{
    sal_uLong   nTargetSize = 4096;
    sal_uLong   nCount = 0;
    HPBYTE  pTarget = static_cast<HPBYTE>(rtl_allocateMemory( nTargetSize ));
    HPBYTE  pTmpTarget = pTarget;

    nBlockBufSize = cBufSize;
    nBlockBufPos = 0;
    pBlockBuf = pSrc;

    while( ProcessOneCode() )
    {
        nCount += nOutBufDataLen;

        if( nCount > nTargetSize )
        {
            sal_uLong   nNewSize = nTargetSize << 1;
            sal_uLong   nOffset = pTmpTarget - pTarget;
            HPBYTE  pTmp = static_cast<HPBYTE>(rtl_allocateMemory( nNewSize ));

            memcpy( pTmp, pTarget, nTargetSize );
            rtl_freeMemory( pTarget );

            nTargetSize = nNewSize;
            pTmpTarget = ( pTarget = pTmp ) + nOffset;
        }

        memcpy( pTmpTarget, pOutBufData, nOutBufDataLen );
        pTmpTarget += nOutBufDataLen;
        pOutBufData += nOutBufDataLen;
        nOutBufDataLen = 0;

        if ( bEOIFound )
            break;
    }

    rCount = nCount;
    rEOI = bEOIFound;

    return pTarget;
}

bool GIFLZWDecompressor::AddToTable( sal_uInt16 nPrevCode, sal_uInt16 nCodeFirstData )
{
    if( nTableSize < 4096 )
    {
        GIFLZWTableEntry* pE = pTable + nTableSize;
        pE->pPrev = pTable + nPrevCode;
        pE->pFirst = pE->pPrev->pFirst;
        GIFLZWTableEntry *pEntry = pTable[nCodeFirstData].pFirst;
        if (!pEntry)
            return false;
        pE->nData = pEntry->nData;
        nTableSize++;

        if ( ( nTableSize == (sal_uInt16) (1 << nCodeSize) ) && ( nTableSize < 4096 ) )
            nCodeSize++;
    }
    return true;
}

bool GIFLZWDecompressor::ProcessOneCode()
{
    sal_uInt16              nCode;
    bool                bRet = false;
    bool                bEndOfBlock = false;

    while( nInputBitsBufSize < nCodeSize )
    {
        if( nBlockBufPos >= nBlockBufSize )
        {
            bEndOfBlock = true;
            break;
        }

        nInputBitsBuf |= ( (sal_uLong) pBlockBuf[ nBlockBufPos++ ] ) << nInputBitsBufSize;
        nInputBitsBufSize += 8;
    }

    if ( !bEndOfBlock )
    {
        // fetch code from input buffer
        nCode = sal::static_int_cast< sal_uInt16 >(
            ( (sal_uInt16) nInputBitsBuf ) & ( ~( 0xffff << nCodeSize ) ));
        nInputBitsBuf >>= nCodeSize;
        nInputBitsBufSize = nInputBitsBufSize - nCodeSize;

        if ( nCode < nClearCode )
        {
            bool bOk = true;
            if ( nOldCode != 0xffff )
                bOk = AddToTable(nOldCode, nCode);
            if (!bOk)
                return false;
        }
        else if ( ( nCode > nEOICode ) && ( nCode <= nTableSize ) )
        {
            if ( nOldCode != 0xffff )
            {
                bool bOk;
                if ( nCode == nTableSize )
                    bOk = AddToTable( nOldCode, nOldCode );
                else
                    bOk = AddToTable( nOldCode, nCode );
                if (!bOk)
                    return false;
            }
        }
        else
        {
            if ( nCode == nClearCode )
            {
                nTableSize = nEOICode + 1;
                nCodeSize = nDataSize + 1;
                nOldCode = 0xffff;
                nOutBufDataLen = 0;
            }
            else
                bEOIFound = true;

            return true;
        }

        nOldCode = nCode;

        if (nCode >= 4096)
            return false;

        // write character(/-sequence) of code nCode in the output buffer:
        GIFLZWTableEntry* pE = pTable + nCode;
        do
        {
            if (pOutBufData == pOutBuf) //can't go back past start
                return false;
            nOutBufDataLen++;
            *(--pOutBufData) = pE->nData;
            pE = pE->pPrev;
        }
        while( pE );

        bRet = true;
    }

    return bRet;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include "ZambeziMiningTask.h"
#include <la-manager/AttrTokenizeWrapper.h>
#include <configuration-manager/ZambeziConfig.h>
#include <document-manager/DocumentManager.h>
#include <common/ResourceManager.h>
#include <glog/logging.h>
#include <fstream>

using namespace sf1r;

ZambeziMiningTask::ZambeziMiningTask(
    const ZambeziConfig& config,
    DocumentManager& documentManager,
    izenelib::ir::Zambezi::NewInvertedIndex& indexer)
    : config_(config)
    , documentManager_(documentManager)
    , indexer_(indexer)
    , startDocId_(0)
{
    if (config_.isDebug)
    {
        ofs_debug_.open((config_.indexFilePath + "debug").c_str(), ios::app);
    }

}

bool ZambeziMiningTask::buildDocument(docid_t docID, const Document& doc)
{
    std::vector<std::string> propNameList;
    std::vector<std::string> propValueList;
    propNameList.push_back("Title");
    propNameList.push_back("Attribute");
    propNameList.push_back("Category");
    propNameList.push_back("OriginalCategory");
    propNameList.push_back("Source");

    for (std::vector<std::string>::iterator i = propNameList.begin(); i != propNameList.end(); ++i)
    {
        std::string propValue;
        doc.getProperty(*i, propValue);
        propValueList.push_back(propValue);
    }

    std::vector<std::pair<std::string, double> > tokenScoreList;
    tokenScoreList = AttrTokenizeWrapper::get()->attr_tokenize_index(propValueList[0]
                                                                , propValueList[1]
                                                                , propValueList[2]
                                                                , propValueList[3]
                                                                , propValueList[4]);
    std::vector<std::string> tokenList;
    std::vector<uint32_t> scoreList;

    for (std::vector<std::pair<std::string, double> >::const_iterator it =
             tokenScoreList.begin(); it != tokenScoreList.end(); ++it)
    {
        tokenList.push_back(it->first);
        scoreList.push_back(uint32_t(it->second));
    }

    if (config_.isDebug)
    {
        ofs_debug_ << docID << '\t' ;
        for (unsigned int i = 0; i < tokenList.size(); ++i)
        {
            ofs_debug_ << tokenList[i] << " " << scoreList[i] << " ; ";
        }
        ofs_debug_ << std::endl;
    }

    indexer_.insertDoc(docID, tokenList, scoreList);
    return true;
}

bool ZambeziMiningTask::preProcess(int64_t timestamp)
{
    startDocId_ = indexer_.totalDocNum() + 1;
    const docid_t endDocId = documentManager_.getMaxDocId();

    LOG(INFO) << "zambezi mining task"
              << ", start docid: " << startDocId_
              << ", end docid: " << endDocId;

    return startDocId_ <= endDocId;
}

bool ZambeziMiningTask::postProcess()
{
    indexer_.flush();

    std::ofstream ofs(config_.indexFilePath.c_str(), std::ios_base::binary);
    if (! ofs)
    {
        LOG(ERROR) << "failed opening file " << config_.indexFilePath;
        return false;
    }

    try
    {
        indexer_.save(ofs);
    }
    catch (const std::exception& e)
    {
        LOG(ERROR) << "exception in writing file: " << e.what()
                   << ", path: " << config_.indexFilePath;
        return false;
    }

    return true;
}
<commit_msg>Rename zambezi debug file to "index.bin.debug".<commit_after>#include "ZambeziMiningTask.h"
#include <la-manager/AttrTokenizeWrapper.h>
#include <configuration-manager/ZambeziConfig.h>
#include <document-manager/DocumentManager.h>
#include <common/ResourceManager.h>
#include <glog/logging.h>
#include <fstream>

using namespace sf1r;

ZambeziMiningTask::ZambeziMiningTask(
    const ZambeziConfig& config,
    DocumentManager& documentManager,
    izenelib::ir::Zambezi::NewInvertedIndex& indexer)
    : config_(config)
    , documentManager_(documentManager)
    , indexer_(indexer)
    , startDocId_(0)
{
    if (config_.isDebug)
    {
        ofs_debug_.open((config_.indexFilePath + ".debug").c_str(), ios::app);
    }

}

bool ZambeziMiningTask::buildDocument(docid_t docID, const Document& doc)
{
    std::vector<std::string> propNameList;
    std::vector<std::string> propValueList;
    propNameList.push_back("Title");
    propNameList.push_back("Attribute");
    propNameList.push_back("Category");
    propNameList.push_back("OriginalCategory");
    propNameList.push_back("Source");

    for (std::vector<std::string>::iterator i = propNameList.begin(); i != propNameList.end(); ++i)
    {
        std::string propValue;
        doc.getProperty(*i, propValue);
        propValueList.push_back(propValue);
    }

    std::vector<std::pair<std::string, double> > tokenScoreList;
    tokenScoreList = AttrTokenizeWrapper::get()->attr_tokenize_index(propValueList[0]
                                                                , propValueList[1]
                                                                , propValueList[2]
                                                                , propValueList[3]
                                                                , propValueList[4]);
    std::vector<std::string> tokenList;
    std::vector<uint32_t> scoreList;

    for (std::vector<std::pair<std::string, double> >::const_iterator it =
             tokenScoreList.begin(); it != tokenScoreList.end(); ++it)
    {
        tokenList.push_back(it->first);
        scoreList.push_back(uint32_t(it->second));
    }

    if (config_.isDebug)
    {
        ofs_debug_ << docID << '\t' ;
        for (unsigned int i = 0; i < tokenList.size(); ++i)
        {
            ofs_debug_ << tokenList[i] << " " << scoreList[i] << " ; ";
        }
        ofs_debug_ << std::endl;
    }

    indexer_.insertDoc(docID, tokenList, scoreList);
    return true;
}

bool ZambeziMiningTask::preProcess(int64_t timestamp)
{
    startDocId_ = indexer_.totalDocNum() + 1;
    const docid_t endDocId = documentManager_.getMaxDocId();

    LOG(INFO) << "zambezi mining task"
              << ", start docid: " << startDocId_
              << ", end docid: " << endDocId;

    return startDocId_ <= endDocId;
}

bool ZambeziMiningTask::postProcess()
{
    indexer_.flush();

    std::ofstream ofs(config_.indexFilePath.c_str(), std::ios_base::binary);
    if (! ofs)
    {
        LOG(ERROR) << "failed opening file " << config_.indexFilePath;
        return false;
    }

    try
    {
        indexer_.save(ofs);
    }
    catch (const std::exception& e)
    {
        LOG(ERROR) << "exception in writing file: " << e.what()
                   << ", path: " << config_.indexFilePath;
        return false;
    }

    return true;
}
<|endoftext|>


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

Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers

This file is part of the Daemon GPL Source Code (Daemon Source Code).

Daemon Source Code 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 3 of the License, or
(at your option) any later version.

Daemon Source Code 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 Daemon Source Code.  If not, see <http://www.gnu.org/licenses/>.

In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code.  If not, please request a copy in writing from id Software at the address
below.

If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.

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

#include "q_shared.h"
#include "qcommon.h"

extern "C" {
    #include "findlocale/findlocale.h"
}

#include "tinygettext/log.hpp"
#include "tinygettext/tinygettext.hpp"
#include "tinygettext/file_system.hpp"

using namespace tinygettext;

// Ugly char buffer
static std::string gettextbuffer[ 4 ];
static int num = -1;

DictionaryManager trans_manager;
DictionaryManager trans_managergame;

cvar_t            *language;
cvar_t            *trans_debug;
cvar_t            *trans_encodings;
cvar_t            *trans_languages;

#ifndef BUILD_SERVER
extern cvar_t *cl_consoleKeys; // should really #include client.h
#endif

/*
====================
DaemonInputbuf

Streambuf based class that uses the engine's File I/O functions for input
====================
*/

class DaemonInputbuf : public std::streambuf
{
private:
	static const size_t BUFFER_SIZE = 8192;
	fileHandle_t fileHandle;
	char  buffer[ BUFFER_SIZE ];
	size_t  putBack;
public:
	DaemonInputbuf( const std::string& filename ) : putBack( 1 )
	{
		char *end;

		end = buffer + BUFFER_SIZE - putBack;
		setg( end, end, end );

		FS_FOpenFileRead( filename.c_str(), &fileHandle, false );
	}

	~DaemonInputbuf()
	{
		if( fileHandle )
		{
			FS_FCloseFile( fileHandle );
		}
	}

	// Unused
	int underflow()
	{
		if( gptr() < egptr() ) // buffer not exhausted
		{
			return traits_type::to_int_type( *gptr() );
		}

		if( !fileHandle )
		{
			return traits_type::eof();
		}

		char *base = buffer;
		char *start = base;

		if( eback() == base )
		{
			// Make arrangements for putback characters
			memmove( base, egptr() - putBack, putBack );
			start += putBack;
		}

		size_t n = FS_Read( start, BUFFER_SIZE - ( start - base ), fileHandle );

		if( n == 0 )
		{
			return traits_type::eof();
		}

		// Set buffer pointers
		setg( base, start, start + n );

		return traits_type::to_int_type( *gptr() );
	}
};

/*
====================
DaemonIstream

Simple istream based class that takes ownership of the streambuf
====================
*/

class DaemonIstream : public std::istream
{
public:
	DaemonIstream( const std::string& filename ) : std::istream( new DaemonInputbuf( filename ) ) {}
	~DaemonIstream()
	{
		delete rdbuf();
	}
};

/*
====================
DaemonFileSystem

Class used by tinygettext to read files and directorys
Uses the engine's File I/O functions for this purpose
====================
*/

class DaemonFileSystem : public FileSystem
{
public:
	DaemonFileSystem() {}

	std::vector<std::string> open_directory( const std::string& pathname )
	{
		int numFiles;
		char **files;
		std::vector<std::string> ret;

		files = FS_ListFiles( pathname.c_str(), nullptr, &numFiles );

		for( int i = 0; i < numFiles; i++ )
		{
			ret.push_back( std::string( files[ i ] ) );
		}

		FS_FreeFileList( files );
		return ret;
	}

	std::unique_ptr<std::istream> open_file( const std::string& filename )
	{
		return std::unique_ptr<std::istream>( new DaemonIstream( filename ) );
	}
};

/*
====================
Logging functions used by tinygettext
====================
*/

void Trans_Error( const std::string& str )
{
	Com_Printf( "^1%s^7", str.c_str() );
}

void Trans_Warning( const std::string& str )
{
	if( trans_debug->integer != 0 )
	{
		Com_Printf( "^3%s^7", str.c_str() );
	}
}

void Trans_Info( const std::string& str )
{
	if( trans_debug->integer != 0 )
	{
		Com_Printf( "%s", str.c_str() );
	}
}

/*
====================
Trans_SetLanguage

Sets a loaded language. If desired language is not found, set closest match.
If no languages are close, force English.
====================
*/

void Trans_SetLanguage( const char* lang )
{
	Language requestLang = Language::from_env( std::string( lang ) );

	// default to english
	Language bestLang = Language::from_env( "en" );
	int bestScore = Language::match( requestLang, bestLang );

	std::set<Language> langs = trans_manager.get_languages();

	for( std::set<Language>::iterator i = langs.begin(); i != langs.end(); i++ )
	{
		int score = Language::match( requestLang, *i );

		if( score > bestScore )
		{
			bestScore = score;
			bestLang = *i;
		}
	}

	// language not found, display warning
	if( bestScore == 0 )
	{
		Com_Printf( S_WARNING "Language \"%s\" (%s) not found. Default to \"English\" (en)\n",
					requestLang.get_name().empty() ? "Unknown Language" : requestLang.get_name().c_str(),
					lang );
	}

	trans_manager.set_language( bestLang );
	trans_managergame.set_language( bestLang );

	Cvar_Set( "language", bestLang.str().c_str() );

	Com_Printf( "Set language to %s" , bestLang.get_name().c_str() );
}

void Trans_UpdateLanguage_f()
{
	Trans_SetLanguage( language->string );

#ifndef BUILD_SERVER
	// update the default console keys string
	Z_Free( cl_consoleKeys->resetString );
	cl_consoleKeys->resetString = CopyString( _("~ ` 0x7e 0x60") );
#endif
}

/*
============
Trans_Init
============
*/
void Trans_Init()
{
	char langList[ MAX_TOKEN_CHARS ] = "";
	char encList[ MAX_TOKEN_CHARS ] = "";
	std::set<Language>  langs;
	Language            lang;

	Cmd_AddCommand( "updatelanguage", Trans_UpdateLanguage_f );

	language = Cvar_Get( "language", "", CVAR_ARCHIVE );
	trans_debug = Cvar_Get( "trans_debug", "0", 0 );
	trans_languages = Cvar_Get( "trans_languages", "", CVAR_ROM );
	trans_encodings = Cvar_Get( "trans_encodings", "", CVAR_ROM );

	// set tinygettext log callbacks
	tinygettext::Log::set_log_error_callback( &Trans_Error );
	tinygettext::Log::set_log_warning_callback( &Trans_Warning );
	tinygettext::Log::set_log_info_callback( &Trans_Info );

	trans_manager.set_filesystem( std::unique_ptr<FileSystem>( new DaemonFileSystem ) );
	trans_managergame.set_filesystem( std::unique_ptr<FileSystem>( new DaemonFileSystem ) );

	trans_manager.add_directory( "translation/client" );
	trans_managergame.add_directory( "translation/game" );

	langs = trans_manager.get_languages();

	for( std::set<Language>::iterator p = langs.begin(); p != langs.end(); p++ )
	{
		Q_strcat( langList, sizeof( langList ), va( "\"%s\" ", p->get_name().c_str() ) );
		Q_strcat( encList, sizeof( encList ), va( "\"%s\" ", p->str().c_str() ) );
	}

	Cvar_Set( "trans_languages", langList );
	Cvar_Set( "trans_encodings", encList );

	Com_Printf( "Loaded %lu language%s\n", ( unsigned long ) langs.size(), ( langs.size() == 1 ? "" : "s" ) );
}

void Trans_LoadDefaultLanguage()
{
	FL_Locale           *locale;

	// Only detect locale if no previous language set.
	if( !language->string[0] )
	{
		FL_FindLocale( &locale, FL_MESSAGES );

		// Invalid or not found. Just use builtin language.
		if( !locale->lang || !locale->lang[0] || !locale->country || !locale->country[0] )
		{
			Cvar_Set( "language", "en" );
		}
		else
		{
			Cvar_Set( "language", va( "%s%s%s", locale->lang,
						  locale->country[0] ? "_" : "",
						  locale->country ) );
		}

		FL_FreeLocale( &locale );
	}

	Trans_SetLanguage( language->string );
}

const char* Trans_Gettext_Internal( const char *msgid, DictionaryManager& manager )
{
	if ( !msgid )
	{
		return msgid;
	}

	num = ( num + 1 ) & 3;
	gettextbuffer[ num ] = manager.get_dictionary().translate( msgid );
	return gettextbuffer[ num ].c_str();
}

const char* Trans_Pgettext_Internal( const char *ctxt, const char *msgid, DictionaryManager& manager )
{
	if ( !ctxt || !msgid )
	{
		return msgid;
	}

	num = ( num + 1 ) & 3;
	gettextbuffer[ num ] = manager.get_dictionary().translate_ctxt( ctxt, msgid );
	return gettextbuffer[ num ].c_str();
}

const char* Trans_GettextPlural_Internal( const char *msgid, const char *msgid_plural, int number, DictionaryManager& manager )
{
	if ( !msgid || !msgid_plural )
	{
		if ( msgid )
		{
			return msgid;
		}

		if ( msgid_plural )
		{
			return msgid_plural;
		}

		return nullptr;
	}

	num = ( num + 1 ) & 3;
	gettextbuffer[ num ] = manager.get_dictionary().translate_plural( msgid, msgid_plural, number );
	return gettextbuffer[ num ].c_str();
}

const char* Trans_Gettext( const char *msgid )
{
	return Trans_Gettext_Internal( msgid, trans_manager );
}

// Unused
const char* Trans_Pgettext( const char *ctxt, const char *msgid )
{
	return Trans_Pgettext_Internal( ctxt, msgid, trans_manager );
}
// Unused
const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num )
{
	return Trans_GettextPlural_Internal( msgid, msgid_plural, num, trans_manager );
}

const char* Trans_GettextGame( const char *msgid )
{
	return Trans_Gettext_Internal( msgid, trans_managergame );
}

const char* Trans_PgettextGame( const char *ctxt, const char *msgid )
{
	return Trans_Pgettext_Internal( ctxt, msgid, trans_managergame );
}

const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num )
{
	return Trans_GettextPlural_Internal( msgid, msgid_plural, num, trans_managergame );
}
<commit_msg>Remove one more function<commit_after>/*
===========================================================================

Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers

This file is part of the Daemon GPL Source Code (Daemon Source Code).

Daemon Source Code 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 3 of the License, or
(at your option) any later version.

Daemon Source Code 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 Daemon Source Code.  If not, see <http://www.gnu.org/licenses/>.

In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code.  If not, please request a copy in writing from id Software at the address
below.

If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.

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

#include "q_shared.h"
#include "qcommon.h"

extern "C" {
    #include "findlocale/findlocale.h"
}

#include "tinygettext/log.hpp"
#include "tinygettext/tinygettext.hpp"
#include "tinygettext/file_system.hpp"

using namespace tinygettext;

// Ugly char buffer
static std::string gettextbuffer[ 4 ];
static int num = -1;

DictionaryManager trans_manager;
DictionaryManager trans_managergame;

cvar_t            *language;
cvar_t            *trans_debug;
cvar_t            *trans_encodings;
cvar_t            *trans_languages;

#ifndef BUILD_SERVER
extern cvar_t *cl_consoleKeys; // should really #include client.h
#endif

/*
====================
DaemonInputbuf

Streambuf based class that uses the engine's File I/O functions for input
====================
*/

class DaemonInputbuf : public std::streambuf
{
private:
	static const size_t BUFFER_SIZE = 8192;
	fileHandle_t fileHandle;
	char  buffer[ BUFFER_SIZE ];
	size_t  putBack;
public:
	DaemonInputbuf( const std::string& filename ) : putBack( 1 )
	{
		char *end;

		end = buffer + BUFFER_SIZE - putBack;
		setg( end, end, end );

		FS_FOpenFileRead( filename.c_str(), &fileHandle, false );
	}

	~DaemonInputbuf()
	{
		if( fileHandle )
		{
			FS_FCloseFile( fileHandle );
		}
	}
};

/*
====================
DaemonIstream

Simple istream based class that takes ownership of the streambuf
====================
*/

class DaemonIstream : public std::istream
{
public:
	DaemonIstream( const std::string& filename ) : std::istream( new DaemonInputbuf( filename ) ) {}
	~DaemonIstream()
	{
		delete rdbuf();
	}
};

/*
====================
DaemonFileSystem

Class used by tinygettext to read files and directorys
Uses the engine's File I/O functions for this purpose
====================
*/

class DaemonFileSystem : public FileSystem
{
public:
	DaemonFileSystem() {}

	std::vector<std::string> open_directory( const std::string& pathname )
	{
		int numFiles;
		char **files;
		std::vector<std::string> ret;

		files = FS_ListFiles( pathname.c_str(), nullptr, &numFiles );

		for( int i = 0; i < numFiles; i++ )
		{
			ret.push_back( std::string( files[ i ] ) );
		}

		FS_FreeFileList( files );
		return ret;
	}

	std::unique_ptr<std::istream> open_file( const std::string& filename )
	{
		return std::unique_ptr<std::istream>( new DaemonIstream( filename ) );
	}
};

/*
====================
Logging functions used by tinygettext
====================
*/

void Trans_Error( const std::string& str )
{
	Com_Printf( "^1%s^7", str.c_str() );
}

void Trans_Warning( const std::string& str )
{
	if( trans_debug->integer != 0 )
	{
		Com_Printf( "^3%s^7", str.c_str() );
	}
}

void Trans_Info( const std::string& str )
{
	if( trans_debug->integer != 0 )
	{
		Com_Printf( "%s", str.c_str() );
	}
}

/*
====================
Trans_SetLanguage

Sets a loaded language. If desired language is not found, set closest match.
If no languages are close, force English.
====================
*/

void Trans_SetLanguage( const char* lang )
{
	Language requestLang = Language::from_env( std::string( lang ) );

	// default to english
	Language bestLang = Language::from_env( "en" );
	int bestScore = Language::match( requestLang, bestLang );

	std::set<Language> langs = trans_manager.get_languages();

	for( std::set<Language>::iterator i = langs.begin(); i != langs.end(); i++ )
	{
		int score = Language::match( requestLang, *i );

		if( score > bestScore )
		{
			bestScore = score;
			bestLang = *i;
		}
	}

	// language not found, display warning
	if( bestScore == 0 )
	{
		Com_Printf( S_WARNING "Language \"%s\" (%s) not found. Default to \"English\" (en)\n",
					requestLang.get_name().empty() ? "Unknown Language" : requestLang.get_name().c_str(),
					lang );
	}

	trans_manager.set_language( bestLang );
	trans_managergame.set_language( bestLang );

	Cvar_Set( "language", bestLang.str().c_str() );

	Com_Printf( "Set language to %s" , bestLang.get_name().c_str() );
}

void Trans_UpdateLanguage_f()
{
	Trans_SetLanguage( language->string );

#ifndef BUILD_SERVER
	// update the default console keys string
	Z_Free( cl_consoleKeys->resetString );
	cl_consoleKeys->resetString = CopyString( _("~ ` 0x7e 0x60") );
#endif
}

/*
============
Trans_Init
============
*/
void Trans_Init()
{
	char langList[ MAX_TOKEN_CHARS ] = "";
	char encList[ MAX_TOKEN_CHARS ] = "";
	std::set<Language>  langs;
	Language            lang;

	Cmd_AddCommand( "updatelanguage", Trans_UpdateLanguage_f );

	language = Cvar_Get( "language", "", CVAR_ARCHIVE );
	trans_debug = Cvar_Get( "trans_debug", "0", 0 );
	trans_languages = Cvar_Get( "trans_languages", "", CVAR_ROM );
	trans_encodings = Cvar_Get( "trans_encodings", "", CVAR_ROM );

	// set tinygettext log callbacks
	tinygettext::Log::set_log_error_callback( &Trans_Error );
	tinygettext::Log::set_log_warning_callback( &Trans_Warning );
	tinygettext::Log::set_log_info_callback( &Trans_Info );

	trans_manager.set_filesystem( std::unique_ptr<FileSystem>( new DaemonFileSystem ) );
	trans_managergame.set_filesystem( std::unique_ptr<FileSystem>( new DaemonFileSystem ) );

	trans_manager.add_directory( "translation/client" );
	trans_managergame.add_directory( "translation/game" );

	langs = trans_manager.get_languages();

	for( std::set<Language>::iterator p = langs.begin(); p != langs.end(); p++ )
	{
		Q_strcat( langList, sizeof( langList ), va( "\"%s\" ", p->get_name().c_str() ) );
		Q_strcat( encList, sizeof( encList ), va( "\"%s\" ", p->str().c_str() ) );
	}

	Cvar_Set( "trans_languages", langList );
	Cvar_Set( "trans_encodings", encList );

	Com_Printf( "Loaded %lu language%s\n", ( unsigned long ) langs.size(), ( langs.size() == 1 ? "" : "s" ) );
}

void Trans_LoadDefaultLanguage()
{
	FL_Locale           *locale;

	// Only detect locale if no previous language set.
	if( !language->string[0] )
	{
		FL_FindLocale( &locale, FL_MESSAGES );

		// Invalid or not found. Just use builtin language.
		if( !locale->lang || !locale->lang[0] || !locale->country || !locale->country[0] )
		{
			Cvar_Set( "language", "en" );
		}
		else
		{
			Cvar_Set( "language", va( "%s%s%s", locale->lang,
						  locale->country[0] ? "_" : "",
						  locale->country ) );
		}

		FL_FreeLocale( &locale );
	}

	Trans_SetLanguage( language->string );
}

const char* Trans_Gettext_Internal( const char *msgid, DictionaryManager& manager )
{
	if ( !msgid )
	{
		return msgid;
	}

	num = ( num + 1 ) & 3;
	gettextbuffer[ num ] = manager.get_dictionary().translate( msgid );
	return gettextbuffer[ num ].c_str();
}

const char* Trans_Pgettext_Internal( const char *ctxt, const char *msgid, DictionaryManager& manager )
{
	if ( !ctxt || !msgid )
	{
		return msgid;
	}

	num = ( num + 1 ) & 3;
	gettextbuffer[ num ] = manager.get_dictionary().translate_ctxt( ctxt, msgid );
	return gettextbuffer[ num ].c_str();
}

const char* Trans_GettextPlural_Internal( const char *msgid, const char *msgid_plural, int number, DictionaryManager& manager )
{
	if ( !msgid || !msgid_plural )
	{
		if ( msgid )
		{
			return msgid;
		}

		if ( msgid_plural )
		{
			return msgid_plural;
		}

		return nullptr;
	}

	num = ( num + 1 ) & 3;
	gettextbuffer[ num ] = manager.get_dictionary().translate_plural( msgid, msgid_plural, number );
	return gettextbuffer[ num ].c_str();
}

const char* Trans_Gettext( const char *msgid )
{
	return Trans_Gettext_Internal( msgid, trans_manager );
}

// Unused
const char* Trans_Pgettext( const char *ctxt, const char *msgid )
{
	return Trans_Pgettext_Internal( ctxt, msgid, trans_manager );
}
// Unused
const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num )
{
	return Trans_GettextPlural_Internal( msgid, msgid_plural, num, trans_manager );
}

const char* Trans_GettextGame( const char *msgid )
{
	return Trans_Gettext_Internal( msgid, trans_managergame );
}

const char* Trans_PgettextGame( const char *ctxt, const char *msgid )
{
	return Trans_Pgettext_Internal( ctxt, msgid, trans_managergame );
}

const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num )
{
	return Trans_GettextPlural_Internal( msgid, msgid_plural, num, trans_managergame );
}
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreShaderPrecompiledHeaders.h"

namespace Ogre {
namespace RTShader {

//-----------------------------------------------------------------------------
Program::Program(GpuProgramType type)
{
    mType               = type;
    mEntryPointFunction = NULL;
    mSkeletalAnimation  = false;
    mColumnMajorMatrices = true;
}

//-----------------------------------------------------------------------------
Program::~Program()
{
    destroyParameters();

    destroyFunctions();
}

//-----------------------------------------------------------------------------
void Program::destroyParameters()
{
    mParameters.clear();
}

//-----------------------------------------------------------------------------
void Program::destroyFunctions()
{
    ShaderFunctionIterator it;

    for (it = mFunctions.begin(); it != mFunctions.end(); ++it)
    {
        OGRE_DELETE *it;
    }
    mFunctions.clear();
}

//-----------------------------------------------------------------------------
GpuProgramType Program::getType() const
{
    return mType;
}

//-----------------------------------------------------------------------------
void Program::addParameter(UniformParameterPtr parameter)
{
    if (getParameterByName(parameter->getName()).get() != NULL)
    {
        OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS,
            "Parameter <" + parameter->getName() + "> already declared in program.",
            "Program::addParameter" );
    }

    mParameters.push_back(parameter);
}

//-----------------------------------------------------------------------------
void Program::removeParameter(UniformParameterPtr parameter)
{
    UniformParameterIterator it;

    for (it = mParameters.begin(); it != mParameters.end(); ++it)
    {
        if ((*it) == parameter)
        {
            (*it).reset();
            mParameters.erase(it);
            break;
        }
    }
}

//-----------------------------------------------------------------------------

static bool isArray(GpuProgramParameters::AutoConstantType autoType)
{
    switch (autoType)
    {
    case GpuProgramParameters::ACT_WORLD_MATRIX_ARRAY_3x4:
    case GpuProgramParameters::ACT_WORLD_MATRIX_ARRAY:
    case GpuProgramParameters::ACT_WORLD_DUALQUATERNION_ARRAY_2x4:
    case GpuProgramParameters::ACT_WORLD_SCALE_SHEAR_MATRIX_ARRAY_3x4:
    case GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR_POWER_SCALED_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR_POWER_SCALED_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_ATTENUATION_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_POSITION_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_POSITION_OBJECT_SPACE_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_POSITION_VIEW_SPACE_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_DIRECTION_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_DIRECTION_OBJECT_SPACE_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_DIRECTION_VIEW_SPACE_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_DISTANCE_OBJECT_SPACE_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_POWER_SCALE_ARRAY:
    case GpuProgramParameters::ACT_SPOTLIGHT_PARAMS_ARRAY:
    case GpuProgramParameters::ACT_DERIVED_LIGHT_DIFFUSE_COLOUR_ARRAY:
    case GpuProgramParameters::ACT_DERIVED_LIGHT_SPECULAR_COLOUR_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_CASTS_SHADOWS_ARRAY:
    case GpuProgramParameters::ACT_TEXTURE_VIEWPROJ_MATRIX_ARRAY:
    case GpuProgramParameters::ACT_TEXTURE_WORLDVIEWPROJ_MATRIX_ARRAY:
    case GpuProgramParameters::ACT_SPOTLIGHT_VIEWPROJ_MATRIX_ARRAY:
    case GpuProgramParameters::ACT_SPOTLIGHT_WORLDVIEWPROJ_MATRIX_ARRAY:
    case GpuProgramParameters::ACT_SHADOW_SCENE_DEPTH_RANGE_ARRAY:
        return true;
    default:
        return false;
    }
}

UniformParameterPtr Program::resolveParameter(GpuProgramParameters::AutoConstantType autoType, size_t data)
{
    UniformParameterPtr param;

    // Check if parameter already exists.
    param = getParameterByAutoType(autoType);
    if (param)
    {
        return param;
    }

    // Create new parameter
    size_t size = 0;
    if(isArray(autoType)) std::swap(size, data); // for array autotypes the extra parameter is the size

    param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size));
    addParameter(param);

    return param;
}

UniformParameterPtr Program::resolveAutoParameterReal(GpuProgramParameters::AutoConstantType autoType,
                                                Real data, size_t size)
{
    UniformParameterPtr param;

    // Check if parameter already exists.
    param = getParameterByAutoType(autoType);
    if (param.get() != NULL)
    {
        if (param->isAutoConstantRealParameter() &&
            param->getAutoConstantRealData() == data)
        {
            param->setSize(std::max(size, param->getSize()));
            return param;
        }
    }

    // Create new parameter.
    param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size));
    addParameter(param);

    return param;
}

//-----------------------------------------------------------------------------
UniformParameterPtr Program::resolveAutoParameterReal(GpuProgramParameters::AutoConstantType autoType, GpuConstantType type,
                                                Real data, size_t size)
{
    UniformParameterPtr param;

    // Check if parameter already exists.
    param = getParameterByAutoType(autoType);
    if (param.get() != NULL)
    {
        if (param->isAutoConstantRealParameter() &&
            param->getAutoConstantRealData() == data)
        {
            param->setSize(std::max(size, param->getSize()));
            return param;
        }
    }

    // Create new parameter.
    param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size, type));
    addParameter(param);

    return param;
}

//-----------------------------------------------------------------------------
UniformParameterPtr Program::resolveAutoParameterInt(GpuProgramParameters::AutoConstantType autoType,
                                           size_t data, size_t size)
{
    UniformParameterPtr param;

    // Check if parameter already exists.
    param = getParameterByAutoType(autoType);
    if (param.get() != NULL)
    {
        if (param->isAutoConstantIntParameter() &&
            param->getAutoConstantIntData() == data)
        {
            param->setSize(std::max(size, param->getSize()));
            return param;
        }
    }

    // Create new parameter.
    param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size));
    addParameter(param);

    return param;
}

//-----------------------------------------------------------------------------
UniformParameterPtr Program::resolveAutoParameterInt(GpuProgramParameters::AutoConstantType autoType, GpuConstantType type,
                                           size_t data, size_t size)
{
    UniformParameterPtr param;

    // Check if parameter already exists.
    param = getParameterByAutoType(autoType);
    if (param.get() != NULL)
    {
        if (param->isAutoConstantIntParameter() &&
            param->getAutoConstantIntData() == data)
        {
            param->setSize(std::max(size, param->getSize()));
            return param;
        }
    }

    // Create new parameter.
    param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size, type));
    addParameter(param);

    return param;
}

//-----------------------------------------------------------------------------
UniformParameterPtr Program::resolveParameter(GpuConstantType type,
                                    int index, uint16 variability,
                                    const String& suggestedName,
                                    size_t size)
{
    UniformParameterPtr param;

    if (index == -1)
    {
        index = 0;

        // Find the next available index of the target type.
        UniformParameterIterator it;

        for (it = mParameters.begin(); it != mParameters.end(); ++it)
        {
            if ((*it)->getType() == type &&
                (*it)->isAutoConstantParameter() == false)
            {
                index++;
            }
        }
    }
    else
    {
        // Check if parameter already exists.
        param = getParameterByType(type, index);
        if (param.get() != NULL)
        {
            return param;
        }
    }

    // Create new parameter.
    param = ParameterFactory::createUniform(type, index, variability, suggestedName, size);
    addParameter(param);

    return param;
}

//-----------------------------------------------------------------------------
UniformParameterPtr Program::getParameterByName(const String& name)
{
    UniformParameterIterator it;

    for (it = mParameters.begin(); it != mParameters.end(); ++it)
    {
        if ((*it)->getName() == name)
        {
            return *it;
        }
    }

    return UniformParameterPtr();
}

//-----------------------------------------------------------------------------
UniformParameterPtr Program::getParameterByType(GpuConstantType type, int index)
{
    UniformParameterIterator it;

    for (it = mParameters.begin(); it != mParameters.end(); ++it)
    {
        if ((*it)->getType() == type &&
            (*it)->getIndex() == index)
        {
            return *it;
        }
    }

    return UniformParameterPtr();
}

//-----------------------------------------------------------------------------
UniformParameterPtr Program::getParameterByAutoType(GpuProgramParameters::AutoConstantType autoType)
{
    UniformParameterIterator it;

    for (it = mParameters.begin(); it != mParameters.end(); ++it)
    {
        if ((*it)->isAutoConstantParameter() && (*it)->getAutoConstantType() == autoType)
        {
            return *it;
        }
    }

    return UniformParameterPtr();
}

//-----------------------------------------------------------------------------
Function* Program::createFunction(const String& name, const String& desc, const Function::FunctionType functionType)
{
    Function* shaderFunction;

    shaderFunction = getFunctionByName(name);
    if (shaderFunction != NULL)
    {
        OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS,
            "Function " + name + " already declared in program.",
            "Program::createFunction" );
    }

    shaderFunction = OGRE_NEW Function(name, desc, functionType);
    mFunctions.push_back(shaderFunction);

    return shaderFunction;
}

//-----------------------------------------------------------------------------
Function* Program::getFunctionByName(const String& name)
{
    ShaderFunctionIterator it;

    for (it = mFunctions.begin(); it != mFunctions.end(); ++it)
    {
        if ((*it)->getName() == name)
        {
            return *it;
        }
    }

    return NULL;
}

//-----------------------------------------------------------------------------
void Program::addDependency(const String& libFileName)
{
    for (unsigned int i=0; i < mDependencies.size(); ++i)
    {
        if (mDependencies[i] == libFileName)
        {
            return;
        }
    }
    mDependencies.push_back(libFileName);
}

void Program::addPreprocessorDefines(const String& defines)
{
    mPreprocessorDefines +=
        mPreprocessorDefines.empty() ? defines : ("," + defines);
}

//-----------------------------------------------------------------------------
size_t Program::getDependencyCount() const
{
    return mDependencies.size();
}

//-----------------------------------------------------------------------------
const String& Program::getDependency(unsigned int index) const
{
    return mDependencies[index];
}

}
}
<commit_msg>RTSS: fix resolving params with autoConstantIntData != 0<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreShaderPrecompiledHeaders.h"

namespace Ogre {
namespace RTShader {

//-----------------------------------------------------------------------------
Program::Program(GpuProgramType type)
{
    mType               = type;
    mEntryPointFunction = NULL;
    mSkeletalAnimation  = false;
    mColumnMajorMatrices = true;
}

//-----------------------------------------------------------------------------
Program::~Program()
{
    destroyParameters();

    destroyFunctions();
}

//-----------------------------------------------------------------------------
void Program::destroyParameters()
{
    mParameters.clear();
}

//-----------------------------------------------------------------------------
void Program::destroyFunctions()
{
    ShaderFunctionIterator it;

    for (it = mFunctions.begin(); it != mFunctions.end(); ++it)
    {
        OGRE_DELETE *it;
    }
    mFunctions.clear();
}

//-----------------------------------------------------------------------------
GpuProgramType Program::getType() const
{
    return mType;
}

//-----------------------------------------------------------------------------
void Program::addParameter(UniformParameterPtr parameter)
{
    if (getParameterByName(parameter->getName()).get() != NULL)
    {
        OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS,
            "Parameter <" + parameter->getName() + "> already declared in program.",
            "Program::addParameter" );
    }

    mParameters.push_back(parameter);
}

//-----------------------------------------------------------------------------
void Program::removeParameter(UniformParameterPtr parameter)
{
    UniformParameterIterator it;

    for (it = mParameters.begin(); it != mParameters.end(); ++it)
    {
        if ((*it) == parameter)
        {
            (*it).reset();
            mParameters.erase(it);
            break;
        }
    }
}

//-----------------------------------------------------------------------------

static bool isArray(GpuProgramParameters::AutoConstantType autoType)
{
    switch (autoType)
    {
    case GpuProgramParameters::ACT_WORLD_MATRIX_ARRAY_3x4:
    case GpuProgramParameters::ACT_WORLD_MATRIX_ARRAY:
    case GpuProgramParameters::ACT_WORLD_DUALQUATERNION_ARRAY_2x4:
    case GpuProgramParameters::ACT_WORLD_SCALE_SHEAR_MATRIX_ARRAY_3x4:
    case GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR_POWER_SCALED_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR_POWER_SCALED_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_ATTENUATION_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_POSITION_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_POSITION_OBJECT_SPACE_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_POSITION_VIEW_SPACE_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_DIRECTION_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_DIRECTION_OBJECT_SPACE_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_DIRECTION_VIEW_SPACE_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_DISTANCE_OBJECT_SPACE_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_POWER_SCALE_ARRAY:
    case GpuProgramParameters::ACT_SPOTLIGHT_PARAMS_ARRAY:
    case GpuProgramParameters::ACT_DERIVED_LIGHT_DIFFUSE_COLOUR_ARRAY:
    case GpuProgramParameters::ACT_DERIVED_LIGHT_SPECULAR_COLOUR_ARRAY:
    case GpuProgramParameters::ACT_LIGHT_CASTS_SHADOWS_ARRAY:
    case GpuProgramParameters::ACT_TEXTURE_VIEWPROJ_MATRIX_ARRAY:
    case GpuProgramParameters::ACT_TEXTURE_WORLDVIEWPROJ_MATRIX_ARRAY:
    case GpuProgramParameters::ACT_SPOTLIGHT_VIEWPROJ_MATRIX_ARRAY:
    case GpuProgramParameters::ACT_SPOTLIGHT_WORLDVIEWPROJ_MATRIX_ARRAY:
    case GpuProgramParameters::ACT_SHADOW_SCENE_DEPTH_RANGE_ARRAY:
        return true;
    default:
        return false;
    }
}

UniformParameterPtr Program::resolveParameter(GpuProgramParameters::AutoConstantType autoType, size_t data)
{
    UniformParameterPtr param;

    // Check if parameter already exists.
    param = getParameterByAutoType(autoType);

    size_t size = 0;
    if(isArray(autoType)) std::swap(size, data); // for array autotypes the extra parameter is the size

    if (param && param->getAutoConstantIntData() == data)
    {
        return param;
    }

    // Create new parameter
    param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size));
    addParameter(param);

    return param;
}

UniformParameterPtr Program::resolveAutoParameterReal(GpuProgramParameters::AutoConstantType autoType,
                                                Real data, size_t size)
{
    UniformParameterPtr param;

    // Check if parameter already exists.
    param = getParameterByAutoType(autoType);
    if (param.get() != NULL)
    {
        if (param->isAutoConstantRealParameter() &&
            param->getAutoConstantRealData() == data)
        {
            param->setSize(std::max(size, param->getSize()));
            return param;
        }
    }

    // Create new parameter.
    param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size));
    addParameter(param);

    return param;
}

//-----------------------------------------------------------------------------
UniformParameterPtr Program::resolveAutoParameterReal(GpuProgramParameters::AutoConstantType autoType, GpuConstantType type,
                                                Real data, size_t size)
{
    UniformParameterPtr param;

    // Check if parameter already exists.
    param = getParameterByAutoType(autoType);
    if (param.get() != NULL)
    {
        if (param->isAutoConstantRealParameter() &&
            param->getAutoConstantRealData() == data)
        {
            param->setSize(std::max(size, param->getSize()));
            return param;
        }
    }

    // Create new parameter.
    param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size, type));
    addParameter(param);

    return param;
}

//-----------------------------------------------------------------------------
UniformParameterPtr Program::resolveAutoParameterInt(GpuProgramParameters::AutoConstantType autoType,
                                           size_t data, size_t size)
{
    UniformParameterPtr param;

    // Check if parameter already exists.
    param = getParameterByAutoType(autoType);
    if (param.get() != NULL)
    {
        if (param->isAutoConstantIntParameter() &&
            param->getAutoConstantIntData() == data)
        {
            param->setSize(std::max(size, param->getSize()));
            return param;
        }
    }

    // Create new parameter.
    param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size));
    addParameter(param);

    return param;
}

//-----------------------------------------------------------------------------
UniformParameterPtr Program::resolveAutoParameterInt(GpuProgramParameters::AutoConstantType autoType, GpuConstantType type,
                                           size_t data, size_t size)
{
    UniformParameterPtr param;

    // Check if parameter already exists.
    param = getParameterByAutoType(autoType);
    if (param.get() != NULL)
    {
        if (param->isAutoConstantIntParameter() &&
            param->getAutoConstantIntData() == data)
        {
            param->setSize(std::max(size, param->getSize()));
            return param;
        }
    }

    // Create new parameter.
    param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size, type));
    addParameter(param);

    return param;
}

//-----------------------------------------------------------------------------
UniformParameterPtr Program::resolveParameter(GpuConstantType type,
                                    int index, uint16 variability,
                                    const String& suggestedName,
                                    size_t size)
{
    UniformParameterPtr param;

    if (index == -1)
    {
        index = 0;

        // Find the next available index of the target type.
        UniformParameterIterator it;

        for (it = mParameters.begin(); it != mParameters.end(); ++it)
        {
            if ((*it)->getType() == type &&
                (*it)->isAutoConstantParameter() == false)
            {
                index++;
            }
        }
    }
    else
    {
        // Check if parameter already exists.
        param = getParameterByType(type, index);
        if (param.get() != NULL)
        {
            return param;
        }
    }

    // Create new parameter.
    param = ParameterFactory::createUniform(type, index, variability, suggestedName, size);
    addParameter(param);

    return param;
}

//-----------------------------------------------------------------------------
UniformParameterPtr Program::getParameterByName(const String& name)
{
    UniformParameterIterator it;

    for (it = mParameters.begin(); it != mParameters.end(); ++it)
    {
        if ((*it)->getName() == name)
        {
            return *it;
        }
    }

    return UniformParameterPtr();
}

//-----------------------------------------------------------------------------
UniformParameterPtr Program::getParameterByType(GpuConstantType type, int index)
{
    UniformParameterIterator it;

    for (it = mParameters.begin(); it != mParameters.end(); ++it)
    {
        if ((*it)->getType() == type &&
            (*it)->getIndex() == index)
        {
            return *it;
        }
    }

    return UniformParameterPtr();
}

//-----------------------------------------------------------------------------
UniformParameterPtr Program::getParameterByAutoType(GpuProgramParameters::AutoConstantType autoType)
{
    UniformParameterIterator it;

    for (it = mParameters.begin(); it != mParameters.end(); ++it)
    {
        if ((*it)->isAutoConstantParameter() && (*it)->getAutoConstantType() == autoType)
        {
            return *it;
        }
    }

    return UniformParameterPtr();
}

//-----------------------------------------------------------------------------
Function* Program::createFunction(const String& name, const String& desc, const Function::FunctionType functionType)
{
    Function* shaderFunction;

    shaderFunction = getFunctionByName(name);
    if (shaderFunction != NULL)
    {
        OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS,
            "Function " + name + " already declared in program.",
            "Program::createFunction" );
    }

    shaderFunction = OGRE_NEW Function(name, desc, functionType);
    mFunctions.push_back(shaderFunction);

    return shaderFunction;
}

//-----------------------------------------------------------------------------
Function* Program::getFunctionByName(const String& name)
{
    ShaderFunctionIterator it;

    for (it = mFunctions.begin(); it != mFunctions.end(); ++it)
    {
        if ((*it)->getName() == name)
        {
            return *it;
        }
    }

    return NULL;
}

//-----------------------------------------------------------------------------
void Program::addDependency(const String& libFileName)
{
    for (unsigned int i=0; i < mDependencies.size(); ++i)
    {
        if (mDependencies[i] == libFileName)
        {
            return;
        }
    }
    mDependencies.push_back(libFileName);
}

void Program::addPreprocessorDefines(const String& defines)
{
    mPreprocessorDefines +=
        mPreprocessorDefines.empty() ? defines : ("," + defines);
}

//-----------------------------------------------------------------------------
size_t Program::getDependencyCount() const
{
    return mDependencies.size();
}

//-----------------------------------------------------------------------------
const String& Program::getDependency(unsigned int index) const
{
    return mDependencies[index];
}

}
}
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mpageswitchslideanimation.h"
#include "mpageswitchslideanimation_p.h"

#include "mscenewindow.h"
#include "mscenemanager.h"
#include "manimationcreator.h"

#include <QPropertyAnimation>

MPageSwitchSlideAnimationPrivate::MPageSwitchSlideAnimationPrivate()
    : MPageSwitchAnimationPrivate(),
      positionNewPageAnimation(NULL),
      positionOldPageAnimation(NULL)
{
}

MPageSwitchSlideAnimationPrivate::~MPageSwitchSlideAnimationPrivate()
{
}

MPageSwitchSlideAnimation::MPageSwitchSlideAnimation(QObject *parent) :
    MPageSwitchAnimation(new MPageSwitchSlideAnimationPrivate, parent)
{
    Q_D(MPageSwitchSlideAnimation);

    d->positionNewPageAnimation = new QPropertyAnimation;
    d->positionNewPageAnimation->setPropertyName("pos");
    d->positionNewPageAnimation->setEasingCurve(style()->easingCurve());
    d->positionNewPageAnimation->setDuration(style()->duration());
    d->positionNewPageAnimation->setEndValue(QPointF(0, 0));
    addAnimation(d->positionNewPageAnimation);

    d->positionOldPageAnimation = new QPropertyAnimation;
    d->positionOldPageAnimation->setPropertyName("pos");
    d->positionOldPageAnimation->setEasingCurve(style()->easingCurve());
    d->positionOldPageAnimation->setDuration(style()->duration());
    d->positionOldPageAnimation->setStartValue(QPointF(0, 0));
    addAnimation(d->positionOldPageAnimation);
}

MPageSwitchSlideAnimation::MPageSwitchSlideAnimation(MPageSwitchSlideAnimationPrivate *dd, QObject *parent) :
    MPageSwitchAnimation(dd, parent)
{
}

void MPageSwitchSlideAnimation::updateState(QAbstractAnimation::State newState,
        QAbstractAnimation::State oldState)
{
    Q_D(MPageSwitchSlideAnimation);
    Q_UNUSED(oldState);

    if (newState != Running)
        return;

    d->positionNewPageAnimation->setTargetObject(newPage());
    d->positionOldPageAnimation->setTargetObject(oldPage());

    if (newPage()) {
        if (transitionDirection() == ToParentPage)
            d->positionNewPageAnimation->setStartValue(QPointF(newPage()->boundingRect().width(), 0));
        else
            d->positionNewPageAnimation->setStartValue(QPointF(-newPage()->boundingRect().width(), 0));
    }

    if (oldPage()) {
        if (transitionDirection() == ToParentPage)
            d->positionOldPageAnimation->setEndValue(QPointF(-oldPage()->boundingRect().width(), 0));
        else
            d->positionOldPageAnimation->setEndValue(QPointF(oldPage()->boundingRect().width(), 0));
    }
}

M_REGISTER_ANIMATION(MPageSwitchSlideAnimation)

<commit_msg>Changes: fixing coverity error CID#1131 RevBy: Matusz<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mpageswitchslideanimation.h"
#include "mpageswitchslideanimation_p.h"

#include "mscenewindow.h"
#include "mscenemanager.h"
#include "manimationcreator.h"

#include <QPropertyAnimation>

MPageSwitchSlideAnimationPrivate::MPageSwitchSlideAnimationPrivate()
    : MPageSwitchAnimationPrivate(),
      sceneWindow(NULL),
      positionNewPageAnimation(NULL),
      positionOldPageAnimation(NULL)
{
}

MPageSwitchSlideAnimationPrivate::~MPageSwitchSlideAnimationPrivate()
{
}

MPageSwitchSlideAnimation::MPageSwitchSlideAnimation(QObject *parent) :
    MPageSwitchAnimation(new MPageSwitchSlideAnimationPrivate, parent)
{
    Q_D(MPageSwitchSlideAnimation);

    d->positionNewPageAnimation = new QPropertyAnimation;
    d->positionNewPageAnimation->setPropertyName("pos");
    d->positionNewPageAnimation->setEasingCurve(style()->easingCurve());
    d->positionNewPageAnimation->setDuration(style()->duration());
    d->positionNewPageAnimation->setEndValue(QPointF(0, 0));
    addAnimation(d->positionNewPageAnimation);

    d->positionOldPageAnimation = new QPropertyAnimation;
    d->positionOldPageAnimation->setPropertyName("pos");
    d->positionOldPageAnimation->setEasingCurve(style()->easingCurve());
    d->positionOldPageAnimation->setDuration(style()->duration());
    d->positionOldPageAnimation->setStartValue(QPointF(0, 0));
    addAnimation(d->positionOldPageAnimation);
}

MPageSwitchSlideAnimation::MPageSwitchSlideAnimation(MPageSwitchSlideAnimationPrivate *dd, QObject *parent) :
    MPageSwitchAnimation(dd, parent)
{
}

void MPageSwitchSlideAnimation::updateState(QAbstractAnimation::State newState,
        QAbstractAnimation::State oldState)
{
    Q_D(MPageSwitchSlideAnimation);
    Q_UNUSED(oldState);

    if (newState != Running)
        return;

    d->positionNewPageAnimation->setTargetObject(newPage());
    d->positionOldPageAnimation->setTargetObject(oldPage());

    if (newPage()) {
        if (transitionDirection() == ToParentPage)
            d->positionNewPageAnimation->setStartValue(QPointF(newPage()->boundingRect().width(), 0));
        else
            d->positionNewPageAnimation->setStartValue(QPointF(-newPage()->boundingRect().width(), 0));
    }

    if (oldPage()) {
        if (transitionDirection() == ToParentPage)
            d->positionOldPageAnimation->setEndValue(QPointF(-oldPage()->boundingRect().width(), 0));
        else
            d->positionOldPageAnimation->setEndValue(QPointF(oldPage()->boundingRect().width(), 0));
    }
}

M_REGISTER_ANIMATION(MPageSwitchSlideAnimation)

<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
**************************************************************************/

#include "cmakeopenprojectwizard.h"
#include "cmakeprojectmanager.h"

#include <utils/pathchooser.h>
#include <projectexplorer/environment.h>

#include <QtGui/QVBoxLayout>
#include <QtGui/QFormLayout>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QPlainTextEdit>
#include <QtCore/QDateTime>
#include <QtCore/QStringList>

using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal;

///////
//  Page Flow:
//   Start (No .user file)
//    |
//    |---> In Source Build --> Page: Tell the user about that
//                               |--> Already existing cbp file (and new enough) --> Page: Ready to load the project
//                               |--> Page: Ask for cmd options, run generator
//    |---> No in source Build --> Page: Ask the user for the build directory
//                                   |--> Already existing cbp file (and new enough) --> Page: Ready to load the project
//                                   |--> Page: Ask for cmd options, run generator

CMakeOpenProjectWizard::CMakeOpenProjectWizard(CMakeManager *cmakeManager, const QString &sourceDirectory)
    : m_cmakeManager(cmakeManager),
      m_sourceDirectory(sourceDirectory),
      m_creatingCbpFiles(false)
{
    int startid;
    if (hasInSourceBuild()) {
        startid = InSourcePageId;
        m_buildDirectory = m_sourceDirectory;
    } else {
        startid = ShadowBuildPageId;
        m_buildDirectory = m_sourceDirectory + "/qtcreator-build";
    }

    setPage(InSourcePageId, new InSourceBuildPage(this));
    setPage(ShadowBuildPageId, new ShadowBuildPage(this));
    setPage(XmlFileUpToDatePageId, new XmlFileUpToDatePage(this));
    setPage(CMakeRunPageId, new CMakeRunPage(this));

    setStartId(startid);
}

CMakeOpenProjectWizard::CMakeOpenProjectWizard(CMakeManager *cmakeManager, const QString &sourceDirectory,
                                               const QStringList &needToCreate, const QStringList &needToUpdate)
    : m_cmakeManager(cmakeManager),
      m_sourceDirectory(sourceDirectory),
      m_creatingCbpFiles(true)
{
    foreach(const QString &buildDirectory, needToCreate)
        addPage(new CMakeRunPage(this, buildDirectory, false));
    foreach(const QString &buildDirectory, needToUpdate)
        addPage(new CMakeRunPage(this, buildDirectory, true));
}

CMakeManager *CMakeOpenProjectWizard::cmakeManager() const
{
    return m_cmakeManager;
}

int CMakeOpenProjectWizard::nextId() const
{
    if (m_creatingCbpFiles)
        return QWizard::nextId();
    int cid = currentId();
    if (cid == InSourcePageId) {
        if (existsUpToDateXmlFile())
            return XmlFileUpToDatePageId;
        else
            return CMakeRunPageId;
    } else if (cid == ShadowBuildPageId) {
        if (existsUpToDateXmlFile())
            return XmlFileUpToDatePageId;
        else
            return CMakeRunPageId;
    }
    return -1;
}

bool CMakeOpenProjectWizard::hasInSourceBuild() const
{
    QFileInfo fi(m_sourceDirectory + "/CMakeCache.txt");
    if (fi.exists())
        return true;
    return false;
}

bool CMakeOpenProjectWizard::existsUpToDateXmlFile() const
{
    QString cbpFile = CMakeManager::findCbpFile(QDir(buildDirectory()));
    if (!cbpFile.isEmpty()) {
        // We already have a cbp file
        QFileInfo cbpFileInfo(cbpFile);
        QFileInfo cmakeListsFileInfo(sourceDirectory() + "/CMakeLists.txt");

        if (cbpFileInfo.lastModified() > cmakeListsFileInfo.lastModified())
            return true;
    }
    return false;
}

QString CMakeOpenProjectWizard::buildDirectory() const
{
    return m_buildDirectory;
}

QString CMakeOpenProjectWizard::sourceDirectory() const
{
    return m_sourceDirectory;
}

void CMakeOpenProjectWizard::setBuildDirectory(const QString &directory)
{
    m_buildDirectory = directory;
}

QStringList CMakeOpenProjectWizard::arguments() const
{
    return m_arguments;
}

void CMakeOpenProjectWizard::setArguments(const QStringList &args)
{
    m_arguments = args;
}

InSourceBuildPage::InSourceBuildPage(CMakeOpenProjectWizard *cmakeWizard)
    : QWizardPage(cmakeWizard), m_cmakeWizard(cmakeWizard)
{
    setLayout(new QVBoxLayout);
    QLabel *label = new QLabel(this);
    label->setWordWrap(true);
    label->setText(tr("Qt Creator has detected an in source build. "
                   "This prevents out of souce builds, Qt Creator won't allow you to change the build directory. "
                   "If you want a out of source build, clean your source directory and open the project again"));
    layout()->addWidget(label);
}

XmlFileUpToDatePage::XmlFileUpToDatePage(CMakeOpenProjectWizard *cmakeWizard)
    : QWizardPage(cmakeWizard), m_cmakeWizard(cmakeWizard)
{
    setLayout(new QVBoxLayout);
    QLabel *label = new QLabel(this);
    label->setWordWrap(true);
    label->setText(tr("Qt Creator has found a recent cbp file, which Qt Creator parses to gather information about the project. "
                   "You can change the command line arguments used to create this file in the project mode. "
                   "Click finish to load the project"));
    layout()->addWidget(label);
}

ShadowBuildPage::ShadowBuildPage(CMakeOpenProjectWizard *cmakeWizard)
    : QWizardPage(cmakeWizard), m_cmakeWizard(cmakeWizard)
{
    QFormLayout *fl = new QFormLayout;
    this->setLayout(fl);

    QLabel *label = new QLabel(this);
    label->setWordWrap(true);
    label->setText(tr("Please enter the directory in which you want to build your project. "
                   "Qt Creator recommends to not use the source directory for building. "
                   "This ensures that the source directory remains clean and enables multiple builds "
                   "with different settings."));
    fl->addWidget(label);
    m_pc = new Core::Utils::PathChooser(this);
    m_pc->setPath(m_cmakeWizard->buildDirectory());
    connect(m_pc, SIGNAL(changed()), this, SLOT(buildDirectoryChanged()));
    fl->addRow("Build directory:", m_pc);
}

void ShadowBuildPage::buildDirectoryChanged()
{
    m_cmakeWizard->setBuildDirectory(m_pc->path());
}

CMakeRunPage::CMakeRunPage(CMakeOpenProjectWizard *cmakeWizard)
    : QWizardPage(cmakeWizard),
      m_cmakeWizard(cmakeWizard),
      m_complete(false)
{
    initWidgets();
}

CMakeRunPage::CMakeRunPage(CMakeOpenProjectWizard *cmakeWizard, const QString &buildDirectory, bool update)
    : QWizardPage(cmakeWizard),
      m_cmakeWizard(cmakeWizard),
      m_complete(false),
      m_update(update),
      m_presetBuildDirectory(buildDirectory)
{
    initWidgets();
}

void CMakeRunPage::initWidgets()
{
    QFormLayout *fl = new QFormLayout;
    setLayout(fl);
    m_descriptionLabel = new QLabel(this);
    m_descriptionLabel->setWordWrap(true);

    fl->addRow(m_descriptionLabel);

    m_argumentsLineEdit = new QLineEdit(this);
    //fl->addRow(tr("Arguments:"), m_argumentsLineEdit);

    m_runCMake = new QPushButton(this);
    m_runCMake->setText(tr("Run CMake"));
    connect(m_runCMake, SIGNAL(clicked()), this, SLOT(runCMake()));
    //fl->addWidget(m_runCMake);

    QHBoxLayout *hbox = new QHBoxLayout;
    hbox->addWidget(m_argumentsLineEdit);
    hbox->addWidget(m_runCMake);

    fl->addRow(tr("Arguments"), hbox);

    m_output = new QPlainTextEdit(this);
    m_output->setReadOnly(true);
    fl->addRow(m_output);
}

void CMakeRunPage::initializePage()
{
    if (m_presetBuildDirectory.isEmpty()) {
        m_buildDirectory = m_cmakeWizard->buildDirectory();
        m_descriptionLabel->setText(
                tr("The directory %1 does not contain a cbp file. Qt Creator needs to create this file, by running cmake. "
                   "Some projects require command line arguments to the initial cmake call.").arg(m_buildDirectory));
    } else {
        m_buildDirectory = m_presetBuildDirectory;
        // TODO tell the user more?
        if (m_update)
            m_descriptionLabel->setText(tr("The directory %1 contains an outdated .cbp file. Qt "
                                           "Creator needs to update this file by running cmake. "
                                           "If you want to add additional command line arguments, "
                                           "add them in the below.").arg(m_buildDirectory));
        else
            m_descriptionLabel->setText(tr("The directory %1, specified in a buildconfiguration, "
                                           "does not contain a cbp file. Qt Creator needs to "
                                           "recreate this file, by running cmake. "
                                           "Some projects require command line arguments to "
                                           "the initial cmake call.").arg(m_buildDirectory));
    }
}

void CMakeRunPage::runCMake()
{
    m_runCMake->setEnabled(false);
    m_argumentsLineEdit->setEnabled(false);
    QStringList arguments = ProjectExplorer::Environment::parseCombinedArgString(m_argumentsLineEdit->text());
    CMakeManager *cmakeManager = m_cmakeWizard->cmakeManager();
    m_cmakeProcess = cmakeManager->createXmlFile(arguments, m_cmakeWizard->sourceDirectory(), m_buildDirectory);
    connect(m_cmakeProcess, SIGNAL(readyRead()), this, SLOT(cmakeReadyRead()));
    connect(m_cmakeProcess, SIGNAL(finished(int)), this, SLOT(cmakeFinished()));
}

void CMakeRunPage::cmakeReadyRead()
{
    m_output->appendPlainText(m_cmakeProcess->readAll());
}

void CMakeRunPage::cmakeFinished()
{
    m_runCMake->setEnabled(true);
    m_argumentsLineEdit->setEnabled(true);
    m_cmakeProcess->deleteLater();
    m_cmakeProcess = 0;
    m_cmakeWizard->setArguments(ProjectExplorer::Environment::parseCombinedArgString(m_argumentsLineEdit->text()));
    //TODO Actually test that running cmake was finished, for setting this bool
    m_complete = true;
    emit completeChanged();
}

void CMakeRunPage::cleanupPage()
{
    m_output->clear();
    m_complete = false;
    emit completeChanged();
}

bool CMakeRunPage::isComplete() const
{
    return m_complete;
}

<commit_msg>Typo fixes for cmake wizard pages.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
**************************************************************************/

#include "cmakeopenprojectwizard.h"
#include "cmakeprojectmanager.h"

#include <utils/pathchooser.h>
#include <projectexplorer/environment.h>

#include <QtGui/QVBoxLayout>
#include <QtGui/QFormLayout>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QPlainTextEdit>
#include <QtCore/QDateTime>
#include <QtCore/QStringList>

using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal;

///////
//  Page Flow:
//   Start (No .user file)
//    |
//    |---> In Source Build --> Page: Tell the user about that
//                               |--> Already existing cbp file (and new enough) --> Page: Ready to load the project
//                               |--> Page: Ask for cmd options, run generator
//    |---> No in source Build --> Page: Ask the user for the build directory
//                                   |--> Already existing cbp file (and new enough) --> Page: Ready to load the project
//                                   |--> Page: Ask for cmd options, run generator

CMakeOpenProjectWizard::CMakeOpenProjectWizard(CMakeManager *cmakeManager, const QString &sourceDirectory)
    : m_cmakeManager(cmakeManager),
      m_sourceDirectory(sourceDirectory),
      m_creatingCbpFiles(false)
{
    int startid;
    if (hasInSourceBuild()) {
        startid = InSourcePageId;
        m_buildDirectory = m_sourceDirectory;
    } else {
        startid = ShadowBuildPageId;
        m_buildDirectory = m_sourceDirectory + "/qtcreator-build";
    }

    setPage(InSourcePageId, new InSourceBuildPage(this));
    setPage(ShadowBuildPageId, new ShadowBuildPage(this));
    setPage(XmlFileUpToDatePageId, new XmlFileUpToDatePage(this));
    setPage(CMakeRunPageId, new CMakeRunPage(this));

    setStartId(startid);
}

CMakeOpenProjectWizard::CMakeOpenProjectWizard(CMakeManager *cmakeManager, const QString &sourceDirectory,
                                               const QStringList &needToCreate, const QStringList &needToUpdate)
    : m_cmakeManager(cmakeManager),
      m_sourceDirectory(sourceDirectory),
      m_creatingCbpFiles(true)
{
    foreach(const QString &buildDirectory, needToCreate)
        addPage(new CMakeRunPage(this, buildDirectory, false));
    foreach(const QString &buildDirectory, needToUpdate)
        addPage(new CMakeRunPage(this, buildDirectory, true));
}

CMakeManager *CMakeOpenProjectWizard::cmakeManager() const
{
    return m_cmakeManager;
}

int CMakeOpenProjectWizard::nextId() const
{
    if (m_creatingCbpFiles)
        return QWizard::nextId();
    int cid = currentId();
    if (cid == InSourcePageId) {
        if (existsUpToDateXmlFile())
            return XmlFileUpToDatePageId;
        else
            return CMakeRunPageId;
    } else if (cid == ShadowBuildPageId) {
        if (existsUpToDateXmlFile())
            return XmlFileUpToDatePageId;
        else
            return CMakeRunPageId;
    }
    return -1;
}

bool CMakeOpenProjectWizard::hasInSourceBuild() const
{
    QFileInfo fi(m_sourceDirectory + "/CMakeCache.txt");
    if (fi.exists())
        return true;
    return false;
}

bool CMakeOpenProjectWizard::existsUpToDateXmlFile() const
{
    QString cbpFile = CMakeManager::findCbpFile(QDir(buildDirectory()));
    if (!cbpFile.isEmpty()) {
        // We already have a cbp file
        QFileInfo cbpFileInfo(cbpFile);
        QFileInfo cmakeListsFileInfo(sourceDirectory() + "/CMakeLists.txt");

        if (cbpFileInfo.lastModified() > cmakeListsFileInfo.lastModified())
            return true;
    }
    return false;
}

QString CMakeOpenProjectWizard::buildDirectory() const
{
    return m_buildDirectory;
}

QString CMakeOpenProjectWizard::sourceDirectory() const
{
    return m_sourceDirectory;
}

void CMakeOpenProjectWizard::setBuildDirectory(const QString &directory)
{
    m_buildDirectory = directory;
}

QStringList CMakeOpenProjectWizard::arguments() const
{
    return m_arguments;
}

void CMakeOpenProjectWizard::setArguments(const QStringList &args)
{
    m_arguments = args;
}

InSourceBuildPage::InSourceBuildPage(CMakeOpenProjectWizard *cmakeWizard)
    : QWizardPage(cmakeWizard), m_cmakeWizard(cmakeWizard)
{
    setLayout(new QVBoxLayout);
    QLabel *label = new QLabel(this);
    label->setWordWrap(true);
    label->setText(tr("Qt Creator has detected an in source build. "
                   "This prevents shadow builds, Qt Creator won't allow you to change the build directory. "
                   "If you want a shadow build, clean your source directory and open the project again."));
    layout()->addWidget(label);
}

XmlFileUpToDatePage::XmlFileUpToDatePage(CMakeOpenProjectWizard *cmakeWizard)
    : QWizardPage(cmakeWizard), m_cmakeWizard(cmakeWizard)
{
    setLayout(new QVBoxLayout);
    QLabel *label = new QLabel(this);
    label->setWordWrap(true);
    label->setText(tr("Qt Creator has found a recent cbp file, which Qt Creator will parse to gather information about the project. "
                   "You can change the command line arguments used to create this file in the project mode. "
                   "Click finish to load the project"));
    layout()->addWidget(label);
}

ShadowBuildPage::ShadowBuildPage(CMakeOpenProjectWizard *cmakeWizard)
    : QWizardPage(cmakeWizard), m_cmakeWizard(cmakeWizard)
{
    QFormLayout *fl = new QFormLayout;
    this->setLayout(fl);

    QLabel *label = new QLabel(this);
    label->setWordWrap(true);
    label->setText(tr("Please enter the directory in which you want to build your project. "
                   "Qt Creator recommends to not use the source directory for building. "
                   "This ensures that the source directory remains clean and enables multiple builds "
                   "with different settings."));
    fl->addWidget(label);
    m_pc = new Core::Utils::PathChooser(this);
    m_pc->setPath(m_cmakeWizard->buildDirectory());
    connect(m_pc, SIGNAL(changed()), this, SLOT(buildDirectoryChanged()));
    fl->addRow("Build directory:", m_pc);
}

void ShadowBuildPage::buildDirectoryChanged()
{
    m_cmakeWizard->setBuildDirectory(m_pc->path());
}

CMakeRunPage::CMakeRunPage(CMakeOpenProjectWizard *cmakeWizard)
    : QWizardPage(cmakeWizard),
      m_cmakeWizard(cmakeWizard),
      m_complete(false)
{
    initWidgets();
}

CMakeRunPage::CMakeRunPage(CMakeOpenProjectWizard *cmakeWizard, const QString &buildDirectory, bool update)
    : QWizardPage(cmakeWizard),
      m_cmakeWizard(cmakeWizard),
      m_complete(false),
      m_update(update),
      m_presetBuildDirectory(buildDirectory)
{
    initWidgets();
}

void CMakeRunPage::initWidgets()
{
    QFormLayout *fl = new QFormLayout;
    setLayout(fl);
    m_descriptionLabel = new QLabel(this);
    m_descriptionLabel->setWordWrap(true);

    fl->addRow(m_descriptionLabel);

    m_argumentsLineEdit = new QLineEdit(this);
    //fl->addRow(tr("Arguments:"), m_argumentsLineEdit);

    m_runCMake = new QPushButton(this);
    m_runCMake->setText(tr("Run CMake"));
    connect(m_runCMake, SIGNAL(clicked()), this, SLOT(runCMake()));
    //fl->addWidget(m_runCMake);

    QHBoxLayout *hbox = new QHBoxLayout;
    hbox->addWidget(m_argumentsLineEdit);
    hbox->addWidget(m_runCMake);

    fl->addRow(tr("Arguments"), hbox);

    m_output = new QPlainTextEdit(this);
    m_output->setReadOnly(true);
    fl->addRow(m_output);
}

void CMakeRunPage::initializePage()
{
    if (m_presetBuildDirectory.isEmpty()) {
        m_buildDirectory = m_cmakeWizard->buildDirectory();
        m_descriptionLabel->setText(
                tr("The directory %1 does not contain a cbp file. Qt Creator needs to create this file by running cmake. "
                   "Some projects require command line arguments to the initial cmake call.").arg(m_buildDirectory));
    } else {
        m_buildDirectory = m_presetBuildDirectory;
        if (m_update)
            m_descriptionLabel->setText(tr("The directory %1 contains an outdated .cbp file. Qt "
                                           "Creator needs to update this file by running cmake. "
                                           "If you want to add additional command line arguments, "
                                           "add them in the below. Note, that cmake remembers command "
                                           "line arguments from the former runs.").arg(m_buildDirectory));
        else
            m_descriptionLabel->setText(tr("The directory %1 specified in a buildconfiguration, "
                                           "does not contain a cbp file. Qt Creator needs to "
                                           "recreate this file, by running cmake. "
                                           "Some projects require command line arguments to "
                                           "the initial cmake call. Note, that cmake remembers command "
                                           "line arguments from the former runs.").arg(m_buildDirectory));
    }
}

void CMakeRunPage::runCMake()
{
    m_runCMake->setEnabled(false);
    m_argumentsLineEdit->setEnabled(false);
    QStringList arguments = ProjectExplorer::Environment::parseCombinedArgString(m_argumentsLineEdit->text());
    CMakeManager *cmakeManager = m_cmakeWizard->cmakeManager();
    m_cmakeProcess = cmakeManager->createXmlFile(arguments, m_cmakeWizard->sourceDirectory(), m_buildDirectory);
    connect(m_cmakeProcess, SIGNAL(readyRead()), this, SLOT(cmakeReadyRead()));
    connect(m_cmakeProcess, SIGNAL(finished(int)), this, SLOT(cmakeFinished()));
}

void CMakeRunPage::cmakeReadyRead()
{
    m_output->appendPlainText(m_cmakeProcess->readAll());
}

void CMakeRunPage::cmakeFinished()
{
    m_runCMake->setEnabled(true);
    m_argumentsLineEdit->setEnabled(true);
    m_cmakeProcess->deleteLater();
    m_cmakeProcess = 0;
    m_cmakeWizard->setArguments(ProjectExplorer::Environment::parseCombinedArgString(m_argumentsLineEdit->text()));
    //TODO Actually test that running cmake was finished, for setting this bool
    m_complete = true;
    emit completeChanged();
}

void CMakeRunPage::cleanupPage()
{
    m_output->clear();
    m_complete = false;
    emit completeChanged();
}

bool CMakeRunPage::isComplete() const
{
    return m_complete;
}

<|endoftext|>