<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program 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 program 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 program. If not, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include <sofa/helper/logging/Messaging.h>
#include <sofa/helper/io/ImagePNG.h>
#include <sofa/helper/system/FileRepository.h>
#include <iostream>

#ifdef SOFA_HAVE_PNG
#include <png.h>
#ifdef _MSC_VER
#pragma comment(lib,"libpng.lib")
#pragma comment(lib,"zlib.lib")
#endif
#endif

#if PNG_LIBPNG_VER >= 10209
#define RECENT_LIBPNG
#endif

namespace sofa
{

namespace helper
{

namespace io
{

//using namespace sofa::defaulttype;

SOFA_DECL_CLASS(ImagePNG)

#ifdef SOFA_HAVE_PNG

// Set the compression level. The valid values for "COMPRESSION_LEVEL" range from [0,9]
// The value 0 implies no compression and 9 implies maximal compression
// The value -1 implies default compression (level 6)

Creator<Image::FactoryImage,ImagePNG> ImagePNGClass("png");

// we have to give our own reading function to libpng in order to use the "fread" function belonging to Sofa
// and not the one belonging to libpng since Sofa do the "fopen" on the FILE struct
void png_my_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
   png_size_t check;

   if (png_ptr == NULL)
      return;

   /* fread() returns 0 on error, so it is OK to store this in a png_size_t
    * instead of an int, which is what fread() actually returns.
    */
   check = fread(data, 1, length, (png_FILE_p)png_get_io_ptr(png_ptr));

   if (check != length)
      png_error(png_ptr, "Read Error");
}

bool ImagePNG::load(std::string filename)
{
    m_bLoaded = 0;

    if (!sofa::helper::system::DataRepository.findFile(filename))
    {
        msg_error("ImagePNG") << "File '" << filename << "' not found ";
        return false;
    }
    FILE *file;
    /* make sure the file is there and open it read-only (binary) */
    if ((file = fopen(filename.c_str(), "rb")) == NULL)
    {
        msg_error("ImagePNG") << "File not found : '" << filename << "'";
        return false;
    }

    png_structp PNG_reader = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (PNG_reader == NULL)
    {
        msg_error("ImagePNG") << "png_create_read_struct failed for file '"<< filename << "'";
        fclose(file);
        return false;
    }

    png_infop PNG_info = png_create_info_struct(PNG_reader);
    if (PNG_info == NULL)
    {
        msg_error("ImagePNG") << "png_create_info_struct failed for file '" << filename << "'";
        png_destroy_read_struct(&PNG_reader, NULL, NULL);
        fclose(file);
        return false;
    }

    png_infop PNG_end_info = png_create_info_struct(PNG_reader);
    if (PNG_end_info == NULL)
    {
        msg_error("ImagePNG") << "png_create_info_struct failed for file '" << filename << "'";
        png_destroy_read_struct(&PNG_reader, &PNG_info, NULL);
        fclose(file);
        return false;
    }

    if (setjmp(png_jmpbuf(PNG_reader)))
    {
        msg_error("ImagePNG") << "Loading failed for PNG file '" << filename << "'";
        png_destroy_read_struct(&PNG_reader, &PNG_info, &PNG_end_info);
        fclose(file);
        return false;
    }

    //png_init_io(PNG_reader, file);
    png_set_read_fn(PNG_reader, file, png_my_read_data);

    png_read_info(PNG_reader, PNG_info);

    png_uint_32 width, height;
    width = png_get_image_width(PNG_reader, PNG_info);
    height = png_get_image_height(PNG_reader, PNG_info);

    png_uint_32 bit_depth, channels, color_type;
    bit_depth = png_get_bit_depth(PNG_reader, PNG_info);
    channels = png_get_channels(PNG_reader, PNG_info);
    color_type = png_get_color_type(PNG_reader, PNG_info);

#ifndef NDEBUG
    msg_info("ImagePNG") << " "<<filename<<": "<<width<<"x"<<height<<"x"<<bit_depth*channels;
#endif
    bool changed = false;
    if (color_type == PNG_COLOR_TYPE_PALETTE)
    {
        png_set_palette_to_rgb(PNG_reader);
        changed = true;
    }

    if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
    {
#ifdef RECENT_LIBPNG
        png_set_expand_gray_1_2_4_to_8(PNG_reader);
#else
        png_set_gray_1_2_4_to_8(PNG_reader);    // deprecated from libpng 1.2.9
#endif
        changed = true;
    }

    if (bit_depth == 16)
    {
        png_set_strip_16(PNG_reader);
        changed = true;
    }
    if (changed)
    {
        png_read_update_info(PNG_reader, PNG_info);
        bit_depth = png_get_bit_depth(PNG_reader, PNG_info);
        channels = png_get_channels(PNG_reader, PNG_info);
//        color_type = png_get_color_type(PNG_reader, PNG_info);

#ifndef NDEBUG
        msg_info("ImagePNG") << "Converted PNG image "<<filename<<": "<<width<<"x"<<height<<"x"<<bit_depth*channels;
#endif
    }

    Image::DataType dataType;
    Image::ChannelFormat channelFormat;
    switch (bit_depth)
    {
    case 8:
        dataType = Image::UNORM8;
        break;
    default:
        msg_error("ImagePNG") << "File '" << filename << "' has unsupported bit depth: " << bit_depth ;
        return false;
    }
    switch (channels)
    {
    case 1:
        channelFormat = Image::L;
        break;
    case 2:
        channelFormat = Image::LA;
        break;
    case 3:
        channelFormat = Image::RGB;
        break;
    case 4:
        channelFormat = Image::RGBA;
        break;
    default:
        msg_error("ImagePNG") << "in '" << filename << "', unsupported number of channels: " << channels ;
        return false;
    }

    init(width, height, 1, 1, dataType, channelFormat);
    png_byte** PNG_rows = (png_byte**)malloc(height * sizeof(png_byte*));

    unsigned char *data = getPixels();
    unsigned lineSize = getLineSize(0);
    for (png_uint_32 row = 0; row < height; ++row)
        PNG_rows[height - 1 - row] = data+row*lineSize;

    png_read_image(PNG_reader, PNG_rows);

    free(PNG_rows);

    png_read_end(PNG_reader, PNG_end_info);

    png_destroy_read_struct(&PNG_reader, &PNG_info, &PNG_end_info);
    fclose(file);
    m_bLoaded = 1;
    return true;
}

// we have to give our own writing function to libpng in order to use the "fwrite" function belonging to Sofa
// and not the one belonging to libpng since Sofa do the "fopen" on the FILE struct
void png_my_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
    png_size_t check;

    if (png_ptr == NULL)
        return;

    check = fwrite(data, 1, length, (png_FILE_p)png_get_io_ptr(png_ptr));

    if (check != length)
        png_error(png_ptr, "Write Error");
}

void png_default_flush(png_structp png_ptr)
{
    png_FILE_p io_ptr;

    if (png_ptr == NULL)
        return;

    io_ptr = (png_FILE_p)(png_get_io_ptr(png_ptr));
    fflush(io_ptr);
}

bool ImagePNG::save(std::string filename, int compression_level)
{

    FILE *file;
#ifndef NDEBUG
    std::cout << "Writing PNG file " << filename << std::endl;
#endif
    /* make sure the file is there and open it read-only (binary) */
    if ((file = fopen(filename.c_str(), "wb")) == NULL)
    {
        msg_error("ImagePNG") << "File write access failed to '" << filename << "'" ;
        return false;
    }

    png_structp PNG_writer = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (PNG_writer == NULL)
    {
        msg_error("ImagePNG") << "png_create_write_struct failed for file '"<< filename << "'";
        fclose(file);
        return false;
    }

    png_infop PNG_info = png_create_info_struct(PNG_writer);
    if (PNG_info == NULL)
    {
        msg_error("ImagePNG") << "png_create_info_struct failed for file '" << filename << "'";
        png_destroy_write_struct(&PNG_writer, NULL);
        fclose(file);
        return false;
    }

    if (setjmp(png_jmpbuf(PNG_writer)))
    {
        msg_error("ImagePNG") << "Writing failed for PNG file '" << filename << "'";
        png_destroy_write_struct(&PNG_writer, &PNG_info);
        fclose(file);
        return false;
    }

    //png_init_io(PNG_writer, file);
    png_set_write_fn(PNG_writer, file, png_my_write_data, png_default_flush);

    png_uint_32 width, height;
    png_uint_32 bit_depth, channels, color_type;

    width = getWidth();
    height = getHeight();

    bit_depth = getBytesPerChannel() * 8;
    channels = getChannelCount();
    if (channels == 1)
        color_type = PNG_COLOR_TYPE_GRAY;
    else if (channels == 2)
        color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
    else if (channels == 3)
        color_type = PNG_COLOR_TYPE_RGB;
    else
        color_type = PNG_COLOR_TYPE_RGB_ALPHA;

    if (bit_depth != 8)
    {
        msg_error("ImagePNG") << "Unsupported bitdepth "<< bit_depth <<" to write to PNG file '"<<filename<<"'";
        png_destroy_write_struct(&PNG_writer, &PNG_info);
        fclose(file);
        return false;
    }
#ifndef NDEBUG
    msg_info("ImagePNG") << "PNG image "<<filename<<": "<<width<<"x"<<height<<"x"<<bit_depth*channels;
#endif
    png_set_IHDR(PNG_writer, PNG_info, width, height,
            bit_depth, color_type, PNG_INTERLACE_NONE,
            PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
    /* set the zlib compression level */
    if (compression_level!=-1)
    {
        if (compression_level>=0 && compression_level<=9)
            png_set_compression_level(PNG_writer, compression_level);
        else
            msg_error("ImagePNG") << "Compression level must be a value between 0 and 9" ;
    }

    png_byte** PNG_rows = (png_byte**)malloc(height * sizeof(png_byte*));

    unsigned char *data = getPixels();
    unsigned lineSize = getLineSize(0);
    for (png_uint_32 row = 0; row < height; ++row)
        PNG_rows[height - 1 - row] = data+row*lineSize;

    png_set_rows(PNG_writer, PNG_info, PNG_rows);

    png_write_png(PNG_writer, PNG_info, PNG_TRANSFORM_IDENTITY, NULL);

    free(PNG_rows);

    png_destroy_write_struct(&PNG_writer, &PNG_info);
    fclose(file);
    return true;
}

#endif

} // namespace io

} // namespace helper

} // namespace sofa

<commit_msg>[ImagePNG] FIX: Library linking in debug configuration under MSVS<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program 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 program 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 program. If not, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#include <sofa/helper/logging/Messaging.h>
#include <sofa/helper/io/ImagePNG.h>
#include <sofa/helper/system/FileRepository.h>
#include <iostream>

#ifdef SOFA_HAVE_PNG
#include <png.h>
#ifdef _MSC_VER
#ifdef _DEBUG
#pragma comment(lib,"libpngd.lib")
#pragma comment(lib,"zlibd.lib")
#else
#pragma comment(lib,"libpng.lib")
#pragma comment(lib,"zlib.lib")
#endif
#endif
#endif

#if PNG_LIBPNG_VER >= 10209
#define RECENT_LIBPNG
#endif

namespace sofa
{

namespace helper
{

namespace io
{

//using namespace sofa::defaulttype;

SOFA_DECL_CLASS(ImagePNG)

#ifdef SOFA_HAVE_PNG

// Set the compression level. The valid values for "COMPRESSION_LEVEL" range from [0,9]
// The value 0 implies no compression and 9 implies maximal compression
// The value -1 implies default compression (level 6)

Creator<Image::FactoryImage,ImagePNG> ImagePNGClass("png");

// we have to give our own reading function to libpng in order to use the "fread" function belonging to Sofa
// and not the one belonging to libpng since Sofa do the "fopen" on the FILE struct
void png_my_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
   png_size_t check;

   if (png_ptr == NULL)
      return;

   /* fread() returns 0 on error, so it is OK to store this in a png_size_t
    * instead of an int, which is what fread() actually returns.
    */
   check = fread(data, 1, length, (png_FILE_p)png_get_io_ptr(png_ptr));

   if (check != length)
      png_error(png_ptr, "Read Error");
}

bool ImagePNG::load(std::string filename)
{
    m_bLoaded = 0;

    if (!sofa::helper::system::DataRepository.findFile(filename))
    {
        msg_error("ImagePNG") << "File '" << filename << "' not found ";
        return false;
    }
    FILE *file;
    /* make sure the file is there and open it read-only (binary) */
    if ((file = fopen(filename.c_str(), "rb")) == NULL)
    {
        msg_error("ImagePNG") << "File not found : '" << filename << "'";
        return false;
    }

    png_structp PNG_reader = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (PNG_reader == NULL)
    {
        msg_error("ImagePNG") << "png_create_read_struct failed for file '"<< filename << "'";
        fclose(file);
        return false;
    }

    png_infop PNG_info = png_create_info_struct(PNG_reader);
    if (PNG_info == NULL)
    {
        msg_error("ImagePNG") << "png_create_info_struct failed for file '" << filename << "'";
        png_destroy_read_struct(&PNG_reader, NULL, NULL);
        fclose(file);
        return false;
    }

    png_infop PNG_end_info = png_create_info_struct(PNG_reader);
    if (PNG_end_info == NULL)
    {
        msg_error("ImagePNG") << "png_create_info_struct failed for file '" << filename << "'";
        png_destroy_read_struct(&PNG_reader, &PNG_info, NULL);
        fclose(file);
        return false;
    }

    if (setjmp(png_jmpbuf(PNG_reader)))
    {
        msg_error("ImagePNG") << "Loading failed for PNG file '" << filename << "'";
        png_destroy_read_struct(&PNG_reader, &PNG_info, &PNG_end_info);
        fclose(file);
        return false;
    }

    //png_init_io(PNG_reader, file);
    png_set_read_fn(PNG_reader, file, png_my_read_data);

    png_read_info(PNG_reader, PNG_info);

    png_uint_32 width, height;
    width = png_get_image_width(PNG_reader, PNG_info);
    height = png_get_image_height(PNG_reader, PNG_info);

    png_uint_32 bit_depth, channels, color_type;
    bit_depth = png_get_bit_depth(PNG_reader, PNG_info);
    channels = png_get_channels(PNG_reader, PNG_info);
    color_type = png_get_color_type(PNG_reader, PNG_info);

#ifndef NDEBUG
    msg_info("ImagePNG") << " "<<filename<<": "<<width<<"x"<<height<<"x"<<bit_depth*channels;
#endif
    bool changed = false;
    if (color_type == PNG_COLOR_TYPE_PALETTE)
    {
        png_set_palette_to_rgb(PNG_reader);
        changed = true;
    }

    if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
    {
#ifdef RECENT_LIBPNG
        png_set_expand_gray_1_2_4_to_8(PNG_reader);
#else
        png_set_gray_1_2_4_to_8(PNG_reader);    // deprecated from libpng 1.2.9
#endif
        changed = true;
    }

    if (bit_depth == 16)
    {
        png_set_strip_16(PNG_reader);
        changed = true;
    }
    if (changed)
    {
        png_read_update_info(PNG_reader, PNG_info);
        bit_depth = png_get_bit_depth(PNG_reader, PNG_info);
        channels = png_get_channels(PNG_reader, PNG_info);
//        color_type = png_get_color_type(PNG_reader, PNG_info);

#ifndef NDEBUG
        msg_info("ImagePNG") << "Converted PNG image "<<filename<<": "<<width<<"x"<<height<<"x"<<bit_depth*channels;
#endif
    }

    Image::DataType dataType;
    Image::ChannelFormat channelFormat;
    switch (bit_depth)
    {
    case 8:
        dataType = Image::UNORM8;
        break;
    default:
        msg_error("ImagePNG") << "File '" << filename << "' has unsupported bit depth: " << bit_depth ;
        return false;
    }
    switch (channels)
    {
    case 1:
        channelFormat = Image::L;
        break;
    case 2:
        channelFormat = Image::LA;
        break;
    case 3:
        channelFormat = Image::RGB;
        break;
    case 4:
        channelFormat = Image::RGBA;
        break;
    default:
        msg_error("ImagePNG") << "in '" << filename << "', unsupported number of channels: " << channels ;
        return false;
    }

    init(width, height, 1, 1, dataType, channelFormat);
    png_byte** PNG_rows = (png_byte**)malloc(height * sizeof(png_byte*));

    unsigned char *data = getPixels();
    unsigned lineSize = getLineSize(0);
    for (png_uint_32 row = 0; row < height; ++row)
        PNG_rows[height - 1 - row] = data+row*lineSize;

    png_read_image(PNG_reader, PNG_rows);

    free(PNG_rows);

    png_read_end(PNG_reader, PNG_end_info);

    png_destroy_read_struct(&PNG_reader, &PNG_info, &PNG_end_info);
    fclose(file);
    m_bLoaded = 1;
    return true;
}

// we have to give our own writing function to libpng in order to use the "fwrite" function belonging to Sofa
// and not the one belonging to libpng since Sofa do the "fopen" on the FILE struct
void png_my_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
{
    png_size_t check;

    if (png_ptr == NULL)
        return;

    check = fwrite(data, 1, length, (png_FILE_p)png_get_io_ptr(png_ptr));

    if (check != length)
        png_error(png_ptr, "Write Error");
}

void png_default_flush(png_structp png_ptr)
{
    png_FILE_p io_ptr;

    if (png_ptr == NULL)
        return;

    io_ptr = (png_FILE_p)(png_get_io_ptr(png_ptr));
    fflush(io_ptr);
}

bool ImagePNG::save(std::string filename, int compression_level)
{

    FILE *file;
#ifndef NDEBUG
    std::cout << "Writing PNG file " << filename << std::endl;
#endif
    /* make sure the file is there and open it read-only (binary) */
    if ((file = fopen(filename.c_str(), "wb")) == NULL)
    {
        msg_error("ImagePNG") << "File write access failed to '" << filename << "'" ;
        return false;
    }

    png_structp PNG_writer = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    if (PNG_writer == NULL)
    {
        msg_error("ImagePNG") << "png_create_write_struct failed for file '"<< filename << "'";
        fclose(file);
        return false;
    }

    png_infop PNG_info = png_create_info_struct(PNG_writer);
    if (PNG_info == NULL)
    {
        msg_error("ImagePNG") << "png_create_info_struct failed for file '" << filename << "'";
        png_destroy_write_struct(&PNG_writer, NULL);
        fclose(file);
        return false;
    }

    if (setjmp(png_jmpbuf(PNG_writer)))
    {
        msg_error("ImagePNG") << "Writing failed for PNG file '" << filename << "'";
        png_destroy_write_struct(&PNG_writer, &PNG_info);
        fclose(file);
        return false;
    }

    //png_init_io(PNG_writer, file);
    png_set_write_fn(PNG_writer, file, png_my_write_data, png_default_flush);

    png_uint_32 width, height;
    png_uint_32 bit_depth, channels, color_type;

    width = getWidth();
    height = getHeight();

    bit_depth = getBytesPerChannel() * 8;
    channels = getChannelCount();
    if (channels == 1)
        color_type = PNG_COLOR_TYPE_GRAY;
    else if (channels == 2)
        color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
    else if (channels == 3)
        color_type = PNG_COLOR_TYPE_RGB;
    else
        color_type = PNG_COLOR_TYPE_RGB_ALPHA;

    if (bit_depth != 8)
    {
        msg_error("ImagePNG") << "Unsupported bitdepth "<< bit_depth <<" to write to PNG file '"<<filename<<"'";
        png_destroy_write_struct(&PNG_writer, &PNG_info);
        fclose(file);
        return false;
    }
#ifndef NDEBUG
    msg_info("ImagePNG") << "PNG image "<<filename<<": "<<width<<"x"<<height<<"x"<<bit_depth*channels;
#endif
    png_set_IHDR(PNG_writer, PNG_info, width, height,
            bit_depth, color_type, PNG_INTERLACE_NONE,
            PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
    /* set the zlib compression level */
    if (compression_level!=-1)
    {
        if (compression_level>=0 && compression_level<=9)
            png_set_compression_level(PNG_writer, compression_level);
        else
            msg_error("ImagePNG") << "Compression level must be a value between 0 and 9" ;
    }

    png_byte** PNG_rows = (png_byte**)malloc(height * sizeof(png_byte*));

    unsigned char *data = getPixels();
    unsigned lineSize = getLineSize(0);
    for (png_uint_32 row = 0; row < height; ++row)
        PNG_rows[height - 1 - row] = data+row*lineSize;

    png_set_rows(PNG_writer, PNG_info, PNG_rows);

    png_write_png(PNG_writer, PNG_info, PNG_TRANSFORM_IDENTITY, NULL);

    free(PNG_rows);

    png_destroy_write_struct(&PNG_writer, &PNG_info);
    fclose(file);
    return true;
}

#endif

} // namespace io

} // namespace helper

} // namespace sofa

<|endoftext|>


<commit_before>
#include "../Flare.h"
#include "FlareGameUserSettings.h"
#include "FlareGame.h"
#include "../Player/FlarePlayerController.h"

/*----------------------------------------------------
	Constructor
----------------------------------------------------*/

UFlareGameUserSettings::UFlareGameUserSettings(const class FObjectInitializer& PCIP)
	: Super(PCIP)
{
}

void UFlareGameUserSettings::SetToDefaults()
{
	Super::SetToDefaults();

	// Graphics
	ScreenPercentage = 100;
	UseTemporalAA = true;
	UseMotionBlur = true;

	// Gameplay
	UseCockpit = true;
	UseAnticollision = false;
	PauseGameInMenus = false;
	MaxShipsInSector = 20;

	// Sound
	MusicVolume = 8;
	MasterVolume = 10;
}

void UFlareGameUserSettings::ApplySettings(bool bCheckForCommandLineOverrides)
{
	FLOG("UFlareGameUserSettings::ApplySettings");

	Super::ApplySettings(bCheckForCommandLineOverrides);

	SetUseTemporalAA(UseTemporalAA);

	SetScreenPercentage(ScreenPercentage);
}

void UFlareGameUserSettings::SetUseTemporalAA(bool NewSetting)
{
	//FLOGV("UFlareGameUserSettings::SetUseTemporalAA %d", NewSetting);
	UseTemporalAA = NewSetting;

	auto TemporalAACVar = IConsoleManager::Get().FindConsoleVariable(TEXT("r.DefaultFeature.AntiAliasing"));
	TemporalAACVar->Set(UseTemporalAA ? AAM_TemporalAA : AAM_FXAA, ECVF_SetByConsole);
}

void UFlareGameUserSettings::SetScreenPercentage(int32 NewScreenPercentage)
{
	//FLOGV("UFlareGameUserSettings::SetScreenPercentage %d", NewScreenPercentage);
	ScreenPercentage = NewScreenPercentage;

	auto ScreenPercentageCVar = IConsoleManager::Get().FindConsoleVariable(TEXT("r.ScreenPercentage"));
	ScreenPercentageCVar->Set(ScreenPercentage, ECVF_SetByConsole);
}
<commit_msg>Fix default music volume<commit_after>
#include "../Flare.h"
#include "FlareGameUserSettings.h"
#include "FlareGame.h"
#include "../Player/FlarePlayerController.h"

/*----------------------------------------------------
	Constructor
----------------------------------------------------*/

UFlareGameUserSettings::UFlareGameUserSettings(const class FObjectInitializer& PCIP)
	: Super(PCIP)
{
}

void UFlareGameUserSettings::SetToDefaults()
{
	Super::SetToDefaults();

	// Graphics
	ScreenPercentage = 100;
	UseTemporalAA = true;
	UseMotionBlur = true;

	// Gameplay
	UseCockpit = true;
	UseAnticollision = false;
	PauseGameInMenus = false;
	MaxShipsInSector = 20;

	// Sound
	MusicVolume = 10;
	MasterVolume = 10;
}

void UFlareGameUserSettings::ApplySettings(bool bCheckForCommandLineOverrides)
{
	FLOG("UFlareGameUserSettings::ApplySettings");

	Super::ApplySettings(bCheckForCommandLineOverrides);

	SetUseTemporalAA(UseTemporalAA);

	SetScreenPercentage(ScreenPercentage);
}

void UFlareGameUserSettings::SetUseTemporalAA(bool NewSetting)
{
	//FLOGV("UFlareGameUserSettings::SetUseTemporalAA %d", NewSetting);
	UseTemporalAA = NewSetting;

	auto TemporalAACVar = IConsoleManager::Get().FindConsoleVariable(TEXT("r.DefaultFeature.AntiAliasing"));
	TemporalAACVar->Set(UseTemporalAA ? AAM_TemporalAA : AAM_FXAA, ECVF_SetByConsole);
}

void UFlareGameUserSettings::SetScreenPercentage(int32 NewScreenPercentage)
{
	//FLOGV("UFlareGameUserSettings::SetScreenPercentage %d", NewScreenPercentage);
	ScreenPercentage = NewScreenPercentage;

	auto ScreenPercentageCVar = IConsoleManager::Get().FindConsoleVariable(TEXT("r.ScreenPercentage"));
	ScreenPercentageCVar->Set(ScreenPercentage, ECVF_SetByConsole);
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/include/usr/pnor/pnor_reasoncodes.H $                     */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2011,2018                        */
/* [+] Google Inc.                                                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#ifndef __PNOR_REASONCODES_H
#define __PNOR_REASONCODES_H

#include <hbotcompid.H>

namespace PNOR
{
    enum PNORModuleId
    {
        // pnorrp.C
        MOD_PNORRP_WAITFORMESSAGE       = 0x01, /**< PnorRP::waitForMessage */
        MOD_PNORRP_COMPUTEDEVICEADDR    = 0x02, /**< PnorRP::computeDeviceAddr */
        MOD_PNORRP_GETSECTIONINFO       = 0x03, /**< PnorRP::getSectionInfo */
        MOD_PNORRP_COMPUTESECTION       = 0x04, /**< PnorRP::computeSection */
        MOD_PNORRP_INITDAEMON           = 0x05, /**< PnorRP::initDaemon */
        MOD_PNORRP_READTOC              = 0x06, /**< PnorRP::readTOC */
        MOD_PNORRP_READFROMDEVICE       = 0x07, /**< PnorRP::readFromDevice */
        MOD_PNORRP_WRITETODEVICE        = 0x08, /**< PnorRP::writeToDevice */
        MOD_PNORRP_DIDSTARTUPFAIL       = 0x09, /**< didStartupFail(rc) */
        MOD_PNORRP_FLUSH                = 0x0A, /**< mm_remove_pages */
        MOD_PNORRP_FIXECC               = 0x0B, /**< PnorRP::fixECC */
        MOD_PNORRP_FINDTOC              = 0x0C, /**< PnorRP::findTOC */
        MOD_PNORRP_GETSIDEINFO          = 0x0D, /**< PnorRP::getSideInfo */
        MOD_PNORRP_SETSIDEINFO          = 0x0E, /**< PnorRP::setSideInfo */

        // pnorvalid.C
        MOD_PNORVALID_MAIN              = 0x0E, /**< validateAltMaster */
        MOD_PNORVALID_MAGIC             = 0x0F, /**< validateAltMaster */

        // pnordd.C
        MOD_PNORDD_VERIFYADDRESSRANGE   = 0x11, /**< PnorDD::verifyAddressRange */
        MOD_PNORDD_READFLASH            = 0x12, /**< PnorDD::readFlash */
        MOD_PNORDD_WRITEFLASH           = 0x13, /**< PnorDD::writeFlash */
        MOD_PNORDD_SFCINIT              = 0x14, /**< PnorDD::sfcInit */
        MOD_PNORDD_ERASEFLASH           = 0x15, /**< PnorDD::eraseFlash */
        MOD_PNORDD_CHECKFORERRORS       = 0x16, /**< PnorDD::checkForErrors */

        // sfc_ibm.C
        MOD_SFCIBM_VERIFYADDRESSRANGE   = 0x40, /**< SfcIBM::verifyAddressRange */
        MOD_SFCIBM_READFLASH            = 0x41, /**< SfcIBM::readFlash */
        MOD_SFCIBM_WRITEFLASH           = 0x42, /**< SfcIBM::writeFlash */
        MOD_SFCIBM_POLLOPCOMPLETE       = 0x43, /**< SfcIBM::pollSfcOpComplete */
        MOD_SFCIBM_SFCINIT              = 0x44, /**< SfcIBM::sfcInit */
        MOD_SFCIBM_ERASEFLASH           = 0x45, /**< SfcIBM::eraseFlash */
        MOD_SFCIBM_CHECKFORERRORS       = 0x46, /**< SfcIBM::checkForErrors */
        MOD_SFCIBM_HWRESET              = 0x47, /**< SfcIBM::hwReset */

        // sfc_fake.C
        MOD_SFCFAKE_VERIFYADDRESSRANGE  = 0x60, /**< SfcFake::verifyAddressRange */
        MOD_SFCFAKE_READFLASH           = 0x61, /**< SfcFake::readFlash */
        MOD_SFCFAKE_WRITEFLASH          = 0x62, /**< SfcFake::writeFlash */
        MOD_SFCFAKE_ERASEFLASH          = 0x63, /**< SfcFake::eraseFlash */
        MOD_SFCFAKE_SENDSPICMD          = 0x64, /**< SfcFake::sendSpiCmd */

        // sfc_ast2X00.C
        MOD_SFCAST2X00_ENABLEWRITEMODE  = 0x80, /**< SfcAST2X00::verifyAddressRange */
        MOD_SFCAST2X00_READFLASH        = 0x81, /**< SfcAST2X00::readFlash */
        MOD_SFCAST2X00_WRITEFLASH       = 0x82, /**< SfcAST2X00::writeFlash */
        MOD_SFCAST2X00_POLLOPCOMPLETE   = 0x83, /**< SfcAST2X00::pollSfcOpComplete */
        MOD_SFCAST2X00_ERASEFLASH       = 0x84, /**< SfcAST2X00::eraseFlash */

        // nor_micron.C
        MOD_NORMICRON_MICRONFLAGSTATUS  = 0xA0, /**< micronFlagStatus */

        // rt_pnor.C
        MOD_RTPNOR_GETSECTIONINFO       = 0xB0, /**< RtPnor::getSectionInfo*/
        MOD_RTPNOR_FLUSH                = 0xB1, /**< RtPnor::flush */
        MOD_RTPNOR_READFROMDEVICE       = 0xB2, /**< RtPnor::readFromDevice */
        MOD_RTPNOR_WRITETODEVICE        = 0xB3, /**< RtPnor::writeToDevice */
        MOD_RTPNOR_GETSIDEINFO          = 0xB4, /**< RtPnor::getSideInfo */

        // pnor_common.C
        MOD_PNORCOMMON_PARSETOC         = 0xC0, /**< PNOR::parseTOC */

        // spnorrp.C
        // Note: 0xD0 is available, so should be the next one used for spnorrp.
        // Remove this comment after doing so.
        MOD_SPNORRP_DIDSTARTUPFAIL      = 0xD1, /**< didSecureStartupFail(rc) */
        MOD_SPNORRP_ALLOCATE_BLOCK      = 0xD2, /**< SPnorRP::initDaemon */
        MOD_SPNORRP_WAITFORMESSAGE      = 0xD3, /**< SPnorRP::waitForMessage */
        MOD_SPNORRP_VERIFYSECTIONS      = 0xD4, /**< SPnorRP::verifySections */
        MOD_SPNORRP_SET_PERMISSION      = 0xD5, /**< SPnorRP::initDaemon */
        MOD_PNORRP_LOADUNLOADSECURESECTION = 0xD6, /**< PnorRP::loadSecureSection */
        MOD_SPNORRP_BASE_EXT_VER_CHK    = 0xD7, /**< SPnorRP::baseExtVersCheck */
        MOD_SPNORRP_KEY_TRAN_CHK        = 0xD8, /**< SPnorRP::keyTransitionCheck */
        MOD_SPNORRP_REMOVE_PAGES        = 0xD9,

        // ast_mboxdd.C
        MOD_ASTMBOXDD_DO_MESSAGE        = 0xE0, /**< astMbox::doMessage */
    };

    enum PNORReasonCode
    {
        RC_INVALID_MESSAGE_TYPE      = PNOR_COMP_ID | 0x01,
        RC_INVALID_ADDRESS           = PNOR_COMP_ID | 0x02,
        RC_INVALID_SECTION           = PNOR_COMP_ID | 0x03,
        RC_EXTERNAL_ERROR            = PNOR_COMP_ID | 0x04,
        RC_STARTUP_FAIL              = PNOR_COMP_ID | 0x05,
        RC_INVALID_ASYNC_MESSAGE     = PNOR_COMP_ID | 0x06,
        RC_UNSUPPORTED_OPERATION     = PNOR_COMP_ID | 0x07,
        RC_LPC_ERROR                 = PNOR_COMP_ID | 0x08,
        RC_BAD_STARTUP_RC            = PNOR_COMP_ID | 0x09,
        //termination_rc
        RC_UNSUPPORTED_HARDWARE      = PNOR_COMP_ID | 0x0A,
        RC_MICRON_INCOMPLETE         = PNOR_COMP_ID | 0x0B,
        //termination_rc
        RC_PARTITION_TABLE_INVALID   = PNOR_COMP_ID | 0x0C,
        //termination_rc
        RC_UNSUPPORTED_MODE          = PNOR_COMP_ID | 0x0D,
        //termination_rc
        RC_UNSUPPORTED_SFCRANGE      = PNOR_COMP_ID | 0x0E,
        //termination_rc
        RC_ECC_UE                    = PNOR_COMP_ID | 0x0F,
        RC_ERROR_IN_STATUS_REG       = PNOR_COMP_ID | 0x10,
        //termination_rc
        RC_REINITIALIZE_SFC          = PNOR_COMP_ID | 0x11,
        RC_SFC_ERROR                 = PNOR_COMP_ID | 0x12,
        //termination_rc
        RC_PNOR_INIT_FAILURE         = PNOR_COMP_ID | 0x13,
        RC_CANNOT_ENABLE_WRITES      = PNOR_COMP_ID | 0x14,
        RC_SFC_TIMEOUT               = PNOR_COMP_ID | 0x15,
        RC_PNOR_READ_FAILED          = PNOR_COMP_ID | 0x16,
        RC_PNOR_WRITE_FAILED         = PNOR_COMP_ID | 0x17,
        RC_CORRUPTED_TOCS            = PNOR_COMP_ID | 0x18,
        RC_BAD_TOC_HEADER            = PNOR_COMP_ID | 0x19,
        RC_SECTION_SIZE_IS_BIG       = PNOR_COMP_ID | 0x1A,
        RC_RTPNOR_INVALID_SECTION    = PNOR_COMP_ID | 0x1B,
        RC_UNCORRECTABLE_ECC         = PNOR_COMP_ID | 0x1C,
        RC_SECTION_SIZE_IS_ZERO      = PNOR_COMP_ID | 0x1D,
        RC_MM_REMOVE_PAGES_FAILED    = PNOR_COMP_ID | 0x1E,
        RC_PNOR_READ_NOT_SUPPORTED   = PNOR_COMP_ID | 0x1F,
        RC_PNOR_WRITE_NOT_SUPPORTED  = PNOR_COMP_ID | 0x20,
        RC_NON_ECC_PROTECTED_SECTION = PNOR_COMP_ID | 0x21,
        RC_WRITABLE_PERM_FAIL        = PNOR_COMP_ID | 0x22,
        RC_WRITE_TRACKED_PERM_FAIL   = PNOR_COMP_ID | 0x23,
        //termination_rc
        RC_PARTITION_TABLE_NOT_FOUND = PNOR_COMP_ID | 0x24,
        //termination_rc
        RC_PARTITION_TABLE_CORRUPTED = PNOR_COMP_ID | 0x25,
        //termination_rc
        RC_FINDTOC_FAILED            = PNOR_COMP_ID | 0x26,
        RC_INVALID_PNOR_SIDE         = PNOR_COMP_ID | 0x27,
        //termination_rc
        RC_INVALID_WORKING_TOC       = PNOR_COMP_ID | 0x28,
        RC_INVALID_TOC               = PNOR_COMP_ID | 0x29,
        RC_WRONG_SIZE_FROM_READ      = PNOR_COMP_ID | 0x2A,
        RC_NULL_TOC_BUFFER           = PNOR_COMP_ID | 0x2B,
        RC_TOC_HDR_CHECKSUM_ERR      = PNOR_COMP_ID | 0x2C,
        RC_PNOR_PARSE_ENTRIES_ERR    = PNOR_COMP_ID | 0x2D,
        RC_PNOR_SET_VADDR_FAILED     = PNOR_COMP_ID | 0x2E,
        RC_BASE_EXT_MISMATCH         = PNOR_COMP_ID | 0x2F,
        RC_KEY_TRAN_FLAG_UNSET       = PNOR_COMP_ID | 0x30,
        RC_BAD_SECURE_MAGIC_NUM      = PNOR_COMP_ID | 0x31,
        RC_MBOX_BAD_SEQUENCE         = PNOR_COMP_ID | 0x32,
        RC_MBOX_ERROR_STATUS         = PNOR_COMP_ID | 0x33,
        RC_UNSIGNED_PNOR_SECTION     = PNOR_COMP_ID | 0x34,
        RC_NOT_A_LOADED_SECTION      = PNOR_COMP_ID | 0x35,
        RC_NOT_A_SUPPORTED_SECTION   = PNOR_COMP_ID | 0x36,
        RC_SECURE_UNLOAD_DISALLOWED  = PNOR_COMP_ID | 0x37,
        RC_SECURE_TOTAL_SIZE_INVAL   = PNOR_COMP_ID | 0x38,
        RC_SECURE_VADDR_MISMATCH     = PNOR_COMP_ID | 0x39,
        RC_SECURE_SIZE_MISMATCH      = PNOR_COMP_ID | 0x3A,
        RC_NOT_PAGE_ALIGNED          = PNOR_COMP_ID | 0x3B,
        RC_SECURE_PRO_SIZE_MISMATCH  = PNOR_COMP_ID | 0x3C,
        RC_READ_ONLY_PERM_FAIL       = PNOR_COMP_ID | 0x3D,

        //@fixme-RTC:131607-Temporary value to allow HWSV compile
        //termination_rc
        RC_PNOR_CORRUPTION           = PNOR_COMP_ID | 0x99,
    };

    enum UserDetailsTypes
    {
        PNOR_UDT_NO_FORMAT           = 0x0,
        PNOR_UDT_PNORDD_PARAMETERS   = 0x1,
    };
};

#endif
<commit_msg>Secure Boot: Report base/extended code mismatch as terminating<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/include/usr/pnor/pnor_reasoncodes.H $                     */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2011,2018                        */
/* [+] Google Inc.                                                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#ifndef __PNOR_REASONCODES_H
#define __PNOR_REASONCODES_H

#include <hbotcompid.H>

namespace PNOR
{
    enum PNORModuleId
    {
        // pnorrp.C
        MOD_PNORRP_WAITFORMESSAGE       = 0x01, /**< PnorRP::waitForMessage */
        MOD_PNORRP_COMPUTEDEVICEADDR    = 0x02, /**< PnorRP::computeDeviceAddr */
        MOD_PNORRP_GETSECTIONINFO       = 0x03, /**< PnorRP::getSectionInfo */
        MOD_PNORRP_COMPUTESECTION       = 0x04, /**< PnorRP::computeSection */
        MOD_PNORRP_INITDAEMON           = 0x05, /**< PnorRP::initDaemon */
        MOD_PNORRP_READTOC              = 0x06, /**< PnorRP::readTOC */
        MOD_PNORRP_READFROMDEVICE       = 0x07, /**< PnorRP::readFromDevice */
        MOD_PNORRP_WRITETODEVICE        = 0x08, /**< PnorRP::writeToDevice */
        MOD_PNORRP_DIDSTARTUPFAIL       = 0x09, /**< didStartupFail(rc) */
        MOD_PNORRP_FLUSH                = 0x0A, /**< mm_remove_pages */
        MOD_PNORRP_FIXECC               = 0x0B, /**< PnorRP::fixECC */
        MOD_PNORRP_FINDTOC              = 0x0C, /**< PnorRP::findTOC */
        MOD_PNORRP_GETSIDEINFO          = 0x0D, /**< PnorRP::getSideInfo */
        MOD_PNORRP_SETSIDEINFO          = 0x0E, /**< PnorRP::setSideInfo */

        // pnorvalid.C
        MOD_PNORVALID_MAIN              = 0x0E, /**< validateAltMaster */
        MOD_PNORVALID_MAGIC             = 0x0F, /**< validateAltMaster */

        // pnordd.C
        MOD_PNORDD_VERIFYADDRESSRANGE   = 0x11, /**< PnorDD::verifyAddressRange */
        MOD_PNORDD_READFLASH            = 0x12, /**< PnorDD::readFlash */
        MOD_PNORDD_WRITEFLASH           = 0x13, /**< PnorDD::writeFlash */
        MOD_PNORDD_SFCINIT              = 0x14, /**< PnorDD::sfcInit */
        MOD_PNORDD_ERASEFLASH           = 0x15, /**< PnorDD::eraseFlash */
        MOD_PNORDD_CHECKFORERRORS       = 0x16, /**< PnorDD::checkForErrors */

        // sfc_ibm.C
        MOD_SFCIBM_VERIFYADDRESSRANGE   = 0x40, /**< SfcIBM::verifyAddressRange */
        MOD_SFCIBM_READFLASH            = 0x41, /**< SfcIBM::readFlash */
        MOD_SFCIBM_WRITEFLASH           = 0x42, /**< SfcIBM::writeFlash */
        MOD_SFCIBM_POLLOPCOMPLETE       = 0x43, /**< SfcIBM::pollSfcOpComplete */
        MOD_SFCIBM_SFCINIT              = 0x44, /**< SfcIBM::sfcInit */
        MOD_SFCIBM_ERASEFLASH           = 0x45, /**< SfcIBM::eraseFlash */
        MOD_SFCIBM_CHECKFORERRORS       = 0x46, /**< SfcIBM::checkForErrors */
        MOD_SFCIBM_HWRESET              = 0x47, /**< SfcIBM::hwReset */

        // sfc_fake.C
        MOD_SFCFAKE_VERIFYADDRESSRANGE  = 0x60, /**< SfcFake::verifyAddressRange */
        MOD_SFCFAKE_READFLASH           = 0x61, /**< SfcFake::readFlash */
        MOD_SFCFAKE_WRITEFLASH          = 0x62, /**< SfcFake::writeFlash */
        MOD_SFCFAKE_ERASEFLASH          = 0x63, /**< SfcFake::eraseFlash */
        MOD_SFCFAKE_SENDSPICMD          = 0x64, /**< SfcFake::sendSpiCmd */

        // sfc_ast2X00.C
        MOD_SFCAST2X00_ENABLEWRITEMODE  = 0x80, /**< SfcAST2X00::verifyAddressRange */
        MOD_SFCAST2X00_READFLASH        = 0x81, /**< SfcAST2X00::readFlash */
        MOD_SFCAST2X00_WRITEFLASH       = 0x82, /**< SfcAST2X00::writeFlash */
        MOD_SFCAST2X00_POLLOPCOMPLETE   = 0x83, /**< SfcAST2X00::pollSfcOpComplete */
        MOD_SFCAST2X00_ERASEFLASH       = 0x84, /**< SfcAST2X00::eraseFlash */

        // nor_micron.C
        MOD_NORMICRON_MICRONFLAGSTATUS  = 0xA0, /**< micronFlagStatus */

        // rt_pnor.C
        MOD_RTPNOR_GETSECTIONINFO       = 0xB0, /**< RtPnor::getSectionInfo*/
        MOD_RTPNOR_FLUSH                = 0xB1, /**< RtPnor::flush */
        MOD_RTPNOR_READFROMDEVICE       = 0xB2, /**< RtPnor::readFromDevice */
        MOD_RTPNOR_WRITETODEVICE        = 0xB3, /**< RtPnor::writeToDevice */
        MOD_RTPNOR_GETSIDEINFO          = 0xB4, /**< RtPnor::getSideInfo */

        // pnor_common.C
        MOD_PNORCOMMON_PARSETOC         = 0xC0, /**< PNOR::parseTOC */

        // spnorrp.C
        // Note: 0xD0 is available, so should be the next one used for spnorrp.
        // Remove this comment after doing so.
        MOD_SPNORRP_DIDSTARTUPFAIL      = 0xD1, /**< didSecureStartupFail(rc) */
        MOD_SPNORRP_ALLOCATE_BLOCK      = 0xD2, /**< SPnorRP::initDaemon */
        MOD_SPNORRP_WAITFORMESSAGE      = 0xD3, /**< SPnorRP::waitForMessage */
        MOD_SPNORRP_VERIFYSECTIONS      = 0xD4, /**< SPnorRP::verifySections */
        MOD_SPNORRP_SET_PERMISSION      = 0xD5, /**< SPnorRP::initDaemon */
        MOD_PNORRP_LOADUNLOADSECURESECTION = 0xD6, /**< PnorRP::loadSecureSection */
        MOD_SPNORRP_BASE_EXT_VER_CHK    = 0xD7, /**< SPnorRP::baseExtVersCheck */
        MOD_SPNORRP_KEY_TRAN_CHK        = 0xD8, /**< SPnorRP::keyTransitionCheck */
        MOD_SPNORRP_REMOVE_PAGES        = 0xD9,

        // ast_mboxdd.C
        MOD_ASTMBOXDD_DO_MESSAGE        = 0xE0, /**< astMbox::doMessage */
    };

    enum PNORReasonCode
    {
        RC_INVALID_MESSAGE_TYPE      = PNOR_COMP_ID | 0x01,
        RC_INVALID_ADDRESS           = PNOR_COMP_ID | 0x02,
        RC_INVALID_SECTION           = PNOR_COMP_ID | 0x03,
        RC_EXTERNAL_ERROR            = PNOR_COMP_ID | 0x04,
        RC_STARTUP_FAIL              = PNOR_COMP_ID | 0x05,
        RC_INVALID_ASYNC_MESSAGE     = PNOR_COMP_ID | 0x06,
        RC_UNSUPPORTED_OPERATION     = PNOR_COMP_ID | 0x07,
        RC_LPC_ERROR                 = PNOR_COMP_ID | 0x08,
        RC_BAD_STARTUP_RC            = PNOR_COMP_ID | 0x09,
        //termination_rc
        RC_UNSUPPORTED_HARDWARE      = PNOR_COMP_ID | 0x0A,
        RC_MICRON_INCOMPLETE         = PNOR_COMP_ID | 0x0B,
        //termination_rc
        RC_PARTITION_TABLE_INVALID   = PNOR_COMP_ID | 0x0C,
        //termination_rc
        RC_UNSUPPORTED_MODE          = PNOR_COMP_ID | 0x0D,
        //termination_rc
        RC_UNSUPPORTED_SFCRANGE      = PNOR_COMP_ID | 0x0E,
        //termination_rc
        RC_ECC_UE                    = PNOR_COMP_ID | 0x0F,
        RC_ERROR_IN_STATUS_REG       = PNOR_COMP_ID | 0x10,
        //termination_rc
        RC_REINITIALIZE_SFC          = PNOR_COMP_ID | 0x11,
        RC_SFC_ERROR                 = PNOR_COMP_ID | 0x12,
        //termination_rc
        RC_PNOR_INIT_FAILURE         = PNOR_COMP_ID | 0x13,
        RC_CANNOT_ENABLE_WRITES      = PNOR_COMP_ID | 0x14,
        RC_SFC_TIMEOUT               = PNOR_COMP_ID | 0x15,
        RC_PNOR_READ_FAILED          = PNOR_COMP_ID | 0x16,
        RC_PNOR_WRITE_FAILED         = PNOR_COMP_ID | 0x17,
        RC_CORRUPTED_TOCS            = PNOR_COMP_ID | 0x18,
        RC_BAD_TOC_HEADER            = PNOR_COMP_ID | 0x19,
        RC_SECTION_SIZE_IS_BIG       = PNOR_COMP_ID | 0x1A,
        RC_RTPNOR_INVALID_SECTION    = PNOR_COMP_ID | 0x1B,
        RC_UNCORRECTABLE_ECC         = PNOR_COMP_ID | 0x1C,
        RC_SECTION_SIZE_IS_ZERO      = PNOR_COMP_ID | 0x1D,
        RC_MM_REMOVE_PAGES_FAILED    = PNOR_COMP_ID | 0x1E,
        RC_PNOR_READ_NOT_SUPPORTED   = PNOR_COMP_ID | 0x1F,
        RC_PNOR_WRITE_NOT_SUPPORTED  = PNOR_COMP_ID | 0x20,
        RC_NON_ECC_PROTECTED_SECTION = PNOR_COMP_ID | 0x21,
        RC_WRITABLE_PERM_FAIL        = PNOR_COMP_ID | 0x22,
        RC_WRITE_TRACKED_PERM_FAIL   = PNOR_COMP_ID | 0x23,
        //termination_rc
        RC_PARTITION_TABLE_NOT_FOUND = PNOR_COMP_ID | 0x24,
        //termination_rc
        RC_PARTITION_TABLE_CORRUPTED = PNOR_COMP_ID | 0x25,
        //termination_rc
        RC_FINDTOC_FAILED            = PNOR_COMP_ID | 0x26,
        RC_INVALID_PNOR_SIDE         = PNOR_COMP_ID | 0x27,
        //termination_rc
        RC_INVALID_WORKING_TOC       = PNOR_COMP_ID | 0x28,
        RC_INVALID_TOC               = PNOR_COMP_ID | 0x29,
        RC_WRONG_SIZE_FROM_READ      = PNOR_COMP_ID | 0x2A,
        RC_NULL_TOC_BUFFER           = PNOR_COMP_ID | 0x2B,
        RC_TOC_HDR_CHECKSUM_ERR      = PNOR_COMP_ID | 0x2C,
        RC_PNOR_PARSE_ENTRIES_ERR    = PNOR_COMP_ID | 0x2D,
        RC_PNOR_SET_VADDR_FAILED     = PNOR_COMP_ID | 0x2E,
        //termination_rc
        RC_BASE_EXT_MISMATCH         = PNOR_COMP_ID | 0x2F,
        RC_KEY_TRAN_FLAG_UNSET       = PNOR_COMP_ID | 0x30,
        RC_BAD_SECURE_MAGIC_NUM      = PNOR_COMP_ID | 0x31,
        RC_MBOX_BAD_SEQUENCE         = PNOR_COMP_ID | 0x32,
        RC_MBOX_ERROR_STATUS         = PNOR_COMP_ID | 0x33,
        RC_UNSIGNED_PNOR_SECTION     = PNOR_COMP_ID | 0x34,
        RC_NOT_A_LOADED_SECTION      = PNOR_COMP_ID | 0x35,
        RC_NOT_A_SUPPORTED_SECTION   = PNOR_COMP_ID | 0x36,
        RC_SECURE_UNLOAD_DISALLOWED  = PNOR_COMP_ID | 0x37,
        RC_SECURE_TOTAL_SIZE_INVAL   = PNOR_COMP_ID | 0x38,
        RC_SECURE_VADDR_MISMATCH     = PNOR_COMP_ID | 0x39,
        RC_SECURE_SIZE_MISMATCH      = PNOR_COMP_ID | 0x3A,
        RC_NOT_PAGE_ALIGNED          = PNOR_COMP_ID | 0x3B,
        RC_SECURE_PRO_SIZE_MISMATCH  = PNOR_COMP_ID | 0x3C,
        RC_READ_ONLY_PERM_FAIL       = PNOR_COMP_ID | 0x3D,

        //@fixme-RTC:131607-Temporary value to allow HWSV compile
        //termination_rc
        RC_PNOR_CORRUPTION           = PNOR_COMP_ID | 0x99,
    };

    enum UserDetailsTypes
    {
        PNOR_UDT_NO_FORMAT           = 0x0,
        PNOR_UDT_PNORDD_PARAMETERS   = 0x1,
    };
};

#endif
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010 Apple Inc. All rights reserved.
 * Copyright (C) 2010 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  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.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "config.h"
#include "core/inspector/InspectorProfilerAgent.h"

#include "InspectorFrontend.h"
#include "bindings/v8/ScriptProfiler.h"
#include "core/inspector/ConsoleAPITypes.h"
#include "core/inspector/InjectedScript.h"
#include "core/inspector/InjectedScriptHost.h"
#include "core/inspector/InspectorConsoleAgent.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/inspector/ScriptCallStack.h"
#include "core/inspector/ScriptProfile.h"
#include "core/page/ConsoleTypes.h"
#include "wtf/CurrentTime.h"
#include "wtf/text/StringConcatenate.h"

namespace WebCore {

namespace ProfilerAgentState {
static const char samplingInterval[] = "samplingInterval";
static const char userInitiatedProfiling[] = "userInitiatedProfiling";
static const char profilerEnabled[] = "profilerEnabled";
static const char profileHeadersRequested[] = "profileHeadersRequested";
}

static const char* const userInitiatedProfileName = "org.webkit.profiles.user-initiated";
static const char* const CPUProfileType = "CPU";

PassOwnPtr<InspectorProfilerAgent> InspectorProfilerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager)
{
    return adoptPtr(new InspectorProfilerAgent(instrumentingAgents, consoleAgent, inspectorState, injectedScriptManager));
}

InspectorProfilerAgent::InspectorProfilerAgent(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager)
    : InspectorBaseAgent<InspectorProfilerAgent>("Profiler", instrumentingAgents, inspectorState)
    , m_consoleAgent(consoleAgent)
    , m_injectedScriptManager(injectedScriptManager)
    , m_frontend(0)
    , m_recordingCPUProfile(false)
    , m_currentUserInitiatedProfileNumber(-1)
    , m_nextUserInitiatedProfileNumber(1)
    , m_profileNameIdleTimeMap(ScriptProfiler::currentProfileNameIdleTimeMap())
    , m_idleStartTime(0.0)
{
}

InspectorProfilerAgent::~InspectorProfilerAgent()
{
}

void InspectorProfilerAgent::addProfile(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, const String& sourceURL)
{
    RefPtr<ScriptProfile> profile = prpProfile;
    m_profiles.add(profile->uid(), profile);
    if (m_frontend && m_state->getBoolean(ProfilerAgentState::profileHeadersRequested))
        m_frontend->addProfileHeader(createProfileHeader(*profile));
    addProfileFinishedMessageToConsole(profile, lineNumber, sourceURL);
}

void InspectorProfilerAgent::addProfile(PassRefPtr<ScriptProfile> prpProfile, PassRefPtr<ScriptCallStack> callStack)
{
    const ScriptCallFrame& lastCaller = callStack->at(0);
    addProfile(prpProfile, lastCaller.lineNumber(), lastCaller.sourceURL());
}

void InspectorProfilerAgent::addProfileFinishedMessageToConsole(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, const String& sourceURL)
{
    if (!m_frontend)
        return;
    RefPtr<ScriptProfile> profile = prpProfile;
    String message = profile->title() + "#" + String::number(profile->uid());
    m_consoleAgent->addMessageToConsole(ConsoleAPIMessageSource, ProfileEndMessageType, DebugMessageLevel, message, sourceURL, lineNumber);
}

PassRefPtr<TypeBuilder::Profiler::ProfileHeader> InspectorProfilerAgent::createProfileHeader(const ScriptProfile& profile)
{
    return TypeBuilder::Profiler::ProfileHeader::create()
        .setUid(profile.uid())
        .setTitle(profile.title())
        .release();
}

void InspectorProfilerAgent::enable(ErrorString*)
{
    m_state->setBoolean(ProfilerAgentState::profilerEnabled, true);
    m_instrumentingAgents->setInspectorProfilerAgent(this);
}

void InspectorProfilerAgent::disable(ErrorString*)
{
    m_instrumentingAgents->setInspectorProfilerAgent(0);
    m_state->setBoolean(ProfilerAgentState::profilerEnabled, false);
    m_state->setBoolean(ProfilerAgentState::profileHeadersRequested, false);
}

bool InspectorProfilerAgent::enabled()
{
    return m_state->getBoolean(ProfilerAgentState::profilerEnabled);
}

void InspectorProfilerAgent::setSamplingInterval(ErrorString* error, int interval)
{
    if (m_recordingCPUProfile) {
        *error = "Cannot change sampling interval when profiling.";
        return;
    }
    m_state->setLong(ProfilerAgentState::samplingInterval, interval);
    ScriptProfiler::setSamplingInterval(interval);
}

String InspectorProfilerAgent::getCurrentUserInitiatedProfileName(bool incrementProfileNumber)
{
    if (incrementProfileNumber)
        m_currentUserInitiatedProfileNumber = m_nextUserInitiatedProfileNumber++;

    return String(userInitiatedProfileName) + "." + String::number(m_currentUserInitiatedProfileNumber);
}

void InspectorProfilerAgent::getProfileHeaders(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Profiler::ProfileHeader> >& headers)
{
    m_state->setBoolean(ProfilerAgentState::profileHeadersRequested, true);
    headers = TypeBuilder::Array<TypeBuilder::Profiler::ProfileHeader>::create();

    ProfilesMap::iterator profilesEnd = m_profiles.end();
    for (ProfilesMap::iterator it = m_profiles.begin(); it != profilesEnd; ++it)
        headers->addItem(createProfileHeader(*it->value));
}

void InspectorProfilerAgent::getCPUProfile(ErrorString* errorString, int rawUid, RefPtr<TypeBuilder::Profiler::CPUProfile>& profileObject)
{
    unsigned uid = static_cast<unsigned>(rawUid);
    ProfilesMap::iterator it = m_profiles.find(uid);
    if (it == m_profiles.end()) {
        *errorString = "Profile wasn't found";
        return;
    }
    profileObject = TypeBuilder::Profiler::CPUProfile::create()
        .setHead(it->value->buildInspectorObjectForHead())
        .setStartTime(it->value->startTime())
        .setEndTime(it->value->endTime());
    profileObject->setSamples(it->value->buildInspectorObjectForSamples());
}

void InspectorProfilerAgent::removeProfile(ErrorString*, const String& type, int rawUid)
{
    unsigned uid = static_cast<unsigned>(rawUid);
    if (type == CPUProfileType) {
        if (m_profiles.contains(uid))
            m_profiles.remove(uid);
    }
}

void InspectorProfilerAgent::clearProfiles(ErrorString*)
{
    stop();
    m_profiles.clear();
    m_currentUserInitiatedProfileNumber = 1;
    m_nextUserInitiatedProfileNumber = 1;
    resetFrontendProfiles();
    m_injectedScriptManager->injectedScriptHost()->clearInspectedObjects();
}

void InspectorProfilerAgent::resetFrontendProfiles()
{
    if (!m_frontend)
        return;
    if (!m_state->getBoolean(ProfilerAgentState::profileHeadersRequested))
        return;
    if (m_profiles.isEmpty())
        m_frontend->resetProfiles();
}

void InspectorProfilerAgent::setFrontend(InspectorFrontend* frontend)
{
    m_frontend = frontend->profiler();
}

void InspectorProfilerAgent::clearFrontend()
{
    m_frontend = 0;
    stop();
    ErrorString error;
    disable(&error);
}

void InspectorProfilerAgent::restore()
{
    resetFrontendProfiles();
    if (long interval = m_state->getLong(ProfilerAgentState::samplingInterval, interval))
        ScriptProfiler::setSamplingInterval(interval);
    if (m_state->getBoolean(ProfilerAgentState::userInitiatedProfiling))
        start();
}

void InspectorProfilerAgent::start(ErrorString*)
{
    if (m_recordingCPUProfile)
        return;
    if (!enabled()) {
        ErrorString error;
        enable(&error);
    }
    m_recordingCPUProfile = true;
    String title = getCurrentUserInitiatedProfileName(true);
    ScriptProfiler::start(title);
    toggleRecordButton(true);
    m_state->setBoolean(ProfilerAgentState::userInitiatedProfiling, true);
}

void InspectorProfilerAgent::stop(ErrorString* errorString, RefPtr<TypeBuilder::Profiler::ProfileHeader>& header)
{
    header = stop(errorString);
}

PassRefPtr<TypeBuilder::Profiler::ProfileHeader> InspectorProfilerAgent::stop(ErrorString* errorString)
{
    if (!m_recordingCPUProfile) {
        if (errorString)
            *errorString = "No recording profiles found";
        return 0;
    }
    m_recordingCPUProfile = false;
    String title = getCurrentUserInitiatedProfileName();
    RefPtr<ScriptProfile> profile = ScriptProfiler::stop(title);
    RefPtr<TypeBuilder::Profiler::ProfileHeader> profileHeader;
    if (profile) {
        addProfile(profile, 0, String());
        profileHeader = createProfileHeader(*profile);
    } else if (errorString)
        *errorString = "Profile wasn't found";
    toggleRecordButton(false);
    m_state->setBoolean(ProfilerAgentState::userInitiatedProfiling, false);
    return profileHeader;
}

void InspectorProfilerAgent::toggleRecordButton(bool isProfiling)
{
    if (m_frontend)
        m_frontend->setRecordingProfile(isProfiling);
}

void InspectorProfilerAgent::idleFinished()
{
    if (!m_profileNameIdleTimeMap || !m_profileNameIdleTimeMap->size())
        return;
    ScriptProfiler::setIdle(false);
    if (!m_idleStartTime)
        return;

    double idleTime = WTF::monotonicallyIncreasingTime() - m_idleStartTime;
    m_idleStartTime = 0.0;
    ProfileNameIdleTimeMap::iterator end = m_profileNameIdleTimeMap->end();
    for (ProfileNameIdleTimeMap::iterator it = m_profileNameIdleTimeMap->begin(); it != end; ++it)
        it->value += idleTime;
}

void InspectorProfilerAgent::idleStarted()
{
    if (!m_profileNameIdleTimeMap || !m_profileNameIdleTimeMap->size())
        return;
    m_idleStartTime = WTF::monotonicallyIncreasingTime();
    ScriptProfiler::setIdle(true);
}

void InspectorProfilerAgent::willProcessTask()
{
    idleFinished();
}

void InspectorProfilerAgent::didProcessTask()
{
    idleStarted();
}

void InspectorProfilerAgent::willEnterNestedRunLoop()
{
    idleStarted();
}

void InspectorProfilerAgent::didLeaveNestedRunLoop()
{
    idleFinished();
}

} // namespace WebCore

<commit_msg>DevTools: Build fix for win bot after r158180.<commit_after>/*
 * Copyright (C) 2010 Apple Inc. All rights reserved.
 * Copyright (C) 2010 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  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.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "config.h"
#include "core/inspector/InspectorProfilerAgent.h"

#include "InspectorFrontend.h"
#include "bindings/v8/ScriptProfiler.h"
#include "core/inspector/ConsoleAPITypes.h"
#include "core/inspector/InjectedScript.h"
#include "core/inspector/InjectedScriptHost.h"
#include "core/inspector/InspectorConsoleAgent.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/inspector/ScriptCallStack.h"
#include "core/inspector/ScriptProfile.h"
#include "core/page/ConsoleTypes.h"
#include "wtf/CurrentTime.h"
#include "wtf/text/StringConcatenate.h"

namespace WebCore {

namespace ProfilerAgentState {
static const char samplingInterval[] = "samplingInterval";
static const char userInitiatedProfiling[] = "userInitiatedProfiling";
static const char profilerEnabled[] = "profilerEnabled";
static const char profileHeadersRequested[] = "profileHeadersRequested";
}

static const char* const userInitiatedProfileName = "org.webkit.profiles.user-initiated";
static const char* const CPUProfileType = "CPU";

PassOwnPtr<InspectorProfilerAgent> InspectorProfilerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager)
{
    return adoptPtr(new InspectorProfilerAgent(instrumentingAgents, consoleAgent, inspectorState, injectedScriptManager));
}

InspectorProfilerAgent::InspectorProfilerAgent(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager)
    : InspectorBaseAgent<InspectorProfilerAgent>("Profiler", instrumentingAgents, inspectorState)
    , m_consoleAgent(consoleAgent)
    , m_injectedScriptManager(injectedScriptManager)
    , m_frontend(0)
    , m_recordingCPUProfile(false)
    , m_currentUserInitiatedProfileNumber(-1)
    , m_nextUserInitiatedProfileNumber(1)
    , m_profileNameIdleTimeMap(ScriptProfiler::currentProfileNameIdleTimeMap())
    , m_idleStartTime(0.0)
{
}

InspectorProfilerAgent::~InspectorProfilerAgent()
{
}

void InspectorProfilerAgent::addProfile(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, const String& sourceURL)
{
    RefPtr<ScriptProfile> profile = prpProfile;
    m_profiles.add(profile->uid(), profile);
    if (m_frontend && m_state->getBoolean(ProfilerAgentState::profileHeadersRequested))
        m_frontend->addProfileHeader(createProfileHeader(*profile));
    addProfileFinishedMessageToConsole(profile, lineNumber, sourceURL);
}

void InspectorProfilerAgent::addProfile(PassRefPtr<ScriptProfile> prpProfile, PassRefPtr<ScriptCallStack> callStack)
{
    const ScriptCallFrame& lastCaller = callStack->at(0);
    addProfile(prpProfile, lastCaller.lineNumber(), lastCaller.sourceURL());
}

void InspectorProfilerAgent::addProfileFinishedMessageToConsole(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, const String& sourceURL)
{
    if (!m_frontend)
        return;
    RefPtr<ScriptProfile> profile = prpProfile;
    String message = profile->title() + "#" + String::number(profile->uid());
    m_consoleAgent->addMessageToConsole(ConsoleAPIMessageSource, ProfileEndMessageType, DebugMessageLevel, message, sourceURL, lineNumber);
}

PassRefPtr<TypeBuilder::Profiler::ProfileHeader> InspectorProfilerAgent::createProfileHeader(const ScriptProfile& profile)
{
    return TypeBuilder::Profiler::ProfileHeader::create()
        .setUid(profile.uid())
        .setTitle(profile.title())
        .release();
}

void InspectorProfilerAgent::enable(ErrorString*)
{
    m_state->setBoolean(ProfilerAgentState::profilerEnabled, true);
    m_instrumentingAgents->setInspectorProfilerAgent(this);
}

void InspectorProfilerAgent::disable(ErrorString*)
{
    m_instrumentingAgents->setInspectorProfilerAgent(0);
    m_state->setBoolean(ProfilerAgentState::profilerEnabled, false);
    m_state->setBoolean(ProfilerAgentState::profileHeadersRequested, false);
}

bool InspectorProfilerAgent::enabled()
{
    return m_state->getBoolean(ProfilerAgentState::profilerEnabled);
}

void InspectorProfilerAgent::setSamplingInterval(ErrorString* error, int interval)
{
    if (m_recordingCPUProfile) {
        *error = "Cannot change sampling interval when profiling.";
        return;
    }
    m_state->setLong(ProfilerAgentState::samplingInterval, interval);
    ScriptProfiler::setSamplingInterval(interval);
}

String InspectorProfilerAgent::getCurrentUserInitiatedProfileName(bool incrementProfileNumber)
{
    if (incrementProfileNumber)
        m_currentUserInitiatedProfileNumber = m_nextUserInitiatedProfileNumber++;

    return String(userInitiatedProfileName) + "." + String::number(m_currentUserInitiatedProfileNumber);
}

void InspectorProfilerAgent::getProfileHeaders(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Profiler::ProfileHeader> >& headers)
{
    m_state->setBoolean(ProfilerAgentState::profileHeadersRequested, true);
    headers = TypeBuilder::Array<TypeBuilder::Profiler::ProfileHeader>::create();

    ProfilesMap::iterator profilesEnd = m_profiles.end();
    for (ProfilesMap::iterator it = m_profiles.begin(); it != profilesEnd; ++it)
        headers->addItem(createProfileHeader(*it->value));
}

void InspectorProfilerAgent::getCPUProfile(ErrorString* errorString, int rawUid, RefPtr<TypeBuilder::Profiler::CPUProfile>& profileObject)
{
    unsigned uid = static_cast<unsigned>(rawUid);
    ProfilesMap::iterator it = m_profiles.find(uid);
    if (it == m_profiles.end()) {
        *errorString = "Profile wasn't found";
        return;
    }
    profileObject = TypeBuilder::Profiler::CPUProfile::create()
        .setHead(it->value->buildInspectorObjectForHead())
        .setStartTime(it->value->startTime())
        .setEndTime(it->value->endTime());
    profileObject->setSamples(it->value->buildInspectorObjectForSamples());
}

void InspectorProfilerAgent::removeProfile(ErrorString*, const String& type, int rawUid)
{
    unsigned uid = static_cast<unsigned>(rawUid);
    if (type == CPUProfileType) {
        if (m_profiles.contains(uid))
            m_profiles.remove(uid);
    }
}

void InspectorProfilerAgent::clearProfiles(ErrorString*)
{
    stop();
    m_profiles.clear();
    m_currentUserInitiatedProfileNumber = 1;
    m_nextUserInitiatedProfileNumber = 1;
    resetFrontendProfiles();
    m_injectedScriptManager->injectedScriptHost()->clearInspectedObjects();
}

void InspectorProfilerAgent::resetFrontendProfiles()
{
    if (!m_frontend)
        return;
    if (!m_state->getBoolean(ProfilerAgentState::profileHeadersRequested))
        return;
    if (m_profiles.isEmpty())
        m_frontend->resetProfiles();
}

void InspectorProfilerAgent::setFrontend(InspectorFrontend* frontend)
{
    m_frontend = frontend->profiler();
}

void InspectorProfilerAgent::clearFrontend()
{
    m_frontend = 0;
    stop();
    ErrorString error;
    disable(&error);
}

void InspectorProfilerAgent::restore()
{
    resetFrontendProfiles();
    if (long interval = m_state->getLong(ProfilerAgentState::samplingInterval, 0))
        ScriptProfiler::setSamplingInterval(interval);
    if (m_state->getBoolean(ProfilerAgentState::userInitiatedProfiling))
        start();
}

void InspectorProfilerAgent::start(ErrorString*)
{
    if (m_recordingCPUProfile)
        return;
    if (!enabled()) {
        ErrorString error;
        enable(&error);
    }
    m_recordingCPUProfile = true;
    String title = getCurrentUserInitiatedProfileName(true);
    ScriptProfiler::start(title);
    toggleRecordButton(true);
    m_state->setBoolean(ProfilerAgentState::userInitiatedProfiling, true);
}

void InspectorProfilerAgent::stop(ErrorString* errorString, RefPtr<TypeBuilder::Profiler::ProfileHeader>& header)
{
    header = stop(errorString);
}

PassRefPtr<TypeBuilder::Profiler::ProfileHeader> InspectorProfilerAgent::stop(ErrorString* errorString)
{
    if (!m_recordingCPUProfile) {
        if (errorString)
            *errorString = "No recording profiles found";
        return 0;
    }
    m_recordingCPUProfile = false;
    String title = getCurrentUserInitiatedProfileName();
    RefPtr<ScriptProfile> profile = ScriptProfiler::stop(title);
    RefPtr<TypeBuilder::Profiler::ProfileHeader> profileHeader;
    if (profile) {
        addProfile(profile, 0, String());
        profileHeader = createProfileHeader(*profile);
    } else if (errorString)
        *errorString = "Profile wasn't found";
    toggleRecordButton(false);
    m_state->setBoolean(ProfilerAgentState::userInitiatedProfiling, false);
    return profileHeader;
}

void InspectorProfilerAgent::toggleRecordButton(bool isProfiling)
{
    if (m_frontend)
        m_frontend->setRecordingProfile(isProfiling);
}

void InspectorProfilerAgent::idleFinished()
{
    if (!m_profileNameIdleTimeMap || !m_profileNameIdleTimeMap->size())
        return;
    ScriptProfiler::setIdle(false);
    if (!m_idleStartTime)
        return;

    double idleTime = WTF::monotonicallyIncreasingTime() - m_idleStartTime;
    m_idleStartTime = 0.0;
    ProfileNameIdleTimeMap::iterator end = m_profileNameIdleTimeMap->end();
    for (ProfileNameIdleTimeMap::iterator it = m_profileNameIdleTimeMap->begin(); it != end; ++it)
        it->value += idleTime;
}

void InspectorProfilerAgent::idleStarted()
{
    if (!m_profileNameIdleTimeMap || !m_profileNameIdleTimeMap->size())
        return;
    m_idleStartTime = WTF::monotonicallyIncreasingTime();
    ScriptProfiler::setIdle(true);
}

void InspectorProfilerAgent::willProcessTask()
{
    idleFinished();
}

void InspectorProfilerAgent::didProcessTask()
{
    idleStarted();
}

void InspectorProfilerAgent::willEnterNestedRunLoop()
{
    idleStarted();
}

void InspectorProfilerAgent::didLeaveNestedRunLoop()
{
    idleFinished();
}

} // namespace WebCore

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "rulenode.h"

#include "buildgraph.h"
#include "buildgraphvisitor.h"
#include "productbuilddata.h"
#include "projectbuilddata.h"
#include "rulesapplicator.h"
#include "transformer.h"
#include "transformerchangetracking.h"

#include <language/language.h>
#include <logging/categories.h>
#include <logging/logger.h>
#include <tools/qbsassert.h>
#include <tools/qttools.h>

namespace qbs {
namespace Internal {

RuleNode::RuleNode()
{
}

RuleNode::~RuleNode()
{
}

void RuleNode::accept(BuildGraphVisitor *visitor)
{
    if (visitor->visit(this))
        acceptChildren(visitor);
    visitor->endVisit(this);
}

QString RuleNode::toString() const
{
    return QLatin1String("RULE ") + m_rule->toString() + QLatin1String(" [")
            + (!product.expired() ? product->name : QLatin1String("<null>")) + QLatin1Char(']')
            + QLatin1String(" located at ") + m_rule->prepareScript.location().toString();
}

void RuleNode::apply(const Logger &logger, const ArtifactSet &changedInputs,
                     const std::unordered_map<QString, const ResolvedProduct *> &productsByName,
                     const std::unordered_map<QString, const ResolvedProject *> &projectsByName,
                     ApplicationResult *result)
{
    ArtifactSet allCompatibleInputs = currentInputArtifacts();
    const ArtifactSet addedInputs = allCompatibleInputs - m_oldInputArtifacts;
    const ArtifactSet removedInputs = m_oldInputArtifacts - allCompatibleInputs;
    result->upToDate = changedInputs.empty() && addedInputs.empty() && removedInputs.empty();

    qCDebug(lcBuildGraph).noquote().nospace()
            << "consider " << (m_rule->isDynamic() ? "dynamic " : "")
            << (m_rule->multiplex ? "multiplex " : "")
            << "rule node " << m_rule->toString()
            << "\n\tchanged: " << changedInputs.toString()
            << "\n\tcompatible: " << allCompatibleInputs.toString()
            << "\n\tadded: " << addedInputs.toString()
            << "\n\tremoved: " << removedInputs.toString();

    ArtifactSet inputs = changedInputs;
    if (m_rule->multiplex)
        inputs = allCompatibleInputs;
    else
        inputs += addedInputs;

    for (Artifact * const input : allCompatibleInputs) {
        for (const Artifact * const output : input->parentArtifacts()) {
            if (output->transformer->rule != m_rule)
                continue;
            if (prepareScriptNeedsRerun(output->transformer.get(),
                                        output->transformer->product().get(),
                                        productsByName, projectsByName)) {
                result->upToDate = false;
                inputs += input;
            }
            break;
        }
        if (m_rule->multiplex)
            break;
    }

    // Handle rules without inputs: We want to run such a rule if and only if it has not run yet
    // or its transformer is not up to date regarding the prepare script.
    if (result->upToDate && (!m_rule->declaresInputs() || !m_rule->requiresInputs)
            && inputs.empty()) {
        bool hasOutputs = false;
        for (const Artifact * const output : filterByType<Artifact>(parents)) {
            if (output->transformer->rule != m_rule)
                continue;
            hasOutputs = true;
            if (prepareScriptNeedsRerun(output->transformer.get(),
                                        output->transformer->product().get(),
                                        productsByName, projectsByName)) {
                result->upToDate = false;
                break;
            }
            if (m_rule->multiplex)
                break;
        }
        if (!hasOutputs)
            result->upToDate = false;
    }

    if (result->upToDate)
        return;
    if (!removedInputs.empty()) {
        ArtifactSet outputArtifactsToRemove;
        for (Artifact * const artifact : removedInputs) {
            for (Artifact *parent : filterByType<Artifact>(artifact->parents)) {
                if (parent->transformer->rule != m_rule) {
                    // parent was not created by our rule.
                    continue;
                }

                // parent must always have a transformer, because it's generated.
                QBS_CHECK(parent->transformer);

                // artifact is a former input of m_rule and parent was created by m_rule
                // the inputs of the transformer must contain artifact
                QBS_CHECK(parent->transformer->inputs.contains(artifact));

                outputArtifactsToRemove += parent;
            }
        }
        RulesApplicator::handleRemovedRuleOutputs(inputs, outputArtifactsToRemove, logger);
    }
    if (!inputs.empty() || !m_rule->declaresInputs() || !m_rule->requiresInputs) {
        RulesApplicator applicator(product.lock(), productsByName, projectsByName, logger);
        applicator.applyRule(m_rule, inputs);
        result->createdNodes = applicator.createdArtifacts();
        result->invalidatedNodes = applicator.invalidatedArtifacts();
    }
    m_oldInputArtifacts = inputs;
    product->topLevelProject()->buildData->setDirty();
}

void RuleNode::load(PersistentPool &pool)
{
    BuildGraphNode::load(pool);
    serializationOp<PersistentPool::Load>(pool);
}

void RuleNode::store(PersistentPool &pool)
{
    BuildGraphNode::store(pool);
    serializationOp<PersistentPool::Store>(pool);
}

ArtifactSet RuleNode::currentInputArtifacts() const
{
    ArtifactSet s;
    for (const FileTag &t : qAsConst(m_rule->inputs)) {
        for (Artifact *artifact : product->lookupArtifactsByFileTag(t)) {
            if (artifact->isTargetOfModule())
                continue;
            if (artifact->transformer && artifact->transformer->rule == m_rule) {
                // Do not add compatible artifacts as inputs that were created by this rule.
                // This can e.g. happen for the ["cpp", "hpp"] -> ["hpp", "cpp", "unmocable"] rule.
                continue;
            }
            s += artifact;
        }
    }

    if (m_rule->inputsFromDependencies.empty())
        return s;
    for (const FileTag &t : qAsConst(m_rule->inputsFromDependencies)) {
        for (Artifact *artifact : product->lookupArtifactsByFileTag(t)) {
            if (!artifact->isTargetOfModule())
                continue;
            if (artifact->transformer && artifact->transformer->rule == m_rule)
                continue;
            if (artifact->fileTags().intersects(m_rule->excludedInputs))
                continue;
            s += artifact;
        }
    }

    for (const ResolvedProductConstPtr &dep : qAsConst(product->dependencies)) {
        if (!dep->buildData)
            continue;
        for (Artifact * const a : filterByType<Artifact>(dep->buildData->allNodes())) {
            if (a->fileTags().intersects(m_rule->inputsFromDependencies)
                    && !a->fileTags().intersects(m_rule->excludedInputs))
                s += a;
        }
    }

    return s;
}

} // namespace Internal
} // namespace qbs
<commit_msg>Do not needlessly throw away output artifacts<commit_after>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "rulenode.h"

#include "buildgraph.h"
#include "buildgraphvisitor.h"
#include "productbuilddata.h"
#include "projectbuilddata.h"
#include "rulesapplicator.h"
#include "transformer.h"
#include "transformerchangetracking.h"

#include <language/language.h>
#include <logging/categories.h>
#include <logging/logger.h>
#include <tools/qbsassert.h>
#include <tools/qttools.h>

namespace qbs {
namespace Internal {

RuleNode::RuleNode()
{
}

RuleNode::~RuleNode()
{
}

void RuleNode::accept(BuildGraphVisitor *visitor)
{
    if (visitor->visit(this))
        acceptChildren(visitor);
    visitor->endVisit(this);
}

QString RuleNode::toString() const
{
    return QLatin1String("RULE ") + m_rule->toString() + QLatin1String(" [")
            + (!product.expired() ? product->name : QLatin1String("<null>")) + QLatin1Char(']')
            + QLatin1String(" located at ") + m_rule->prepareScript.location().toString();
}

void RuleNode::apply(const Logger &logger, const ArtifactSet &changedInputs,
                     const std::unordered_map<QString, const ResolvedProduct *> &productsByName,
                     const std::unordered_map<QString, const ResolvedProject *> &projectsByName,
                     ApplicationResult *result)
{
    ArtifactSet allCompatibleInputs = currentInputArtifacts();
    const ArtifactSet addedInputs = allCompatibleInputs - m_oldInputArtifacts;
    const ArtifactSet removedInputs = m_oldInputArtifacts - allCompatibleInputs;
    result->upToDate = changedInputs.empty() && addedInputs.empty() && removedInputs.empty();

    qCDebug(lcBuildGraph).noquote().nospace()
            << "consider " << (m_rule->isDynamic() ? "dynamic " : "")
            << (m_rule->multiplex ? "multiplex " : "")
            << "rule node " << m_rule->toString()
            << "\n\tchanged: " << changedInputs.toString()
            << "\n\tcompatible: " << allCompatibleInputs.toString()
            << "\n\tadded: " << addedInputs.toString()
            << "\n\tremoved: " << removedInputs.toString();

    ArtifactSet inputs = changedInputs;
    if (m_rule->multiplex)
        inputs = allCompatibleInputs;
    else
        inputs += addedInputs;

    for (Artifact * const input : allCompatibleInputs) {
        for (const Artifact * const output : input->parentArtifacts()) {
            if (output->transformer->rule != m_rule)
                continue;
            if (prepareScriptNeedsRerun(output->transformer.get(),
                                        output->transformer->product().get(),
                                        productsByName, projectsByName)) {
                result->upToDate = false;
                inputs += input;
            }
            break;
        }
        if (m_rule->multiplex)
            break;
    }

    // Handle rules without inputs: We want to run such a rule if and only if it has not run yet
    // or its transformer is not up to date regarding the prepare script.
    if (result->upToDate && (!m_rule->declaresInputs() || !m_rule->requiresInputs)
            && inputs.empty()) {
        bool hasOutputs = false;
        for (const Artifact * const output : filterByType<Artifact>(parents)) {
            if (output->transformer->rule != m_rule)
                continue;
            hasOutputs = true;
            if (prepareScriptNeedsRerun(output->transformer.get(),
                                        output->transformer->product().get(),
                                        productsByName, projectsByName)) {
                result->upToDate = false;
                break;
            }
            if (m_rule->multiplex)
                break;
        }
        if (!hasOutputs)
            result->upToDate = false;
    }

    if (result->upToDate)
        return;

    const bool mustApplyRule = !inputs.empty() || !m_rule->declaresInputs()
            || !m_rule->requiresInputs;

    // For a non-multiplex rule, the removal of an input always implies that the
    // corresponding outputs disappear.
    // For a multiplex rule, the outputs disappear only if *all* inputs are gone *and*
    // the rule requires inputs. This is exactly the opposite condition of whether to
    // re-apply the rule.
    const bool removedInputForcesOutputRemoval = !m_rule->multiplex || !mustApplyRule;
    ArtifactSet outputArtifactsToRemove;
    std::vector<std::pair<Artifact *, Artifact *>> connectionsToBreak;
    for (Artifact * const artifact : removedInputs) {
        for (Artifact *parent : filterByType<Artifact>(artifact->parents)) {
            if (parent->transformer->rule != m_rule) {
                // parent was not created by our rule.
                continue;
            }

            // parent must always have a transformer, because it's generated.
            QBS_CHECK(parent->transformer);

            // artifact is a former input of m_rule and parent was created by m_rule
            // the inputs of the transformer must contain artifact
            QBS_CHECK(parent->transformer->inputs.contains(artifact));

            if (removedInputForcesOutputRemoval)
                outputArtifactsToRemove += parent;
            else
                connectionsToBreak.push_back(std::make_pair(parent, artifact));
        }
    }
    for (const auto &connection : connectionsToBreak)
        disconnect(connection.first, connection.second);
    if (!outputArtifactsToRemove.empty())
        RulesApplicator::handleRemovedRuleOutputs(inputs, outputArtifactsToRemove, logger);

    if (mustApplyRule) {
        RulesApplicator applicator(product.lock(), productsByName, projectsByName, logger);
        applicator.applyRule(m_rule, inputs);
        result->createdNodes = applicator.createdArtifacts();
        result->invalidatedNodes = applicator.invalidatedArtifacts();
    }
    m_oldInputArtifacts = inputs;
    product->topLevelProject()->buildData->setDirty();
}

void RuleNode::load(PersistentPool &pool)
{
    BuildGraphNode::load(pool);
    serializationOp<PersistentPool::Load>(pool);
}

void RuleNode::store(PersistentPool &pool)
{
    BuildGraphNode::store(pool);
    serializationOp<PersistentPool::Store>(pool);
}

ArtifactSet RuleNode::currentInputArtifacts() const
{
    ArtifactSet s;
    for (const FileTag &t : qAsConst(m_rule->inputs)) {
        for (Artifact *artifact : product->lookupArtifactsByFileTag(t)) {
            if (artifact->isTargetOfModule())
                continue;
            if (artifact->transformer && artifact->transformer->rule == m_rule) {
                // Do not add compatible artifacts as inputs that were created by this rule.
                // This can e.g. happen for the ["cpp", "hpp"] -> ["hpp", "cpp", "unmocable"] rule.
                continue;
            }
            s += artifact;
        }
    }

    if (m_rule->inputsFromDependencies.empty())
        return s;
    for (const FileTag &t : qAsConst(m_rule->inputsFromDependencies)) {
        for (Artifact *artifact : product->lookupArtifactsByFileTag(t)) {
            if (!artifact->isTargetOfModule())
                continue;
            if (artifact->transformer && artifact->transformer->rule == m_rule)
                continue;
            if (artifact->fileTags().intersects(m_rule->excludedInputs))
                continue;
            s += artifact;
        }
    }

    for (const ResolvedProductConstPtr &dep : qAsConst(product->dependencies)) {
        if (!dep->buildData)
            continue;
        for (Artifact * const a : filterByType<Artifact>(dep->buildData->allNodes())) {
            if (a->fileTags().intersects(m_rule->inputsFromDependencies)
                    && !a->fileTags().intersects(m_rule->excludedInputs))
                s += a;
        }
    }

    return s;
}

} // namespace Internal
} // namespace qbs
<|endoftext|>


<commit_before>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker 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 Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>

#include "logMsg/logMsg.h"

#include "common/Format.h"
#include "common/tag.h"
#include "ngsi/ContextElementResponse.h"
#include "ngsi10/QueryContextResponse.h"
#include "rest/ConnectionInfo.h"

/* ****************************************************************************
*
* ContextElementResponse::render -
*/
std::string ContextElementResponse::render
(
  ConnectionInfo*     ciP,
  RequestType         requestType,
  const std::string&  indent,
  bool                comma
)
{
  std::string xmlTag   = "contextElementResponse";
  std::string jsonTag  = "contextElement";
  std::string out      = "";

  out += startTag(indent, xmlTag, jsonTag, ciP->outFormat, false, false);
  out += contextElement.render(ciP, requestType, indent + "  ", true);
  out += statusCode.render(ciP->outFormat, indent + "  ", false);
  out += endTag(indent, xmlTag, ciP->outFormat, comma, false);

  return out;
}

/* ****************************************************************************
*
* ContextElementResponse::release -
*/
void ContextElementResponse::release(void)
{
  contextElement.release();
  statusCode.release();
}

/* ****************************************************************************
*
* ContextElementResponse::check -
*/
std::string ContextElementResponse::check
(
  RequestType         requestType,
  Format              format,
  const std::string&  indent,
  const std::string&  predetectedError,
  int                 counter
)
{
  std::string res;

  if ((res = contextElement.check(requestType, format, indent, predetectedError, counter)) != "OK")
  {
    return res;
  }

  if ((res = statusCode.check(requestType, format, indent, predetectedError, counter)) != "OK")
  {
    return res;
  }

  return "OK";
}

/* ****************************************************************************
*
* ContextElementResponse::present -
*/
void ContextElementResponse::present(const std::string& indent, int ix)
{
  contextElement.present(indent, ix);
  statusCode.present(indent);
}

/* ****************************************************************************
*
* ContextElementResponse::fill -
*/
void ContextElementResponse::fill(QueryContextResponse* qcrP)
{
  if (qcrP == NULL)
  {
    statusCode.fill(SccContextElementNotFound);
    return;
  }

  if (qcrP->contextElementResponseVector.size() == 0)
  {
    statusCode.fill(&qcrP->errorCode);
    return;
  }

  //
  // FIXME P7: If more than one context element is found, we simply select the first one.
  //           A better approach would be to change this convop to return a vector of responses.
  //           Adding awarning with 'Bad Input' - with this I mean that the user that sends the
  //           query needs to avoid using this conv op to make any queries that can giv e more than
  //           one unique context element :-).
  //
  if (qcrP->contextElementResponseVector.size() > 1)
  {
    LM_W(("Bad Input (more than one context element found the this query - selecting the first one"));
  }

  contextElement.fill(&qcrP->contextElementResponseVector[0]->contextElement);

  if (qcrP->errorCode.code != SccNone)
  {
    statusCode.fill(&qcrP->errorCode);
  }
}
<commit_msg>fixed a typo<commit_after>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker 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 Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>

#include "logMsg/logMsg.h"

#include "common/Format.h"
#include "common/tag.h"
#include "ngsi/ContextElementResponse.h"
#include "ngsi10/QueryContextResponse.h"
#include "rest/ConnectionInfo.h"

/* ****************************************************************************
*
* ContextElementResponse::render -
*/
std::string ContextElementResponse::render
(
  ConnectionInfo*     ciP,
  RequestType         requestType,
  const std::string&  indent,
  bool                comma
)
{
  std::string xmlTag   = "contextElementResponse";
  std::string jsonTag  = "contextElement";
  std::string out      = "";

  out += startTag(indent, xmlTag, jsonTag, ciP->outFormat, false, false);
  out += contextElement.render(ciP, requestType, indent + "  ", true);
  out += statusCode.render(ciP->outFormat, indent + "  ", false);
  out += endTag(indent, xmlTag, ciP->outFormat, comma, false);

  return out;
}

/* ****************************************************************************
*
* ContextElementResponse::release -
*/
void ContextElementResponse::release(void)
{
  contextElement.release();
  statusCode.release();
}

/* ****************************************************************************
*
* ContextElementResponse::check -
*/
std::string ContextElementResponse::check
(
  RequestType         requestType,
  Format              format,
  const std::string&  indent,
  const std::string&  predetectedError,
  int                 counter
)
{
  std::string res;

  if ((res = contextElement.check(requestType, format, indent, predetectedError, counter)) != "OK")
  {
    return res;
  }

  if ((res = statusCode.check(requestType, format, indent, predetectedError, counter)) != "OK")
  {
    return res;
  }

  return "OK";
}

/* ****************************************************************************
*
* ContextElementResponse::present -
*/
void ContextElementResponse::present(const std::string& indent, int ix)
{
  contextElement.present(indent, ix);
  statusCode.present(indent);
}

/* ****************************************************************************
*
* ContextElementResponse::fill -
*/
void ContextElementResponse::fill(QueryContextResponse* qcrP)
{
  if (qcrP == NULL)
  {
    statusCode.fill(SccContextElementNotFound);
    return;
  }

  if (qcrP->contextElementResponseVector.size() == 0)
  {
    statusCode.fill(&qcrP->errorCode);
    return;
  }

  //
  // FIXME P7: If more than one context element is found, we simply select the first one.
  //           A better approach would be to change this convop to return a vector of responses.
  //           Adding a warning with 'Bad Input' - with this I mean that the user that sends the
  //           query needs to avoid using this conv op to make any queries that can giv e more than
  //           one unique context element :-).
  //
  if (qcrP->contextElementResponseVector.size() > 1)
  {
    LM_W(("Bad Input (more than one context element found the this query - selecting the first one"));
  }

  contextElement.fill(&qcrP->contextElementResponseVector[0]->contextElement);

  if (qcrP->errorCode.code != SccNone)
  {
    statusCode.fill(&qcrP->errorCode);
  }
}
<|endoftext|>