<commit_before>/******************************************************************************
* Copyright (c) 2014, Connor Manning, connor@hobu.co
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in
*       the documentation and/or other materials provided
*       with the distribution.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
*       names of its contributors may be used to endorse or promote
*       products derived from this software without specific prior
*       written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/

#include "IcebridgeReader.hpp"
#include <pdal/util/FileUtils.hpp>
#include <pdal/PointView.hpp>
#include <pdal/pdal_macros.hpp>

#include <map>

namespace
{
    const std::vector<pdal::hdf5::Hdf5ColumnData> hdf5Columns =
    {
        { "instrument_parameters/time_hhmmss",  H5::PredType::NATIVE_FLOAT },
        { "latitude",                           H5::PredType::NATIVE_FLOAT },
        { "longitude",                          H5::PredType::NATIVE_FLOAT },
        { "elevation",                          H5::PredType::NATIVE_FLOAT },
        { "instrument_parameters/xmt_sigstr",   H5::PredType::NATIVE_INT   },
        { "instrument_parameters/rcv_sigstr",   H5::PredType::NATIVE_INT   },
        { "instrument_parameters/azimuth",      H5::PredType::NATIVE_FLOAT },
        { "instrument_parameters/pitch",        H5::PredType::NATIVE_FLOAT },
        { "instrument_parameters/roll",         H5::PredType::NATIVE_FLOAT },
        { "instrument_parameters/gps_pdop",     H5::PredType::NATIVE_FLOAT },
        { "instrument_parameters/pulse_width",  H5::PredType::NATIVE_FLOAT },
        { "instrument_parameters/rel_time",     H5::PredType::NATIVE_FLOAT }
    };
}

namespace pdal
{

static PluginInfo const s_info = PluginInfo(
    "readers.icebridge",
    "NASA HDF5-based IceBridge ATM reader. \n" \
        "See http://nsidc.org/data/docs/daac/icebridge/ilatm1b/index.html \n" \
        "for more information.",
    "http://pdal.io/stages/readers.icebridge.html" );

CREATE_SHARED_PLUGIN(1, 0, IcebridgeReader, Reader, s_info)

std::string IcebridgeReader::getName() const { return s_info.name; }

Options IcebridgeReader::getDefaultOptions()
{
    Options options;
    options.add("filename", "", "file to read from");
    return options;
}

Dimension::IdList IcebridgeReader::getDefaultDimensions()
{
    Dimension::IdList ids;

    using namespace Dimension;

    ids.push_back(Id::OffsetTime);
    ids.push_back(Id::Y);
    ids.push_back(Id::X);
    ids.push_back(Id::Z);
    ids.push_back(Id::StartPulse);
    ids.push_back(Id::ReflectedPulse);
    ids.push_back(Id::ScanAngleRank);
    ids.push_back(Id::Pitch);
    ids.push_back(Id::Roll);
    ids.push_back(Id::Pdop);
    ids.push_back(Id::PulseWidth);
    ids.push_back(Id::GpsTime);
    return ids;
}

void IcebridgeReader::addDimensions(PointLayoutPtr layout)
{
    return layout->registerDims(getDefaultDimensions());
}

void IcebridgeReader::ready(PointTableRef table)
{
    m_hdf5Handler.initialize(m_filename, hdf5Columns);
    m_index = 0;
}

void IcebridgeReader::initialize(PointTableRef)
{
    // Data are WGS84 (4326) with ITRF2000 datum (6656)
    // See http://nsidc.org/data/docs/daac/icebridge/ilvis2/index.html for
    // background
    SpatialReference ref("EPSG:4326");
    setSpatialReference(m_metadata, ref);
}

// If longitude between 0-180, just return it, degrees east; if between 180
// and 360, subtract 360 to get negative value.
double IcebridgeReader::convertLongitude(double longitude)
{
    longitude = fmod(longitude, 360.0);
    if (longitude <= -180)
        longitude += 360;
    else if (longitude > 180)
        longitude -= 360;
    return longitude;
}

point_count_t IcebridgeReader::read(PointViewPtr view, point_count_t count)
{
    //All data we read for icebridge is currently 4 bytes wide, so
    //  just allocate once and forget it.
    //This could be a huge allocation.  Perhaps we should do something
    //  in the icebridge handler?

    PointId startId = view->size();
    point_count_t remaining = m_hdf5Handler.getNumPoints() - m_index;
    count = std::min(count, remaining);

    std::unique_ptr<unsigned char>
        rawData(new unsigned char[count * sizeof(float)]);

    //Not loving the position-linked data, but fine for now.
    Dimension::IdList dims = getDefaultDimensions();
    auto di = dims.begin();
    for (auto ci = hdf5Columns.begin(); ci != hdf5Columns.end(); ++ci, ++di)
    {
        PointId nextId = startId;
        PointId idx = m_index;
        const hdf5::Hdf5ColumnData& column = *ci;

        try
        {
            m_hdf5Handler.getColumnEntries(rawData.get(), column.name, count,
                m_index);
            void *p = (void *)rawData.get();

            // This is ugly but avoids a test in a tight loop.
            if (column.predType == H5::PredType::NATIVE_FLOAT)
            {
                // Offset time is in ms but icebridge stores in seconds.
                if (*di == Dimension::Id::OffsetTime)
                {
                    float *fval = (float *)p;
                    for (PointId i = 0; i < count; ++i)
                    {
                        view->setField(*di, nextId++, *fval * 1000);
                        fval++;
                    }
                }
                else
                {
                    float *fval = (float *)p;
                    for (PointId i = 0; i < count; ++i)
                        view->setField(*di, nextId++, *fval++);
                }
            }
            else if (column.predType == H5::PredType::NATIVE_INT)
            {
                int32_t *ival = (int32_t *)p;
                for (PointId i = 0; i < count; ++i)
                    view->setField(*di, nextId++, *ival++);
            }
        }
        catch(...)
        {
            throw icebridge_error("Error fetching column data");
        }
    }
    return count;
}

void IcebridgeReader::processOptions(const Options& options)
{
    m_metadataFile =
        options.getValueOrDefault<std::string>("metadata", "");
    if (!m_metadataFile.empty() && ! FileUtils::fileExists(m_metadataFile))
    {
        std::ostringstream oss;
        oss << "Invalid metadata file: '" << m_metadataFile << "'";
        throw pdal_error(oss.str());
    }

}

void IcebridgeReader::done(PointTableRef table)
{
    m_hdf5Handler.close();
    if (!m_metadataFile.empty())
    {
        m_mdReader.readMetadataFile(m_metadataFile, &m_metadata);
    }

}

bool IcebridgeReader::eof()
{
    return m_index >= m_hdf5Handler.getNumPoints();
}

} // namespace pdal
<commit_msg>offset readers.icebridge longitude #1214<commit_after>/******************************************************************************
* Copyright (c) 2014, Connor Manning, connor@hobu.co
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in
*       the documentation and/or other materials provided
*       with the distribution.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
*       names of its contributors may be used to endorse or promote
*       products derived from this software without specific prior
*       written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/

#include "IcebridgeReader.hpp"
#include <pdal/util/FileUtils.hpp>
#include <pdal/PointView.hpp>
#include <pdal/pdal_macros.hpp>

#include <map>

namespace
{
    const std::vector<pdal::hdf5::Hdf5ColumnData> hdf5Columns =
    {
        { "instrument_parameters/time_hhmmss",  H5::PredType::NATIVE_FLOAT },
        { "latitude",                           H5::PredType::NATIVE_FLOAT },
        { "longitude",                          H5::PredType::NATIVE_FLOAT },
        { "elevation",                          H5::PredType::NATIVE_FLOAT },
        { "instrument_parameters/xmt_sigstr",   H5::PredType::NATIVE_INT   },
        { "instrument_parameters/rcv_sigstr",   H5::PredType::NATIVE_INT   },
        { "instrument_parameters/azimuth",      H5::PredType::NATIVE_FLOAT },
        { "instrument_parameters/pitch",        H5::PredType::NATIVE_FLOAT },
        { "instrument_parameters/roll",         H5::PredType::NATIVE_FLOAT },
        { "instrument_parameters/gps_pdop",     H5::PredType::NATIVE_FLOAT },
        { "instrument_parameters/pulse_width",  H5::PredType::NATIVE_FLOAT },
        { "instrument_parameters/rel_time",     H5::PredType::NATIVE_FLOAT }
    };
}

namespace pdal
{

static PluginInfo const s_info = PluginInfo(
    "readers.icebridge",
    "NASA HDF5-based IceBridge ATM reader. \n" \
        "See http://nsidc.org/data/docs/daac/icebridge/ilatm1b/index.html \n" \
        "for more information.",
    "http://pdal.io/stages/readers.icebridge.html" );

CREATE_SHARED_PLUGIN(1, 0, IcebridgeReader, Reader, s_info)

std::string IcebridgeReader::getName() const { return s_info.name; }

Options IcebridgeReader::getDefaultOptions()
{
    Options options;
    options.add("filename", "", "file to read from");
    return options;
}

Dimension::IdList IcebridgeReader::getDefaultDimensions()
{
    Dimension::IdList ids;

    using namespace Dimension;

    ids.push_back(Id::OffsetTime);
    ids.push_back(Id::Y);
    ids.push_back(Id::X);
    ids.push_back(Id::Z);
    ids.push_back(Id::StartPulse);
    ids.push_back(Id::ReflectedPulse);
    ids.push_back(Id::ScanAngleRank);
    ids.push_back(Id::Pitch);
    ids.push_back(Id::Roll);
    ids.push_back(Id::Pdop);
    ids.push_back(Id::PulseWidth);
    ids.push_back(Id::GpsTime);
    return ids;
}

void IcebridgeReader::addDimensions(PointLayoutPtr layout)
{
    return layout->registerDims(getDefaultDimensions());
}

void IcebridgeReader::ready(PointTableRef table)
{
    m_hdf5Handler.initialize(m_filename, hdf5Columns);
    m_index = 0;
}

void IcebridgeReader::initialize(PointTableRef)
{
    // Data are WGS84 (4326) with ITRF2000 datum (6656)
    // See http://nsidc.org/data/docs/daac/icebridge/ilvis2/index.html for
    // background
    SpatialReference ref("EPSG:4326");
    setSpatialReference(m_metadata, ref);
}

// If longitude between 0-180, just return it, degrees east; if between 180
// and 360, subtract 360 to get negative value.
double IcebridgeReader::convertLongitude(double longitude)
{
    longitude = fmod(longitude, 360.0);
    if (longitude <= -180)
        longitude += 360;
    else if (longitude > 180)
        longitude -= 360;
    return longitude;
}

// If longitude between 0-180, just return it, degrees east; if between 180
// and 360, subtract 360 to get negative value.
double convertLongitude(double longitude)
{
    longitude = fmod(longitude, 360.0);
    if (longitude <= -180)
        longitude += 360;
    else if (longitude > 180)
        longitude -= 360;
    return longitude;
}

point_count_t IcebridgeReader::read(PointViewPtr view, point_count_t count)
{
    //All data we read for icebridge is currently 4 bytes wide, so
    //  just allocate once and forget it.
    //This could be a huge allocation.  Perhaps we should do something
    //  in the icebridge handler?

    PointId startId = view->size();
    point_count_t remaining = m_hdf5Handler.getNumPoints() - m_index;
    count = std::min(count, remaining);

    std::unique_ptr<unsigned char>
        rawData(new unsigned char[count * sizeof(float)]);

    //Not loving the position-linked data, but fine for now.
    Dimension::IdList dims = getDefaultDimensions();
    auto di = dims.begin();
    for (auto ci = hdf5Columns.begin(); ci != hdf5Columns.end(); ++ci, ++di)
    {
        PointId nextId = startId;
        PointId idx = m_index;
        const hdf5::Hdf5ColumnData& column = *ci;

        try
        {
            m_hdf5Handler.getColumnEntries(rawData.get(), column.name, count,
                m_index);
            void *p = (void *)rawData.get();

            // This is ugly but avoids a test in a tight loop.
            if (column.predType == H5::PredType::NATIVE_FLOAT)
            {
                // Offset time is in ms but icebridge stores in seconds.
                if (*di == Dimension::Id::OffsetTime)
                {
                    float *fval = (float *)p;
                    for (PointId i = 0; i < count; ++i)
                    {
                        view->setField(*di, nextId++, *fval * 1000);
                        fval++;
                    }
                }
                else if (*di == Dimension::Id::X)
                {
                    // Longitude is 0-360. Convert
                    float *fval = (float *)p;
                    double dval = (double)(*fval);
                    dval = convertLongitude(dval);
                    for (PointId i = 0; i < count; ++i)
                    {
                        view->setField(*di, nextId++, dval);
                        fval++;
                    }

                }
                else
                {
                    float *fval = (float *)p;
                    for (PointId i = 0; i < count; ++i)
                        view->setField(*di, nextId++, *fval++);
                }
            }
            else if (column.predType == H5::PredType::NATIVE_INT)
            {
                int32_t *ival = (int32_t *)p;
                for (PointId i = 0; i < count; ++i)
                    view->setField(*di, nextId++, *ival++);
            }
        }
        catch(...)
        {
            throw icebridge_error("Error fetching column data");
        }
    }
    return count;
}

void IcebridgeReader::processOptions(const Options& options)
{
    m_metadataFile =
        options.getValueOrDefault<std::string>("metadata", "");
    if (!m_metadataFile.empty() && ! FileUtils::fileExists(m_metadataFile))
    {
        std::ostringstream oss;
        oss << "Invalid metadata file: '" << m_metadataFile << "'";
        throw pdal_error(oss.str());
    }

}

void IcebridgeReader::done(PointTableRef table)
{
    m_hdf5Handler.close();
    if (!m_metadataFile.empty())
    {
        m_mdReader.readMetadataFile(m_metadataFile, &m_metadata);
    }

}

bool IcebridgeReader::eof()
{
    return m_index >= m_hdf5Handler.getNumPoints();
}

} // namespace pdal
<|endoftext|>


<commit_before>#ifndef STATIC_LINK
#define IMPLEMENT_API
#endif

#if defined(HX_WINDOWS) || defined(HX_MACOS) || defined(HX_LINUX)
#define NEKO_COMPATIBLE
#endif

#include <hx/CFFIPrime.h>
#include "SamcodesAmazonMobileAnalytics.h"

using namespace samcodesamazonmobileanalytics;

#ifdef IPHONE
void samcodesamazonmobileanalytics_init(HxString appId, HxString identityPoolId)
{
	init(appId.c_str(), identityPoolId.c_str());
}
DEFINE_PRIME2v(samcodesamazonmobileanalytics_init)

void samcodesamazonmobileanalytics_add_global_attribute(HxString attributeName, HxString attributeValue)
{
	addGlobalAttribute(attributeName.c_str(), attributeValue.c_str());
}
DEFINE_PRIME2v(samcodesamazonmobileanalytics_add_global_attribute)

void samcodesamazonmobileanalytics_add_global_attribute_for_event_type(HxString eventType, HxString attributeName, HxString attributeValue)
{
	addGlobalAttributeForEventType(eventType.c_str(), attributeName.c_str(), attributeValue.c_str());
}
DEFINE_PRIME3v(samcodesamazonmobileanalytics_add_global_attribute_for_event_type)

void samcodesamazonmobileanalytics_remove_global_attribute(HxString attributeName)
{
	removeGlobalAttribute(attributeName.c_str());
}
DEFINE_PRIME1v(samcodesamazonmobileanalytics_remove_global_attribute)

void samcodesamazonmobileanalytics_remove_global_attribute_for_event_type(HxString eventType, HxString attributeName)
{
	removeGlobalAttributeForEventType(eventType.c_str(), attributeName.c_str());
}
DEFINE_PRIME2v(samcodesamazonmobileanalytics_remove_global_attribute_for_event_type)

void samcodesamazonmobileanalytics_add_global_metric(HxString metricName, float metricValue)
{
	addGlobalMetric(metricName.c_str(), metricValue);
}
DEFINE_PRIME2v(samcodesamazonmobileanalytics_add_global_metric)

void samcodesamazonmobileanalytics_add_global_metric_for_event_type(HxString eventType, HxString metricName, float metricValue)
{
	addGlobalMetricForEventType(eventType.c_str(), metricName.c_str(), metricValue);
}
DEFINE_PRIME3v(samcodesamazonmobileanalytics_add_global_metric_for_event_type)

void samcodesamazonmobileanalytics_remove_global_metric(HxString metricName)
{
	removeGlobalMetric(metricName.c_str());
}
DEFINE_PRIME1v(samcodesamazonmobileanalytics_remove_global_metric)

void samcodesamazonmobileanalytics_remove_global_metric_for_event_type(HxString eventType, HxString metricName)
{
	removeGlobalMetricForEventType(eventType.c_str(), metricName.c_str());
}
DEFINE_PRIME2v(samcodesamazonmobileanalytics_remove_global_metric_for_event_type)

void samcodesamazonmobileanalytics_submit_events()
{
	submitEvents();
}
DEFINE_PRIME0v(samcodesamazonmobileanalytics_submit_events)

static value samcodesamazonmobileanalytics_record_event(value eventType, value attributeNames, value attributeValues, value metricNames, value metricValues)
{
	int attributeNamesSize = val_array_size(attributeNames);
	int attributeValuesSize = val_array_size(attributeValues);
	int metricNamesSize = val_array_size(metricNames);
	int metricValuesSize = val_array_size(metricValues);

	if(attributeNamesSize != attributeValuesSize || metricNamesSize != metricValuesSize)
	{
		return alloc_null(); // These should always be the same length (since they map as key => value pairs)
	}

	const char** arrAttributeKeys = new const char*[attributeNamesSize];
	const char** arrAttributeValues = new const char*[attributeNamesSize];
	const char** arrMetricKeys = new const char*[metricNamesSize];
	const char** arrMetricValues = new float*[metricNamesSize];

	for(int i = 0; i < attributeNamesSize; i++)
	{
		value key = val_array_i(attributeNames, i);
		value v = val_array_i(attributeValues, i);
		arrAttributeKeys[i] = val_string(key);
		arrAttributeValues[i] = val_string(v);
	}
	for(int i = 0; i < metricNamesSize; i++)
	{
		value key = val_array_i(metricNames, i);
		value v = val_array_i(metricValues, i);
		arrMetricKeys[i] = val_string(key);
		arrMetricValues[i] = val_float(v);
	}

	recordEvent(val_get_string(eventType), arrAttributeKeys, arrAttributeValues, arrMetricKeys, arrMetricValues, attributeNamesSize, metricNamesSize);

	delete[] arrAttributeKeys;
	delete[] arrAttributeValues;
	delete[] arrMetricKeys;
	delete[] arrMetricValues;

	return alloc_null();
}
DEFINE_PRIM(samcodesamazonmobileanalytics_record_event, 5)

extern "C" void samcodesamazonmobileanalytics_main()
{

}
DEFINE_ENTRY_POINT(samcodesamazonmobileanalytics_main);

extern "C" int samcodesamazonmobileanalytics_register_prims()
{
	return 0;
}

#endif<commit_msg>And another iOS typo...<commit_after>#ifndef STATIC_LINK
#define IMPLEMENT_API
#endif

#if defined(HX_WINDOWS) || defined(HX_MACOS) || defined(HX_LINUX)
#define NEKO_COMPATIBLE
#endif

#include <hx/CFFIPrime.h>
#include "SamcodesAmazonMobileAnalytics.h"

using namespace samcodesamazonmobileanalytics;

#ifdef IPHONE
void samcodesamazonmobileanalytics_init(HxString appId, HxString identityPoolId)
{
	init(appId.c_str(), identityPoolId.c_str());
}
DEFINE_PRIME2v(samcodesamazonmobileanalytics_init)

void samcodesamazonmobileanalytics_add_global_attribute(HxString attributeName, HxString attributeValue)
{
	addGlobalAttribute(attributeName.c_str(), attributeValue.c_str());
}
DEFINE_PRIME2v(samcodesamazonmobileanalytics_add_global_attribute)

void samcodesamazonmobileanalytics_add_global_attribute_for_event_type(HxString eventType, HxString attributeName, HxString attributeValue)
{
	addGlobalAttributeForEventType(eventType.c_str(), attributeName.c_str(), attributeValue.c_str());
}
DEFINE_PRIME3v(samcodesamazonmobileanalytics_add_global_attribute_for_event_type)

void samcodesamazonmobileanalytics_remove_global_attribute(HxString attributeName)
{
	removeGlobalAttribute(attributeName.c_str());
}
DEFINE_PRIME1v(samcodesamazonmobileanalytics_remove_global_attribute)

void samcodesamazonmobileanalytics_remove_global_attribute_for_event_type(HxString eventType, HxString attributeName)
{
	removeGlobalAttributeForEventType(eventType.c_str(), attributeName.c_str());
}
DEFINE_PRIME2v(samcodesamazonmobileanalytics_remove_global_attribute_for_event_type)

void samcodesamazonmobileanalytics_add_global_metric(HxString metricName, float metricValue)
{
	addGlobalMetric(metricName.c_str(), metricValue);
}
DEFINE_PRIME2v(samcodesamazonmobileanalytics_add_global_metric)

void samcodesamazonmobileanalytics_add_global_metric_for_event_type(HxString eventType, HxString metricName, float metricValue)
{
	addGlobalMetricForEventType(eventType.c_str(), metricName.c_str(), metricValue);
}
DEFINE_PRIME3v(samcodesamazonmobileanalytics_add_global_metric_for_event_type)

void samcodesamazonmobileanalytics_remove_global_metric(HxString metricName)
{
	removeGlobalMetric(metricName.c_str());
}
DEFINE_PRIME1v(samcodesamazonmobileanalytics_remove_global_metric)

void samcodesamazonmobileanalytics_remove_global_metric_for_event_type(HxString eventType, HxString metricName)
{
	removeGlobalMetricForEventType(eventType.c_str(), metricName.c_str());
}
DEFINE_PRIME2v(samcodesamazonmobileanalytics_remove_global_metric_for_event_type)

void samcodesamazonmobileanalytics_submit_events()
{
	submitEvents();
}
DEFINE_PRIME0v(samcodesamazonmobileanalytics_submit_events)

static value samcodesamazonmobileanalytics_record_event(value eventType, value attributeNames, value attributeValues, value metricNames, value metricValues)
{
	int attributeNamesSize = val_array_size(attributeNames);
	int attributeValuesSize = val_array_size(attributeValues);
	int metricNamesSize = val_array_size(metricNames);
	int metricValuesSize = val_array_size(metricValues);

	if(attributeNamesSize != attributeValuesSize || metricNamesSize != metricValuesSize)
	{
		return alloc_null(); // These should always be the same length (since they map as key => value pairs)
	}

	const char** arrAttributeKeys = new const char*[attributeNamesSize];
	const char** arrAttributeValues = new const char*[attributeNamesSize];
	const char** arrMetricKeys = new const char*[metricNamesSize];
	const float** arrMetricValues = new float*[metricNamesSize];

	for(int i = 0; i < attributeNamesSize; i++)
	{
		value key = val_array_i(attributeNames, i);
		value v = val_array_i(attributeValues, i);
		arrAttributeKeys[i] = val_string(key);
		arrAttributeValues[i] = val_string(v);
	}
	for(int i = 0; i < metricNamesSize; i++)
	{
		value key = val_array_i(metricNames, i);
		value v = val_array_i(metricValues, i);
		arrMetricKeys[i] = val_string(key);
		arrMetricValues[i] = val_float(v);
	}

	recordEvent(val_get_string(eventType), arrAttributeKeys, arrAttributeValues, arrMetricKeys, arrMetricValues, attributeNamesSize, metricNamesSize);

	delete[] arrAttributeKeys;
	delete[] arrAttributeValues;
	delete[] arrMetricKeys;
	delete[] arrMetricValues;

	return alloc_null();
}
DEFINE_PRIM(samcodesamazonmobileanalytics_record_event, 5)

extern "C" void samcodesamazonmobileanalytics_main()
{

}
DEFINE_ENTRY_POINT(samcodesamazonmobileanalytics_main);

extern "C" int samcodesamazonmobileanalytics_register_prims()
{
	return 0;
}

#endif<|endoftext|>


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

#include "ash/desktop_background/desktop_background_resources.h"

#include "base/logging.h"
#include "base/rand_util.h"
#include "grit/ash_wallpaper_resources.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/image/image.h"

namespace {

// Keeps in sync (same order) with WallpaperLayout enum in header file.
const char* kWallpaperLayoutArrays[] = {
    "CENTER",
    "CENTER_CROPPED",
    "STRETCH",
    "TILE"
};

const ash::WallpaperInfo kDefaultWallpapers[] = {
#if !defined(GOOGLE_CHROME_BUILD)
    {
        {
            IDR_AURA_WALLPAPERS_ROMAINGUY_0_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_ROMAINGUY_0_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_ROMAINGUY_0_THUMB,
        "Romain Guy",
        "http://www.curious-creature.org"
    },
#else
    {
        {
            IDR_AURA_WALLPAPERS_1_NATURE0_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_1_NATURE0_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_1_NATURE0_THUMB,
        "Kathy Collins / Getty Images",
        "http://www.gettyimages.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_1_NATURE1_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_1_NATURE1_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_1_NATURE1_THUMB,
        "Johannes van Donge",
        "http://www.diginature.nl"
    },
    {
        {
            IDR_AURA_WALLPAPERS_1_NATURE2_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_1_NATURE2_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_1_NATURE2_THUMB,
        "Oleg Zhukov",
        "http://500px.com/eosboy"
    },
    {
        {
            IDR_AURA_WALLPAPERS_1_NATURE3_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_1_NATURE3_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_1_NATURE3_THUMB,
        "Stefano Ronchi",
        "http://www.stefanoronchi.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_1_NATURE4_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_1_NATURE4_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_1_NATURE4_THUMB,
        "Stefano Ronchi",
        "http://www.stefanoronchi.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_1_NATURE5_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_1_NATURE5_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_1_NATURE5_THUMB,
        "Mario Moreno",
        "http://www.mariomorenophotography.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_1_NATURE6_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_1_NATURE6_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_1_NATURE6_THUMB,
        "Walter Soestbergen",
        "http://www.waltersoestbergen.nl"
    },
    {
        {
            IDR_AURA_WALLPAPERS_1_NATURE7_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_1_NATURE7_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_1_NATURE7_THUMB,
        "Mark Bridger",
        "http://www.bridgephotography.co.uk"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE0_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE0_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE0_THUMB,
        "Vitali Prokopenko",
        "http://www.vitphoto.com/"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE1_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE1_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE1_THUMB,
        "Romain Guy",
        "http://www.curious-creature.org"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE2_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE2_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE2_THUMB,
        "Mark Bridger",
        "http://www.bridgephotography.co.uk"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE3_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE3_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE3_THUMB,
        "Mike Reyfman",
        "http://mikereyfman.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE4_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE4_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE4_THUMB,
        "Mike Reyfman",
        "http://mikereyfman.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE5_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE5_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE5_THUMB,
        "Mike Reyfman",
        "http://mikereyfman.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE6_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE6_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE6_THUMB,
        "Mike Reyfman",
        "http://mikereyfman.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE7_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE7_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE7_THUMB,
        "Romain Guy",
        "http://www.curious-creature.org"
    },
    {
        {
            IDR_AURA_WALLPAPERS_3_URBAN0_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_3_URBAN0_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_3_URBAN0_THUMB,
        "Paulo FLOP",
        "http://500px.com/FLOP"
    },
    {
        {
            IDR_AURA_WALLPAPERS_3_URBAN1_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_3_URBAN1_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_3_URBAN1_THUMB,
        "Mike Reyfman",
        "http://mikereyfman.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_3_URBAN2_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_3_URBAN2_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_3_URBAN2_THUMB,
        "Neil Kremer",
        "http://lightshedimagery.smugmug.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_3_URBAN3_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_3_URBAN3_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_3_URBAN3_THUMB,
        "Neil Kremer",
        "http://lightshedimagery.smugmug.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE8_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE8_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE8_THUMB,
        "Clemens Günthermann",
        "http://www.clegue.com"
    },
#endif
    {
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT1_LARGE,
            ash::TILE
        },
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT1_SMALL,
            ash::TILE
        },
        IDR_AURA_WALLPAPERS_5_GRADIENT1_THUMB,
        "Chromium",
        "http://www.chromium.org"
    },
    {
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT2_LARGE,
            ash::TILE
        },
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT2_SMALL,
            ash::TILE
        },
        IDR_AURA_WALLPAPERS_5_GRADIENT2_THUMB,
        "Chromium",
        "http://www.chromium.org"
    },
    {
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT3_LARGE,
            ash::TILE
        },
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT3_SMALL,
            ash::TILE
        },
        IDR_AURA_WALLPAPERS_5_GRADIENT3_THUMB,
        "Chromium",
        "http://www.chromium.org"
    },
    {
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT4_LARGE,
            ash::TILE
        },
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT4_SMALL,
            ash::TILE
        },
        IDR_AURA_WALLPAPERS_5_GRADIENT4_THUMB,
        "Chromium",
        "http://www.chromium.org"
    },
    {
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT5_LARGE,
            ash::TILE
        },
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT5_SMALL,
            ash::TILE
        },
        IDR_AURA_WALLPAPERS_5_GRADIENT5_THUMB,
        "Chromium",
        "http://www.chromium.org"
    },
    {
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT6_LARGE,
            ash::TILE
        },
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT6_SMALL,
            ash::TILE
        },
        IDR_AURA_WALLPAPERS_5_GRADIENT6_THUMB,
        "Chromium",
        "http://www.chromium.org"
    },
    {
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT7_LARGE,
            ash::TILE
        },
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT7_SMALL,
            ash::TILE
        },
        IDR_AURA_WALLPAPERS_5_GRADIENT7_THUMB,
        "Chromium",
        "http://www.chromium.org"
    }
};

const int kWallpaperLayoutCount = arraysize(kWallpaperLayoutArrays);
const int kDefaultWallpaperCount = arraysize(kDefaultWallpapers);
const int kInvalidWallpaperIndex = -1;
const int kSolidColorIndex = -2;

// TODO(saintlou): These hardcoded indexes, although checked against the size
// of the array are really hacky.
#if defined(GOOGLE_CHROME_BUILD)
const int kDefaultWallpaperIndex = 20; // IDR_AURA_WALLPAPERS_2_LANDSCAPE8
const int kLastRandomWallpaperIndex = 19; // The first 20 are random.
const int kGuestWallpaperIndex = kDefaultWallpaperIndex;
#else
// Set default wallpaper to the grey background for faster wallpaper loading
// time in browser tests. Otherwise, some of the tests will finish before
// wallpaper loaded and cause crashes.
const int kDefaultWallpaperIndex = 5;  // IDR_AURA_WALLPAPERS_5_GRADIENT5
const int kLastRandomWallpaperIndex = 8;
const int kGuestWallpaperIndex = kDefaultWallpaperIndex;
#endif

}  // namespace

namespace ash {

int GetDefaultWallpaperIndex() {
  DCHECK(kDefaultWallpaperIndex < kDefaultWallpaperCount);
  return std::min(kDefaultWallpaperIndex, kDefaultWallpaperCount - 1);
}

int GetGuestWallpaperIndex() {
  DCHECK(kGuestWallpaperIndex < kDefaultWallpaperCount);
  return std::min(kGuestWallpaperIndex, kDefaultWallpaperCount - 1);
}

int GetInvalidWallpaperIndex() {
  return kInvalidWallpaperIndex;
}

WallpaperLayout GetLayoutEnum(const std::string& layout) {
  for (int i = 0; i < kWallpaperLayoutCount; i++) {
    if (layout.compare(kWallpaperLayoutArrays[i]) == 0)
      return static_cast<WallpaperLayout>(i);
  }
  // Default to use CENTER layout.
  return CENTER;
}

int GetNextWallpaperIndex(int index) {
  DCHECK(kLastRandomWallpaperIndex < kDefaultWallpaperCount);
  return (index + 1) % (kLastRandomWallpaperIndex + 1);
}

int GetSolidColorIndex() {
  return kSolidColorIndex;
}

int GetWallpaperCount() {
  return kDefaultWallpaperCount;
}

const WallpaperInfo& GetWallpaperInfo(int index) {
  DCHECK(index >= 0 && index < kDefaultWallpaperCount);
  return kDefaultWallpapers[index];
}

const WallpaperViewInfo& GetWallpaperViewInfo(int index,
                                              WallpaperResolution resolution) {
  if (resolution == SMALL)
    return kDefaultWallpapers[index].small_wallpaper;
  else
    return kDefaultWallpapers[index].large_wallpaper;
}

}  // namespace ash
<commit_msg>Change guest wallpaper to IDR_AURA_WALLPAPERS_2_LANDSCAPE7.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/desktop_background/desktop_background_resources.h"

#include "base/logging.h"
#include "base/rand_util.h"
#include "grit/ash_wallpaper_resources.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/image/image.h"

namespace {

// Keeps in sync (same order) with WallpaperLayout enum in header file.
const char* kWallpaperLayoutArrays[] = {
    "CENTER",
    "CENTER_CROPPED",
    "STRETCH",
    "TILE"
};

const ash::WallpaperInfo kDefaultWallpapers[] = {
#if !defined(GOOGLE_CHROME_BUILD)
    {
        {
            IDR_AURA_WALLPAPERS_ROMAINGUY_0_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_ROMAINGUY_0_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_ROMAINGUY_0_THUMB,
        "Romain Guy",
        "http://www.curious-creature.org"
    },
#else
    {
        {
            IDR_AURA_WALLPAPERS_1_NATURE0_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_1_NATURE0_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_1_NATURE0_THUMB,
        "Kathy Collins / Getty Images",
        "http://www.gettyimages.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_1_NATURE1_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_1_NATURE1_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_1_NATURE1_THUMB,
        "Johannes van Donge",
        "http://www.diginature.nl"
    },
    {
        {
            IDR_AURA_WALLPAPERS_1_NATURE2_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_1_NATURE2_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_1_NATURE2_THUMB,
        "Oleg Zhukov",
        "http://500px.com/eosboy"
    },
    {
        {
            IDR_AURA_WALLPAPERS_1_NATURE3_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_1_NATURE3_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_1_NATURE3_THUMB,
        "Stefano Ronchi",
        "http://www.stefanoronchi.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_1_NATURE4_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_1_NATURE4_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_1_NATURE4_THUMB,
        "Stefano Ronchi",
        "http://www.stefanoronchi.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_1_NATURE5_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_1_NATURE5_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_1_NATURE5_THUMB,
        "Mario Moreno",
        "http://www.mariomorenophotography.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_1_NATURE6_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_1_NATURE6_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_1_NATURE6_THUMB,
        "Walter Soestbergen",
        "http://www.waltersoestbergen.nl"
    },
    {
        {
            IDR_AURA_WALLPAPERS_1_NATURE7_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_1_NATURE7_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_1_NATURE7_THUMB,
        "Mark Bridger",
        "http://www.bridgephotography.co.uk"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE0_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE0_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE0_THUMB,
        "Vitali Prokopenko",
        "http://www.vitphoto.com/"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE1_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE1_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE1_THUMB,
        "Romain Guy",
        "http://www.curious-creature.org"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE2_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE2_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE2_THUMB,
        "Mark Bridger",
        "http://www.bridgephotography.co.uk"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE3_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE3_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE3_THUMB,
        "Mike Reyfman",
        "http://mikereyfman.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE4_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE4_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE4_THUMB,
        "Mike Reyfman",
        "http://mikereyfman.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE5_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE5_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE5_THUMB,
        "Mike Reyfman",
        "http://mikereyfman.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE6_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE6_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE6_THUMB,
        "Mike Reyfman",
        "http://mikereyfman.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE7_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE7_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE7_THUMB,
        "Romain Guy",
        "http://www.curious-creature.org"
    },
    {
        {
            IDR_AURA_WALLPAPERS_3_URBAN0_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_3_URBAN0_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_3_URBAN0_THUMB,
        "Paulo FLOP",
        "http://500px.com/FLOP"
    },
    {
        {
            IDR_AURA_WALLPAPERS_3_URBAN1_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_3_URBAN1_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_3_URBAN1_THUMB,
        "Mike Reyfman",
        "http://mikereyfman.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_3_URBAN2_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_3_URBAN2_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_3_URBAN2_THUMB,
        "Neil Kremer",
        "http://lightshedimagery.smugmug.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_3_URBAN3_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_3_URBAN3_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_3_URBAN3_THUMB,
        "Neil Kremer",
        "http://lightshedimagery.smugmug.com"
    },
    {
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE8_LARGE,
            ash::CENTER_CROPPED
        },
        {
            IDR_AURA_WALLPAPERS_2_LANDSCAPE8_SMALL,
            ash::CENTER
        },
        IDR_AURA_WALLPAPERS_2_LANDSCAPE8_THUMB,
        "Clemens Günthermann",
        "http://www.clegue.com"
    },
#endif
    {
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT1_LARGE,
            ash::TILE
        },
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT1_SMALL,
            ash::TILE
        },
        IDR_AURA_WALLPAPERS_5_GRADIENT1_THUMB,
        "Chromium",
        "http://www.chromium.org"
    },
    {
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT2_LARGE,
            ash::TILE
        },
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT2_SMALL,
            ash::TILE
        },
        IDR_AURA_WALLPAPERS_5_GRADIENT2_THUMB,
        "Chromium",
        "http://www.chromium.org"
    },
    {
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT3_LARGE,
            ash::TILE
        },
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT3_SMALL,
            ash::TILE
        },
        IDR_AURA_WALLPAPERS_5_GRADIENT3_THUMB,
        "Chromium",
        "http://www.chromium.org"
    },
    {
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT4_LARGE,
            ash::TILE
        },
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT4_SMALL,
            ash::TILE
        },
        IDR_AURA_WALLPAPERS_5_GRADIENT4_THUMB,
        "Chromium",
        "http://www.chromium.org"
    },
    {
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT5_LARGE,
            ash::TILE
        },
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT5_SMALL,
            ash::TILE
        },
        IDR_AURA_WALLPAPERS_5_GRADIENT5_THUMB,
        "Chromium",
        "http://www.chromium.org"
    },
    {
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT6_LARGE,
            ash::TILE
        },
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT6_SMALL,
            ash::TILE
        },
        IDR_AURA_WALLPAPERS_5_GRADIENT6_THUMB,
        "Chromium",
        "http://www.chromium.org"
    },
    {
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT7_LARGE,
            ash::TILE
        },
        {
            IDR_AURA_WALLPAPERS_5_GRADIENT7_SMALL,
            ash::TILE
        },
        IDR_AURA_WALLPAPERS_5_GRADIENT7_THUMB,
        "Chromium",
        "http://www.chromium.org"
    }
};

const int kWallpaperLayoutCount = arraysize(kWallpaperLayoutArrays);
const int kDefaultWallpaperCount = arraysize(kDefaultWallpapers);
const int kInvalidWallpaperIndex = -1;
const int kSolidColorIndex = -2;

// TODO(saintlou): These hardcoded indexes, although checked against the size
// of the array are really hacky.
#if defined(GOOGLE_CHROME_BUILD)
const int kDefaultWallpaperIndex = 20; // IDR_AURA_WALLPAPERS_2_LANDSCAPE8
const int kLastRandomWallpaperIndex = 19; // The first 20 are random.
const int kGuestWallpaperIndex = 15; // IDR_AURA_WALLPAPERS_2_LANDSCAPE7
#else
// Set default wallpaper to the grey background for faster wallpaper loading
// time in browser tests. Otherwise, some of the tests will finish before
// wallpaper loaded and cause crashes.
const int kDefaultWallpaperIndex = 5;  // IDR_AURA_WALLPAPERS_5_GRADIENT5
const int kLastRandomWallpaperIndex = 8;
const int kGuestWallpaperIndex = kDefaultWallpaperIndex;
#endif

}  // namespace

namespace ash {

int GetDefaultWallpaperIndex() {
  DCHECK(kDefaultWallpaperIndex < kDefaultWallpaperCount);
  return std::min(kDefaultWallpaperIndex, kDefaultWallpaperCount - 1);
}

int GetGuestWallpaperIndex() {
  DCHECK(kGuestWallpaperIndex < kDefaultWallpaperCount);
  return std::min(kGuestWallpaperIndex, kDefaultWallpaperCount - 1);
}

int GetInvalidWallpaperIndex() {
  return kInvalidWallpaperIndex;
}

WallpaperLayout GetLayoutEnum(const std::string& layout) {
  for (int i = 0; i < kWallpaperLayoutCount; i++) {
    if (layout.compare(kWallpaperLayoutArrays[i]) == 0)
      return static_cast<WallpaperLayout>(i);
  }
  // Default to use CENTER layout.
  return CENTER;
}

int GetNextWallpaperIndex(int index) {
  DCHECK(kLastRandomWallpaperIndex < kDefaultWallpaperCount);
  return (index + 1) % (kLastRandomWallpaperIndex + 1);
}

int GetSolidColorIndex() {
  return kSolidColorIndex;
}

int GetWallpaperCount() {
  return kDefaultWallpaperCount;
}

const WallpaperInfo& GetWallpaperInfo(int index) {
  DCHECK(index >= 0 && index < kDefaultWallpaperCount);
  return kDefaultWallpapers[index];
}

const WallpaperViewInfo& GetWallpaperViewInfo(int index,
                                              WallpaperResolution resolution) {
  if (resolution == SMALL)
    return kDefaultWallpapers[index].small_wallpaper;
  else
    return kDefaultWallpapers[index].large_wallpaper;
}

}  // namespace ash
<|endoftext|>


<commit_before>#ifndef slic3r_SearchComboBox_hpp_
#define slic3r_SearchComboBox_hpp_

#include <vector>
#include <map>

#include <wx/panel.h>
#include <wx/sizer.h>
#include <wx/listctrl.h>

#include <wx/combo.h>

#include <wx/checkbox.h>
#include <wx/dialog.h>

#include "GUI_Utils.hpp"
#include "Preset.hpp"
#include "wxExtensions.hpp"

namespace Slic3r {

namespace Search{

class SearchDialog;

struct InputInfo
{
    DynamicPrintConfig* config  {nullptr};
    Preset::Type        type    {Preset::TYPE_INVALID};
    ConfigOptionMode    mode    {comSimple};
};

struct GroupAndCategory {
    wxString        group;
    wxString        category;
};

struct Option {
    bool operator<(const Option& other) const { return other.label > this->label; }
    bool operator>(const Option& other) const { return other.label < this->label; }

    // Fuzzy matching works at a character level. Thus matching with wide characters is a safer bet than with short characters,
    // though for some languages (Chinese?) it may not work correctly.
    std::wstring    opt_key;
    Preset::Type    type {Preset::TYPE_INVALID};
    std::wstring    label;
    std::wstring    label_local;
    std::wstring    group;
    std::wstring    group_local;
    std::wstring    category;
    std::wstring    category_local;
};

struct FoundOption {
	// UTF8 encoding, to be consumed by ImGUI by reference.
    std::string     label;
    std::string     marked_label;
    std::string     tooltip;
    size_t          option_idx {0};
    int             outScore {0};

    // Returning pointers to contents of std::string members, to be used by ImGUI for rendering.
    void get_marked_label_and_tooltip(const char** label, const char** tooltip) const;
};

struct OptionViewParameters
{
    bool category   {false};
    bool english    {false};

    int  hovered_id {0};
};

class OptionsSearcher
{
    std::string                             search_line;
    std::map<std::string, GroupAndCategory> groups_and_categories;
    PrinterTechnology                       printer_technology;

    std::vector<Option>                     options {};
    std::vector<FoundOption>                found {};

    void append_options(DynamicPrintConfig* config, Preset::Type type, ConfigOptionMode mode);

    void sort_options() {
        std::sort(options.begin(), options.end(), [](const Option& o1, const Option& o2) {
            return o1.label < o2.label; });
    }
    void sort_found() {
        std::sort(found.begin(), found.end(), [](const FoundOption& f1, const FoundOption& f2) {
            return f1.outScore > f2.outScore || (f1.outScore == f2.outScore && f1.label < f2.label); });
    };

    size_t options_size() const { return options.size(); }
    size_t found_size()   const { return found.size(); }

public:
    OptionViewParameters                    view_params;

    SearchDialog*                           search_dialog { nullptr };

    OptionsSearcher();
    ~OptionsSearcher();

    void init(std::vector<InputInfo> input_values);
    void apply(DynamicPrintConfig *config,
               Preset::Type        type,
               ConfigOptionMode    mode);
    bool search();
    bool search(const std::string& search, bool force = false);

    void add_key(const std::string& opt_key, const wxString& group, const wxString& category);

    size_t size() const         { return found_size(); }

    const FoundOption& operator[](const size_t pos) const noexcept { return found[pos]; }
    const Option& get_option(size_t pos_in_filter) const;

    const std::vector<FoundOption>& found_options() { return found; }
    const GroupAndCategory&         get_group_and_category (const std::string& opt_key) { return groups_and_categories[opt_key]; }
    std::string& search_string() { return search_line; }

    void set_printer_technology(PrinterTechnology pt) { printer_technology = pt; }
};

class SearchComboPopup : public wxListBox, public wxComboPopup
{
public:
    // Initialize member variables
    void Init();

    // Create popup control
    virtual bool Create(wxWindow* parent);
    // Return pointer to the created control
    virtual wxWindow* GetControl() { return this; }

    // Translate string into a list selection
    virtual void SetStringValue(const wxString& s);
    // Get list selection as a string
    virtual wxString GetStringValue() const {
        // we shouldn't change a combo control's string
        return m_input_string;
    }

    void ProcessSelection(int selection);

    // Do mouse hot-tracking (which is typical in list popups)
    void OnMouseMove(wxMouseEvent& event);
    // On mouse left up, set the value and close the popup
    void OnMouseClick(wxMouseEvent& WXUNUSED(event));
    // process Up/Down arrows and Enter press
    void OnKeyDown(wxKeyEvent& event);

protected:
    wxString m_input_string;
};

//------------------------------------------
//          SearchDialog
//------------------------------------------
class SearchListModel;
class SearchDialog : public GUI::DPIDialog
{
    wxString search_str;
    wxString default_string;

    bool     prevent_list_events {false};

    wxTextCtrl*         search_line         { nullptr };
    wxDataViewCtrl*     search_list         { nullptr };
    SearchListModel*    search_list_model   { nullptr };
    wxCheckBox*         check_category      { nullptr };
    wxCheckBox*         check_english       { nullptr };

    OptionsSearcher*    searcher            { nullptr };

    void OnInputText(wxCommandEvent& event);
    void OnLeftUpInTextCtrl(wxEvent& event);
    void OnKeyDown(wxKeyEvent& event);

    void OnActivate(wxDataViewEvent& event);
    void OnSelect(wxDataViewEvent& event);

    void OnCheck(wxCommandEvent& event);
    void OnMotion(wxMouseEvent& event);
    void OnLeftDown(wxMouseEvent& event);

    void update_list();

public:
    SearchDialog(OptionsSearcher* searcher);
    ~SearchDialog() {}

    void Popup(wxPoint position = wxDefaultPosition);
    void ProcessSelection(wxDataViewItem selection);

protected:
    void on_dpi_changed(const wxRect& suggested_rect) override;
    virtual void on_sys_color_changed() override;
};

// ----------------------------------------------------------------------------
// SearchListModel
// ----------------------------------------------------------------------------

class SearchListModel : public wxDataViewVirtualListModel
{
    std::vector<std::pair<wxString, int>>   m_values;
    ScalableBitmap                          m_icon[5];

public:
    enum {
        colIcon,
        colMarkedText,
        colMax
    };

    SearchListModel(wxWindow* parent);

    // helper methods to change the model

    void Clear();
    void Prepend(const std::string& text);
    void msw_rescale();

    // implementation of base class virtuals to define model

    virtual unsigned int GetColumnCount() const wxOVERRIDE { return colMax; }
    virtual wxString GetColumnType(unsigned int col) const wxOVERRIDE;
    virtual void GetValueByRow(wxVariant& variant, unsigned int row, unsigned int col) const wxOVERRIDE;
    virtual bool GetAttrByRow(unsigned int row, unsigned int col, wxDataViewItemAttr& attr) const wxOVERRIDE { return true; }
    virtual bool SetValueByRow(const wxVariant& variant, unsigned int row, unsigned int col) wxOVERRIDE { return false; }
};

} // Search namespace
}

#endif //slic3r_SearchComboBox_hpp_
<commit_msg>Fix of #4282 (wxOVERRIDE macro not available in wxWidgets 3.0) Now that we use C++17, there is no point in using it in PrusaSlicer codebase<commit_after>#ifndef slic3r_SearchComboBox_hpp_
#define slic3r_SearchComboBox_hpp_

#include <vector>
#include <map>

#include <wx/panel.h>
#include <wx/sizer.h>
#include <wx/listctrl.h>

#include <wx/combo.h>

#include <wx/checkbox.h>
#include <wx/dialog.h>

#include "GUI_Utils.hpp"
#include "Preset.hpp"
#include "wxExtensions.hpp"

namespace Slic3r {

namespace Search{

class SearchDialog;

struct InputInfo
{
    DynamicPrintConfig* config  {nullptr};
    Preset::Type        type    {Preset::TYPE_INVALID};
    ConfigOptionMode    mode    {comSimple};
};

struct GroupAndCategory {
    wxString        group;
    wxString        category;
};

struct Option {
    bool operator<(const Option& other) const { return other.label > this->label; }
    bool operator>(const Option& other) const { return other.label < this->label; }

    // Fuzzy matching works at a character level. Thus matching with wide characters is a safer bet than with short characters,
    // though for some languages (Chinese?) it may not work correctly.
    std::wstring    opt_key;
    Preset::Type    type {Preset::TYPE_INVALID};
    std::wstring    label;
    std::wstring    label_local;
    std::wstring    group;
    std::wstring    group_local;
    std::wstring    category;
    std::wstring    category_local;
};

struct FoundOption {
	// UTF8 encoding, to be consumed by ImGUI by reference.
    std::string     label;
    std::string     marked_label;
    std::string     tooltip;
    size_t          option_idx {0};
    int             outScore {0};

    // Returning pointers to contents of std::string members, to be used by ImGUI for rendering.
    void get_marked_label_and_tooltip(const char** label, const char** tooltip) const;
};

struct OptionViewParameters
{
    bool category   {false};
    bool english    {false};

    int  hovered_id {0};
};

class OptionsSearcher
{
    std::string                             search_line;
    std::map<std::string, GroupAndCategory> groups_and_categories;
    PrinterTechnology                       printer_technology;

    std::vector<Option>                     options {};
    std::vector<FoundOption>                found {};

    void append_options(DynamicPrintConfig* config, Preset::Type type, ConfigOptionMode mode);

    void sort_options() {
        std::sort(options.begin(), options.end(), [](const Option& o1, const Option& o2) {
            return o1.label < o2.label; });
    }
    void sort_found() {
        std::sort(found.begin(), found.end(), [](const FoundOption& f1, const FoundOption& f2) {
            return f1.outScore > f2.outScore || (f1.outScore == f2.outScore && f1.label < f2.label); });
    };

    size_t options_size() const { return options.size(); }
    size_t found_size()   const { return found.size(); }

public:
    OptionViewParameters                    view_params;

    SearchDialog*                           search_dialog { nullptr };

    OptionsSearcher();
    ~OptionsSearcher();

    void init(std::vector<InputInfo> input_values);
    void apply(DynamicPrintConfig *config,
               Preset::Type        type,
               ConfigOptionMode    mode);
    bool search();
    bool search(const std::string& search, bool force = false);

    void add_key(const std::string& opt_key, const wxString& group, const wxString& category);

    size_t size() const         { return found_size(); }

    const FoundOption& operator[](const size_t pos) const noexcept { return found[pos]; }
    const Option& get_option(size_t pos_in_filter) const;

    const std::vector<FoundOption>& found_options() { return found; }
    const GroupAndCategory&         get_group_and_category (const std::string& opt_key) { return groups_and_categories[opt_key]; }
    std::string& search_string() { return search_line; }

    void set_printer_technology(PrinterTechnology pt) { printer_technology = pt; }
};

class SearchComboPopup : public wxListBox, public wxComboPopup
{
public:
    // Initialize member variables
    void Init();

    // Create popup control
    virtual bool Create(wxWindow* parent);
    // Return pointer to the created control
    virtual wxWindow* GetControl() { return this; }

    // Translate string into a list selection
    virtual void SetStringValue(const wxString& s);
    // Get list selection as a string
    virtual wxString GetStringValue() const {
        // we shouldn't change a combo control's string
        return m_input_string;
    }

    void ProcessSelection(int selection);

    // Do mouse hot-tracking (which is typical in list popups)
    void OnMouseMove(wxMouseEvent& event);
    // On mouse left up, set the value and close the popup
    void OnMouseClick(wxMouseEvent& WXUNUSED(event));
    // process Up/Down arrows and Enter press
    void OnKeyDown(wxKeyEvent& event);

protected:
    wxString m_input_string;
};

//------------------------------------------
//          SearchDialog
//------------------------------------------
class SearchListModel;
class SearchDialog : public GUI::DPIDialog
{
    wxString search_str;
    wxString default_string;

    bool     prevent_list_events {false};

    wxTextCtrl*         search_line         { nullptr };
    wxDataViewCtrl*     search_list         { nullptr };
    SearchListModel*    search_list_model   { nullptr };
    wxCheckBox*         check_category      { nullptr };
    wxCheckBox*         check_english       { nullptr };

    OptionsSearcher*    searcher            { nullptr };

    void OnInputText(wxCommandEvent& event);
    void OnLeftUpInTextCtrl(wxEvent& event);
    void OnKeyDown(wxKeyEvent& event);

    void OnActivate(wxDataViewEvent& event);
    void OnSelect(wxDataViewEvent& event);

    void OnCheck(wxCommandEvent& event);
    void OnMotion(wxMouseEvent& event);
    void OnLeftDown(wxMouseEvent& event);

    void update_list();

public:
    SearchDialog(OptionsSearcher* searcher);
    ~SearchDialog() {}

    void Popup(wxPoint position = wxDefaultPosition);
    void ProcessSelection(wxDataViewItem selection);

protected:
    void on_dpi_changed(const wxRect& suggested_rect) override;
    virtual void on_sys_color_changed() override;
};

// ----------------------------------------------------------------------------
// SearchListModel
// ----------------------------------------------------------------------------

class SearchListModel : public wxDataViewVirtualListModel
{
    std::vector<std::pair<wxString, int>>   m_values;
    ScalableBitmap                          m_icon[5];

public:
    enum {
        colIcon,
        colMarkedText,
        colMax
    };

    SearchListModel(wxWindow* parent);

    // helper methods to change the model

    void Clear();
    void Prepend(const std::string& text);
    void msw_rescale();

    // implementation of base class virtuals to define model

    virtual unsigned int GetColumnCount() const override { return colMax; }
    virtual wxString GetColumnType(unsigned int col) const override;
    virtual void GetValueByRow(wxVariant& variant, unsigned int row, unsigned int col) const override;
    virtual bool GetAttrByRow(unsigned int row, unsigned int col, wxDataViewItemAttr& attr) const override { return true; }
    virtual bool SetValueByRow(const wxVariant& variant, unsigned int row, unsigned int col) override { return false; }
};

} // Search namespace
}

#endif //slic3r_SearchComboBox_hpp_
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 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
 *
 *****************************************************************************/

// boost
#include <boost/python.hpp>
#include <boost/make_shared.hpp>

// mapnik
#include <mapnik/params.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/value.hpp>

using mapnik::parameter;
using mapnik::parameters;

struct parameter_pickle_suite : boost::python::pickle_suite
{
    static boost::python::tuple
    getinitargs(const parameter& p)
    {
        using namespace boost::python;
        return boost::python::make_tuple(p.first,p.second);
    }
};

struct parameters_pickle_suite : boost::python::pickle_suite
{
    static boost::python::tuple
    getstate(const parameters& p)
    {
        using namespace boost::python;
        dict d;
        parameters::const_iterator pos=p.begin();
        while(pos!=p.end())
        {
            d[pos->first] = pos->second;
            ++pos;
        }
        return boost::python::make_tuple(d);
    }

    static void setstate(parameters& p, boost::python::tuple state)
    {
        using namespace boost::python;
        if (len(state) != 1)
        {
            PyErr_SetObject(PyExc_ValueError,
                            ("expected 1-item tuple in call to __setstate__; got %s"
                             % state).ptr()
                );
            throw_error_already_set();
        }

        dict d = extract<dict>(state[0]);
        boost::python::list keys = d.keys();
        for (int i=0; i<len(keys); ++i)
        {
            std::string key = extract<std::string>(keys[i]);
            object obj = d[key];
            extract<std::string> ex0(obj);
            extract<int> ex1(obj);
            extract<double> ex2(obj);
            extract<UnicodeString> ex3(obj);

            // TODO - this is never hit - we need proper python string -> std::string to get invoked here
            if (ex0.check())
            {
                p[key] = ex0();
            }
            else if (ex1.check())
            {
                p[key] = ex1();
            }
            else if (ex2.check())
            {
                p[key] = ex2();
            }
            else if (ex3.check())
            {
                std::string buffer;
                mapnik::to_utf8(ex3(),buffer);
                p[key] = buffer;
            }
            else
            {
                std::clog <<  "could not unpickle key: " << key << "\n";
            }
        }
    }
};

mapnik::value_holder get_params_by_key1(mapnik::parameters const& p, std::string const& key)
{
    parameters::const_iterator pos = p.find(key);
    if (pos != p.end())
    {
        // will be auto-converted to proper python type by `mapnik_params_to_python`
        return pos->second;
    }
    return mapnik::value_null();
}

mapnik::value_holder get_params_by_key2(mapnik::parameters const& p, std::string const& key)
{
    parameters::const_iterator pos = p.find(key);
    if (pos == p.end())
    {
        PyErr_SetString(PyExc_KeyError, key.c_str());
        boost::python::throw_error_already_set();
    }
    // will be auto-converted to proper python type by `mapnik_params_to_python`
    return pos->second;
}

mapnik::parameter get_params_by_index(mapnik::parameters const& p, int index)
{
    if (index < 0 || static_cast<unsigned>(index) > p.size())
    {
        PyErr_SetString(PyExc_IndexError, "Index is out of range");
        throw boost::python::error_already_set();
    }

    parameters::const_iterator itr = p.begin();
    parameters::const_iterator end = p.end();

    unsigned idx = 0;
    while (itr != end)
    {
        if (idx == index)
        {
            return *itr;
        }
        ++idx;
        ++itr;
    }
    PyErr_SetString(PyExc_IndexError, "Index is out of range");
    throw boost::python::error_already_set();
}

void add_parameter(mapnik::parameters & p, mapnik::parameter const& param)
{
    p[param.first] = param.second;
}

mapnik::value_holder get_param(mapnik::parameter const& p, int index)
{
    if (index == 0)
    {
        return p.first;
    }
    else if (index == 1)
    {
        return p.second;
    }
    else
    {
        PyErr_SetString(PyExc_IndexError, "Index is out of range");
        throw boost::python::error_already_set();
    }
}

boost::shared_ptr<mapnik::parameter> create_parameter_from_string(std::string const& key, std::string const& value)
{
    return boost::make_shared<mapnik::parameter>(key,mapnik::value_holder(value));
}

boost::shared_ptr<mapnik::parameter> create_parameter_from_int(std::string const& key, int value)
{
    return boost::make_shared<mapnik::parameter>(key,mapnik::value_holder(value));
}

boost::shared_ptr<mapnik::parameter> create_parameter_from_float(std::string const& key, double value)
{
    return boost::make_shared<mapnik::parameter>(key,mapnik::value_holder(value));
}

void export_parameters()
{
    using namespace boost::python;
    class_<parameter,boost::shared_ptr<parameter> >("Parameter",no_init)
        .def("__init__", make_constructor(create_parameter_from_string),
             "Create a mapnik.Parameter from a pair of values, the first being a string\n"
             "and the second being either a string, and integer, or a float")
        .def("__init__", make_constructor(create_parameter_from_int),
             "Create a mapnik.Parameter from a pair of values, the first being a string\n"
             "and the second being either a string, and integer, or a float")
        .def("__init__", make_constructor(create_parameter_from_float),
             "Create a mapnik.Parameter from a pair of values, the first being a string\n"
             "and the second being either a string, and integer, or a float")
        .def_pickle(parameter_pickle_suite())
        .def("__getitem__",get_param)
        ;

    class_<parameters>("Parameters",init<>())
        .def_pickle(parameters_pickle_suite())
        .def("get",get_params_by_key1)
        .def("__getitem__",get_params_by_key2)
        .def("__getitem__",get_params_by_index)
        .def("__len__",&parameters::size)
        .def("append",add_parameter)
        .def("iteritems",iterator<parameters>())
        ;
}
<commit_msg>avoid compiler warning<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 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
 *
 *****************************************************************************/

// boost
#include <boost/python.hpp>
#include <boost/make_shared.hpp>

// mapnik
#include <mapnik/params.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/value.hpp>

using mapnik::parameter;
using mapnik::parameters;

struct parameter_pickle_suite : boost::python::pickle_suite
{
    static boost::python::tuple
    getinitargs(const parameter& p)
    {
        using namespace boost::python;
        return boost::python::make_tuple(p.first,p.second);
    }
};

struct parameters_pickle_suite : boost::python::pickle_suite
{
    static boost::python::tuple
    getstate(const parameters& p)
    {
        using namespace boost::python;
        dict d;
        parameters::const_iterator pos=p.begin();
        while(pos!=p.end())
        {
            d[pos->first] = pos->second;
            ++pos;
        }
        return boost::python::make_tuple(d);
    }

    static void setstate(parameters& p, boost::python::tuple state)
    {
        using namespace boost::python;
        if (len(state) != 1)
        {
            PyErr_SetObject(PyExc_ValueError,
                            ("expected 1-item tuple in call to __setstate__; got %s"
                             % state).ptr()
                );
            throw_error_already_set();
        }

        dict d = extract<dict>(state[0]);
        boost::python::list keys = d.keys();
        for (int i=0; i<len(keys); ++i)
        {
            std::string key = extract<std::string>(keys[i]);
            object obj = d[key];
            extract<std::string> ex0(obj);
            extract<int> ex1(obj);
            extract<double> ex2(obj);
            extract<UnicodeString> ex3(obj);

            // TODO - this is never hit - we need proper python string -> std::string to get invoked here
            if (ex0.check())
            {
                p[key] = ex0();
            }
            else if (ex1.check())
            {
                p[key] = ex1();
            }
            else if (ex2.check())
            {
                p[key] = ex2();
            }
            else if (ex3.check())
            {
                std::string buffer;
                mapnik::to_utf8(ex3(),buffer);
                p[key] = buffer;
            }
            else
            {
                std::clog <<  "could not unpickle key: " << key << "\n";
            }
        }
    }
};

mapnik::value_holder get_params_by_key1(mapnik::parameters const& p, std::string const& key)
{
    parameters::const_iterator pos = p.find(key);
    if (pos != p.end())
    {
        // will be auto-converted to proper python type by `mapnik_params_to_python`
        return pos->second;
    }
    return mapnik::value_null();
}

mapnik::value_holder get_params_by_key2(mapnik::parameters const& p, std::string const& key)
{
    parameters::const_iterator pos = p.find(key);
    if (pos == p.end())
    {
        PyErr_SetString(PyExc_KeyError, key.c_str());
        boost::python::throw_error_already_set();
    }
    // will be auto-converted to proper python type by `mapnik_params_to_python`
    return pos->second;
}

mapnik::parameter get_params_by_index(mapnik::parameters const& p, int index)
{
    if (index < 0 || static_cast<unsigned>(index) > p.size())
    {
        PyErr_SetString(PyExc_IndexError, "Index is out of range");
        throw boost::python::error_already_set();
    }

    parameters::const_iterator itr = p.begin();
    parameters::const_iterator end = p.end();

    int idx = 0;
    while (itr != end)
    {
        if (idx == index)
        {
            return *itr;
        }
        ++idx;
        ++itr;
    }
    PyErr_SetString(PyExc_IndexError, "Index is out of range");
    throw boost::python::error_already_set();
}

void add_parameter(mapnik::parameters & p, mapnik::parameter const& param)
{
    p[param.first] = param.second;
}

mapnik::value_holder get_param(mapnik::parameter const& p, int index)
{
    if (index == 0)
    {
        return p.first;
    }
    else if (index == 1)
    {
        return p.second;
    }
    else
    {
        PyErr_SetString(PyExc_IndexError, "Index is out of range");
        throw boost::python::error_already_set();
    }
}

boost::shared_ptr<mapnik::parameter> create_parameter_from_string(std::string const& key, std::string const& value)
{
    return boost::make_shared<mapnik::parameter>(key,mapnik::value_holder(value));
}

boost::shared_ptr<mapnik::parameter> create_parameter_from_int(std::string const& key, int value)
{
    return boost::make_shared<mapnik::parameter>(key,mapnik::value_holder(value));
}

boost::shared_ptr<mapnik::parameter> create_parameter_from_float(std::string const& key, double value)
{
    return boost::make_shared<mapnik::parameter>(key,mapnik::value_holder(value));
}

void export_parameters()
{
    using namespace boost::python;
    class_<parameter,boost::shared_ptr<parameter> >("Parameter",no_init)
        .def("__init__", make_constructor(create_parameter_from_string),
             "Create a mapnik.Parameter from a pair of values, the first being a string\n"
             "and the second being either a string, and integer, or a float")
        .def("__init__", make_constructor(create_parameter_from_int),
             "Create a mapnik.Parameter from a pair of values, the first being a string\n"
             "and the second being either a string, and integer, or a float")
        .def("__init__", make_constructor(create_parameter_from_float),
             "Create a mapnik.Parameter from a pair of values, the first being a string\n"
             "and the second being either a string, and integer, or a float")
        .def_pickle(parameter_pickle_suite())
        .def("__getitem__",get_param)
        ;

    class_<parameters>("Parameters",init<>())
        .def_pickle(parameters_pickle_suite())
        .def("get",get_params_by_key1)
        .def("__getitem__",get_params_by_key2)
        .def("__getitem__",get_params_by_index)
        .def("__len__",&parameters::size)
        .def("append",add_parameter)
        .def("iteritems",iterator<parameters>())
        ;
}
<|endoftext|>


<commit_before>// Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "AutoPacketGraph.h"
#include "AutoPacketProfiler.h"
#include "demangle.h"
#include <fstream>

AutoPacketGraph::AutoPacketGraph()
{
}

bool AutoPacketGraph::ExportGV(const std::string& filename) const
{
  std::ofstream file(filename);
  if (!file && !file.good()) {
    return false;
  }

  file << "digraph AutoPacketGraph {\n";

  std::lock_guard<std::mutex> lk(m_lock);
  for (auto& itr : m_deliveryGraph) {
    const DeliveryEdge& edge = itr.first;
    // TODO: use counts and labels
//    size_t count = itr.second;

    // string format: "type" -> "AutoFilter" (or vice versa)
    std::stringstream ss;
    ss << "  \"";
    if (edge.input) {
      ss << autowiring::demangle(edge.type_info) << "\" -> \"" << autowiring::demangle(edge.descriptor.GetType());
    } else {
      ss << autowiring::demangle(edge.descriptor.GetType()) << "\" -> \"" << autowiring::demangle(edge.type_info);
    }
    ss << "\"" << std::endl;

    file << ss.str();
  }

  file << "}\n";

  return true;
}

void AutoPacketGraph::RecordDelivery(const std::type_info* ti, const AutoFilterDescriptor& descriptor, bool input) {
  DeliveryEdge edge { ti, descriptor, input };

  std::lock_guard<std::mutex> lk(m_lock);
  auto itr = m_deliveryGraph.find(edge);
  if (itr == m_deliveryGraph.end()) {
    m_deliveryGraph[edge] = 1;
  } else {
    itr->second++;
  }
}
<commit_msg>Adding the packet “count” to the graph<commit_after>// Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "AutoPacketGraph.h"
#include "AutoPacketProfiler.h"
#include "demangle.h"
#include <fstream>

AutoPacketGraph::AutoPacketGraph()
{
}

bool AutoPacketGraph::ExportGV(const std::string& filename) const
{
  std::ofstream file(filename);
  if (!file && !file.good()) {
    return false;
  }

  file << "digraph AutoPacketGraph {\n";

  std::lock_guard<std::mutex> lk(m_lock);
  for (auto& itr : m_deliveryGraph) {
    const DeliveryEdge& edge = itr.first;
    size_t count = itr.second;

    // string format: "type" -> "AutoFilter" (or vice versa)
    std::stringstream ss;
    ss << "  \"";
    if (edge.input) {
      ss << autowiring::demangle(edge.type_info) << "\" -> \"" << autowiring::demangle(edge.descriptor.GetType());
    } else {
      ss << autowiring::demangle(edge.descriptor.GetType()) << "\" -> \"" << autowiring::demangle(edge.type_info);
    }

    // TODO: count should probably be optional
    ss << "\" [label=\"" << count << "\"];" << std::endl;

    file << ss.str();
  }

  file << "}\n";

  return true;
}

void AutoPacketGraph::RecordDelivery(const std::type_info* ti, const AutoFilterDescriptor& descriptor, bool input) {
  DeliveryEdge edge { ti, descriptor, input };

  std::lock_guard<std::mutex> lk(m_lock);
  auto itr = m_deliveryGraph.find(edge);
  if (itr == m_deliveryGraph.end()) {
    m_deliveryGraph[edge] = 1;
  } else {
    itr->second++;
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2016-2017 gtalent2@gmail.com
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <QApplication>
#include <QDesktopWidget>
#include <QDialog>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMenuBar>
#include <QVector>
#include "lib/newwizard.hpp"
#include "lib/project.hpp"
#include "mainwindow.hpp"

namespace nostalgia {
namespace studio {

MainWindow::MainWindow(NostalgiaStudioProfile config, QWidget *parent) {
	auto screenSize = QApplication::desktop()->screenGeometry();

	// set window to 75% of screen width, and center NostalgiaStudioProfile
	auto sizePct = 0.75;
	resize(screenSize.width() * sizePct, screenSize.height() * sizePct);
	move(-x(), -y());
	move(screenSize.width() * (1 - sizePct) / 2, screenSize.height() * (1 - sizePct) / 2);

	setWindowTitle(config.app_name);

	setupMenu();
}

MainWindow::~MainWindow() {
	for (auto f : m_cleanupTasks) {
		f();
	}
}

void MainWindow::setupMenu() {
	auto menu = menuBar();
	auto fileMenu = menu->addMenu(tr("&File"));

	// New...
	addAction(
		fileMenu,
		tr("&New..."),
		tr(""),
		QKeySequence::New,
		this,
		SLOT(showNewWizard())
	);

	// Exit
	addAction(
		fileMenu,
		tr("E&xit"),
		tr("Exit the application"),
		QKeySequence::Quit,
		QApplication::quit
	);
}

void MainWindow::addAction(QMenu *menu, QString text, QString toolTip,
                           QKeySequence::StandardKey key, const QObject *tgt, const char *cb) {
	auto action = menu->addAction(text);
	action->setShortcuts(key);
	action->setStatusTip(toolTip);
	auto conn = connect(action, SIGNAL(triggered()), tgt, cb);
	m_cleanupTasks.push_back([this, conn]() {
		QObject::disconnect(conn);
	});
}

void MainWindow::addAction(QMenu *menu, QString text, QString toolTip,
                           QKeySequence::StandardKey key, void (*cb)()) {
	auto action = menu->addAction(text);
	action->setShortcuts(key);
	action->setStatusTip(toolTip);
	auto conn = connect(action, &QAction::triggered, cb);
	m_cleanupTasks.push_back([this, conn]() {
		QObject::disconnect(conn);
	});
}

void MainWindow::showNewWizard() {
	const QString PROJECT_NAME = "projectName";
	const QString PROJECT_PATH = "projectPath";
	Wizard wizard;
	auto ws = new WizardSelect();
	wizard.addPage(ws);
	ws->addOption(tr("Project"),
			[&wizard, PROJECT_NAME, PROJECT_PATH]() {
			QVector<QWizardPage*> pgs;
			auto pg = new WizardFormPage();
			pg->addLineEdit(tr("Project &Name:"), PROJECT_NAME + "*", "", [PROJECT_PATH, pg, &wizard](QString projectName) {
					auto projectPath = wizard.field(PROJECT_PATH).toString();
					auto path = projectPath + "/" + projectName;
					if (!QDir(path).exists()) {
						return 0;
					} else {
						pg->showValidationError(tr("This project directory already exists."));
						return 1;
					}
				}
			);
			pg->addDirBrowse(tr("Project &Path:"), PROJECT_PATH + "*");
			pgs.push_back(pg);
			pgs.push_back(new WizardConclusionPage(tr("Creating project: %1/%2"), {PROJECT_PATH, PROJECT_NAME}));

			return pgs;
		}
	);
	wizard.setAccept([&wizard, ws, PROJECT_NAME, PROJECT_PATH]() {
			auto projectName = wizard.field(PROJECT_NAME).toString();
			auto projectPath = wizard.field(PROJECT_PATH).toString();
			if (QDir(projectPath).exists()) {
				auto path = projectPath + "/" + projectName;
				if (!QDir(path).exists()) {
					Project(path).create();
				}
			}
		}
	);
	wizard.show();
	wizard.exec();
}

}
}
<commit_msg>Fix a non-constant tr("...")<commit_after>/*
 * Copyright 2016-2017 gtalent2@gmail.com
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <QApplication>
#include <QDesktopWidget>
#include <QDialog>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMenuBar>
#include <QVector>
#include "lib/newwizard.hpp"
#include "lib/project.hpp"
#include "mainwindow.hpp"

namespace nostalgia {
namespace studio {

MainWindow::MainWindow(NostalgiaStudioProfile config, QWidget *parent) {
	auto screenSize = QApplication::desktop()->screenGeometry();

	// set window to 75% of screen width, and center NostalgiaStudioProfile
	auto sizePct = 0.75;
	resize(screenSize.width() * sizePct, screenSize.height() * sizePct);
	move(-x(), -y());
	move(screenSize.width() * (1 - sizePct) / 2, screenSize.height() * (1 - sizePct) / 2);

	setWindowTitle(config.app_name);

	setupMenu();
}

MainWindow::~MainWindow() {
	for (auto f : m_cleanupTasks) {
		f();
	}
}

void MainWindow::setupMenu() {
	auto menu = menuBar();
	auto fileMenu = menu->addMenu(tr("&File"));

	// New...
	addAction(
		fileMenu,
		tr("&New..."),
		tr(""),
		QKeySequence::New,
		this,
		SLOT(showNewWizard())
	);

	// Exit
	addAction(
		fileMenu,
		tr("E&xit"),
		tr("Exit the application"),
		QKeySequence::Quit,
		QApplication::quit
	);
}

void MainWindow::addAction(QMenu *menu, QString text, QString toolTip,
                           QKeySequence::StandardKey key, const QObject *tgt, const char *cb) {
	auto action = menu->addAction(text);
	action->setShortcuts(key);
	action->setStatusTip(toolTip);
	auto conn = connect(action, SIGNAL(triggered()), tgt, cb);
	m_cleanupTasks.push_back([this, conn]() {
		QObject::disconnect(conn);
	});
}

void MainWindow::addAction(QMenu *menu, QString text, QString toolTip,
                           QKeySequence::StandardKey key, void (*cb)()) {
	auto action = menu->addAction(text);
	action->setShortcuts(key);
	action->setStatusTip(toolTip);
	auto conn = connect(action, &QAction::triggered, cb);
	m_cleanupTasks.push_back([this, conn]() {
		QObject::disconnect(conn);
	});
}

void MainWindow::showNewWizard() {
	const QString PROJECT_NAME = "projectName";
	const QString PROJECT_PATH = "projectPath";
	Wizard wizard;
	auto ws = new WizardSelect();
	wizard.addPage(ws);
	ws->addOption(tr("Project"),
			[&wizard, PROJECT_NAME, PROJECT_PATH]() {
			QVector<QWizardPage*> pgs;
			auto pg = new WizardFormPage();
			pg->addLineEdit(tr("Project &Name:"), PROJECT_NAME + "*", "", [PROJECT_PATH, pg, &wizard](QString projectName) {
					auto projectPath = wizard.field(PROJECT_PATH).toString();
					auto path = projectPath + "/" + projectName;
					if (!QDir(path).exists()) {
						return 0;
					} else {
						pg->showValidationError(tr("This project directory already exists."));
						return 1;
					}
				}
			);
			pg->addDirBrowse(tr("Project &Path:"), PROJECT_PATH + "*");
			pgs.push_back(pg);
			pgs.push_back(new WizardConclusionPage(tr("Creating project: ") + "%1/%2", {PROJECT_PATH, PROJECT_NAME}));

			return pgs;
		}
	);
	wizard.setAccept([&wizard, ws, PROJECT_NAME, PROJECT_PATH]() {
			auto projectName = wizard.field(PROJECT_NAME).toString();
			auto projectPath = wizard.field(PROJECT_PATH).toString();
			if (QDir(projectPath).exists()) {
				auto path = projectPath + "/" + projectName;
				if (!QDir(path).exists()) {
					Project(path).create();
				}
			}
		}
	);
	wizard.show();
	wizard.exec();
}

}
}
<|endoftext|>