<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: EnhancedPDFExportHelper.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: vg $ $Date: 2008-01-29 08:19:12 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _ENHANCEDPDFEXPORTHELPER_HXX
#define _ENHANCEDPDFEXPORTHELPER_HXX

#ifndef _VCL_PDFEXTOUTDEVDATA_HXX
#include <vcl/pdfextoutdevdata.hxx>
#endif
#ifndef INCLUDED_I18NPOOL_LANG_H
#include <i18npool/lang.h>
#endif
#ifndef _SWRECT_HXX
#include <swrect.hxx>
#endif
#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif

#include <map>
#include <vector>
#include <set>

class vcl::PDFExtOutDevData;
class OutputDevice;
class SwFrm;
class SwLinePortion;
class SwTxtPainter;
class SwEditShell;
class rtl::OUString;
class MultiSelection;
class SwTxtNode;
class SwNumRule;
class SwTable;
class SwNumberTreeNode;
class String;
class SvxLanguageItem;

/*
 * Mapping of OOo elements to tagged pdf elements:
 *
 * OOo element                              tagged pdf element
 * -----------                              ------------------
 *
 * Grouping elements:
 *
 * SwRootFrm                                Document
 *                                          Part
 *                                          Art
 * SwSection                                Sect
 * SwFtnContFrm and SwFlyFrm                Div
 * SwFmt "Quotations"                       BlockQuote
 * SwFmt "Caption"                          Caption
 * SwSection (TOC)                          TOC
 * SwTxtNode in TOC                         TOCI
 * SwSection (Index)                        Index
 *
 * Block-Level Structure Elements:
 *
 * SwTxtNode                                P
 * SwFmt "Heading"                          H
 * SwTxtNode with Outline                   H1 - H6
 * SwTxtNode with NumRule                   L, LI, LBody
 * SwTable                                  Table
 * SwRowFrm                                 TR
 * SwCellFrm in Headline row or
 * SwFtm "Table Heading"                    TH
 * SwCellFrm                                TD
 *
 * Inline-Level Structure Elements:
 *
 * SwTxtPortion                             Span
 * SwFmt "Quotation"                        Quote
 * SwFtnFrm                                 Note
 *                                          Form
 *                                          Reference
 * SwFldPortion (AuthorityField)            BibEntry
 * SwFmt "Source Text"                      Code
 * SwFtnPortion, SwFldPortion (RefField)    Link
 *
 * Illustration elements:
 *
 * SwFlyFrm with SwNoTxtFrm                 Figure
 * SwFlyFrm with Math OLE Object            Formula
 *
 */

struct Num_Info
{
    const SwFrm& mrFrm;
    Num_Info( const SwFrm& rFrm ) : mrFrm( rFrm ) {};
};

struct Frm_Info
{
    const SwFrm& mrFrm;
    Frm_Info( const SwFrm& rFrm ) : mrFrm( rFrm ) {};
};

struct Por_Info
{
    const SwLinePortion& mrPor;
    const SwTxtPainter& mrTxtPainter;
    Por_Info( const SwLinePortion& rPor, const SwTxtPainter& rTxtPainer )
            : mrPor( rPor ), mrTxtPainter( rTxtPainer ) {};
};

struct lt_TableColumn
{
    bool operator()( long nVal1, long nVal2 ) const
    {
        return nVal1 + ( MINLAY - 1 ) < nVal2;
    }
};

/*************************************************************************
 *                class SwTaggedPDFHelper
 * Analyses a given frame during painting and generates the appropriate
 * structure elements.
 *************************************************************************/

class SwTaggedPDFHelper
{
    private:

    // This will be incremented for each BeginTag() call.
    // It denotes the number of tags to close during EndStructureElements();
    BYTE nEndStructureElement;

    //  If an already existing tag is reopened for follows of flow frames,
    // this value stores the tag id which has to be restored.
    sal_Int32 nRestoreCurrentTag;

    vcl::PDFExtOutDevData* mpPDFExtOutDevData;

    const Num_Info* mpNumInfo;
    const Frm_Info* mpFrmInfo;
    const Por_Info* mpPorInfo;

    void BeginTag( vcl::PDFWriter::StructElement, const String* pUserDefined = 0 );
    void EndTag();

    void SetAttributes( vcl::PDFWriter::StructElement eType );

    // These functions are called by the c'tor, d'tor
    void BeginNumberedListStructureElements();
    void BeginBlockStructureElements();
    void BeginInlineStructureElements();
    void EndStructureElements();

    bool CheckReopenTag();
    bool CheckRestoreTag() const;

    public:

    // pFrmInfo != 0 => BeginBlockStructureElement
    // pPorInfo != 0 => BeginInlineStructureElement
    // pFrmInfo, pPorInfo = 0 => BeginNonStructureElement
    SwTaggedPDFHelper( const Num_Info* pNumInfo, const Frm_Info* pFrmInfo, const Por_Info* pPorInfo,
                       OutputDevice& rOut );
    ~SwTaggedPDFHelper();

    static bool IsExportTaggedPDF( const OutputDevice& rOut );
};

/*************************************************************************
 *                class SwEnhancedPDFExportHelper
 * Analyses the document structure and export Notes, Hyperlinks, References,
 * and Outline. Link ids created during pdf export are stored in
 * aReferenceIdMap and aHyperlinkIdMap, in order to use them during
 * tagged pdf output. Therefore the SwEnhancedPDFExportHelper is used
 * before painting. Unfortunately links from the EditEngine into the
 * Writer document require to be exported after they have been painted.
 * Therefore SwEnhancedPDFExportHelper also has to be used after the
 * painting process, the parameter bEditEngineOnly indicated that only
 * the bookmarks from the EditEngine have to be processed.
 *************************************************************************/

typedef std::set< long, lt_TableColumn > TableColumnsMapEntry;
typedef std::pair< SwRect, sal_Int32 > IdMapEntry;
typedef std::vector< IdMapEntry > LinkIdMap;
typedef std::map< const SwTable*, TableColumnsMapEntry > TableColumnsMap;
typedef std::map< const SwNumberTreeNode*, sal_Int32 > NumListIdMap;
typedef std::map< const SwNumberTreeNode*, sal_Int32 > NumListBodyIdMap;
typedef std::map< const void*, sal_Int32 > FrmTagIdMap;

class SwEnhancedPDFExportHelper
{
    private:

    SwEditShell& mrSh;
    OutputDevice& mrOut;

    MultiSelection* pPageRange;

    bool mbSkipEmptyPages;
    bool mbEditEngineOnly;

    static TableColumnsMap aTableColumnsMap;
    static LinkIdMap aLinkIdMap;
    static NumListIdMap aNumListIdMap;
    static NumListBodyIdMap aNumListBodyIdMap;
    static FrmTagIdMap aFrmTagIdMap;

    static LanguageType eLanguageDefault;

    void EnhancedPDFExport();
    sal_Int32 CalcOutputPageNum( const SwRect& rRect ) const;

    void MakeHeaderFooterLinks( vcl::PDFExtOutDevData& rPDFExtOutDevData,
                                const SwTxtNode& rTNd, const SwRect& rLinkRect,
                                sal_Int32 nDestId, const String& rURL, bool bIntern ) const;

    public:

    SwEnhancedPDFExportHelper( SwEditShell& rSh,
                               OutputDevice& rOut,
                               const rtl::OUString& rPageRange,
                               bool bSkipEmptyPages,
                               bool bEditEngineOnly );

    ~SwEnhancedPDFExportHelper();

    static TableColumnsMap& GetTableColumnsMap() {return aTableColumnsMap; }
    static LinkIdMap& GetLinkIdMap() { return aLinkIdMap; }
    static NumListIdMap& GetNumListIdMap() {return aNumListIdMap; }
    static NumListBodyIdMap& GetNumListBodyIdMap() {return aNumListBodyIdMap; }
    static FrmTagIdMap& GetFrmTagIdMap() { return aFrmTagIdMap; }

    static const LanguageType GetDefaultLanguage() {return eLanguageDefault; }
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.8.108); FILE MERGED 2008/04/01 15:56:04 thb 1.8.108.3: #i85898# Stripping all external header guards 2008/04/01 12:53:25 thb 1.8.108.2: #i85898# Stripping all external header guards 2008/03/31 16:52:32 rt 1.8.108.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: EnhancedPDFExportHelper.hxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _ENHANCEDPDFEXPORTHELPER_HXX
#define _ENHANCEDPDFEXPORTHELPER_HXX

#include <vcl/pdfextoutdevdata.hxx>
#include <i18npool/lang.h>
#include <swrect.hxx>
#include <swtypes.hxx>

#include <map>
#include <vector>
#include <set>

class vcl::PDFExtOutDevData;
class OutputDevice;
class SwFrm;
class SwLinePortion;
class SwTxtPainter;
class SwEditShell;
class rtl::OUString;
class MultiSelection;
class SwTxtNode;
class SwNumRule;
class SwTable;
class SwNumberTreeNode;
class String;
class SvxLanguageItem;

/*
 * Mapping of OOo elements to tagged pdf elements:
 *
 * OOo element                              tagged pdf element
 * -----------                              ------------------
 *
 * Grouping elements:
 *
 * SwRootFrm                                Document
 *                                          Part
 *                                          Art
 * SwSection                                Sect
 * SwFtnContFrm and SwFlyFrm                Div
 * SwFmt "Quotations"                       BlockQuote
 * SwFmt "Caption"                          Caption
 * SwSection (TOC)                          TOC
 * SwTxtNode in TOC                         TOCI
 * SwSection (Index)                        Index
 *
 * Block-Level Structure Elements:
 *
 * SwTxtNode                                P
 * SwFmt "Heading"                          H
 * SwTxtNode with Outline                   H1 - H6
 * SwTxtNode with NumRule                   L, LI, LBody
 * SwTable                                  Table
 * SwRowFrm                                 TR
 * SwCellFrm in Headline row or
 * SwFtm "Table Heading"                    TH
 * SwCellFrm                                TD
 *
 * Inline-Level Structure Elements:
 *
 * SwTxtPortion                             Span
 * SwFmt "Quotation"                        Quote
 * SwFtnFrm                                 Note
 *                                          Form
 *                                          Reference
 * SwFldPortion (AuthorityField)            BibEntry
 * SwFmt "Source Text"                      Code
 * SwFtnPortion, SwFldPortion (RefField)    Link
 *
 * Illustration elements:
 *
 * SwFlyFrm with SwNoTxtFrm                 Figure
 * SwFlyFrm with Math OLE Object            Formula
 *
 */

struct Num_Info
{
    const SwFrm& mrFrm;
    Num_Info( const SwFrm& rFrm ) : mrFrm( rFrm ) {};
};

struct Frm_Info
{
    const SwFrm& mrFrm;
    Frm_Info( const SwFrm& rFrm ) : mrFrm( rFrm ) {};
};

struct Por_Info
{
    const SwLinePortion& mrPor;
    const SwTxtPainter& mrTxtPainter;
    Por_Info( const SwLinePortion& rPor, const SwTxtPainter& rTxtPainer )
            : mrPor( rPor ), mrTxtPainter( rTxtPainer ) {};
};

struct lt_TableColumn
{
    bool operator()( long nVal1, long nVal2 ) const
    {
        return nVal1 + ( MINLAY - 1 ) < nVal2;
    }
};

/*************************************************************************
 *                class SwTaggedPDFHelper
 * Analyses a given frame during painting and generates the appropriate
 * structure elements.
 *************************************************************************/

class SwTaggedPDFHelper
{
    private:

    // This will be incremented for each BeginTag() call.
    // It denotes the number of tags to close during EndStructureElements();
    BYTE nEndStructureElement;

    //  If an already existing tag is reopened for follows of flow frames,
    // this value stores the tag id which has to be restored.
    sal_Int32 nRestoreCurrentTag;

    vcl::PDFExtOutDevData* mpPDFExtOutDevData;

    const Num_Info* mpNumInfo;
    const Frm_Info* mpFrmInfo;
    const Por_Info* mpPorInfo;

    void BeginTag( vcl::PDFWriter::StructElement, const String* pUserDefined = 0 );
    void EndTag();

    void SetAttributes( vcl::PDFWriter::StructElement eType );

    // These functions are called by the c'tor, d'tor
    void BeginNumberedListStructureElements();
    void BeginBlockStructureElements();
    void BeginInlineStructureElements();
    void EndStructureElements();

    bool CheckReopenTag();
    bool CheckRestoreTag() const;

    public:

    // pFrmInfo != 0 => BeginBlockStructureElement
    // pPorInfo != 0 => BeginInlineStructureElement
    // pFrmInfo, pPorInfo = 0 => BeginNonStructureElement
    SwTaggedPDFHelper( const Num_Info* pNumInfo, const Frm_Info* pFrmInfo, const Por_Info* pPorInfo,
                       OutputDevice& rOut );
    ~SwTaggedPDFHelper();

    static bool IsExportTaggedPDF( const OutputDevice& rOut );
};

/*************************************************************************
 *                class SwEnhancedPDFExportHelper
 * Analyses the document structure and export Notes, Hyperlinks, References,
 * and Outline. Link ids created during pdf export are stored in
 * aReferenceIdMap and aHyperlinkIdMap, in order to use them during
 * tagged pdf output. Therefore the SwEnhancedPDFExportHelper is used
 * before painting. Unfortunately links from the EditEngine into the
 * Writer document require to be exported after they have been painted.
 * Therefore SwEnhancedPDFExportHelper also has to be used after the
 * painting process, the parameter bEditEngineOnly indicated that only
 * the bookmarks from the EditEngine have to be processed.
 *************************************************************************/

typedef std::set< long, lt_TableColumn > TableColumnsMapEntry;
typedef std::pair< SwRect, sal_Int32 > IdMapEntry;
typedef std::vector< IdMapEntry > LinkIdMap;
typedef std::map< const SwTable*, TableColumnsMapEntry > TableColumnsMap;
typedef std::map< const SwNumberTreeNode*, sal_Int32 > NumListIdMap;
typedef std::map< const SwNumberTreeNode*, sal_Int32 > NumListBodyIdMap;
typedef std::map< const void*, sal_Int32 > FrmTagIdMap;

class SwEnhancedPDFExportHelper
{
    private:

    SwEditShell& mrSh;
    OutputDevice& mrOut;

    MultiSelection* pPageRange;

    bool mbSkipEmptyPages;
    bool mbEditEngineOnly;

    static TableColumnsMap aTableColumnsMap;
    static LinkIdMap aLinkIdMap;
    static NumListIdMap aNumListIdMap;
    static NumListBodyIdMap aNumListBodyIdMap;
    static FrmTagIdMap aFrmTagIdMap;

    static LanguageType eLanguageDefault;

    void EnhancedPDFExport();
    sal_Int32 CalcOutputPageNum( const SwRect& rRect ) const;

    void MakeHeaderFooterLinks( vcl::PDFExtOutDevData& rPDFExtOutDevData,
                                const SwTxtNode& rTNd, const SwRect& rLinkRect,
                                sal_Int32 nDestId, const String& rURL, bool bIntern ) const;

    public:

    SwEnhancedPDFExportHelper( SwEditShell& rSh,
                               OutputDevice& rOut,
                               const rtl::OUString& rPageRange,
                               bool bSkipEmptyPages,
                               bool bEditEngineOnly );

    ~SwEnhancedPDFExportHelper();

    static TableColumnsMap& GetTableColumnsMap() {return aTableColumnsMap; }
    static LinkIdMap& GetLinkIdMap() { return aLinkIdMap; }
    static NumListIdMap& GetNumListIdMap() {return aNumListIdMap; }
    static NumListBodyIdMap& GetNumListBodyIdMap() {return aNumListBodyIdMap; }
    static FrmTagIdMap& GetFrmTagIdMap() { return aFrmTagIdMap; }

    static const LanguageType GetDefaultLanguage() {return eLanguageDefault; }
};

#endif
<|endoftext|>


<commit_before>/**
 * Clever programming language
 * Copyright (c) Clever Team
 *
 * This file is distributed under the MIT license. See LICENSE for details.
 */

#include <cmath>
#include <cstdlib>
#include <ctime>

#include "core/value.h"
#include "core/native_types.h"
#include "core/modmanager.h"
#include "modules/std/math/math.h"

#ifndef M_PI
#define M_PI    3.14159265358979323846
#endif

namespace clever { namespace modules { namespace std {

namespace math {

// round(double)
static CLEVER_FUNCTION(round)
{
	if (!clever_static_check_args("d")) {
		return;
	}
	double value = args[0]->getDouble();

#ifdef CLEVER_MSVC
	result->setDouble((value > 0.0) ? ::floor(value + 0.5) : ::ceil(value - 0.5));
#else
	result->setDouble(::round(value));
#endif
}

// ceil(number)
static CLEVER_FUNCTION(ceil)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::ceil(args[0]->getInt()));
	} else {
		result->setDouble(::std::ceil(args[0]->getDouble()));
	}
}

// sqrt(number)
static CLEVER_FUNCTION(sqrt)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::sqrt(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::sqrt(args[0]->getDouble()));
	}
}

// floor(number)
static CLEVER_FUNCTION(floor)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::floor(args[0]->getInt()));
	} else if (args[0]->isDouble()) {
		result->setDouble(::std::floor(args[0]->getDouble()));
	}
}

// abs(number)
static CLEVER_FUNCTION(abs)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::labs(args[0]->getInt()));
	} else {
		result->setDouble(::std::abs(args[0]->getDouble()));
	}
}

// cos(number)
static CLEVER_FUNCTION(cos)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::cos(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::cos(args[0]->getDouble()));
	}
}

// acos(number)
static CLEVER_FUNCTION(acos)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::acos(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::acos(args[0]->getDouble()));
	}
}

// cosh(number)
static CLEVER_FUNCTION(cosh)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::cosh(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::cosh(args[0]->getDouble()));
	}
}

// sin(number)
static CLEVER_FUNCTION(sin)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::sin(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::sin(args[0]->getDouble()));
	}
}

// asin(number)
static CLEVER_FUNCTION(asin)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::asin(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::asin(args[0]->getDouble()));
	}
}

// sinh(number)
static CLEVER_FUNCTION(sinh)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::sinh(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::sinh(args[0]->getDouble()));
	}
}

// tan(number)
static CLEVER_FUNCTION(tan)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::tan(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::tan(args[0]->getDouble()));
	}
}

// tanh(number)
static CLEVER_FUNCTION(tanh)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::tanh(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::tanh(args[0]->getDouble()));
	}
}

// atan(number [, number])
static CLEVER_FUNCTION(atan)
{
	if (!clever_static_check_args("n|n")) {
		return;
	}

	if (args.size() == 1) {
		if (args[0]->isInt()) {
			result->setInt(::std::atan(double(args[0]->getInt())));
		} else {
			result->setDouble(::std::atan(args[0]->getDouble()));
		}
	} else {
		double y = args[0]->isInt() ? double(args[0]->getInt()) : args[0]->getDouble();
		double x = args[1]->isInt() ? double(args[1]->getInt()) : args[1]->getDouble();

		if (args[0]->isInt()) {
			result->setInt(::std::atan2(y, x));
		} else {
			result->setDouble(::std::atan2(y, x));
		}
	}
}

// log(number)
static CLEVER_FUNCTION(log)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::log(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::log(args[0]->getDouble()));
	}
}

// exp(number)
static CLEVER_FUNCTION(exp)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::exp(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::exp(args[0]->getDouble()));
	}
}

// rand()
// generate a random number betwen 0 and 1
static CLEVER_FUNCTION(rand)
{
	if (!clever_static_check_no_args()) {
		return;
	}

	result->setDouble(static_cast<double>(::std::rand()) / RAND_MAX);
}

} // clever::modules::std::math

// Load module data
CLEVER_MODULE_INIT(Math)
{
	::std::srand(::std::time(NULL));

	addFunction(new Function("round", &CLEVER_NS_FNAME(math, round)));
	addFunction(new Function("ceil",  &CLEVER_NS_FNAME(math, ceil)));
	addFunction(new Function("sqrt",  &CLEVER_NS_FNAME(math, sqrt)));
	addFunction(new Function("floor", &CLEVER_NS_FNAME(math, floor)));
	addFunction(new Function("exp",   &CLEVER_NS_FNAME(math, exp)));
	addFunction(new Function("abs",   &CLEVER_NS_FNAME(math, abs)));
	addFunction(new Function("cos",   &CLEVER_NS_FNAME(math, cos)));
	addFunction(new Function("acos",  &CLEVER_NS_FNAME(math, acos)));
	addFunction(new Function("cosh",  &CLEVER_NS_FNAME(math, cosh)));
	addFunction(new Function("sin",   &CLEVER_NS_FNAME(math, sin)));
	addFunction(new Function("sinh",  &CLEVER_NS_FNAME(math, sinh)));
	addFunction(new Function("asin",  &CLEVER_NS_FNAME(math, asin)));
	addFunction(new Function("tan",   &CLEVER_NS_FNAME(math, tan)));
	addFunction(new Function("tanh",  &CLEVER_NS_FNAME(math, tanh)));
	addFunction(new Function("atan",  &CLEVER_NS_FNAME(math, atan)));
	addFunction(new Function("log",   &CLEVER_NS_FNAME(math, log)));
	addFunction(new Function("rand",  &CLEVER_NS_FNAME(math, rand)));

	addVariable("PI",       new Value(M_PI, true));
}

}}} // clever::modules::std
<commit_msg>math:rand added<commit_after>/**
 * Clever programming language
 * Copyright (c) Clever Team
 *
 * This file is distributed under the MIT license. See LICENSE for details.
 */

#include <cmath>
#include <cstdlib>
#include <ctime>

#include "core/value.h"
#include "core/native_types.h"
#include "core/modmanager.h"
#include "modules/std/math/math.h"

#ifndef M_PI
#define M_PI    3.14159265358979323846
#endif

namespace clever { namespace modules { namespace std {

namespace math {

// round(double)
static CLEVER_FUNCTION(round)
{
	if (!clever_static_check_args("d")) {
		return;
	}
	double value = args[0]->getDouble();

#ifdef CLEVER_MSVC
	result->setDouble((value > 0.0) ? ::floor(value + 0.5) : ::ceil(value - 0.5));
#else
	result->setDouble(::round(value));
#endif
}

// ceil(number)
static CLEVER_FUNCTION(ceil)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::ceil(args[0]->getInt()));
	} else {
		result->setDouble(::std::ceil(args[0]->getDouble()));
	}
}

// sqrt(number)
static CLEVER_FUNCTION(sqrt)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::sqrt(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::sqrt(args[0]->getDouble()));
	}
}

// floor(number)
static CLEVER_FUNCTION(floor)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::floor(args[0]->getInt()));
	} else if (args[0]->isDouble()) {
		result->setDouble(::std::floor(args[0]->getDouble()));
	}
}

// abs(number)
static CLEVER_FUNCTION(abs)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::labs(args[0]->getInt()));
	} else {
		result->setDouble(::std::abs(args[0]->getDouble()));
	}
}

// cos(number)
static CLEVER_FUNCTION(cos)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::cos(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::cos(args[0]->getDouble()));
	}
}

// acos(number)
static CLEVER_FUNCTION(acos)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::acos(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::acos(args[0]->getDouble()));
	}
}

// cosh(number)
static CLEVER_FUNCTION(cosh)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::cosh(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::cosh(args[0]->getDouble()));
	}
}

// sin(number)
static CLEVER_FUNCTION(sin)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::sin(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::sin(args[0]->getDouble()));
	}
}

// asin(number)
static CLEVER_FUNCTION(asin)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::asin(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::asin(args[0]->getDouble()));
	}
}

// sinh(number)
static CLEVER_FUNCTION(sinh)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::sinh(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::sinh(args[0]->getDouble()));
	}
}

// tan(number)
static CLEVER_FUNCTION(tan)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::tan(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::tan(args[0]->getDouble()));
	}
}

// tanh(number)
static CLEVER_FUNCTION(tanh)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::tanh(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::tanh(args[0]->getDouble()));
	}
}

// atan(number [, number])
static CLEVER_FUNCTION(atan)
{
	if (!clever_static_check_args("n|n")) {
		return;
	}

	if (args.size() == 1) {
		if (args[0]->isInt()) {
			result->setInt(::std::atan(double(args[0]->getInt())));
		} else {
			result->setDouble(::std::atan(args[0]->getDouble()));
		}
	} else {
		double y = args[0]->isInt() ? double(args[0]->getInt()) : args[0]->getDouble();
		double x = args[1]->isInt() ? double(args[1]->getInt()) : args[1]->getDouble();

		if (args[0]->isInt()) {
			result->setInt(::std::atan2(y, x));
		} else {
			result->setDouble(::std::atan2(y, x));
		}
	}
}

// log(number)
static CLEVER_FUNCTION(log)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::log(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::log(args[0]->getDouble()));
	}
}

// exp(number)
static CLEVER_FUNCTION(exp)
{
	if (!clever_static_check_args("n")) {
		return;
	}

	if (args[0]->isInt()) {
		result->setInt(::std::exp(double(args[0]->getInt())));
	} else {
		result->setDouble(::std::exp(args[0]->getDouble()));
	}
}

// rand()
// generate a random number betwen 0 and 1
static CLEVER_FUNCTION(rand)
{
	if (!clever_static_check_no_args()) {
		return;
	}

	result->setDouble(static_cast<double>(::std::rand()) / RAND_MAX);
}

// srand()
// generate a seed to random number generator
static CLEVER_FUNCTION(srand)
{
	if (!clever_static_check_args("i")) {
		return;
	}
	::std::srand(args[0]->getInt());
}

} // clever::modules::std::math

// Load module data
CLEVER_MODULE_INIT(Math)
{
	::std::srand(::std::time(NULL));

	addFunction(new Function("round", &CLEVER_NS_FNAME(math, round)));
	addFunction(new Function("ceil",  &CLEVER_NS_FNAME(math, ceil)));
	addFunction(new Function("sqrt",  &CLEVER_NS_FNAME(math, sqrt)));
	addFunction(new Function("floor", &CLEVER_NS_FNAME(math, floor)));
	addFunction(new Function("exp",   &CLEVER_NS_FNAME(math, exp)));
	addFunction(new Function("abs",   &CLEVER_NS_FNAME(math, abs)));
	addFunction(new Function("cos",   &CLEVER_NS_FNAME(math, cos)));
	addFunction(new Function("acos",  &CLEVER_NS_FNAME(math, acos)));
	addFunction(new Function("cosh",  &CLEVER_NS_FNAME(math, cosh)));
	addFunction(new Function("sin",   &CLEVER_NS_FNAME(math, sin)));
	addFunction(new Function("sinh",  &CLEVER_NS_FNAME(math, sinh)));
	addFunction(new Function("asin",  &CLEVER_NS_FNAME(math, asin)));
	addFunction(new Function("tan",   &CLEVER_NS_FNAME(math, tan)));
	addFunction(new Function("tanh",  &CLEVER_NS_FNAME(math, tanh)));
	addFunction(new Function("atan",  &CLEVER_NS_FNAME(math, atan)));
	addFunction(new Function("log",   &CLEVER_NS_FNAME(math, log)));
	addFunction(new Function("rand",  &CLEVER_NS_FNAME(math, rand)));
	addFunction(new Function("srand",  &CLEVER_NS_FNAME(math, srand)));

	addVariable("PI",       new Value(M_PI, true));
}

}}} // clever::modules::std
<|endoftext|>


<commit_before>/*!
	@file
	@author		Albert Semenov
	@date		05/2009
*/
#include "Precompiled.h"
#include "BaseManager.h"
#include "MyGUI_Diagnostic.h"

#include <SDL_image.h>

#ifdef MYGUI_CHECK_MEMORY_LEAKS
#	undef new
#	undef delete
#endif

// имя класса окна
const char* WND_CLASS_NAME = "MyGUI_Demo_window";

namespace base
{
	BaseManager::BaseManager() :
		mGUI(nullptr),
		mPlatform(nullptr),
		mWindow(nullptr),
		mContext(nullptr),
		mExit(false),
		mWindowOn(false),
		mResourceFileName("MyGUI_Core.xml")
	{
		// initialize SDL
		MYGUI_ASSERT(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_EVENTS) == 0, "Failed initializing SDL.");
		// initialize SDL_image
		MYGUI_ASSERT(IMG_Init(~0) != 0, "Failed to initializing SDL_image");
	}

	BaseManager::~BaseManager()
	{
		SDL_GL_DeleteContext(mContext);
		IMG_Quit();
		SDL_Quit();
	}

	void BaseManager::_windowResized( int w, int h )
{
		if (mPlatform)
			mPlatform->getRenderManagerPtr()->setViewSize(w, h);

		setInputViewSize(w, h);
	}

	bool BaseManager::create(int _width, int _height)
	{
		const unsigned int width = _width;
		const unsigned int height = _height;
		bool windowed = true;

		// create window and position it at the center of the screen
		SDL_DisplayMode currDisp;
		MYGUI_ASSERT(SDL_GetCurrentDisplayMode(0, &currDisp) == 0, "Failed to retrieve screen info.");
		int left = (currDisp.w - width) / 2;
		int top = (currDisp.h - height) / 2;

		mWindow = SDL_CreateWindow("OpenGL Render Window", left, top, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
		MYGUI_ASSERT(mWindow != nullptr, "Failed to create SDL window.");
		mContext = SDL_GL_CreateContext(mWindow);
		MYGUI_ASSERT(mContext != nullptr, "Failed to create SDL context.");
		mWindowOn = true;

		if (!createRender(width, height, windowed))
		{
			return false;
		}

		createGui();

		createInput();

		createPointerManager();

		// this needs to be called before createScene() since some demos require
		// screen size to properly position the widgets
		_windowResized(width, height);

		createScene();

		return true;
	}

	void BaseManager::run()
	{
		while (!mExit)
		{
			while (SDL_PollEvent(&mEvent) != 0)
			{
				switch (mEvent.type)
				{
				// keyboard events
				case SDL_KEYDOWN:
					mKeyCode = mEvent.key.keysym.sym;
					keyPressed(mKeyCode, nullptr);
					break;
				case SDL_TEXTINPUT:
					mKeyCode = SDLK_UNKNOWN;
					keyPressed(mKeyCode, &mEvent.text);
					break;
				case SDL_KEYUP:
					keyReleased(mEvent.key);
					break;
				// mouse events
				case SDL_MOUSEMOTION:
					mouseMoved(mEvent.motion);
					break;
				case SDL_MOUSEBUTTONDOWN:
					mousePressed(mEvent.button);
					break;
				case SDL_MOUSEBUTTONUP:
					mouseReleased(mEvent.button);
					break;
				case SDL_MOUSEWHEEL:
					mouseWheelMoved(mEvent.wheel);
					break;
					// drop file events
				case SDL_DROPFILE:
					break;
					// windows events
				case SDL_WINDOWEVENT:
					switch (mEvent.window.event)
					{
					case SDL_WINDOWEVENT_CLOSE:
						mExit = true;
						break;
					case SDL_WINDOWEVENT_RESIZED:
						_windowResized(mEvent.window.data1, mEvent.window.data2);
						break;
					case SDL_WINDOWEVENT_SHOWN:
					case SDL_WINDOWEVENT_RESTORED:
					case SDL_WINDOWEVENT_EXPOSED:
					case SDL_WINDOWEVENT_MAXIMIZED:
						mWindowOn = true;
						break;
					case SDL_WINDOWEVENT_MINIMIZED:
					case SDL_WINDOWEVENT_HIDDEN:
						mWindowOn = false;
					default:
						break;
					}
					break;
				default:
					break;
				}
			}
			glClearColor(0, 0, 0, 1);
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

			drawOneFrame();
			if (!mWindowOn)
				SDL_Delay(50);
		}
	}

	void BaseManager::destroy()
	{
		destroyScene();

		destroyPointerManager();

		destroyInput();

		destroyGui();

		destroyRender();

	}

	void BaseManager::setupResources()
	{
		MyGUI::xml::Document doc;

		if (!doc.open(std::string("resources.xml")))
			doc.getLastError();

		MyGUI::xml::ElementPtr root = doc.getRoot();
		if (root == nullptr || root->getName() != "Paths")
			return;

		MyGUI::xml::ElementEnumerator node = root->getElementEnumerator();
		while (node.next())
		{
			if (node->getName() == "Path")
			{
				if (node->findAttribute("root") != "")
				{
					bool root = MyGUI::utility::parseBool(node->findAttribute("root"));
					if (root)
						mRootMedia = node->getContent();
				}
				addResourceLocation(node->getContent(), false);
			}
		}

		addResourceLocation(getRootMedia() + "/Common/Base");
	}

	void BaseManager::createGui()
	{
		mPlatform = new MyGUI::OpenGLPlatform();
		mPlatform->initialise(this);

		setupResources();

		mGUI = new MyGUI::Gui();
		mGUI->initialise(mResourceFileName);

		SDL_StartTextInput();
	}

	void BaseManager::destroyGui()
	{
		SDL_StopTextInput();
		if (mGUI)
		{
			mGUI->shutdown();
			delete mGUI;
			mGUI = nullptr;
		}

		if (mPlatform)
		{
			mPlatform->shutdown();
			delete mPlatform;
			mPlatform = nullptr;
		}
	}

	void BaseManager::setWindowMaximized(bool _value)
	{
		if (mWindow != nullptr && _value)
		{
			SDL_MaximizeWindow(mWindow);
		}
	}

	bool BaseManager::getWindowMaximized()
	{
		Uint32 windowState = SDL_GetWindowFlags(mWindow);
		return windowState & SDL_WINDOW_MAXIMIZED || windowState & SDL_WINDOW_FULLSCREEN;
	}

	void BaseManager::setWindowCoord(const MyGUI::IntCoord& _value)
	{
		if (_value.empty())
			return;

		MyGUI::IntCoord coord = _value;

		SDL_SetWindowPosition(mWindow, coord.left, coord.top);
	}

	MyGUI::IntCoord BaseManager::getWindowCoord()
	{
		int left, top, width, height;
		SDL_GetWindowPosition(mWindow, &left, &top);
		SDL_GetWindowSize(mWindow, &width, &height);
		return MyGUI::IntCoord(left, top, width, height);
	}

	void BaseManager::setWindowCaption(const std::wstring& _text)
	{
		MyGUI::UString title(_text);
		SDL_SetWindowTitle(mWindow, title.asUTF8_c_str());
	}

	void BaseManager::prepare()
	{
	}

	void BaseManager::addResourceLocation(const std::string& _name, bool _recursive)
	{
		mPlatform->getDataManagerPtr()->addResourceLocation(_name, _recursive);
	}

	void BaseManager::injectMouseMove(int _absx, int _absy, int _absz)
	{
		if (!mGUI)
			return;

		MyGUI::InputManager::getInstance().injectMouseMove(_absx, _absy, _absz);
	}

	void BaseManager::injectMousePress(int _absx, int _absy, MyGUI::MouseButton _id)
	{
		if (!mGUI)
			return;

		MyGUI::InputManager::getInstance().injectMousePress(_absx, _absy, _id);
	}

	void BaseManager::injectMouseRelease(int _absx, int _absy, MyGUI::MouseButton _id)
	{
		if (!mGUI)
			return;

		MyGUI::InputManager::getInstance().injectMouseRelease(_absx, _absy, _id);
	}

	void BaseManager::injectKeyPress(MyGUI::KeyCode _key, MyGUI::Char _text)
	{
		if (!mGUI)
			return;

		if (_key == MyGUI::KeyCode::Escape)
		{
			mExit = true;
			return;
		}

		MyGUI::InputManager::getInstance().injectKeyPress(_key, _text);
	}

	void BaseManager::injectKeyRelease(MyGUI::KeyCode _key)
	{
		if (!mGUI)
			return;

		MyGUI::InputManager::getInstance().injectKeyRelease(_key);
	}

	bool BaseManager::createRender(int _width, int _height, bool _windowed)
	{
		return true;
	}

	void BaseManager::drawOneFrame()
	{
		if (mPlatform)
			mPlatform->getRenderManagerPtr()->drawOneFrame();

		SDL_GL_SwapWindow(mWindow);
	}

	void BaseManager::destroyRender()
	{
	}

	void* BaseManager::convertPixelData(SDL_Surface *_image, MyGUI::PixelFormat& _myGuiPixelFormat)
	{
		void* ret = nullptr;
		SDL_PixelFormat *format = _image->format;
		unsigned int bpp = format->BytesPerPixel;
		switch (bpp) {
		case 1:
			_myGuiPixelFormat = MyGUI::PixelFormat::L8;
			break;
		case 2:
			_myGuiPixelFormat = MyGUI::PixelFormat::L8A8;
			break;
		case 3:
			_myGuiPixelFormat = MyGUI::PixelFormat::R8G8B8;
			break;
		case 4:
			_myGuiPixelFormat = MyGUI::PixelFormat::R8G8B8A8;
			break;
		default:
			break;
		}
		SDL_LockSurface(_image);

		int pitchSrc = _image->pitch;	//the length of a row of pixels in bytes
		int bppSrc = pitchSrc / _image->w;
		size_t size = _image->h * pitchSrc;
		ret = new unsigned char[size];
		unsigned char* ptr_source = (unsigned char*)_image->pixels;
		unsigned char* ptr_dst = (unsigned char*)ret;
		int pitchDst = _image->w * bpp;
		if (pitchSrc == pitchDst)
		{
			memcpy(ret, _image->pixels, size);
		}
		else
		{
			for (unsigned int y = 0; y < (unsigned int)_image->h; ++y)
			{
				memcpy(ptr_dst, ptr_source, pitchDst);
				ptr_dst += pitchDst;
				ptr_source += pitchSrc;
			}
		}

		SDL_UnlockSurface(_image);
		return ret;
	}

	void* BaseManager::loadImage(int& _width, int& _height, MyGUI::PixelFormat& _format, const std::string& _filename)
	{
		std::string fullname = MyGUI::OpenGLDataManager::getInstance().getDataPath(_filename);
		void* result = nullptr;
		SDL_Surface *image = nullptr;
		SDL_Surface *cvtImage = nullptr;		// converted surface with RGBA/RGB pixel format
		image = IMG_Load(fullname.c_str());
		if (image != nullptr) {
			_width = image->w;
			_height = image->h;

			int bpp = image->format->BytesPerPixel;
			if (bpp < 3)
			{
				result = convertPixelData(image, _format);
			}
			else
			{
				Uint32 pixelFmt = bpp == 3 ? SDL_PIXELFORMAT_BGR24 : SDL_PIXELFORMAT_ARGB8888;
				cvtImage = SDL_ConvertSurfaceFormat(image, pixelFmt, 0);
				result = convertPixelData(cvtImage, _format);
				SDL_FreeSurface(cvtImage);
			}
			SDL_FreeSurface(image);
		}
		MYGUI_ASSERT(result != nullptr, "Failed to load image.");
		return result;
	}

	void BaseManager::saveImage(int _width, int _height, MyGUI::PixelFormat _format, void* _texture, const std::string& _filename)
	{

	}

	void BaseManager::quit()
	{
		mExit = true;
	}

	const std::string& BaseManager::getRootMedia()
	{
		return mRootMedia;
	}

	void BaseManager::setResourceFilename(const std::string& _flename)
	{
		mResourceFileName = _flename;
	}

} // namespace base
<commit_msg>add missing include<commit_after>/*!
	@file
	@author		Albert Semenov
	@date		05/2009
*/
#include "Precompiled.h"
#include "BaseManager.h"
#include "MyGUI_Diagnostic.h"

#include <SDL_image.h>
#include "GL/glew.h"

#ifdef MYGUI_CHECK_MEMORY_LEAKS
#	undef new
#	undef delete
#endif

// имя класса окна
const char* WND_CLASS_NAME = "MyGUI_Demo_window";

namespace base
{
	BaseManager::BaseManager() :
		mGUI(nullptr),
		mPlatform(nullptr),
		mWindow(nullptr),
		mContext(nullptr),
		mExit(false),
		mWindowOn(false),
		mResourceFileName("MyGUI_Core.xml")
	{
		// initialize SDL
		MYGUI_ASSERT(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_EVENTS) == 0, "Failed initializing SDL.");
		// initialize SDL_image
		MYGUI_ASSERT(IMG_Init(~0) != 0, "Failed to initializing SDL_image");
	}

	BaseManager::~BaseManager()
	{
		SDL_GL_DeleteContext(mContext);
		IMG_Quit();
		SDL_Quit();
	}

	void BaseManager::_windowResized( int w, int h )
{
		if (mPlatform)
			mPlatform->getRenderManagerPtr()->setViewSize(w, h);

		setInputViewSize(w, h);
	}

	bool BaseManager::create(int _width, int _height)
	{
		const unsigned int width = _width;
		const unsigned int height = _height;
		bool windowed = true;

		// create window and position it at the center of the screen
		SDL_DisplayMode currDisp;
		MYGUI_ASSERT(SDL_GetCurrentDisplayMode(0, &currDisp) == 0, "Failed to retrieve screen info.");
		int left = (currDisp.w - width) / 2;
		int top = (currDisp.h - height) / 2;

		mWindow = SDL_CreateWindow("OpenGL Render Window", left, top, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
		MYGUI_ASSERT(mWindow != nullptr, "Failed to create SDL window.");
		mContext = SDL_GL_CreateContext(mWindow);
		MYGUI_ASSERT(mContext != nullptr, "Failed to create SDL context.");
		mWindowOn = true;

		if (!createRender(width, height, windowed))
		{
			return false;
		}

		createGui();

		createInput();

		createPointerManager();

		// this needs to be called before createScene() since some demos require
		// screen size to properly position the widgets
		_windowResized(width, height);

		createScene();

		return true;
	}

	void BaseManager::run()
	{
		while (!mExit)
		{
			while (SDL_PollEvent(&mEvent) != 0)
			{
				switch (mEvent.type)
				{
				// keyboard events
				case SDL_KEYDOWN:
					mKeyCode = mEvent.key.keysym.sym;
					keyPressed(mKeyCode, nullptr);
					break;
				case SDL_TEXTINPUT:
					mKeyCode = SDLK_UNKNOWN;
					keyPressed(mKeyCode, &mEvent.text);
					break;
				case SDL_KEYUP:
					keyReleased(mEvent.key);
					break;
				// mouse events
				case SDL_MOUSEMOTION:
					mouseMoved(mEvent.motion);
					break;
				case SDL_MOUSEBUTTONDOWN:
					mousePressed(mEvent.button);
					break;
				case SDL_MOUSEBUTTONUP:
					mouseReleased(mEvent.button);
					break;
				case SDL_MOUSEWHEEL:
					mouseWheelMoved(mEvent.wheel);
					break;
					// drop file events
				case SDL_DROPFILE:
					break;
					// windows events
				case SDL_WINDOWEVENT:
					switch (mEvent.window.event)
					{
					case SDL_WINDOWEVENT_CLOSE:
						mExit = true;
						break;
					case SDL_WINDOWEVENT_RESIZED:
						_windowResized(mEvent.window.data1, mEvent.window.data2);
						break;
					case SDL_WINDOWEVENT_SHOWN:
					case SDL_WINDOWEVENT_RESTORED:
					case SDL_WINDOWEVENT_EXPOSED:
					case SDL_WINDOWEVENT_MAXIMIZED:
						mWindowOn = true;
						break;
					case SDL_WINDOWEVENT_MINIMIZED:
					case SDL_WINDOWEVENT_HIDDEN:
						mWindowOn = false;
					default:
						break;
					}
					break;
				default:
					break;
				}
			}
			glClearColor(0, 0, 0, 1);
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

			drawOneFrame();
			if (!mWindowOn)
				SDL_Delay(50);
		}
	}

	void BaseManager::destroy()
	{
		destroyScene();

		destroyPointerManager();

		destroyInput();

		destroyGui();

		destroyRender();

	}

	void BaseManager::setupResources()
	{
		MyGUI::xml::Document doc;

		if (!doc.open(std::string("resources.xml")))
			doc.getLastError();

		MyGUI::xml::ElementPtr root = doc.getRoot();
		if (root == nullptr || root->getName() != "Paths")
			return;

		MyGUI::xml::ElementEnumerator node = root->getElementEnumerator();
		while (node.next())
		{
			if (node->getName() == "Path")
			{
				if (node->findAttribute("root") != "")
				{
					bool root = MyGUI::utility::parseBool(node->findAttribute("root"));
					if (root)
						mRootMedia = node->getContent();
				}
				addResourceLocation(node->getContent(), false);
			}
		}

		addResourceLocation(getRootMedia() + "/Common/Base");
	}

	void BaseManager::createGui()
	{
		mPlatform = new MyGUI::OpenGLPlatform();
		mPlatform->initialise(this);

		setupResources();

		mGUI = new MyGUI::Gui();
		mGUI->initialise(mResourceFileName);

		SDL_StartTextInput();
	}

	void BaseManager::destroyGui()
	{
		SDL_StopTextInput();
		if (mGUI)
		{
			mGUI->shutdown();
			delete mGUI;
			mGUI = nullptr;
		}

		if (mPlatform)
		{
			mPlatform->shutdown();
			delete mPlatform;
			mPlatform = nullptr;
		}
	}

	void BaseManager::setWindowMaximized(bool _value)
	{
		if (mWindow != nullptr && _value)
		{
			SDL_MaximizeWindow(mWindow);
		}
	}

	bool BaseManager::getWindowMaximized()
	{
		Uint32 windowState = SDL_GetWindowFlags(mWindow);
		return windowState & SDL_WINDOW_MAXIMIZED || windowState & SDL_WINDOW_FULLSCREEN;
	}

	void BaseManager::setWindowCoord(const MyGUI::IntCoord& _value)
	{
		if (_value.empty())
			return;

		MyGUI::IntCoord coord = _value;

		SDL_SetWindowPosition(mWindow, coord.left, coord.top);
	}

	MyGUI::IntCoord BaseManager::getWindowCoord()
	{
		int left, top, width, height;
		SDL_GetWindowPosition(mWindow, &left, &top);
		SDL_GetWindowSize(mWindow, &width, &height);
		return MyGUI::IntCoord(left, top, width, height);
	}

	void BaseManager::setWindowCaption(const std::wstring& _text)
	{
		MyGUI::UString title(_text);
		SDL_SetWindowTitle(mWindow, title.asUTF8_c_str());
	}

	void BaseManager::prepare()
	{
	}

	void BaseManager::addResourceLocation(const std::string& _name, bool _recursive)
	{
		mPlatform->getDataManagerPtr()->addResourceLocation(_name, _recursive);
	}

	void BaseManager::injectMouseMove(int _absx, int _absy, int _absz)
	{
		if (!mGUI)
			return;

		MyGUI::InputManager::getInstance().injectMouseMove(_absx, _absy, _absz);
	}

	void BaseManager::injectMousePress(int _absx, int _absy, MyGUI::MouseButton _id)
	{
		if (!mGUI)
			return;

		MyGUI::InputManager::getInstance().injectMousePress(_absx, _absy, _id);
	}

	void BaseManager::injectMouseRelease(int _absx, int _absy, MyGUI::MouseButton _id)
	{
		if (!mGUI)
			return;

		MyGUI::InputManager::getInstance().injectMouseRelease(_absx, _absy, _id);
	}

	void BaseManager::injectKeyPress(MyGUI::KeyCode _key, MyGUI::Char _text)
	{
		if (!mGUI)
			return;

		if (_key == MyGUI::KeyCode::Escape)
		{
			mExit = true;
			return;
		}

		MyGUI::InputManager::getInstance().injectKeyPress(_key, _text);
	}

	void BaseManager::injectKeyRelease(MyGUI::KeyCode _key)
	{
		if (!mGUI)
			return;

		MyGUI::InputManager::getInstance().injectKeyRelease(_key);
	}

	bool BaseManager::createRender(int _width, int _height, bool _windowed)
	{
		return true;
	}

	void BaseManager::drawOneFrame()
	{
		if (mPlatform)
			mPlatform->getRenderManagerPtr()->drawOneFrame();

		SDL_GL_SwapWindow(mWindow);
	}

	void BaseManager::destroyRender()
	{
	}

	void* BaseManager::convertPixelData(SDL_Surface *_image, MyGUI::PixelFormat& _myGuiPixelFormat)
	{
		void* ret = nullptr;
		SDL_PixelFormat *format = _image->format;
		unsigned int bpp = format->BytesPerPixel;
		switch (bpp) {
		case 1:
			_myGuiPixelFormat = MyGUI::PixelFormat::L8;
			break;
		case 2:
			_myGuiPixelFormat = MyGUI::PixelFormat::L8A8;
			break;
		case 3:
			_myGuiPixelFormat = MyGUI::PixelFormat::R8G8B8;
			break;
		case 4:
			_myGuiPixelFormat = MyGUI::PixelFormat::R8G8B8A8;
			break;
		default:
			break;
		}
		SDL_LockSurface(_image);

		int pitchSrc = _image->pitch;	//the length of a row of pixels in bytes
		int bppSrc = pitchSrc / _image->w;
		size_t size = _image->h * pitchSrc;
		ret = new unsigned char[size];
		unsigned char* ptr_source = (unsigned char*)_image->pixels;
		unsigned char* ptr_dst = (unsigned char*)ret;
		int pitchDst = _image->w * bpp;
		if (pitchSrc == pitchDst)
		{
			memcpy(ret, _image->pixels, size);
		}
		else
		{
			for (unsigned int y = 0; y < (unsigned int)_image->h; ++y)
			{
				memcpy(ptr_dst, ptr_source, pitchDst);
				ptr_dst += pitchDst;
				ptr_source += pitchSrc;
			}
		}

		SDL_UnlockSurface(_image);
		return ret;
	}

	void* BaseManager::loadImage(int& _width, int& _height, MyGUI::PixelFormat& _format, const std::string& _filename)
	{
		std::string fullname = MyGUI::OpenGLDataManager::getInstance().getDataPath(_filename);
		void* result = nullptr;
		SDL_Surface *image = nullptr;
		SDL_Surface *cvtImage = nullptr;		// converted surface with RGBA/RGB pixel format
		image = IMG_Load(fullname.c_str());
		if (image != nullptr) {
			_width = image->w;
			_height = image->h;

			int bpp = image->format->BytesPerPixel;
			if (bpp < 3)
			{
				result = convertPixelData(image, _format);
			}
			else
			{
				Uint32 pixelFmt = bpp == 3 ? SDL_PIXELFORMAT_BGR24 : SDL_PIXELFORMAT_ARGB8888;
				cvtImage = SDL_ConvertSurfaceFormat(image, pixelFmt, 0);
				result = convertPixelData(cvtImage, _format);
				SDL_FreeSurface(cvtImage);
			}
			SDL_FreeSurface(image);
		}
		MYGUI_ASSERT(result != nullptr, "Failed to load image.");
		return result;
	}

	void BaseManager::saveImage(int _width, int _height, MyGUI::PixelFormat _format, void* _texture, const std::string& _filename)
	{

	}

	void BaseManager::quit()
	{
		mExit = true;
	}

	const std::string& BaseManager::getRootMedia()
	{
		return mRootMedia;
	}

	void BaseManager::setResourceFilename(const std::string& _flename)
	{
		mResourceFileName = _flename;
	}

} // namespace base
<|endoftext|>


<commit_before>
#include <TurboBadger/tb_widgets.h>
#include <TurboBadger/tb_widgets_common.h>

#include <Atomic/IO/Log.h>

#include "UIEvents.h"
#include "UI.h"
#include "UIButton.h"

using namespace tb;

namespace Atomic
{

UIButton::UIButton(Context* context, bool createWidget) : UIWidget(context, false)
{
    if (createWidget)
    {
        widget_ = new TBButton();
        widget_->SetDelegate(this);
        GetSubsystem<UI>()->WrapWidget(this, widget_);
    }
}

UIButton::~UIButton()
{

}

void UIButton::SetSqueezable(bool value)
{
    if (!widget_)
        return;

    ((TBButton*)widget_)->SetSqueezable(value);
}

bool UIButton::OnEvent(const tb::TBWidgetEvent &ev)
{
    return UIWidget::OnEvent(ev);
}

}
<commit_msg>Button, which has a link, now will handle it<commit_after>
#include <TurboBadger/tb_widgets.h>
#include <TurboBadger/tb_widgets_common.h>

#include <Atomic/IO/Log.h>
#include <Atomic/IO/FileSystem.h>

#include "UIEvents.h"
#include "UI.h"
#include "UIButton.h"

using namespace tb;

namespace Atomic
{

UIButton::UIButton(Context* context, bool createWidget) : UIWidget(context, false)
{
    if (createWidget)
    {
        widget_ = new TBButton();
        widget_->SetDelegate(this);
        GetSubsystem<UI>()->WrapWidget(this, widget_);
    }
}

UIButton::~UIButton()
{

}

void UIButton::SetSqueezable(bool value)
{
    if (!widget_)
        return;

    ((TBButton*)widget_)->SetSqueezable(value);
}

bool UIButton::OnEvent(const tb::TBWidgetEvent &ev)
{
	if (ev.type == EVENT_TYPE_CLICK) {
		String text = GetText();
		if (text.StartsWith("http://") || text.StartsWith("https://")) {
			FileSystem* fileSystem = GetSubsystem<FileSystem>();
			fileSystem->SystemOpen(text);
		}
	}
    return UIWidget::OnEvent(ev);
}

}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

#ifndef FEATURE_STYLE_PROCESSOR_HPP
#define FEATURE_STYLE_PROCESSOR_HPP

// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/map.hpp>
#include <mapnik/attribute_collector.hpp>
#include <mapnik/expression_evaluator.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/scale_denominator.hpp>

#ifdef MAPNIK_DEBUG
//#include <mapnik/wall_clock_timer.hpp>
#endif
//stl
#include <vector>

namespace mapnik
{
template <typename Processor>
class feature_style_processor
{
    struct symbol_dispatch : public boost::static_visitor<>
    {
	symbol_dispatch (Processor & output,
			 Feature const& f,
			 proj_transform const& prj_trans)
	    : output_(output),
	      f_(f),
	      prj_trans_(prj_trans)  {}

	template <typename T>
	void operator () (T const& sym) const
	{
	    output_.process(sym,f_,prj_trans_);
	}

	Processor & output_;
	Feature const& f_;
	proj_transform const& prj_trans_;
    };
public:
    feature_style_processor(Map const& m)
	: m_(m) {}

    void apply()
    {
#ifdef MAPNIK_DEBUG
	//mapnik::wall_clock_progress_timer t(std::clog, "map rendering took: ");
#endif
	Processor & p = static_cast<Processor&>(*this);
	p.start_map_processing(m_);

	try
	{
	    projection proj(m_.srs()); // map projection
	    double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic());
#ifdef MAPNIK_DEBUG
	    std::clog << "scale denominator = " << scale_denom << "\n";
#endif
	    std::vector<layer>::const_iterator itr = m_.layers().begin();
	    std::vector<layer>::const_iterator end = m_.layers().end();

	    while (itr != end)
	    {
		if (itr->isVisible(scale_denom))
		{
		    apply_to_layer(*itr, p, proj, scale_denom);
		}
		++itr;
	    }
	}
	catch (proj_init_error& ex)
	{
	    std::clog << "proj_init_error:" << ex.what() << "\n";
	}

	p.end_map_processing(m_);
    }
private:
    void apply_to_layer(layer const& lay, Processor & p,
			projection const& proj0,double scale_denom)
    {
#ifdef MAPNIK_DEBUG
	//wall_clock_progress_timer timer(clog, "end layer rendering: ");
#endif
	p.start_layer_processing(lay);
	boost::shared_ptr<datasource> ds=lay.datasource();
	if (ds)
	{
	    box2d<double> ext = m_.get_buffered_extent();
	    projection proj1(lay.srs());
	    proj_transform prj_trans(proj0,proj1);

	    box2d<double> layer_ext = lay.envelope();

      double lx0 = layer_ext.minx();
      double ly0 = layer_ext.miny();
      double lz0 = 0.0;
      double lx1 = layer_ext.maxx();
      double ly1 = layer_ext.maxy();
      double lz1 = 0.0;
      // back project layers extent into main map projection
      prj_trans.backward(lx0,ly0,lz0);
      prj_trans.backward(lx1,ly1,lz1);

      // if no intersection then nothing to do for layer
      if ( lx0 > ext.maxx() || lx1 < ext.minx() || ly0 > ext.maxy() || ly1 < ext.miny() )
	    {
          return;
	    }

      // clip query bbox
      lx0 = std::max(ext.minx(),lx0);
      ly0 = std::max(ext.miny(),ly0);
      lx1 = std::min(ext.maxx(),lx1);
      ly1 = std::min(ext.maxy(),ly1);

      prj_trans.forward(lx0,ly0,lz0);
      prj_trans.forward(lx1,ly1,lz1);
      box2d<double> bbox(lx0,ly0,lx1,ly1);

      double resolution = m_.getWidth()/bbox.width();
      query q(bbox,resolution,scale_denom); //BBOX query

	    std::vector<std::string> const& style_names = lay.styles();
	    std::vector<std::string>::const_iterator stylesIter = style_names.begin();
	    std::vector<std::string>::const_iterator stylesEnd = style_names.end();
	    for (;stylesIter != stylesEnd; ++stylesIter)
	    {
		std::set<std::string> names;
		attribute_collector collector(names);
		std::vector<rule_type*> if_rules;
		std::vector<rule_type*> else_rules;

		bool active_rules=false;

		boost::optional<feature_type_style const&> style=m_.find_style(*stylesIter);
		if (!style) continue;

		const std::vector<rule_type>& rules=(*style).get_rules();
		std::vector<rule_type>::const_iterator ruleIter=rules.begin();
		std::vector<rule_type>::const_iterator ruleEnd=rules.end();

		for (;ruleIter!=ruleEnd;++ruleIter)
		{
		    if (ruleIter->active(scale_denom))
		    {
                        active_rules=true;
			// collect unique attribute names
			collector(*ruleIter);
			if (ruleIter->has_else_filter())
                        {
			    else_rules.push_back(const_cast<rule_type*>(&(*ruleIter)));
                        }
                        else
                        {
			    if_rules.push_back(const_cast<rule_type*>(&(*ruleIter)));
                        }
		    }
		}
		std::set<std::string>::const_iterator namesIter=names.begin();
		std::set<std::string>::const_iterator namesEnd =names.end();

		// push all property names
		for (;namesIter!=namesEnd;++namesIter)
		{
		    q.add_property_name(*namesIter);
		}
		if (active_rules)
		{
		    featureset_ptr fs=ds->features(q);
		    if (fs)
		    {
                        feature_ptr feature;
                        while ((feature = fs->next()))
                        {
			    bool do_else=true;
			    std::vector<rule_type*>::const_iterator itr=if_rules.begin();
			    std::vector<rule_type*>::const_iterator end=if_rules.end();
			    for (;itr != end;++itr)
			    {
				expression_ptr const& expr=(*itr)->get_filter();
				value_type result = boost::apply_visitor(evaluate<Feature,value_type>(*feature),*expr);
				if (result.to_bool())
				{
				    do_else=false;
				    const rule_type::symbolizers& symbols = (*itr)->get_symbolizers();
				    rule_type::symbolizers::const_iterator symIter=symbols.begin();
				    rule_type::symbolizers::const_iterator symEnd =symbols.end();
				    for (;symIter != symEnd;++symIter)
				    {
					boost::apply_visitor
					    (symbol_dispatch(p,*feature,prj_trans),*symIter);
				    }
				}
			    }
			    if (do_else)
			    {
				//else filter
				std::vector<rule_type*>::const_iterator itr=
				    else_rules.begin();
				std::vector<rule_type*>::const_iterator end=
				    else_rules.end();
				for (;itr != end;++itr)
				{
				    const rule_type::symbolizers& symbols = (*itr)->get_symbolizers();
				    rule_type::symbolizers::const_iterator symIter= symbols.begin();
				    rule_type::symbolizers::const_iterator symEnd = symbols.end();

				    for (;symIter!=symEnd;++symIter)
				    {
					boost::apply_visitor
					    (symbol_dispatch(p,*feature,prj_trans),*symIter);
				    }
				}
			    }
                        }
		    }
		}
	    }
	}
	p.end_layer_processing(lay);
    }
    Map const& m_;
};
}

#endif //FEATURE_STYLE_PROCESSOR_HPP
<commit_msg>+ minor formatting<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

#ifndef FEATURE_STYLE_PROCESSOR_HPP
#define FEATURE_STYLE_PROCESSOR_HPP

// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/map.hpp>
#include <mapnik/attribute_collector.hpp>
#include <mapnik/expression_evaluator.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/scale_denominator.hpp>

#ifdef MAPNIK_DEBUG
//#include <mapnik/wall_clock_timer.hpp>
#endif
//stl
#include <vector>

namespace mapnik
{
template <typename Processor>
class feature_style_processor
{
    struct symbol_dispatch : public boost::static_visitor<>
    {
	symbol_dispatch (Processor & output,
			 Feature const& f,
			 proj_transform const& prj_trans)
	    : output_(output),
	      f_(f),
	      prj_trans_(prj_trans)  {}

	template <typename T>
	void operator () (T const& sym) const
	{
	    output_.process(sym,f_,prj_trans_);
	}

	Processor & output_;
	Feature const& f_;
	proj_transform const& prj_trans_;
    };
public:
    feature_style_processor(Map const& m)
	: m_(m) {}

    void apply()
    {
#ifdef MAPNIK_DEBUG
	//mapnik::wall_clock_progress_timer t(std::clog, "map rendering took: ");
#endif
	Processor & p = static_cast<Processor&>(*this);
	p.start_map_processing(m_);

	try
	{
	    projection proj(m_.srs()); // map projection
	    double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic());
#ifdef MAPNIK_DEBUG
	    std::clog << "scale denominator = " << scale_denom << "\n";
#endif
	    std::vector<layer>::const_iterator itr = m_.layers().begin();
	    std::vector<layer>::const_iterator end = m_.layers().end();

	    while (itr != end)
	    {
		if (itr->isVisible(scale_denom))
		{
		    apply_to_layer(*itr, p, proj, scale_denom);
		}
		++itr;
	    }
	}
	catch (proj_init_error& ex)
	{
	    std::clog << "proj_init_error:" << ex.what() << "\n";
	}

	p.end_map_processing(m_);
    }
private:
    void apply_to_layer(layer const& lay, Processor & p,
			projection const& proj0,double scale_denom)
    {
#ifdef MAPNIK_DEBUG
	//wall_clock_progress_timer timer(clog, "end layer rendering: ");
#endif
	p.start_layer_processing(lay);
	boost::shared_ptr<datasource> ds=lay.datasource();
	if (ds)
	{
	    box2d<double> ext = m_.get_buffered_extent();
	    projection proj1(lay.srs());
	    proj_transform prj_trans(proj0,proj1);

	    box2d<double> layer_ext = lay.envelope();

      double lx0 = layer_ext.minx();
      double ly0 = layer_ext.miny();
      double lz0 = 0.0;
      double lx1 = layer_ext.maxx();
      double ly1 = layer_ext.maxy();
      double lz1 = 0.0;
      // back project layers extent into main map projection
      prj_trans.backward(lx0,ly0,lz0);
      prj_trans.backward(lx1,ly1,lz1);

      // if no intersection then nothing to do for layer
      if ( lx0 > ext.maxx() || lx1 < ext.minx() || ly0 > ext.maxy() || ly1 < ext.miny() )
      {
          return;
      }

      // clip query bbox
      lx0 = std::max(ext.minx(),lx0);
      ly0 = std::max(ext.miny(),ly0);
      lx1 = std::min(ext.maxx(),lx1);
      ly1 = std::min(ext.maxy(),ly1);

      prj_trans.forward(lx0,ly0,lz0);
      prj_trans.forward(lx1,ly1,lz1);
      box2d<double> bbox(lx0,ly0,lx1,ly1);

      double resolution = m_.getWidth()/bbox.width();
      query q(bbox,resolution,scale_denom); //BBOX query

	    std::vector<std::string> const& style_names = lay.styles();
	    std::vector<std::string>::const_iterator stylesIter = style_names.begin();
	    std::vector<std::string>::const_iterator stylesEnd = style_names.end();
	    for (;stylesIter != stylesEnd; ++stylesIter)
	    {
		std::set<std::string> names;
		attribute_collector collector(names);
		std::vector<rule_type*> if_rules;
		std::vector<rule_type*> else_rules;

		bool active_rules=false;

		boost::optional<feature_type_style const&> style=m_.find_style(*stylesIter);
		if (!style) continue;

		const std::vector<rule_type>& rules=(*style).get_rules();
		std::vector<rule_type>::const_iterator ruleIter=rules.begin();
		std::vector<rule_type>::const_iterator ruleEnd=rules.end();

		for (;ruleIter!=ruleEnd;++ruleIter)
		{
		    if (ruleIter->active(scale_denom))
		    {
                        active_rules=true;
			// collect unique attribute names
			collector(*ruleIter);
			if (ruleIter->has_else_filter())
                        {
			    else_rules.push_back(const_cast<rule_type*>(&(*ruleIter)));
                        }
                        else
                        {
			    if_rules.push_back(const_cast<rule_type*>(&(*ruleIter)));
                        }
		    }
		}
		std::set<std::string>::const_iterator namesIter=names.begin();
		std::set<std::string>::const_iterator namesEnd =names.end();

		// push all property names
		for (;namesIter!=namesEnd;++namesIter)
		{
		    q.add_property_name(*namesIter);
		}
		if (active_rules)
		{
		    featureset_ptr fs=ds->features(q);
		    if (fs)
		    {
                        feature_ptr feature;
                        while ((feature = fs->next()))
                        {
			    bool do_else=true;
			    std::vector<rule_type*>::const_iterator itr=if_rules.begin();
			    std::vector<rule_type*>::const_iterator end=if_rules.end();
			    for (;itr != end;++itr)
			    {
				expression_ptr const& expr=(*itr)->get_filter();
				value_type result = boost::apply_visitor(evaluate<Feature,value_type>(*feature),*expr);
				if (result.to_bool())
				{
				    do_else=false;
				    const rule_type::symbolizers& symbols = (*itr)->get_symbolizers();
				    rule_type::symbolizers::const_iterator symIter=symbols.begin();
				    rule_type::symbolizers::const_iterator symEnd =symbols.end();
				    for (;symIter != symEnd;++symIter)
				    {
					boost::apply_visitor
					    (symbol_dispatch(p,*feature,prj_trans),*symIter);
				    }
				}
			    }
			    if (do_else)
			    {
				//else filter
				std::vector<rule_type*>::const_iterator itr=
				    else_rules.begin();
				std::vector<rule_type*>::const_iterator end=
				    else_rules.end();
				for (;itr != end;++itr)
				{
				    const rule_type::symbolizers& symbols = (*itr)->get_symbolizers();
				    rule_type::symbolizers::const_iterator symIter= symbols.begin();
				    rule_type::symbolizers::const_iterator symEnd = symbols.end();

				    for (;symIter!=symEnd;++symIter)
				    {
					boost::apply_visitor
					    (symbol_dispatch(p,*feature,prj_trans),*symIter);
				    }
				}
			    }
                        }
		    }
		}
	    }
	}
	p.end_layer_processing(lay);
    }
    Map const& m_;
};
}

#endif //FEATURE_STYLE_PROCESSOR_HPP
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2012 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_GRID_RENDERER_BASE_HPP
#define MAPNIK_GRID_RENDERER_BASE_HPP

#include "agg_renderer_base.h"
#include <mapnik/grid/grid_pixfmt.hpp>
#include <mapnik/grid/grid_pixel.hpp>

namespace mapnik {

typedef agg::renderer_base<mapnik::pixfmt_gray32> grid_renderer_base_type;

}

#endif //MAPNIK_AGG_RASTERIZER_HPP
<commit_msg>complete 64 bit default for grid_renderer<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2012 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_GRID_RENDERER_BASE_HPP
#define MAPNIK_GRID_RENDERER_BASE_HPP

#include "agg_renderer_base.h"
#include <mapnik/grid/grid_pixfmt.hpp>
#include <mapnik/grid/grid_pixel.hpp>

namespace mapnik {

typedef agg::renderer_base<mapnik::pixfmt_gray64> grid_renderer_base_type;

}

#endif //MAPNIK_AGG_RASTERIZER_HPP
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * Copyright (c) 2010 Kohei Yoshida
 *
 * 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.
 *
 ************************************************************************/

#ifndef __MDDS_MIXED_TYPE_MATRIX_ELEMENT_HPP__
#define __MDDS_MIXED_TYPE_MATRIX_ELEMENT_HPP__

namespace mdds {

enum matrix_element_t
{
    element_empty   = 0,
    element_numeric = 1,
    element_boolean = 2,
    element_string  = 3
};

template<typename _String>
struct element
{
    typedef _String     string_type;

    matrix_element_t m_type;

    union
    {
        double       m_numeric;
        bool         m_boolean;
        string_type* mp_string;
    };

    element() : m_type(element_empty) {}
    element(const element& r) : m_type(r.m_type)
    {
        switch (m_type)
        {
            case element_boolean:
                m_boolean = r.m_boolean;
                break;
            case element_numeric:
                m_numeric = r.m_numeric;
                break;
            case element_string:
                mp_string = new string_type(*r.mp_string);
                break;
            case element_empty:
            default:
                ;
        }
    }

    explicit element(double v) : m_type(element_numeric), m_numeric(v) {}
    explicit element(bool v) : m_type(element_boolean), m_boolean(v) {}
    explicit element(string_type* p) : m_type(element_string), mp_string(p) {}

    bool operator== (const element& r) const
    {
        if (m_type != r.m_type)
            return false;

        switch (m_type)
        {
            case element_boolean:
                return m_boolean == r.m_boolean;
            case element_numeric:
                return m_numeric == r.m_numeric;
            case element_string:
                return *mp_string == *r.mp_string;
            case element_empty:
            default:
                ;
        }

        return true;
    }

    element& operator= (const element& r)
    {
        if (m_type == element_string)
            delete mp_string;

        m_type = r.m_type;

        switch (m_type)
        {
            case element_boolean:
                m_boolean = r.m_boolean;
                break;
            case element_numeric:
                m_numeric = r.m_numeric;
                break;
            case element_string:
                mp_string = new string_type(*r.mp_string);
                break;
            case element_empty:
            default:
                ;
        }
        return *this;
    }

    ~element()
    {
        clear_string();
    }

    void clear_string()
    {
        if (m_type == element_string)
            delete mp_string;
    }

    void set_empty()
    {
        clear_string();
        m_type = element_empty;
    }

    void set_numeric(double val)
    {
        clear_string();
        m_type = element_numeric;
        m_numeric = val;
    }

    void set_boolean(bool val)
    {
        clear_string();
        m_type = element_boolean;
        m_boolean = val;
    }

    void set_string(string_type* str)
    {
        clear_string();
        m_type = element_string;
        mp_string = str;
    }
};

}

#endif
<commit_msg>Check for assignment to self.<commit_after>/*************************************************************************
 *
 * Copyright (c) 2010 Kohei Yoshida
 *
 * 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.
 *
 ************************************************************************/

#ifndef __MDDS_MIXED_TYPE_MATRIX_ELEMENT_HPP__
#define __MDDS_MIXED_TYPE_MATRIX_ELEMENT_HPP__

namespace mdds {

enum matrix_element_t
{
    element_empty   = 0,
    element_numeric = 1,
    element_boolean = 2,
    element_string  = 3
};

template<typename _String>
struct element
{
    typedef _String     string_type;

    matrix_element_t m_type;

    union
    {
        double       m_numeric;
        bool         m_boolean;
        string_type* mp_string;
    };

    element() : m_type(element_empty) {}
    element(const element& r) : m_type(r.m_type)
    {
        switch (m_type)
        {
            case element_boolean:
                m_boolean = r.m_boolean;
                break;
            case element_numeric:
                m_numeric = r.m_numeric;
                break;
            case element_string:
                mp_string = new string_type(*r.mp_string);
                break;
            case element_empty:
            default:
                ;
        }
    }

    explicit element(double v) : m_type(element_numeric), m_numeric(v) {}
    explicit element(bool v) : m_type(element_boolean), m_boolean(v) {}
    explicit element(string_type* p) : m_type(element_string), mp_string(p) {}

    bool operator== (const element& r) const
    {
        if (m_type != r.m_type)
            return false;

        switch (m_type)
        {
            case element_boolean:
                return m_boolean == r.m_boolean;
            case element_numeric:
                return m_numeric == r.m_numeric;
            case element_string:
                return *mp_string == *r.mp_string;
            case element_empty:
            default:
                ;
        }

        return true;
    }

    element& operator= (const element& r)
    {
        if (&r == this)
            // assignment to self.
            return *this;

        if (m_type == element_string)
            delete mp_string;

        m_type = r.m_type;

        switch (m_type)
        {
            case element_boolean:
                m_boolean = r.m_boolean;
                break;
            case element_numeric:
                m_numeric = r.m_numeric;
                break;
            case element_string:
                mp_string = new string_type(*r.mp_string);
                break;
            case element_empty:
            default:
                ;
        }
        return *this;
    }

    ~element()
    {
        clear_string();
    }

    void clear_string()
    {
        if (m_type == element_string)
            delete mp_string;
    }

    void set_empty()
    {
        clear_string();
        m_type = element_empty;
    }

    void set_numeric(double val)
    {
        clear_string();
        m_type = element_numeric;
        m_numeric = val;
    }

    void set_boolean(bool val)
    {
        clear_string();
        m_type = element_boolean;
        m_boolean = val;
    }

    void set_string(string_type* str)
    {
        clear_string();
        m_type = element_string;
        mp_string = str;
    }
};

}

#endif
<|endoftext|>


<commit_before>/**
 * @file llfloaterdeleteenvpreset.cpp
 * @brief Floater to delete a water / sky / day cycle preset.
 *
 * $LicenseInfo:firstyear=2011&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2011, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "llfloaterdeleteenvpreset.h"

// libs
#include "llbutton.h"
#include "llcombobox.h"
#include "llnotificationsutil.h"

// newview
#include "lldaycyclemanager.h"
#include "llwaterparammanager.h"

static bool confirmation_callback(const LLSD& notification, const LLSD& response, boost::function<void()> cb)
{
	S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
	if (option == 0)
	{
		cb();
	}
	return false;

}

LLFloaterDeleteEnvPreset::LLFloaterDeleteEnvPreset(const LLSD &key)
:	LLFloater(key)
,	mPresetCombo(NULL)
{
}

// virtual
BOOL LLFloaterDeleteEnvPreset::postBuild()
{
	mPresetCombo = getChild<LLComboBox>("preset_combo");
	mPresetCombo->setCommitCallback(boost::bind(&LLFloaterDeleteEnvPreset::postPopulate, this));

	getChild<LLButton>("delete")->setCommitCallback(boost::bind(&LLFloaterDeleteEnvPreset::onBtnDelete, this));
	getChild<LLButton>("cancel")->setCommitCallback(boost::bind(&LLFloaterDeleteEnvPreset::onBtnCancel, this));

	// Listen to presets addition/removal.
	LLDayCycleManager::instance().setModifyCallback(boost::bind(&LLFloaterDeleteEnvPreset::populateDayCyclesList, this));
	LLWLParamManager::instance().setPresetListChangeCallback(boost::bind(&LLFloaterDeleteEnvPreset::populateSkyPresetsList, this));
	LLWaterParamManager::instance().setPresetListChangeCallback(boost::bind(&LLFloaterDeleteEnvPreset::populateWaterPresetsList, this));

	return TRUE;
}

// virtual
void LLFloaterDeleteEnvPreset::onOpen(const LLSD& key)
{
	std::string param = key.asString();
	std::string floater_title = getString(std::string("title_") + param);
	std::string combo_label = getString(std::string("label_" + param));

	// Update floater title.
	setTitle(floater_title);

	// Update the combobox label.
	getChild<LLUICtrl>("label")->setValue(combo_label);

	// Populate the combobox.
	if (param == "water")
	{
		populateWaterPresetsList();
	}
	else if (param == "sky")
	{
		populateSkyPresetsList();
	}
	else if (param == "day_cycle")
	{
		populateDayCyclesList();
	}
	else
	{
		llwarns << "Unrecognized key" << llendl;
	}
}

void LLFloaterDeleteEnvPreset::onBtnDelete()
{
	std::string param = mKey.asString();
	std::string preset_name = mPresetCombo->getValue().asString();
	boost::function<void()> confirm_cb;

	if (param == "water")
	{
		// Don't allow deleting system presets.
		if (LLWaterParamManager::instance().isSystemPreset(preset_name))
		{
			LLNotificationsUtil::add("WLNoEditDefault");
			return;
		}

		confirm_cb = boost::bind(&LLFloaterDeleteEnvPreset::onDeleteWaterPresetConfirmation, this);
	}
	else if (param == "sky")
	{
		// Don't allow deleting presets referenced by local day cycles.
		if (LLDayCycleManager::instance().isSkyPresetReferenced(preset_name))
		{
			LLNotificationsUtil::add("GenericAlert", LLSD().with("MESSAGE", getString("msg_sky_is_referenced")));
			return;
		}

		LLWLParamManager& wl_mgr = LLWLParamManager::instance();

		// Don't allow deleting system presets.
		if (wl_mgr.isSystemPreset(preset_name))
		{
			LLNotificationsUtil::add("WLNoEditDefault");
			return;
		}

		confirm_cb = boost::bind(&LLFloaterDeleteEnvPreset::onDeleteSkyPresetConfirmation, this);
	}
	else if (param == "day_cycle")
	{
		LLDayCycleManager& day_mgr = LLDayCycleManager::instance();

		// Don't allow deleting system presets.
		if (day_mgr.isSystemPreset(preset_name))
		{
			LLNotificationsUtil::add("WLNoEditDefault");
			return;
		}

		confirm_cb = boost::bind(&LLFloaterDeleteEnvPreset::onDeleteDayCycleConfirmation, this);
	}
	else
	{
		llwarns << "Unrecognized key" << llendl;
	}

	LLSD args;
	args["MESSAGE"] = getString("msg_confirm_deletion");
	LLNotificationsUtil::add("GenericAlertYesCancel", args, LLSD(),
		boost::bind(&confirmation_callback, _1, _2, confirm_cb));
}

void LLFloaterDeleteEnvPreset::onBtnCancel()
{
	closeFloater();
}

void LLFloaterDeleteEnvPreset::populateWaterPresetsList()
{
	if (mKey.asString() != "water") return;

	mPresetCombo->removeall();

	std::string cur_preset;
	LLEnvManagerNew& env_mgr = LLEnvManagerNew::instance();
	if (!env_mgr.getUseRegionSettings())
	{
		cur_preset = env_mgr.getWaterPresetName();
	}

	// *TODO: Reload the list when user preferences change.
	LLWaterParamManager& water_mgr = LLWaterParamManager::instance();
	const std::map<std::string, LLWaterParamSet> &water_params_map = water_mgr.mParamList;
	for (std::map<std::string, LLWaterParamSet>::const_iterator it = water_params_map.begin(); it != water_params_map.end(); it++)
	{
		std::string name = it->first;

		// list only user presets
		if (water_mgr.isSystemPreset(name))
		{
			continue;
		}

		bool enabled = (name != cur_preset); // don't allow deleting current preset
		mPresetCombo->add(name, ADD_BOTTOM, enabled);
	}

	postPopulate();
}

void LLFloaterDeleteEnvPreset::populateSkyPresetsList()
{
	if (mKey.asString() != "sky") return;

	mPresetCombo->removeall();

	std::string cur_preset;
	LLEnvManagerNew& env_mgr = LLEnvManagerNew::instance();
	if (!env_mgr.getUseRegionSettings() && env_mgr.getUseFixedSky())
	{
		cur_preset = env_mgr.getSkyPresetName();
	}

	// *TODO: Reload the list when user preferences change.
	LLWLParamManager& sky_mgr = LLWLParamManager::instance();
	const std::map<LLWLParamKey, LLWLParamSet> &sky_params_map = sky_mgr.mParamList;
	for (std::map<LLWLParamKey, LLWLParamSet>::const_iterator it = sky_params_map.begin(); it != sky_params_map.end(); it++)
	{
		const LLWLParamKey& key = it->first;

		// list only local user presets
		if (key.scope == LLEnvKey::SCOPE_REGION || sky_mgr.isSystemPreset(key.name))
		{
			continue;
		}

		bool enabled = (key.name != cur_preset);
		mPresetCombo->add(key.name, ADD_BOTTOM, enabled);
	}

	postPopulate();
}

void LLFloaterDeleteEnvPreset::populateDayCyclesList()
{
	if (mKey.asString() != "day_cycle") return;

	mPresetCombo->removeall();

	std::string cur_day;
	LLEnvManagerNew& env_mgr = LLEnvManagerNew::instance();
	if (!env_mgr.getUseRegionSettings() && env_mgr.getUseDayCycle())
	{
		cur_day = env_mgr.getDayCycleName();
	}

	const LLDayCycleManager::dc_map_t& map = LLDayCycleManager::instance().getPresets();
	for (LLDayCycleManager::dc_map_t::const_iterator it = map.begin(); it != map.end(); ++it)
	{
		mPresetCombo->add(it->first, ADD_BOTTOM, it->first != cur_day);
	}

	postPopulate();
}

void LLFloaterDeleteEnvPreset::postPopulate()
{
	// Handle empty list and empty selection.
	bool has_selection = mPresetCombo->getItemCount() > 1 && mPresetCombo->getSelectedValue().isDefined();

	if (!has_selection)
	{
		mPresetCombo->setLabel(getString("combo_label"));
	}

	getChild<LLButton>("delete")->setEnabled(has_selection);
}

void LLFloaterDeleteEnvPreset::onDeleteDayCycleConfirmation()
{
	LLDayCycleManager::instance().deletePreset(mPresetCombo->getValue().asString());
}

void LLFloaterDeleteEnvPreset::onDeleteSkyPresetConfirmation()
{
	LLWLParamKey key(mPresetCombo->getValue().asString(), LLEnvKey::SCOPE_LOCAL);
	LLWLParamManager::instance().removeParamSet(key, true);
}

void LLFloaterDeleteEnvPreset::onDeleteWaterPresetConfirmation()
{
	LLWaterParamManager::instance().removeParamSet(mPresetCombo->getValue().asString(), true);
}
<commit_msg>STORM-1253 WIP Disabled removing system day cycles.<commit_after>/**
 * @file llfloaterdeleteenvpreset.cpp
 * @brief Floater to delete a water / sky / day cycle preset.
 *
 * $LicenseInfo:firstyear=2011&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2011, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "llfloaterdeleteenvpreset.h"

// libs
#include "llbutton.h"
#include "llcombobox.h"
#include "llnotificationsutil.h"

// newview
#include "lldaycyclemanager.h"
#include "llwaterparammanager.h"

static bool confirmation_callback(const LLSD& notification, const LLSD& response, boost::function<void()> cb)
{
	S32 option = LLNotificationsUtil::getSelectedOption(notification, response);
	if (option == 0)
	{
		cb();
	}
	return false;

}

LLFloaterDeleteEnvPreset::LLFloaterDeleteEnvPreset(const LLSD &key)
:	LLFloater(key)
,	mPresetCombo(NULL)
{
}

// virtual
BOOL LLFloaterDeleteEnvPreset::postBuild()
{
	mPresetCombo = getChild<LLComboBox>("preset_combo");
	mPresetCombo->setCommitCallback(boost::bind(&LLFloaterDeleteEnvPreset::postPopulate, this));

	getChild<LLButton>("delete")->setCommitCallback(boost::bind(&LLFloaterDeleteEnvPreset::onBtnDelete, this));
	getChild<LLButton>("cancel")->setCommitCallback(boost::bind(&LLFloaterDeleteEnvPreset::onBtnCancel, this));

	// Listen to presets addition/removal.
	LLDayCycleManager::instance().setModifyCallback(boost::bind(&LLFloaterDeleteEnvPreset::populateDayCyclesList, this));
	LLWLParamManager::instance().setPresetListChangeCallback(boost::bind(&LLFloaterDeleteEnvPreset::populateSkyPresetsList, this));
	LLWaterParamManager::instance().setPresetListChangeCallback(boost::bind(&LLFloaterDeleteEnvPreset::populateWaterPresetsList, this));

	return TRUE;
}

// virtual
void LLFloaterDeleteEnvPreset::onOpen(const LLSD& key)
{
	std::string param = key.asString();
	std::string floater_title = getString(std::string("title_") + param);
	std::string combo_label = getString(std::string("label_" + param));

	// Update floater title.
	setTitle(floater_title);

	// Update the combobox label.
	getChild<LLUICtrl>("label")->setValue(combo_label);

	// Populate the combobox.
	if (param == "water")
	{
		populateWaterPresetsList();
	}
	else if (param == "sky")
	{
		populateSkyPresetsList();
	}
	else if (param == "day_cycle")
	{
		populateDayCyclesList();
	}
	else
	{
		llwarns << "Unrecognized key" << llendl;
	}
}

void LLFloaterDeleteEnvPreset::onBtnDelete()
{
	std::string param = mKey.asString();
	std::string preset_name = mPresetCombo->getValue().asString();
	boost::function<void()> confirm_cb;

	if (param == "water")
	{
		// Don't allow deleting system presets.
		if (LLWaterParamManager::instance().isSystemPreset(preset_name))
		{
			LLNotificationsUtil::add("WLNoEditDefault");
			return;
		}

		confirm_cb = boost::bind(&LLFloaterDeleteEnvPreset::onDeleteWaterPresetConfirmation, this);
	}
	else if (param == "sky")
	{
		// Don't allow deleting presets referenced by local day cycles.
		if (LLDayCycleManager::instance().isSkyPresetReferenced(preset_name))
		{
			LLNotificationsUtil::add("GenericAlert", LLSD().with("MESSAGE", getString("msg_sky_is_referenced")));
			return;
		}

		LLWLParamManager& wl_mgr = LLWLParamManager::instance();

		// Don't allow deleting system presets.
		if (wl_mgr.isSystemPreset(preset_name))
		{
			LLNotificationsUtil::add("WLNoEditDefault");
			return;
		}

		confirm_cb = boost::bind(&LLFloaterDeleteEnvPreset::onDeleteSkyPresetConfirmation, this);
	}
	else if (param == "day_cycle")
	{
		LLDayCycleManager& day_mgr = LLDayCycleManager::instance();

		// Don't allow deleting system presets.
		if (day_mgr.isSystemPreset(preset_name))
		{
			LLNotificationsUtil::add("WLNoEditDefault");
			return;
		}

		confirm_cb = boost::bind(&LLFloaterDeleteEnvPreset::onDeleteDayCycleConfirmation, this);
	}
	else
	{
		llwarns << "Unrecognized key" << llendl;
	}

	LLSD args;
	args["MESSAGE"] = getString("msg_confirm_deletion");
	LLNotificationsUtil::add("GenericAlertYesCancel", args, LLSD(),
		boost::bind(&confirmation_callback, _1, _2, confirm_cb));
}

void LLFloaterDeleteEnvPreset::onBtnCancel()
{
	closeFloater();
}

void LLFloaterDeleteEnvPreset::populateWaterPresetsList()
{
	if (mKey.asString() != "water") return;

	mPresetCombo->removeall();

	std::string cur_preset;
	LLEnvManagerNew& env_mgr = LLEnvManagerNew::instance();
	if (!env_mgr.getUseRegionSettings())
	{
		cur_preset = env_mgr.getWaterPresetName();
	}

	// *TODO: Reload the list when user preferences change.
	LLWaterParamManager& water_mgr = LLWaterParamManager::instance();
	const std::map<std::string, LLWaterParamSet> &water_params_map = water_mgr.mParamList;
	for (std::map<std::string, LLWaterParamSet>::const_iterator it = water_params_map.begin(); it != water_params_map.end(); it++)
	{
		std::string name = it->first;

		// list only user presets
		if (water_mgr.isSystemPreset(name))
		{
			continue;
		}

		bool enabled = (name != cur_preset); // don't allow deleting current preset
		mPresetCombo->add(name, ADD_BOTTOM, enabled);
	}

	postPopulate();
}

void LLFloaterDeleteEnvPreset::populateSkyPresetsList()
{
	if (mKey.asString() != "sky") return;

	mPresetCombo->removeall();

	std::string cur_preset;
	LLEnvManagerNew& env_mgr = LLEnvManagerNew::instance();
	if (!env_mgr.getUseRegionSettings() && env_mgr.getUseFixedSky())
	{
		cur_preset = env_mgr.getSkyPresetName();
	}

	// *TODO: Reload the list when user preferences change.
	LLWLParamManager& sky_mgr = LLWLParamManager::instance();
	const std::map<LLWLParamKey, LLWLParamSet> &sky_params_map = sky_mgr.mParamList;
	for (std::map<LLWLParamKey, LLWLParamSet>::const_iterator it = sky_params_map.begin(); it != sky_params_map.end(); it++)
	{
		const LLWLParamKey& key = it->first;

		// list only local user presets
		if (key.scope == LLEnvKey::SCOPE_REGION || sky_mgr.isSystemPreset(key.name))
		{
			continue;
		}

		bool enabled = (key.name != cur_preset);
		mPresetCombo->add(key.name, ADD_BOTTOM, enabled);
	}

	postPopulate();
}

void LLFloaterDeleteEnvPreset::populateDayCyclesList()
{
	if (mKey.asString() != "day_cycle") return;

	mPresetCombo->removeall();

	std::string cur_day;
	LLEnvManagerNew& env_mgr = LLEnvManagerNew::instance();
	if (!env_mgr.getUseRegionSettings() && env_mgr.getUseDayCycle())
	{
		cur_day = env_mgr.getDayCycleName();
	}

	LLDayCycleManager& day_mgr = LLDayCycleManager::instance();
	const LLDayCycleManager::dc_map_t& map = day_mgr.getPresets();
	for (LLDayCycleManager::dc_map_t::const_iterator it = map.begin(); it != map.end(); ++it)
	{
		const std::string& name = it->first;

		// list only user presets
		if (day_mgr.isSystemPreset(name))
		{
			continue;
		}

		mPresetCombo->add(name, ADD_BOTTOM, name != cur_day);
	}

	postPopulate();
}

void LLFloaterDeleteEnvPreset::postPopulate()
{
	// Handle empty list and empty selection.
	bool has_selection = mPresetCombo->getItemCount() > 1 && mPresetCombo->getSelectedValue().isDefined();

	if (!has_selection)
	{
		mPresetCombo->setLabel(getString("combo_label"));
	}

	getChild<LLButton>("delete")->setEnabled(has_selection);
}

void LLFloaterDeleteEnvPreset::onDeleteDayCycleConfirmation()
{
	LLDayCycleManager::instance().deletePreset(mPresetCombo->getValue().asString());
}

void LLFloaterDeleteEnvPreset::onDeleteSkyPresetConfirmation()
{
	LLWLParamKey key(mPresetCombo->getValue().asString(), LLEnvKey::SCOPE_LOCAL);
	LLWLParamManager::instance().removeParamSet(key, true);
}

void LLFloaterDeleteEnvPreset::onDeleteWaterPresetConfirmation()
{
	LLWaterParamManager::instance().removeParamSet(mPresetCombo->getValue().asString(), true);
}
<|endoftext|>