<commit_before>#ifndef MAPNIK_WARNING_HPP
#define MAPNIK_WARNING_HPP

#if defined(_MSC_VER)
#define MAPNIK_DISABLE_WARNING_PUSH           __pragma(warning(push))
#define MAPNIK_DISABLE_WARNING_POP            __pragma(warning(pop))
#define MAPNIK_DISABLE_WARNING(warningNumber) __pragma(warning(disable : warningNumber))

// add warnings to deactivate here
// example: #define DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER    DISABLE_WARNING(4100)
#define MAPNIK_DISABLE_WARNING_UNKNOWN_PRAGMAS               MAPNIK_DISABLE_WARNING(4068)
#define MAPNIK_DISABLE_WARNING_PRAGMAS                       // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_PRAGMA_MESSAGES               // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_UNSEQUENCED                   // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_UNUSED_FUNCTION               // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_UNUSED_PARAMETER              // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_REDECLARED_CLASS_MEMBER       // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_UNUSED_LOCAL_TYPEDEF          // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_UNUSED_LOCAL_TYPEDEFS         // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_SHADOW                        // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_CPP11_NARROWING               // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_SIGN_CONVERSION               // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_SIGN_COMPARE                  // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_CONVERSION                    MAPNIK_DISABLE_WARNING(4244)
#define MAPNIK_DISABLE_WARNING_CPP_98_COMPAT_PEDANTIC        // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_DISABLE_MACRO_EXPANSION       // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_OLD_STYLE_CAST                // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_DOCUMENTATION                 // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_DOCUMENTATION_UNKNOWN_COMMAND // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_UNDEF                         // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_DEPRECATED                    MAPNIK_DISABLE_WARNING(4996)
#define MAPNIK_DISABLE_WARNING_PADDED                        // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_CPP_98_COMPAT                 // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_RESERVED_ID_MACRO             // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_WEAK_VTABLE                   // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_EXTRA_SEMI                    // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_GLOBAL_CONSTRUCTORS           // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_HEADER_HYGIENE                // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_EXIT_TIME_DESTRUCTORS         // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_SWITCH_ENUM                   // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_MISSING_NORETURN              // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_COVERED_SWITCH_DEFAULT        // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_WARNING_FLOAT_EQUAL                   // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_LONG_LONG                             // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_UNDEFINED_VAR_TEMPLATE                // MAPNIK_DISABLE_WARNING(??)
#define MAPNIK_DISABLE_UNUSED_VARIABLE                       MAPNIK_DISABLE_WARNING(4101)
#define MAPNIK_DISABLE_MISMATCHED_TAGS                       // MAPNIK_DISABLE_WARNING(??)

#elif defined(__GNUC__) || defined(__clang__)
#define MAPNIK_DO_PRAGMA(X)                                  _Pragma(#X)
#define MAPNIK_DISABLE_WARNING_PUSH                          MAPNIK_DO_PRAGMA(GCC diagnostic push)
#define MAPNIK_DISABLE_WARNING_POP                           MAPNIK_DO_PRAGMA(GCC diagnostic pop)
#define MAPNIK_DISABLE_WARNING(warningName)                  MAPNIK_DO_PRAGMA(GCC diagnostic ignored #warningName)
// add warnings to deactivate here
// example: #define DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER    DISABLE_WARNING(-Wunused-parameter)
#define MAPNIK_DISABLE_WARNING_UNKNOWN_PRAGMAS               MAPNIK_DISABLE_WARNING(-Wunknown - pragmas)
#define MAPNIK_DISABLE_WARNING_PRAGMAS                       MAPNIK_DISABLE_WARNING(-Wpragmas)
#define MAPNIK_DISABLE_WARNING_PRAGMA_MESSAGES               MAPNIK_DISABLE_WARNING(-W #pragma - messages)
#define MAPNIK_DISABLE_WARNING_UNSEQUENCED                   MAPNIK_DISABLE_WARNING(-Wunsequenced)
#define MAPNIK_DISABLE_WARNING_UNUSED_FUNCTION               MAPNIK_DISABLE_WARNING(-Wunused - function)
#define MAPNIK_DISABLE_WARNING_UNUSED_PARAMETER              MAPNIK_DISABLE_WARNING(-Wunused - parameter)
#define MAPNIK_DISABLE_WARNING_REDECLARED_CLASS_MEMBER       MAPNIK_DISABLE_WARNING(-Wredeclared - class - member)
#define MAPNIK_DISABLE_WARNING_UNUSED_LOCAL_TYPEDEF          MAPNIK_DISABLE_WARNING(-Wunused - local - typedef)
#define MAPNIK_DISABLE_WARNING_UNUSED_LOCAL_TYPEDEFS         MAPNIK_DISABLE_WARNING(-Wunused - local - typedefs)
#define MAPNIK_DISABLE_WARNING_SHADOW                        MAPNIK_DISABLE_WARNING(-Wshadow)
#define MAPNIK_DISABLE_WARNING_CPP11_NARROWING               MAPNIK_DISABLE_WARNING(-Wc++ 11 - narrowing)
#define MAPNIK_DISABLE_WARNING_SIGN_CONVERSION               MAPNIK_DISABLE_WARNING(-Wsign - conversion)
#define MAPNIK_DISABLE_WARNING_SIGN_COMPARE                  MAPNIK_DISABLE_WARNING(-Wsign - compare)
#define MAPNIK_DISABLE_WARNING_CONVERSION                    MAPNIK_DISABLE_WARNING(-Wconversion)
#define MAPNIK_DISABLE_WARNING_CPP_98_COMPAT_PEDANTIC        MAPNIK_DISABLE_WARNING(-Wc++ 98 - compat - pedantic)
#define MAPNIK_DISABLE_WARNING_DISABLE_MACRO_EXPANSION       MAPNIK_DISABLE_WARNING(-Wdisabled - macro - expansion)
#define MAPNIK_DISABLE_WARNING_OLD_STYLE_CAST                MAPNIK_DISABLE_WARNING(-Wold - style - cast)
#define MAPNIK_DISABLE_WARNING_DOCUMENTATION                 MAPNIK_DISABLE_WARNING(-Wdocumentation)
#define MAPNIK_DISABLE_WARNING_DOCUMENTATION_UNKNOWN_COMMAND MAPNIK_DISABLE_WARNING(-Wdocumentation - unknown - command)
#define MAPNIK_DISABLE_WARNING_UNDEF                         MAPNIK_DISABLE_WARNING(-Wundef)
#define MAPNIK_DISABLE_WARNING_DEPRECATED                    MAPNIK_DISABLE_WARNING(-Wdeprecated)
#define MAPNIK_DISABLE_WARNING_PADDED                        MAPNIK_DISABLE_WARNING(-Wpadded)
#define MAPNIK_DISABLE_WARNING_CPP_98_COMPAT                 MAPNIK_DISABLE_WARNING(-Wc++ 98 - compat)
#define MAPNIK_DISABLE_WARNING_RESERVED_ID_MACRO             MAPNIK_DISABLE_WARNING(-Wreserved - id - macro)
#define MAPNIK_DISABLE_WARNING_WEAK_VTABLE                   MAPNIK_DISABLE_WARNING(-Wweak - vtables)
#define MAPNIK_DISABLE_WARNING_EXTRA_SEMI                    MAPNIK_DISABLE_WARNING(-Wextra - semi)
#define MAPNIK_DISABLE_WARNING_GLOBAL_CONSTRUCTORS           MAPNIK_DISABLE_WARNING(-Wglobal - constructors)
#define MAPNIK_DISABLE_WARNING_HEADER_HYGIENE                MAPNIK_DISABLE_WARNING(-Wheader - hygiene)
#define MAPNIK_DISABLE_WARNING_EXIT_TIME_DESTRUCTORS         MAPNIK_DISABLE_WARNING(-Wexit - time - destructors)
#define MAPNIK_DISABLE_WARNING_SWITCH_ENUM                   MAPNIK_DISABLE_WARNING(-Wswitch - enum)
#define MAPNIK_DISABLE_WARNING_MISSING_NORETURN              MAPNIK_DISABLE_WARNING(-Wmissing - noreturn)
#define MAPNIK_DISABLE_WARNING_COVERED_SWITCH_DEFAULT        MAPNIK_DISABLE_WARNING(-Wcovered - switch - default)
#define MAPNIK_DISABLE_WARNING_FLOAT_EQUAL                   MAPNIK_DISABLE_WARNING(-Wfloat - equal)
#define MAPNIK_DISABLE_LONG_LONG                             MAPNIK_DISABLE_WARNING(-Wlong - long)
#define MAPNIK_DISABLE_UNDEFINED_VAR_TEMPLATE                MAPNIK_DISABLE_WARNING(-Wundefined - var - template)
#define MAPNIK_DISABLE_UNUSED_VARIABLE                       MAPNIK_DISABLE_WARNING(-Wunused - variable)
#define MAPNIK_DISABLE_MISMATCHED_TAGS                       MAPNIK_DISABLE_WARNING(-Wmismatched - tags)
#else
#define MAPNIK_DISABLE_WARNING_PUSH
#define MAPNIK_DISABLE_WARNING_POP
// add all of the above warnings here (will be used if unknown compiler)
#define MAPNIK_DISABLE_WARNING_UNKNOWN_PRAGMAS
#define MAPNIK_DISABLE_WARNING_PRAGMAS
#define MAPNIK_DISABLE_WARNING_PRAGMA_MESSAGES
#define MAPNIK_DISABLE_WARNING_UNSEQUENCED
#define MAPNIK_DISABLE_WARNING_UNUSED_FUNCTION
#define MAPNIK_DISABLE_WARNING_UNUSED_PARAMETER
#define MAPNIK_DISABLE_WARNING_REDECLARED_CLASS_MEMBER
#define MAPNIK_DISABLE_WARNING_UNUSED_LOCAL_TYPEDEF
#define MAPNIK_DISABLE_WARNING_UNUSED_LOCAL_TYPEDEFS
#define MAPNIK_DISABLE_WARNING_SHADOW
#define MAPNIK_DISABLE_WARNING_CPP11_NARROWING
#define MAPNIK_DISABLE_WARNING_SIGN_CONVERSION
#define MAPNIK_DISABLE_WARNING_SIGN_COMPARE
#define MAPNIK_DISABLE_WARNING_CONVERSION
#define MAPNIK_DISABLE_WARNING_CPP_98_COMPAT_PEDANTIC
#define MAPNIK_DISABLE_WARNING_DISABLE_MACRO_EXPANSION
#define MAPNIK_DISABLE_WARNING_OLD_STYLE_CAST
#define MAPNIK_DISABLE_WARNING_DOCUMENTATION
#define MAPNIK_DISABLE_WARNING_DOCUMENTATION_UNKNOWN_COMMAND
#define MAPNIK_DISABLE_WARNING_UNDEF
#define MAPNIK_DISABLE_WARNING_DEPRECATED
#define MAPNIK_DISABLE_WARNING_PADDED
#define MAPNIK_DISABLE_WARNING_CPP_98_COMPAT
#define MAPNIK_DISABLE_WARNING_RESERVED_ID_MACRO
#define MAPNIK_DISABLE_WARNING_WEAK_VTABLE
#define MAPNIK_DISABLE_WARNING_EXTRA_SEMI
#define MAPNIK_DISABLE_WARNING_GLOBAL_CONSTRUCTORS
#define MAPNIK_DISABLE_WARNING_HEADER_HYGIENE
#define MAPNIK_DISABLE_WARNING_EXIT_TIME_DESTRUCTORS
#define MAPNIK_DISABLE_WARNING_SWITCH_ENUM
#define MAPNIK_DISABLE_WARNING_MISSING_NORETURN
#define MAPNIK_DISABLE_WARNING_COVERED_SWITCH_DEFAULT
#define MAPNIK_DISABLE_WARNING_FLOAT_EQUAL
#define MAPNIK_DISABLE_LONG_LONG
#define MAPNIK_DISABLE_UNDEFINED_VAR_TEMPLATE
#define MAPNIK_DISABLE_UNUSED_VARIABLE
#define MAPNIK_DISABLE_MISMATCHED_TAGS
#endif
#endif<commit_msg>fix formatting of warning.hpp<commit_after>#ifndef MAPNIK_WARNING_HPP
#define MAPNIK_WARNING_HPP
// clang-format off
#if defined(_MSC_VER)
    #define MAPNIK_DISABLE_WARNING_PUSH           __pragma(warning( push ))
    #define MAPNIK_DISABLE_WARNING_POP            __pragma(warning( pop ))
    #define MAPNIK_DISABLE_WARNING(warningNumber) __pragma(warning( disable : warningNumber ))

    // add warnings to deactivate here
    // example: #define DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER    DISABLE_WARNING(4100)
    #define MAPNIK_DISABLE_WARNING_UNKNOWN_PRAGMAS         MAPNIK_DISABLE_WARNING(4068)
    #define MAPNIK_DISABLE_WARNING_PRAGMAS                 //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_PRAGMA_MESSAGES         //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_UNSEQUENCED             //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_UNUSED_FUNCTION         //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_UNUSED_PARAMETER        //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_REDECLARED_CLASS_MEMBER //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_UNUSED_LOCAL_TYPEDEF    //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_UNUSED_LOCAL_TYPEDEFS   //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_SHADOW                  //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_CPP11_NARROWING         //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_SIGN_CONVERSION         //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_SIGN_COMPARE            //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_CONVERSION              MAPNIK_DISABLE_WARNING(4244)
    #define MAPNIK_DISABLE_WARNING_CPP_98_COMPAT_PEDANTIC  //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_DISABLE_MACRO_EXPANSION //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_OLD_STYLE_CAST          //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_DOCUMENTATION           //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_DOCUMENTATION_UNKNOWN_COMMAND //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_UNDEF                   //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_DEPRECATED              MAPNIK_DISABLE_WARNING(4996)
    #define MAPNIK_DISABLE_WARNING_PADDED                  //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_CPP_98_COMPAT           //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_RESERVED_ID_MACRO       //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_WEAK_VTABLE             //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_EXTRA_SEMI              //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_GLOBAL_CONSTRUCTORS     //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_HEADER_HYGIENE          //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_EXIT_TIME_DESTRUCTORS   //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_SWITCH_ENUM             //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_MISSING_NORETURN        //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_COVERED_SWITCH_DEFAULT  //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_WARNING_FLOAT_EQUAL             //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_LONG_LONG                       //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_UNDEFINED_VAR_TEMPLATE          //MAPNIK_DISABLE_WARNING(??)
    #define MAPNIK_DISABLE_UNUSED_VARIABLE                 MAPNIK_DISABLE_WARNING(4101)
    #define MAPNIK_DISABLE_MISMATCHED_TAGS                 //MAPNIK_DISABLE_WARNING(??)

#elif defined(__GNUC__) || defined(__clang__)
    #define MAPNIK_DO_PRAGMA(X) _Pragma(#X)
    #define MAPNIK_DISABLE_WARNING_PUSH           MAPNIK_DO_PRAGMA(GCC diagnostic push)
    #define MAPNIK_DISABLE_WARNING_POP            MAPNIK_DO_PRAGMA(GCC diagnostic pop)
    #define MAPNIK_DISABLE_WARNING(warningName)   MAPNIK_DO_PRAGMA(GCC diagnostic ignored #warningName)
   // add warnings to deactivate here
   // example: #define DISABLE_WARNING_UNREFERENCED_FORMAL_PARAMETER    DISABLE_WARNING(-Wunused-parameter)
    #define MAPNIK_DISABLE_WARNING_UNKNOWN_PRAGMAS         MAPNIK_DISABLE_WARNING(-Wunknown-pragmas)
    #define MAPNIK_DISABLE_WARNING_PRAGMAS                 MAPNIK_DISABLE_WARNING(-Wpragmas)
    #define MAPNIK_DISABLE_WARNING_PRAGMA_MESSAGES         MAPNIK_DISABLE_WARNING(-W#pragma-messages)
    #define MAPNIK_DISABLE_WARNING_UNSEQUENCED             MAPNIK_DISABLE_WARNING(-Wunsequenced)
    #define MAPNIK_DISABLE_WARNING_UNUSED_FUNCTION         MAPNIK_DISABLE_WARNING(-Wunused-function)
    #define MAPNIK_DISABLE_WARNING_UNUSED_PARAMETER        MAPNIK_DISABLE_WARNING(-Wunused-parameter)
    #define MAPNIK_DISABLE_WARNING_REDECLARED_CLASS_MEMBER MAPNIK_DISABLE_WARNING(-Wredeclared-class-member)
    #define MAPNIK_DISABLE_WARNING_UNUSED_LOCAL_TYPEDEF    MAPNIK_DISABLE_WARNING(-Wunused-local-typedef)
    #define MAPNIK_DISABLE_WARNING_UNUSED_LOCAL_TYPEDEFS   MAPNIK_DISABLE_WARNING(-Wunused-local-typedefs)
    #define MAPNIK_DISABLE_WARNING_SHADOW                  MAPNIK_DISABLE_WARNING(-Wshadow)
    #define MAPNIK_DISABLE_WARNING_CPP11_NARROWING         MAPNIK_DISABLE_WARNING(-Wc++11-narrowing)
    #define MAPNIK_DISABLE_WARNING_SIGN_CONVERSION         MAPNIK_DISABLE_WARNING(-Wsign-conversion)
    #define MAPNIK_DISABLE_WARNING_SIGN_COMPARE            MAPNIK_DISABLE_WARNING(-Wsign-compare)
    #define MAPNIK_DISABLE_WARNING_CONVERSION              MAPNIK_DISABLE_WARNING(-Wconversion)
    #define MAPNIK_DISABLE_WARNING_CPP_98_COMPAT_PEDANTIC  MAPNIK_DISABLE_WARNING(-Wc++98-compat-pedantic)
    #define MAPNIK_DISABLE_WARNING_DISABLE_MACRO_EXPANSION MAPNIK_DISABLE_WARNING(-Wdisabled-macro-expansion)
    #define MAPNIK_DISABLE_WARNING_OLD_STYLE_CAST          MAPNIK_DISABLE_WARNING(-Wold-style-cast)
    #define MAPNIK_DISABLE_WARNING_DOCUMENTATION           MAPNIK_DISABLE_WARNING(-Wdocumentation)
    #define MAPNIK_DISABLE_WARNING_DOCUMENTATION_UNKNOWN_COMMAND MAPNIK_DISABLE_WARNING(-Wdocumentation-unknown-command)
    #define MAPNIK_DISABLE_WARNING_UNDEF                   MAPNIK_DISABLE_WARNING(-Wundef)
    #define MAPNIK_DISABLE_WARNING_DEPRECATED              MAPNIK_DISABLE_WARNING(-Wdeprecated)
    #define MAPNIK_DISABLE_WARNING_PADDED                  MAPNIK_DISABLE_WARNING(-Wpadded)
    #define MAPNIK_DISABLE_WARNING_CPP_98_COMPAT           MAPNIK_DISABLE_WARNING(-Wc++98-compat)
    #define MAPNIK_DISABLE_WARNING_RESERVED_ID_MACRO       MAPNIK_DISABLE_WARNING(-Wreserved-id-macro)
    #define MAPNIK_DISABLE_WARNING_WEAK_VTABLE             MAPNIK_DISABLE_WARNING(-Wweak-vtables)
    #define MAPNIK_DISABLE_WARNING_EXTRA_SEMI              MAPNIK_DISABLE_WARNING(-Wextra-semi)
    #define MAPNIK_DISABLE_WARNING_GLOBAL_CONSTRUCTORS     MAPNIK_DISABLE_WARNING(-Wglobal-constructors)
    #define MAPNIK_DISABLE_WARNING_HEADER_HYGIENE          MAPNIK_DISABLE_WARNING(-Wheader-hygiene)
    #define MAPNIK_DISABLE_WARNING_EXIT_TIME_DESTRUCTORS   MAPNIK_DISABLE_WARNING(-Wexit-time-destructors)
    #define MAPNIK_DISABLE_WARNING_SWITCH_ENUM             MAPNIK_DISABLE_WARNING(-Wswitch-enum)
    #define MAPNIK_DISABLE_WARNING_MISSING_NORETURN        MAPNIK_DISABLE_WARNING(-Wmissing-noreturn)
    #define MAPNIK_DISABLE_WARNING_COVERED_SWITCH_DEFAULT  MAPNIK_DISABLE_WARNING(-Wcovered-switch-default)
    #define MAPNIK_DISABLE_WARNING_FLOAT_EQUAL             MAPNIK_DISABLE_WARNING(-Wfloat-equal)
    #define MAPNIK_DISABLE_LONG_LONG                       MAPNIK_DISABLE_WARNING(-Wlong-long)
    #define MAPNIK_DISABLE_UNDEFINED_VAR_TEMPLATE          MAPNIK_DISABLE_WARNING(-Wundefined-var-template)
    #define MAPNIK_DISABLE_UNUSED_VARIABLE                 MAPNIK_DISABLE_WARNING(-Wunused-variable)
    #define MAPNIK_DISABLE_MISMATCHED_TAGS                 MAPNIK_DISABLE_WARNING(-Wmismatched-tags)
#else
    #define MAPNIK_DISABLE_WARNING_PUSH
    #define MAPNIK_DISABLE_WARNING_POP
    // add all of the above warnings here (will be used if unknown compiler)
    #define MAPNIK_DISABLE_WARNING_UNKNOWN_PRAGMAS
    #define MAPNIK_DISABLE_WARNING_PRAGMAS
    #define MAPNIK_DISABLE_WARNING_PRAGMA_MESSAGES
    #define MAPNIK_DISABLE_WARNING_UNSEQUENCED
    #define MAPNIK_DISABLE_WARNING_UNUSED_FUNCTION
    #define MAPNIK_DISABLE_WARNING_UNUSED_PARAMETER
    #define MAPNIK_DISABLE_WARNING_REDECLARED_CLASS_MEMBER
    #define MAPNIK_DISABLE_WARNING_UNUSED_LOCAL_TYPEDEF
    #define MAPNIK_DISABLE_WARNING_UNUSED_LOCAL_TYPEDEFS
    #define MAPNIK_DISABLE_WARNING_SHADOW
    #define MAPNIK_DISABLE_WARNING_CPP11_NARROWING
    #define MAPNIK_DISABLE_WARNING_SIGN_CONVERSION
    #define MAPNIK_DISABLE_WARNING_SIGN_COMPARE
    #define MAPNIK_DISABLE_WARNING_CONVERSION
    #define MAPNIK_DISABLE_WARNING_CPP_98_COMPAT_PEDANTIC
    #define MAPNIK_DISABLE_WARNING_DISABLE_MACRO_EXPANSION
    #define MAPNIK_DISABLE_WARNING_OLD_STYLE_CAST
    #define MAPNIK_DISABLE_WARNING_DOCUMENTATION
    #define MAPNIK_DISABLE_WARNING_DOCUMENTATION_UNKNOWN_COMMAND
    #define MAPNIK_DISABLE_WARNING_UNDEF
    #define MAPNIK_DISABLE_WARNING_DEPRECATED
    #define MAPNIK_DISABLE_WARNING_PADDED
    #define MAPNIK_DISABLE_WARNING_CPP_98_COMPAT
    #define MAPNIK_DISABLE_WARNING_RESERVED_ID_MACRO
    #define MAPNIK_DISABLE_WARNING_WEAK_VTABLE
    #define MAPNIK_DISABLE_WARNING_EXTRA_SEMI
    #define MAPNIK_DISABLE_WARNING_GLOBAL_CONSTRUCTORS
    #define MAPNIK_DISABLE_WARNING_HEADER_HYGIENE
    #define MAPNIK_DISABLE_WARNING_EXIT_TIME_DESTRUCTORS
    #define MAPNIK_DISABLE_WARNING_SWITCH_ENUM
    #define MAPNIK_DISABLE_WARNING_MISSING_NORETURN
    #define MAPNIK_DISABLE_WARNING_COVERED_SWITCH_DEFAULT
    #define MAPNIK_DISABLE_WARNING_FLOAT_EQUAL
    #define MAPNIK_DISABLE_LONG_LONG
    #define MAPNIK_DISABLE_UNDEFINED_VAR_TEMPLATE
    #define MAPNIK_DISABLE_UNUSED_VARIABLE
    #define MAPNIK_DISABLE_MISMATCHED_TAGS
#endif
// clang-format on
#endif
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009-2010, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#ifndef __OPENCV_ALL_HPP__
#define __OPENCV_ALL_HPP__

#include "opencv2/opencv_modules.hpp"

#include "opencv2/core.hpp"
#ifdef HAVE_OPENCV_IMGPROC
#include "opencv2/imgproc.hpp"
#endif
#ifdef HAVE_OPENCV_PHOTO
#include "opencv2/photo.hpp"
#endif
#ifdef HAVE_OPENCV_VIDEO
#include "opencv2/video.hpp"
#endif
#ifdef HAVE_OPENCV_FEATURES2D
#include "opencv2/features2d.hpp"
#endif
#ifdef HAVE_OPENCV_OBJDETECT
#include "opencv2/objdetect.hpp"
#endif
#ifdef HAVE_OPENCV_CALIB3D
#include "opencv2/calib3d.hpp"
#endif
#ifdef HAVE_OPENCV_IMGCODECS
#include "opencv2/imgcodecs.hpp"
#endif
#ifdef HAVE_OPENCV_VIDEOIO
#include "opencv2/videoio.hpp"
#endif
#ifdef HAVE_OPENCV_HIGHGUI
#include "opencv2/highgui.hpp"
#endif
#ifdef HAVE_OPENCV_ML
#include "opencv2/ml.hpp"
#endif

#endif
<commit_msg>fix including of correct header files #7027<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009-2010, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#ifndef __OPENCV_ALL_HPP__
#define __OPENCV_ALL_HPP__

// File that defines what modules where included during the build of OpenCV
// These are purely the defines of the correct HAVE_OPENCV_modulename values
#include "opencv2/opencv_modules.hpp"

// Then the list of defines is checked to include the correct headers
// Core library is always included --> without no OpenCV functionality available
#include "opencv2/core.hpp"

// Then the optional modules are checked
// REMARK: keep the includes ordened as the module order on the GitHub repo
#ifdef HAVE_OPENCV_CALIB3D
#include "opencv2/calib3d.hpp"
#endif
#ifdef HAVE_OPENCV_CUDAARITHM
#include "opencv2/cudaarithm.hpp"
#endif
#ifdef HAVE_OPENCV_CUDABGSEGM
#include "opencv2/cudabgsegm.hpp"
#endif
#ifdef HAVE_OPENCV_CUDACODEC
#include "opencv2/cudacodec.hpp"
#endif
#ifdef HAVE_OPENCV_CUDAFEATURES2D
#include "opencv2/cudafeatures2d.hpp"
#endif
#ifdef HAVE_OPENCV_CUDAFILTERS
#include "opencv2/cudafilters.hpp"
#endif
#ifdef HAVE_OPENCV_CUDAIMGPROC
#include "opencv2/cudaimgproc.hpp"
#endif
#ifdef HAVE_OPENCV_CUDALEGACY
#include "opencv2/cudalegacy.hpp"
#endif
#ifdef HAVE_OPENCV_CUDAOBJDETECT
#include "opencv2/cudaobjdetect.hpp"
#endif
#ifdef HAVE_OPENCV_CUDAOPTFLOW
#include "opencv2/cudaoptflow.hpp"
#endif
#ifdef HAVE_OPENCV_CUDASTEREO
#include "opencv2/cudastereo.hpp"
#endif
#ifdef HAVE_OPENCV_CUDAWARPING
#include "opencv2/cudawarping.hpp"
#endif
#ifdef HAVE_OPENCV_CUDEV
#include "opencv2/cudev.hpp"
#endif
#ifdef HAVE_OPENCV_FEATURES2D
#include "opencv2/features2d.hpp"
#endif
#ifdef HAVE_OPENCV_FLANN
#include "opencv2/flann.hpp"
#endif
#ifdef HAVE_OPENCV_HIGHGUI
#include "opencv2/highgui.hpp"
#endif
#ifdef HAVE_OPENCV_IMGCODECS
#include "opencv2/imgcodecs.hpp"
#endif
#ifdef HAVE_OPENCV_IMGPROC
#include "opencv2/imgproc.hpp"
#endif
#ifdef HAVE_OPENCV_ML
#include "opencv2/ml.hpp"
#endif
#ifdef HAVE_OPENCV_OBJDETECT
#include "opencv2/objdetect.hpp"
#endif
#ifdef HAVE_OPENCV_PHOTO
#include "opencv2/photo.hpp"
#endif
#ifdef HAVE_OPENCV_SHAPE
#include "opencv2/shape.hpp"
#endif
#ifdef HAVE_OPENCV_STITCHING
#include "opencv2/stitching.hpp"
#endif
#ifdef HAVE_OPENCV_SUPERRES
#include "opencv2/superres.hpp"
#endif
#ifdef HAVE_OPENCV_VIDEO
#include "opencv2/video.hpp"
#endif
#ifdef HAVE_OPENCV_VIDEOIO
#include "opencv2/videoio.hpp"
#endif
#ifdef HAVE_OPENCV_VIDEOSTAB
#include "opencv2/videostab.hpp"
#endif
#ifdef HAVE_OPENCV_VIZ
#include "opencv2/viz.hpp"
#endif

#endif
<|endoftext|>


<commit_before>#ifndef INCLUDE_AL_TIME_HPP
#define INCLUDE_AL_TIME_HPP

/*
 *  AlloSphere Research Group / Media Arts & Technology, UCSB, 2009
 */

/*
	Copyright (C) 2006-2008. The Regents of the University of California (REGENTS).
	All Rights Reserved.

	Permission to use, copy, modify, distribute, and distribute modified versions
	of this software and its documentation without fee and without a signed
	licensing agreement, is hereby granted, provided that the above copyright
	notice, the list of contributors, this paragraph and the following two paragraphs
	appear in all copies, modifications, and distributions.

	IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
	SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
	OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
	BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

	REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
	THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
	PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
	HEREUNDER IS PROVIDED "AS IS". REGENTS HAS  NO OBLIGATION TO PROVIDE
	MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/

/*
	C++ helper wrapeprs for al_time
*/

#include "system/al_Time.h"

namespace al{

/// Sleep for an interval of seconds
void wait(al_sec dt){ al_sleep(dt); }

/// Timer with stopwatch-like functionality for benchmarking, etc.
class Timer {
public:
	Timer(): mStart(0), mStop(0){}

	al_nsec elapsed(){ return mStop - mStart; }					///< Returns nsec between start() and stop() calls
	al_sec elapsedSec(){ return al_time_ns2s * elapsed(); }		///< Returns  sec between start() and stop() calls
	void start(){ mStart=al_time_nsec(); }							///< Set start time as current time
	void stop(){ mStop=al_time_nsec(); }								///< Set stop time as current time

private:
	al_nsec mStart, mStop;	// start and stop times
};

/*
	Helper object for events intended to run at a particular rate/period,
		but which might be subject to drift, latency and jitter.
	A curve mapping logical to real time can be drawn over an event period
		by interpolating between t0 and t1
	@see http://www.kokkinizita.net/papers/usingdll.pdf
*/
class DelayLockedLoop {
public:

	DelayLockedLoop(al_sec step_period, double bandwidth = 0.5) {
		tperiod = step_period;
		setBandwidth(bandwidth);
		mReset = true;
	}

	// degree of smoothing
	void setBandwidth(double bandwidth);

	// call this after an xrun: will reset the timing adjustments
	void reset() { mReset = true; }

	// trigger this from the periodic event
	// realtime is the source time that we are trying to smoothly follow
	void step(al_sec realtime);

	// retrieve the current period/rate estimation (smoothed)
	al_sec period_smoothed() const { return t2; }
	al_sec rate_smoothed() const { return 1./t2; }
	// retrieve the ideal period/rate
	al_sec period_ideal() const { return tperiod; }
	al_sec rate_ideal() const { return 1./tperiod; }

	// returns an estimate of corresponding real-time between current event & next
	// by linear interpolation of current event timestamp & projected next event timestamp
	al_sec realtime_interp(double alpha) const { return t0 + alpha*(t1-t0); }

protected:
	al_sec tperiod;	// event period in seconds
	al_sec t0;		// 0th-order component: timestamp of the current event
	al_sec t1;		// 1st-order component: ideally the timestamp of the next event
	al_sec t2;		// 2nd-order component (akin to acceleration, or smoothed event period)
	double mB, mC;	// 1st & 2nd order weights
	bool mReset;
};

} // al::

#endif /* INCLUDE_AL_TIME_CPP_H */

<commit_msg>inlined al::wait()<commit_after>#ifndef INCLUDE_AL_TIME_HPP
#define INCLUDE_AL_TIME_HPP

/*
 *  AlloSphere Research Group / Media Arts & Technology, UCSB, 2009
 */

/*
	Copyright (C) 2006-2008. The Regents of the University of California (REGENTS).
	All Rights Reserved.

	Permission to use, copy, modify, distribute, and distribute modified versions
	of this software and its documentation without fee and without a signed
	licensing agreement, is hereby granted, provided that the above copyright
	notice, the list of contributors, this paragraph and the following two paragraphs
	appear in all copies, modifications, and distributions.

	IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
	SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING
	OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS
	BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

	REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
	THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
	PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED
	HEREUNDER IS PROVIDED "AS IS". REGENTS HAS  NO OBLIGATION TO PROVIDE
	MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/

/*
	C++ helper wrapeprs for al_time
*/

#include "system/al_Time.h"

namespace al{

/// Sleep for an interval of seconds
inline void wait(al_sec dt){ al_sleep(dt); }

/// Timer with stopwatch-like functionality for benchmarking, etc.
class Timer {
public:
	Timer(): mStart(0), mStop(0){}

	al_nsec elapsed(){ return mStop - mStart; }					///< Returns nsec between start() and stop() calls
	al_sec elapsedSec(){ return al_time_ns2s * elapsed(); }		///< Returns  sec between start() and stop() calls
	void start(){ mStart=al_time_nsec(); }							///< Set start time as current time
	void stop(){ mStop=al_time_nsec(); }								///< Set stop time as current time

private:
	al_nsec mStart, mStop;	// start and stop times
};

/*
	Helper object for events intended to run at a particular rate/period,
		but which might be subject to drift, latency and jitter.
	A curve mapping logical to real time can be drawn over an event period
		by interpolating between t0 and t1
	@see http://www.kokkinizita.net/papers/usingdll.pdf
*/
class DelayLockedLoop {
public:

	DelayLockedLoop(al_sec step_period, double bandwidth = 0.5) {
		tperiod = step_period;
		setBandwidth(bandwidth);
		mReset = true;
	}

	// degree of smoothing
	void setBandwidth(double bandwidth);

	// call this after an xrun: will reset the timing adjustments
	void reset() { mReset = true; }

	// trigger this from the periodic event
	// realtime is the source time that we are trying to smoothly follow
	void step(al_sec realtime);

	// retrieve the current period/rate estimation (smoothed)
	al_sec period_smoothed() const { return t2; }
	al_sec rate_smoothed() const { return 1./t2; }
	// retrieve the ideal period/rate
	al_sec period_ideal() const { return tperiod; }
	al_sec rate_ideal() const { return 1./tperiod; }

	// returns an estimate of corresponding real-time between current event & next
	// by linear interpolation of current event timestamp & projected next event timestamp
	al_sec realtime_interp(double alpha) const { return t0 + alpha*(t1-t0); }

protected:
	al_sec tperiod;	// event period in seconds
	al_sec t0;		// 0th-order component: timestamp of the current event
	al_sec t1;		// 1st-order component: ideally the timestamp of the next event
	al_sec t2;		// 2nd-order component (akin to acceleration, or smoothed event period)
	double mB, mC;	// 1st & 2nd order weights
	bool mReset;
};

} // al::

#endif /* INCLUDE_AL_TIME_CPP_H */

<|endoftext|>


<commit_before>#ifndef LOSSY_COUNTING_MODEL_H
#define LOSSY_COUNTING_MODEL_H

#include <iostream>
#include <map>
#include <unordered_map>
#include <vector>
#include <algorithm>

/**
 * Lossy Counting Model implemenation for processing a
 * data stream according to the following constraints:
 * - Single Pass
 * - Limited memory
 * - Volume of data in real-time
 */
template<typename T>
class LossyCountingModel {
public:
  /**
   * holds a LCM Model state
   */
  struct State {
    double    f; /// frequency
    double    e; /// error
    unsigned long      w; /// window size
    unsigned long long N; /// stream length
  };

private:
  using histogram_type = typename std::unordered_map<T,int>;

  double              _frequency;
  double              _error;
  unsigned long       _window_size;
  unsigned long long  _total_processed_elements = 0;
  histogram_type      _histogram;

public:
  /**
   * Setup a Lossy Counting Model with sampling
   * frequency and error.
   */
  LossyCountingModel(double frequency, double error):
    _frequency(frequency),
    _error(error),
    _window_size(1.0 / error)
  { }

  /**
   * process a single item of the datastream
   * \return true if the sampling window was processed after this item,
   *         false otherwise
   */
  bool processItem(const T & e) noexcept {
    ++(_histogram[e]);
    ++_total_processed_elements;
    if((_total_processed_elements % _window_size) == (_window_size - 1))
    {
      _decreaseAllFrequencies();
      return true;
    }
    return false;
  }

  /**
   * Process N elements from begin iterator without copying it to a
   * temporary buffer. The caller is responsible for providing enough
   * elements
   */
  template<typename Iter>
  void processWindow(Iter it){
    for(unsigned int cnt = 0; cnt<_window_size; ++cnt){
      ++(_histogram[*it]);
      ++_total_processed_elements;
      ++it;
    }
    _decreaseAllFrequencies();
  }

  /**
   * returns the final histogram containing only elements
   * with count exceeding fN - eN. The type of the container
   * the final histogram is stored in can be set using the
   * template parameter.
   */
  template<typename ContainerT = std::map<T,int>>
  ContainerT computeOutput() const noexcept {
    ContainerT result;

    const int threshold = (_frequency * _total_processed_elements) -
                    (_error * _total_processed_elements);

    std::copy_if(_histogram.begin(), _histogram.end(),
        std::inserter(result, result.end()),
        [&](const std::pair<T,int> & el){
          return el.second >= threshold;
          });
    return result;
  }

  State getState() const noexcept {
    return State{_frequency, _error, _window_size, _total_processed_elements};
  }

private:
  void _decreaseAllFrequencies(){
    auto it = _histogram.begin();
    while(it != _histogram.end()){
      if(it->second == 1){
        _histogram.erase(it++);
      } else {
        --(it->second);
        ++it;
      }
    }
  }
};
#endif

<commit_msg>removed useless includes<commit_after>#ifndef LOSSY_COUNTING_MODEL_H
#define LOSSY_COUNTING_MODEL_H

#include <map>
#include <unordered_map>
#include <vector>
#include <algorithm>

/**
 * Lossy Counting Model implemenation for processing a
 * data stream according to the following constraints:
 * - Single Pass
 * - Limited memory
 * - Volume of data in real-time
 */
template<typename T>
class LossyCountingModel {
public:
  /**
   * holds a LCM Model state
   */
  struct State {
    double    f; /// frequency
    double    e; /// error
    unsigned long      w; /// window size
    unsigned long long N; /// stream length
  };

private:
  using histogram_type = typename std::unordered_map<T,int>;

  double              _frequency;
  double              _error;
  unsigned long       _window_size;
  unsigned long long  _total_processed_elements = 0;
  histogram_type      _histogram;

public:
  /**
   * Setup a Lossy Counting Model with sampling
   * frequency and error.
   */
  LossyCountingModel(double frequency, double error):
    _frequency(frequency),
    _error(error),
    _window_size(1.0 / error)
  { }

  /**
   * process a single item of the datastream
   * \return true if the sampling window was processed after this item,
   *         false otherwise
   */
  bool processItem(const T & e) noexcept {
    ++(_histogram[e]);
    ++_total_processed_elements;
    if((_total_processed_elements % _window_size) == (_window_size - 1))
    {
      _decreaseAllFrequencies();
      return true;
    }
    return false;
  }

  /**
   * Process N elements from begin iterator without copying it to a
   * temporary buffer. The caller is responsible for providing enough
   * elements
   */
  template<typename Iter>
  void processWindow(Iter it){
    for(unsigned int cnt = 0; cnt<_window_size; ++cnt){
      ++(_histogram[*it]);
      ++_total_processed_elements;
      ++it;
    }
    _decreaseAllFrequencies();
  }

  /**
   * returns the final histogram containing only elements
   * with count exceeding fN - eN. The type of the container
   * the final histogram is stored in can be set using the
   * template parameter.
   */
  template<typename ContainerT = std::map<T,int>>
  ContainerT computeOutput() const noexcept {
    ContainerT result;

    const int threshold = (_frequency * _total_processed_elements) -
                    (_error * _total_processed_elements);

    std::copy_if(_histogram.begin(), _histogram.end(),
        std::inserter(result, result.end()),
        [&](const std::pair<T,int> & el){
          return el.second >= threshold;
          });
    return result;
  }

  State getState() const noexcept {
    return State{_frequency, _error, _window_size, _total_processed_elements};
  }

private:
  void _decreaseAllFrequencies(){
    auto it = _histogram.begin();
    while(it != _histogram.end()){
      if(it->second == 1){
        _histogram.erase(it++);
      } else {
        --(it->second);
        ++it;
      }
    }
  }
};
#endif

<|endoftext|>


<commit_before>/**
 * @author See Contributors.txt for code contributors and overview of BadgerDB.
 *
 * @section LICENSE
 * Copyright (c) 2012 Database Group, Computer Sciences Department, University of Wisconsin-Madison.
 */

#include <memory>
#include <iostream>
#include "buffer.h"
#include "exceptions/buffer_exceeded_exception.h"
#include "exceptions/page_not_pinned_exception.h"
#include "exceptions/page_pinned_exception.h"
#include "exceptions/bad_buffer_exception.h"
#include "exceptions/hash_not_found_exception.h"

namespace badgerdb {

//----------------------------------------
// Constructor of the class BufMgr
//----------------------------------------

BufMgr::BufMgr(std::uint32_t bufs)
	: numBufs(bufs) {
	bufDescTable = new BufDesc[bufs];

  for (FrameId i = 0; i < bufs; i++)
  {
  	bufDescTable[i].frameNo = i;
  	bufDescTable[i].valid = false;
  }

  bufPool = new Page[bufs];

  int htsize = ((((int) (bufs * 1.2))*2)/2)+1;
  hashTable = new BufHashTbl (htsize);  // allocate the buffer hash table

  clockHand = bufs - 1;
}

//flush all the frames and clear all memory
BufMgr::~BufMgr() {
}

void BufMgr::advanceClock()
{
    clockHand = (clockHand + 1) % numBufs;
}

//Implement the clock algorithm
//add a pinned count, if pinned count = numBufs, then throw exception
//run through each buf and check for validity following diagram.
void BufMgr::allocBuf(FrameId & frame)
{
    //track if a frame has been found
    bool frameFound = false;

    std::uint32_t pinnedCount = 0;

    //start loop, until frame is found. Only time it will leave loop is if frame is found
    //or bufferexceededexception occurs
    while(!frameFound && (pinnedCount < numBufs)){

        advanceClock();

        //found a buffer frame that can be used, exit loop
        if(!bufDescTable[clockHand].valid){

            frameFound = true;
            break;

        } //check the refbit, if it is false then frame is found and the entry in the hashtable needs to be removed
        else if(bufDescTable[clockHand].refbit){
            bufDescTable[clockHand].refbit = false;
            continue;
        } else if(bufDescTable[clockHand].pinCnt > 0) {
            pinnedCount++;
            continue;
        }else{

            if(bufDescTable[clockHand].dirty){
                bufDescTable[clockHand].file->writePage(bufPool[clockHand]);
            }
            frameFound = true;
            //remove the hashtable entry
            hashTable->remove(bufDescTable[clockHand].file, bufDescTable[clockHand].pageNo);
        }

    }
    //All pages are pinned
    if(pinnedCount == numBufs){
        throw BufferExceededException();
    } else {
        frame = clockHand;

        bufDescTable[clockHand].Clear();
    }

}

void BufMgr::readPage(File* file, const PageId pageNo, Page*& page)
{
    /*
    // check whether page is already in buffer pool with lookup(), throws HashNotFoundExc.
    try {
        hashTable->lookup(file, pageNo, file->readPage(pageNo));

        // no exception thrown, in hash table

        // set appropriate refbit
        bufDescTable[pageNo];

        // increment pin count

        // return pointer to frame containing the page via page parameter
    }
    catch (const HashNotFoundException& e) {
        // not in buffer pool

        // allocate buffer frame
        allocBuf(file->readPage(pageNo));

        // insert page into hash table
        hashTable->insert(file, pageNo, bufDescTable[pageNo].frameNo);
    }
     */

}

//set the frame that the page is allocated to
void BufMgr::unPinPage(File* file, const PageId pageNo, const bool dirty)
{

	//check hashtable for page
	try {
		hashTable->lookup(file, pageNo, bufDescTable->frameNo);
		//check if pin cnt is already set to 0. throw appropriate error
		if (bufDescTable[bufDescTable->frameNo].pinCnt == 0){
		throw PageNotPinnedException(file->filename(), pageNo, bufDescTable->frameNo);
		}
		//get dirtty

		bufDescTable[bufDescTable->frameNo].dirty = dirty;

		//decrement pin count
		bufDescTable[bufDescTable->frameNo].pinCnt--;

	}
	catch(const HashNotFoundException& e){

	}

}

void BufMgr::allocPage(File* file, PageId &pageNo, Page*& page)
{

	//allocate page and get buffer frame pool
	Page filePage = file->allocatePage();
	allocBuf(bufDescTable->frameNo);
	pageNo = filePage.page_number();

	//insert into hashtable then set frame
	hashTable->insert(file, pageNo, bufDescTable->frameNo);
	bufDescTable[bufDescTable->frameNo].Set(file, pageNo);
	bufPool[bufDescTable->frameNo] = filePage;
	//passs correct pointer
	page = &bufPool[bufDescTable->frameNo];

}

//
void BufMgr::flushFile(const File* file)
{

}

//
void BufMgr::disposePage(File* file, const PageId PageNo)
{

    // if allocated in buffer pool, free it
    try {
        hashTable->lookup(file, PageNo, bufDescTable->frameNo);
        // remove page from hash table
        hashTable->remove(file, PageNo);
    }
    catch (const HashNotFoundException& e) {
        // not in hash table, shouldn't need to do anything
    }

    file->deletePage(PageNo);
}

void BufMgr::printSelf(void)
{
  BufDesc* tmpbuf;
	int validFrames = 0;

  for (std::uint32_t i = 0; i < numBufs; i++)
	{
  	tmpbuf = &(bufDescTable[i]);
		std::cout << "FrameNo:" << i << " ";
		tmpbuf->Print();

  	if (tmpbuf->valid == true)
    	validFrames++;
  }

	std::cout << "Total Number of Valid Frames:" << validFrames << "\n";
}

}
<commit_msg>changed FrameNo implentaion<commit_after>/**
 * @author See Contributors.txt for code contributors and overview of BadgerDB.
 *
 * @section LICENSE
 * Copyright (c) 2012 Database Group, Computer Sciences Department, University of Wisconsin-Madison.
 */

#include <memory>
#include <iostream>
#include "buffer.h"
#include "exceptions/buffer_exceeded_exception.h"
#include "exceptions/page_not_pinned_exception.h"
#include "exceptions/page_pinned_exception.h"
#include "exceptions/bad_buffer_exception.h"
#include "exceptions/hash_not_found_exception.h"

namespace badgerdb {

//----------------------------------------
// Constructor of the class BufMgr
//----------------------------------------

BufMgr::BufMgr(std::uint32_t bufs)
	: numBufs(bufs) {
	bufDescTable = new BufDesc[bufs];

  for (FrameId i = 0; i < bufs; i++)
  {
  	bufDescTable[i].frameNo = i;
  	bufDescTable[i].valid = false;
  }

  bufPool = new Page[bufs];

  int htsize = ((((int) (bufs * 1.2))*2)/2)+1;
  hashTable = new BufHashTbl (htsize);  // allocate the buffer hash table

  clockHand = bufs - 1;
}

//flush all the frames and clear all memory
BufMgr::~BufMgr() {
}

void BufMgr::advanceClock()
{
    clockHand = (clockHand + 1) % numBufs;
}

//Implement the clock algorithm
//add a pinned count, if pinned count = numBufs, then throw exception
//run through each buf and check for validity following diagram.
void BufMgr::allocBuf(FrameId & frame)
{
    //track if a frame has been found
    bool frameFound = false;

    std::uint32_t pinnedCount = 0;

    //start loop, until frame is found. Only time it will leave loop is if frame is found
    //or bufferexceededexception occurs
    while(!frameFound && (pinnedCount < numBufs)){

        advanceClock();

        //found a buffer frame that can be used, exit loop
        if(!bufDescTable[clockHand].valid){

            frameFound = true;
            break;

        } //check the refbit, if it is false then frame is found and the entry in the hashtable needs to be removed
        else if(bufDescTable[clockHand].refbit){
            bufDescTable[clockHand].refbit = false;
            continue;
        } else if(bufDescTable[clockHand].pinCnt > 0) {
            pinnedCount++;
            continue;
        }else{

            if(bufDescTable[clockHand].dirty){
                bufDescTable[clockHand].file->writePage(bufPool[clockHand]);
            }
            frameFound = true;
            //remove the hashtable entry
            hashTable->remove(bufDescTable[clockHand].file, bufDescTable[clockHand].pageNo);
        }

    }
    //All pages are pinned
    if(pinnedCount == numBufs){
        throw BufferExceededException();
    } else {
        frame = clockHand;

        bufDescTable[clockHand].Clear();
    }

}

void BufMgr::readPage(File* file, const PageId pageNo, Page*& page)
{
    /*
    // check whether page is already in buffer pool with lookup(), throws HashNotFoundExc.
    try {
        hashTable->lookup(file, pageNo, file->readPage(pageNo));

        // no exception thrown, in hash table

        // set appropriate refbit
        bufDescTable[pageNo];

        // increment pin count

        // return pointer to frame containing the page via page parameter
    }
    catch (const HashNotFoundException& e) {
        // not in buffer pool

        // allocate buffer frame
        allocBuf(file->readPage(pageNo));

        // insert page into hash table
        hashTable->insert(file, pageNo, bufDescTable[pageNo].frameNo);
    }
     */

}

//set the frame that the page is allocated to
void BufMgr::unPinPage(File* file, const PageId pageNo, const bool dirty)
{
	FrameId frameNo = 0;
	//check hashtable for page
	try {
		hashTable->lookup(file, pageNo, frameNo);
		//check if pin cnt is already set to 0. throw appropriate error
		if (bufDescTable[frameNo].pinCnt == 0){
		throw PageNotPinnedException(file->filename(), pageNo, frameNo);
		}
		//get dirtty

		bufDescTable[frameNo].dirty = dirty;

		//decrement pin count
		bufDescTable[frameNo].pinCnt--;

	}
	catch(const HashNotFoundException& e){

	}

}

void BufMgr::allocPage(File* file, PageId &pageNo, Page*& page)
{
	FrameId frameNo = 0;
	//allocate page and get buffer frame pool
	Page filePage = file->allocatePage();
	allocBuf(frameNo);
	pageNo = filePage.page_number();

	//insert into hashtable then set frame
	hashTable->insert(file, pageNo, frameNo);
	bufDescTable[frameNo].Set(file, pageNo);
	bufPool[frameNo] = filePage;
	//passs correct pointer
	page = &bufPool[frameNo];

}

//
void BufMgr::flushFile(const File* file)
{

}

//
void BufMgr::disposePage(File* file, const PageId PageNo)
{
	FrameId frameNo = 0;
    // if allocated in buffer pool, free it
    try {
        hashTable->lookup(file, PageNo, frameNo);
        // remove page from hash table
        hashTable->remove(file, PageNo);
    }
    catch (const HashNotFoundException& e) {
        // not in hash table, shouldn't need to do anything
    }

    file->deletePage(PageNo);
}

void BufMgr::printSelf(void)
{
  BufDesc* tmpbuf;
	int validFrames = 0;

  for (std::uint32_t i = 0; i < numBufs; i++)
	{
  	tmpbuf = &(bufDescTable[i]);
		std::cout << "FrameNo:" << i << " ";
		tmpbuf->Print();

  	if (tmpbuf->valid == true)
    	validFrames++;
  }

	std::cout << "Total Number of Valid Frames:" << validFrames << "\n";
}

}
<|endoftext|>


<commit_before>/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/

#include <qi/assert.hpp>
#include <qi/buffer.hpp>
#include <qi/log.hpp>

#include <cstdio>
#include <cstring>
#include <stdexcept>
#include <iomanip>
#include <ctype.h>

#include <boost/pool/singleton_pool.hpp>
#include <boost/make_shared.hpp>

#include "buffer_p.hpp"

qiLogCategory("qi.Buffer");

namespace qi
{
  BufferPrivate::BufferPrivate() // cppcheck-suppress uninitMemberVar
    : _bigdata(0)
    , _cachedSubBufferTotalSize(0)
    , used(0)
    , available(sizeof(_data))
  {
  }

  BufferPrivate::~BufferPrivate()
  {
    if (_bigdata)
    {
      free(_bigdata);
      _bigdata = NULL;
    }
  }

  struct MyPoolTag { };
  using buffer_pool = boost::singleton_pool<MyPoolTag, sizeof(BufferPrivate)>;

  void* BufferPrivate::operator new(size_t sz)
  {
    QI_ASSERT(sz <= sizeof(BufferPrivate));
    return buffer_pool::malloc();
  }

  void BufferPrivate::operator delete(void* ptr)
  {
    buffer_pool::free(ptr);
  }

  int BufferPrivate::indexOfSubBuffer(size_t offset) const
  {
    for(unsigned i = 0; i < _subBuffers.size(); ++i) {
      if (_subBuffers[i].first == offset) {
        return i;
      }
    }

    return -1;
  }

  Buffer::Buffer()
    : _p(boost::make_shared<BufferPrivate>())
  {
  }

  Buffer::Buffer(const Buffer& b)
  {
    (*this) = b;
  }

  Buffer& Buffer::operator=(const Buffer& b)
  {
    _p = b._p;
    return *this;
  }

  Buffer::Buffer(Buffer&& b)
    : _p(std::move(b._p))
  {
    // The default state of a qi::Buffer contains a valid BufferPrivate pointer.
    b._p = boost::make_shared<BufferPrivate>();
  }

  Buffer& Buffer::operator=(Buffer&& b)
  {
    _p = std::move(b._p);
    b._p = boost::make_shared<BufferPrivate>();
    return *this;
  }

  unsigned char* BufferPrivate::data()
  {
    if (_bigdata)
      return (_bigdata);

    return (_data);
  }

  bool BufferPrivate::resize(size_t neededSize)
  {
    neededSize += BLOCK; // Should be enough in most cases;

    qiLogDebug() << "Resizing buffer from " << available << " to " << neededSize;
    unsigned char *newBigdata;

    newBigdata = static_cast<unsigned char *>(realloc(_bigdata, neededSize));
    if (newBigdata == NULL)
      return false;
    if (!_bigdata && used > 0)
      ::memcpy(newBigdata, _data, used);
    available = neededSize;
    _bigdata = newBigdata; // Don't worry, realloc free previous buffer if needed
    return true;
  }

  bool Buffer::write(const void *data, size_t size)
  {
    if (_p->used + size > _p->available)
    {
      bool ret = _p->resize(_p->used + size);
      if (!ret) {
        qiLogVerbose() << "write(" << size << ") failed, buffer size is " << _p->available;
        return false;
      }
    }

    memcpy(_p->data() + _p->used, data, size);
    _p->used += size;

    return true;
  }

  size_t Buffer::addSubBuffer(const Buffer& buffer)
  {
    size_t subBufferSize = buffer.size();
    size_t actualUsed = _p->used;

    write((uint32_t*)&subBufferSize, sizeof(uint32_t));

    _p->_subBuffers.push_back(std::make_pair(actualUsed, buffer));
    _p->_cachedSubBufferTotalSize += buffer.totalSize();
    return actualUsed;
  }

  bool Buffer::hasSubBuffer(size_t offset) const
  {
    return (_p->indexOfSubBuffer(offset) != -1);
  }

  const Buffer& Buffer::subBuffer(size_t offset) const
  {
    int index = _p->indexOfSubBuffer(offset);

    if (index == -1)
      throw std::runtime_error("No sub-buffer at the specified offset.");

    return _p->_subBuffers[index].second;
  }

  size_t Buffer::size() const
  {
    return _p->used;
  }

  size_t Buffer::totalSize() const
  {
    return size() + _p->_cachedSubBufferTotalSize;
  }

  const std::vector<std::pair<size_t, Buffer> > & Buffer::subBuffers() const
  {
    return _p->_subBuffers;
  }

  /*
  ** We need to allocate memory as soon as this function is called
  ** Returned memory MUST be coherent with the buffer used (either on stack/heap)
  ** As we can't know if the buffer will be used on heap later, we've to resize on heap
  */
  void *Buffer::reserve(size_t size)
  {
    if (_p->used + size > _p->available)
      _p->resize(_p->used + size);

    void *p = _p->data() + _p->used;
    _p->used += size;

    return p;
  }

  void Buffer::clear()
  {
    _p->used = 0;
    _p->_subBuffers.clear();
    _p->_cachedSubBufferTotalSize = 0;
  }

  void* Buffer::data()
  {
    return _p ? _p->data() : 0;
  }

  const void* Buffer::data() const
  {
    return _p ? _p->data() : 0;
  }

  const void *Buffer::read(size_t offset, size_t length) const
  {
    if (offset + length > _p->used)
    {
      qiLogDebug() << "Attempt to read " << offset+length
       <<" on buffer of size " << _p->used;
      return  nullptr;
    }
    return (char*)_p->data() + offset;
  }

  size_t Buffer::read(void* buffer, size_t offset, size_t length) const
  {
    if (offset > _p->used)
    {
      qiLogDebug() << "Attempt to read " << offset+length
      <<" on buffer of size " << _p->used;
      return -1;
    }
    size_t copy = std::min(length, _p->used - offset);
    memcpy(buffer, (char*)_p->data()+offset, copy);
    return copy;
  }

  namespace detail {
    void printBuffer(std::ostream& stream, const Buffer& buffer)
    {
      if (buffer.size() == 0) {
        qiLogDebug() << "dump on empty buffer";
        return;
      }

      std::ios_base::fmtflags flags = stream.flags();
      unsigned int i = 0;
      const unsigned char* data = (const unsigned char*)buffer.data();

      while (i < buffer.size()) {
        if (i % 16 == 0) stream << std::hex << std::setfill('0') << std::setw(8) << i << ": ";
        stream << std::setw(2) << (const unsigned int) data[i];
        i++;
        if (i % 2 == 0) stream << ' ';
        if (i % 16 == 0)
        {
          for (unsigned int j = i - 16; j < i ; j++)
          {
            char c = data[j];
            stream << (isgraph(c) ? c : '.');
          }
          stream << '\n';
        }
      }

      while (i % 16 != 0) {
        stream << "  ";
        if (i % 2 == 0) stream << ' ';
        i++;
      }
      stream << ' ';

      for (unsigned int j = i - 16; j < buffer.size(); j++) {
        char c = data[j];
        stream << (isgraph(c) ? c : '.');
      }

      stream.flags(flags);
    }
  }
} // !qi
<commit_msg>Fixed buffer content logging calling isgraph() with invalid values.<commit_after>/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/

#include <qi/assert.hpp>
#include <qi/buffer.hpp>
#include <qi/log.hpp>

#include <cstdio>
#include <cstring>
#include <stdexcept>
#include <iomanip>
#include <ctype.h>

#include <boost/pool/singleton_pool.hpp>
#include <boost/make_shared.hpp>

#include "buffer_p.hpp"

qiLogCategory("qi.Buffer");

namespace qi
{
  BufferPrivate::BufferPrivate() // cppcheck-suppress uninitMemberVar
    : _bigdata(0)
    , _cachedSubBufferTotalSize(0)
    , used(0)
    , available(sizeof(_data))
  {
  }

  BufferPrivate::~BufferPrivate()
  {
    if (_bigdata)
    {
      free(_bigdata);
      _bigdata = NULL;
    }
  }

  struct MyPoolTag { };
  using buffer_pool = boost::singleton_pool<MyPoolTag, sizeof(BufferPrivate)>;

  void* BufferPrivate::operator new(size_t sz)
  {
    QI_ASSERT(sz <= sizeof(BufferPrivate));
    return buffer_pool::malloc();
  }

  void BufferPrivate::operator delete(void* ptr)
  {
    buffer_pool::free(ptr);
  }

  int BufferPrivate::indexOfSubBuffer(size_t offset) const
  {
    for(unsigned i = 0; i < _subBuffers.size(); ++i) {
      if (_subBuffers[i].first == offset) {
        return i;
      }
    }

    return -1;
  }

  Buffer::Buffer()
    : _p(boost::make_shared<BufferPrivate>())
  {
  }

  Buffer::Buffer(const Buffer& b)
  {
    (*this) = b;
  }

  Buffer& Buffer::operator=(const Buffer& b)
  {
    _p = b._p;
    return *this;
  }

  Buffer::Buffer(Buffer&& b)
    : _p(std::move(b._p))
  {
    // The default state of a qi::Buffer contains a valid BufferPrivate pointer.
    b._p = boost::make_shared<BufferPrivate>();
  }

  Buffer& Buffer::operator=(Buffer&& b)
  {
    _p = std::move(b._p);
    b._p = boost::make_shared<BufferPrivate>();
    return *this;
  }

  unsigned char* BufferPrivate::data()
  {
    if (_bigdata)
      return (_bigdata);

    return (_data);
  }

  bool BufferPrivate::resize(size_t neededSize)
  {
    neededSize += BLOCK; // Should be enough in most cases;

    qiLogDebug() << "Resizing buffer from " << available << " to " << neededSize;
    unsigned char *newBigdata;

    newBigdata = static_cast<unsigned char *>(realloc(_bigdata, neededSize));
    if (newBigdata == NULL)
      return false;
    if (!_bigdata && used > 0)
      ::memcpy(newBigdata, _data, used);
    available = neededSize;
    _bigdata = newBigdata; // Don't worry, realloc free previous buffer if needed
    return true;
  }

  bool Buffer::write(const void *data, size_t size)
  {
    if (_p->used + size > _p->available)
    {
      bool ret = _p->resize(_p->used + size);
      if (!ret) {
        qiLogVerbose() << "write(" << size << ") failed, buffer size is " << _p->available;
        return false;
      }
    }

    memcpy(_p->data() + _p->used, data, size);
    _p->used += size;

    return true;
  }

  size_t Buffer::addSubBuffer(const Buffer& buffer)
  {
    size_t subBufferSize = buffer.size();
    size_t actualUsed = _p->used;

    write((uint32_t*)&subBufferSize, sizeof(uint32_t));

    _p->_subBuffers.push_back(std::make_pair(actualUsed, buffer));
    _p->_cachedSubBufferTotalSize += buffer.totalSize();
    return actualUsed;
  }

  bool Buffer::hasSubBuffer(size_t offset) const
  {
    return (_p->indexOfSubBuffer(offset) != -1);
  }

  const Buffer& Buffer::subBuffer(size_t offset) const
  {
    int index = _p->indexOfSubBuffer(offset);

    if (index == -1)
      throw std::runtime_error("No sub-buffer at the specified offset.");

    return _p->_subBuffers[index].second;
  }

  size_t Buffer::size() const
  {
    return _p->used;
  }

  size_t Buffer::totalSize() const
  {
    return size() + _p->_cachedSubBufferTotalSize;
  }

  const std::vector<std::pair<size_t, Buffer> > & Buffer::subBuffers() const
  {
    return _p->_subBuffers;
  }

  /*
  ** We need to allocate memory as soon as this function is called
  ** Returned memory MUST be coherent with the buffer used (either on stack/heap)
  ** As we can't know if the buffer will be used on heap later, we've to resize on heap
  */
  void *Buffer::reserve(size_t size)
  {
    if (_p->used + size > _p->available)
      _p->resize(_p->used + size);

    void *p = _p->data() + _p->used;
    _p->used += size;

    return p;
  }

  void Buffer::clear()
  {
    _p->used = 0;
    _p->_subBuffers.clear();
    _p->_cachedSubBufferTotalSize = 0;
  }

  void* Buffer::data()
  {
    return _p ? _p->data() : 0;
  }

  const void* Buffer::data() const
  {
    return _p ? _p->data() : 0;
  }

  const void *Buffer::read(size_t offset, size_t length) const
  {
    if (offset + length > _p->used)
    {
      qiLogDebug() << "Attempt to read " << offset+length
       <<" on buffer of size " << _p->used;
      return  nullptr;
    }
    return (char*)_p->data() + offset;
  }

  size_t Buffer::read(void* buffer, size_t offset, size_t length) const
  {
    if (offset > _p->used)
    {
      qiLogDebug() << "Attempt to read " << offset+length
      <<" on buffer of size " << _p->used;
      return -1;
    }
    size_t copy = std::min(length, _p->used - offset);
    memcpy(buffer, (char*)_p->data()+offset, copy);
    return copy;
  }

  namespace detail {
    void printBuffer(std::ostream& stream, const Buffer& buffer)
    {
      if (buffer.size() == 0) {
        qiLogDebug() << "dump on empty buffer";
        return;
      }

      std::ios_base::fmtflags flags = stream.flags();
      unsigned int i = 0;
      const unsigned char* data = (const unsigned char*)buffer.data();

      while (i < buffer.size()) {
        if (i % 16 == 0) stream << std::hex << std::setfill('0') << std::setw(8) << i << ": ";
        stream << std::setw(2) << (const unsigned int) data[i];
        i++;
        if (i % 2 == 0) stream << ' ';
        if (i % 16 == 0)
        {
          for (unsigned int j = i - 16; j < i ; j++)
          {
            char c = data[j];
            stream << (isgraph(c) ? c : '.');
          }
          stream << '\n';
        }
      }

      while (i % 16 != 0) {
        stream << "  ";
        if (i % 2 == 0) stream << ' ';
        i++;
      }
      stream << ' ';

      for (unsigned int j = i - 16; j < buffer.size(); j++) {
        char c = data[j];
        stream << (c >= 0 && isgraph(c) ? c : '.'); // isgraph() required a value which can be represented by an unsigned char
      }

      stream.flags(flags);
    }
  }
} // !qi
<|endoftext|>


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

#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#include <objbase.h>
#endif
#include <algorithm>

#include "chrome/renderer/render_thread.h"

#include "base/shared_memory.h"
#include "chrome/common/chrome_plugin_lib.h"
#include "chrome/common/ipc_logging.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/notification_service.h"
// TODO(port)
#if defined(OS_WIN)
#include "chrome/plugin/plugin_channel.h"
#else
#include <vector>
#include "base/scoped_handle.h"
#include "chrome/plugin/plugin_channel_base.h"
#include "webkit/glue/weburlrequest.h"
#endif
#include "chrome/renderer/net/render_dns_master.h"
#include "chrome/renderer/render_process.h"
#include "chrome/renderer/render_view.h"
#include "chrome/renderer/user_script_slave.h"
#include "chrome/renderer/visitedlink_slave.h"
#include "webkit/glue/cache_manager.h"

RenderThread* g_render_thread;

static const unsigned int kCacheStatsDelayMS = 2000 /* milliseconds */;

// V8 needs a 1MB stack size.
static const size_t kStackSize = 1024 * 1024;

//-----------------------------------------------------------------------------
// Methods below are only called on the owner's thread:

RenderThread::RenderThread(const std::wstring& channel_name)
    : Thread("Chrome_RenderThread"),
      owner_loop_(MessageLoop::current()),
      channel_name_(channel_name),
      visited_link_slave_(NULL),
      user_script_slave_(NULL),
      render_dns_master_(NULL),
      in_send_(0) {
  DCHECK(owner_loop_);
  base::Thread::Options options;
  options.stack_size = kStackSize;
  // When we run plugins in process, we actually run them on the render thread,
  // which means that we need to make the render thread pump UI events.
  if (RenderProcess::ShouldLoadPluginsInProcess())
    options.message_loop_type = MessageLoop::TYPE_UI;
  StartWithOptions(options);
}

RenderThread::~RenderThread() {
  Stop();
}

void RenderThread::OnChannelError() {
  owner_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}

bool RenderThread::Send(IPC::Message* msg) {
  in_send_++;
  bool rv = channel_->Send(msg);
  in_send_--;
  return rv;
}

void RenderThread::AddFilter(IPC::ChannelProxy::MessageFilter* filter) {
  channel_->AddFilter(filter);
}

void RenderThread::RemoveFilter(IPC::ChannelProxy::MessageFilter* filter) {
  channel_->RemoveFilter(filter);
}

void RenderThread::Resolve(const char* name, size_t length) {
  return render_dns_master_->Resolve(name, length);
}

void RenderThread::AddRoute(int32 routing_id,
                            IPC::Channel::Listener* listener) {
  DCHECK(MessageLoop::current() == message_loop());

  // This corresponds to the AddRoute call done in CreateView.
  router_.AddRoute(routing_id, listener);
}

void RenderThread::RemoveRoute(int32 routing_id) {
  DCHECK(MessageLoop::current() == message_loop());

  router_.RemoveRoute(routing_id);
}

void RenderThread::Init() {
  DCHECK(!g_render_thread);
  g_render_thread = this;

  notification_service_.reset(new NotificationService);

  cache_stats_factory_.reset(
      new ScopedRunnableMethodFactory<RenderThread>(this));

  channel_.reset(new IPC::SyncChannel(channel_name_,
      IPC::Channel::MODE_CLIENT, this, NULL, owner_loop_, true,
      RenderProcess::GetShutDownEvent()));

#if defined(OS_WIN)
  // The renderer thread should wind-up COM.
  CoInitialize(0);
#endif

  visited_link_slave_ = new VisitedLinkSlave();
  user_script_slave_ = new UserScriptSlave();
  render_dns_master_.reset(new RenderDnsMaster());

#ifdef IPC_MESSAGE_LOG_ENABLED
  IPC::Logging::current()->SetIPCSender(this);
#endif
}

void RenderThread::CleanUp() {
  DCHECK(g_render_thread == this);
  g_render_thread = NULL;

  // Need to destruct the SyncChannel to the browser before we go away because
  // it caches a pointer to this thread.
  channel_.reset();

// TODO(port)
#if defined(OS_WIN)
  // Clean up plugin channels before this thread goes away.
  PluginChannelBase::CleanupChannels();
#endif

#ifdef IPC_MESSAGE_LOG_ENABLED
  IPC::Logging::current()->SetIPCSender(NULL);
#endif

  notification_service_.reset();

  delete visited_link_slave_;
  visited_link_slave_ = NULL;

  delete user_script_slave_;
  user_script_slave_ = NULL;

#if defined(OS_WIN)
  CoUninitialize();
#endif
}

void RenderThread::OnUpdateVisitedLinks(base::SharedMemoryHandle table) {
  DCHECK(base::SharedMemory::IsHandleValid(table)) << "Bad table handle";
  visited_link_slave_->Init(table);
}

void RenderThread::OnUpdateUserScripts(
    base::SharedMemoryHandle scripts) {
  DCHECK(base::SharedMemory::IsHandleValid(scripts)) << "Bad scripts handle";
  user_script_slave_->UpdateScripts(scripts);
}

void RenderThread::OnMessageReceived(const IPC::Message& msg) {
  // NOTE: We could subclass router_ to intercept OnControlMessageReceived, but
  // it seems simpler to just process any control messages that we care about
  // up-front and then send the rest of the messages onto router_.

  if (msg.routing_id() == MSG_ROUTING_CONTROL) {
    IPC_BEGIN_MESSAGE_MAP(RenderThread, msg)
      IPC_MESSAGE_HANDLER(ViewMsg_VisitedLink_NewTable, OnUpdateVisitedLinks)
      IPC_MESSAGE_HANDLER(ViewMsg_SetNextPageID, OnSetNextPageID)
      // TODO(port): removed from render_messages_internal.h;
      // is there a new non-windows message I should add here?
      IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
      IPC_MESSAGE_HANDLER(ViewMsg_SetCacheCapacities, OnSetCacheCapacities)
      IPC_MESSAGE_HANDLER(ViewMsg_GetCacheResourceStats,
                          OnGetCacheResourceStats)
      IPC_MESSAGE_HANDLER(ViewMsg_PluginMessage, OnPluginMessage)
      IPC_MESSAGE_HANDLER(ViewMsg_UserScripts_NewScripts,
                          OnUpdateUserScripts)
      // send the rest to the router
      IPC_MESSAGE_UNHANDLED(router_.OnMessageReceived(msg))
    IPC_END_MESSAGE_MAP()
  } else {
    router_.OnMessageReceived(msg);
  }
}

void RenderThread::OnPluginMessage(const FilePath& plugin_path,
                                   const std::vector<uint8>& data) {
  if (!ChromePluginLib::IsInitialized()) {
    return;
  }
  CHECK(ChromePluginLib::IsPluginThread());
  ChromePluginLib *chrome_plugin = ChromePluginLib::Find(plugin_path);
  if (chrome_plugin) {
    void *data_ptr = const_cast<void*>(reinterpret_cast<const void*>(&data[0]));
    uint32 data_len = static_cast<uint32>(data.size());
    chrome_plugin->functions().on_message(data_ptr, data_len);
  }
}

void RenderThread::OnSetNextPageID(int32 next_page_id) {
  // This should only be called at process initialization time, so we shouldn't
  // have to worry about thread-safety.
  // TODO(port)
#if !defined(OS_LINUX)
  RenderView::SetNextPageID(next_page_id);
#endif
}

void RenderThread::OnCreateNewView(gfx::NativeViewId parent_hwnd,
                                   ModalDialogEvent modal_dialog_event,
                                   const WebPreferences& webkit_prefs,
                                   int32 view_id) {
  // When bringing in render_view, also bring in webkit's glue and jsbindings.
  base::WaitableEvent* waitable_event = new base::WaitableEvent(
#if defined(OS_WIN)
      modal_dialog_event.event);
#else
      true, false);
#endif

  // TODO(darin): once we have a RenderThread per RenderView, this will need to
  // change to assert that we are not creating more than one view.
  RenderView::Create(
      this, parent_hwnd, waitable_event, MSG_ROUTING_NONE, webkit_prefs,
      new SharedRenderViewCounter(0), view_id);
}

void RenderThread::OnSetCacheCapacities(size_t min_dead_capacity,
                                        size_t max_dead_capacity,
                                        size_t capacity) {
#if defined(OS_WIN)
  CacheManager::SetCapacities(min_dead_capacity, max_dead_capacity, capacity);
#else
  // TODO(port)
  NOTIMPLEMENTED();
#endif
}

void RenderThread::OnGetCacheResourceStats() {
#if defined(OS_WIN)
  CacheManager::ResourceTypeStats stats;
  CacheManager::GetResourceTypeStats(&stats);
  Send(new ViewHostMsg_ResourceTypeStats(stats));
#else
  // TODO(port)
  NOTIMPLEMENTED();
#endif
}

void RenderThread::InformHostOfCacheStats() {
#if defined(OS_WIN)
  CacheManager::UsageStats stats;
  CacheManager::GetUsageStats(&stats);
  Send(new ViewHostMsg_UpdatedCacheStats(stats));
#else
  // TODO(port)
  NOTIMPLEMENTED();
#endif
}

void RenderThread::InformHostOfCacheStatsLater() {
  // Rate limit informing the host of our cache stats.
  if (!cache_stats_factory_->empty())
    return;

  MessageLoop::current()->PostDelayedTask(FROM_HERE,
      cache_stats_factory_->NewRunnableMethod(
          &RenderThread::InformHostOfCacheStats),
      kCacheStatsDelayMS);
}
<commit_msg>Remove some NOTIMPLMENTEDs which are apparently no longer necessary.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "build/build_config.h"

#if defined(OS_WIN)
#include <windows.h>
#include <objbase.h>
#endif
#include <algorithm>

#include "chrome/renderer/render_thread.h"

#include "base/shared_memory.h"
#include "chrome/common/chrome_plugin_lib.h"
#include "chrome/common/ipc_logging.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/notification_service.h"
// TODO(port)
#if defined(OS_WIN)
#include "chrome/plugin/plugin_channel.h"
#else
#include <vector>
#include "base/scoped_handle.h"
#include "chrome/plugin/plugin_channel_base.h"
#include "webkit/glue/weburlrequest.h"
#endif
#include "chrome/renderer/net/render_dns_master.h"
#include "chrome/renderer/render_process.h"
#include "chrome/renderer/render_view.h"
#include "chrome/renderer/user_script_slave.h"
#include "chrome/renderer/visitedlink_slave.h"
#include "webkit/glue/cache_manager.h"

RenderThread* g_render_thread;

static const unsigned int kCacheStatsDelayMS = 2000 /* milliseconds */;

// V8 needs a 1MB stack size.
static const size_t kStackSize = 1024 * 1024;

//-----------------------------------------------------------------------------
// Methods below are only called on the owner's thread:

RenderThread::RenderThread(const std::wstring& channel_name)
    : Thread("Chrome_RenderThread"),
      owner_loop_(MessageLoop::current()),
      channel_name_(channel_name),
      visited_link_slave_(NULL),
      user_script_slave_(NULL),
      render_dns_master_(NULL),
      in_send_(0) {
  DCHECK(owner_loop_);
  base::Thread::Options options;
  options.stack_size = kStackSize;
  // When we run plugins in process, we actually run them on the render thread,
  // which means that we need to make the render thread pump UI events.
  if (RenderProcess::ShouldLoadPluginsInProcess())
    options.message_loop_type = MessageLoop::TYPE_UI;
  StartWithOptions(options);
}

RenderThread::~RenderThread() {
  Stop();
}

void RenderThread::OnChannelError() {
  owner_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}

bool RenderThread::Send(IPC::Message* msg) {
  in_send_++;
  bool rv = channel_->Send(msg);
  in_send_--;
  return rv;
}

void RenderThread::AddFilter(IPC::ChannelProxy::MessageFilter* filter) {
  channel_->AddFilter(filter);
}

void RenderThread::RemoveFilter(IPC::ChannelProxy::MessageFilter* filter) {
  channel_->RemoveFilter(filter);
}

void RenderThread::Resolve(const char* name, size_t length) {
  return render_dns_master_->Resolve(name, length);
}

void RenderThread::AddRoute(int32 routing_id,
                            IPC::Channel::Listener* listener) {
  DCHECK(MessageLoop::current() == message_loop());

  // This corresponds to the AddRoute call done in CreateView.
  router_.AddRoute(routing_id, listener);
}

void RenderThread::RemoveRoute(int32 routing_id) {
  DCHECK(MessageLoop::current() == message_loop());

  router_.RemoveRoute(routing_id);
}

void RenderThread::Init() {
  DCHECK(!g_render_thread);
  g_render_thread = this;

  notification_service_.reset(new NotificationService);

  cache_stats_factory_.reset(
      new ScopedRunnableMethodFactory<RenderThread>(this));

  channel_.reset(new IPC::SyncChannel(channel_name_,
      IPC::Channel::MODE_CLIENT, this, NULL, owner_loop_, true,
      RenderProcess::GetShutDownEvent()));

#if defined(OS_WIN)
  // The renderer thread should wind-up COM.
  CoInitialize(0);
#endif

  visited_link_slave_ = new VisitedLinkSlave();
  user_script_slave_ = new UserScriptSlave();
  render_dns_master_.reset(new RenderDnsMaster());

#ifdef IPC_MESSAGE_LOG_ENABLED
  IPC::Logging::current()->SetIPCSender(this);
#endif
}

void RenderThread::CleanUp() {
  DCHECK(g_render_thread == this);
  g_render_thread = NULL;

  // Need to destruct the SyncChannel to the browser before we go away because
  // it caches a pointer to this thread.
  channel_.reset();

// TODO(port)
#if defined(OS_WIN)
  // Clean up plugin channels before this thread goes away.
  PluginChannelBase::CleanupChannels();
#endif

#ifdef IPC_MESSAGE_LOG_ENABLED
  IPC::Logging::current()->SetIPCSender(NULL);
#endif

  notification_service_.reset();

  delete visited_link_slave_;
  visited_link_slave_ = NULL;

  delete user_script_slave_;
  user_script_slave_ = NULL;

#if defined(OS_WIN)
  CoUninitialize();
#endif
}

void RenderThread::OnUpdateVisitedLinks(base::SharedMemoryHandle table) {
  DCHECK(base::SharedMemory::IsHandleValid(table)) << "Bad table handle";
  visited_link_slave_->Init(table);
}

void RenderThread::OnUpdateUserScripts(
    base::SharedMemoryHandle scripts) {
  DCHECK(base::SharedMemory::IsHandleValid(scripts)) << "Bad scripts handle";
  user_script_slave_->UpdateScripts(scripts);
}

void RenderThread::OnMessageReceived(const IPC::Message& msg) {
  // NOTE: We could subclass router_ to intercept OnControlMessageReceived, but
  // it seems simpler to just process any control messages that we care about
  // up-front and then send the rest of the messages onto router_.

  if (msg.routing_id() == MSG_ROUTING_CONTROL) {
    IPC_BEGIN_MESSAGE_MAP(RenderThread, msg)
      IPC_MESSAGE_HANDLER(ViewMsg_VisitedLink_NewTable, OnUpdateVisitedLinks)
      IPC_MESSAGE_HANDLER(ViewMsg_SetNextPageID, OnSetNextPageID)
      // TODO(port): removed from render_messages_internal.h;
      // is there a new non-windows message I should add here?
      IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
      IPC_MESSAGE_HANDLER(ViewMsg_SetCacheCapacities, OnSetCacheCapacities)
      IPC_MESSAGE_HANDLER(ViewMsg_GetCacheResourceStats,
                          OnGetCacheResourceStats)
      IPC_MESSAGE_HANDLER(ViewMsg_PluginMessage, OnPluginMessage)
      IPC_MESSAGE_HANDLER(ViewMsg_UserScripts_NewScripts,
                          OnUpdateUserScripts)
      // send the rest to the router
      IPC_MESSAGE_UNHANDLED(router_.OnMessageReceived(msg))
    IPC_END_MESSAGE_MAP()
  } else {
    router_.OnMessageReceived(msg);
  }
}

void RenderThread::OnPluginMessage(const FilePath& plugin_path,
                                   const std::vector<uint8>& data) {
  if (!ChromePluginLib::IsInitialized()) {
    return;
  }
  CHECK(ChromePluginLib::IsPluginThread());
  ChromePluginLib *chrome_plugin = ChromePluginLib::Find(plugin_path);
  if (chrome_plugin) {
    void *data_ptr = const_cast<void*>(reinterpret_cast<const void*>(&data[0]));
    uint32 data_len = static_cast<uint32>(data.size());
    chrome_plugin->functions().on_message(data_ptr, data_len);
  }
}

void RenderThread::OnSetNextPageID(int32 next_page_id) {
  // This should only be called at process initialization time, so we shouldn't
  // have to worry about thread-safety.
  // TODO(port)
#if !defined(OS_LINUX)
  RenderView::SetNextPageID(next_page_id);
#endif
}

void RenderThread::OnCreateNewView(gfx::NativeViewId parent_hwnd,
                                   ModalDialogEvent modal_dialog_event,
                                   const WebPreferences& webkit_prefs,
                                   int32 view_id) {
  // When bringing in render_view, also bring in webkit's glue and jsbindings.
  base::WaitableEvent* waitable_event = new base::WaitableEvent(
#if defined(OS_WIN)
      modal_dialog_event.event);
#else
      true, false);
#endif

  // TODO(darin): once we have a RenderThread per RenderView, this will need to
  // change to assert that we are not creating more than one view.
  RenderView::Create(
      this, parent_hwnd, waitable_event, MSG_ROUTING_NONE, webkit_prefs,
      new SharedRenderViewCounter(0), view_id);
}

void RenderThread::OnSetCacheCapacities(size_t min_dead_capacity,
                                        size_t max_dead_capacity,
                                        size_t capacity) {
#if defined(OS_WIN) || defined(OS_LINUX)
  CacheManager::SetCapacities(min_dead_capacity, max_dead_capacity, capacity);
#else
  // TODO(port)
  NOTIMPLEMENTED();
#endif
}

void RenderThread::OnGetCacheResourceStats() {
#if defined(OS_WIN) || defined(OS_LINUX)
  CacheManager::ResourceTypeStats stats;
  CacheManager::GetResourceTypeStats(&stats);
  Send(new ViewHostMsg_ResourceTypeStats(stats));
#else
  // TODO(port)
  NOTIMPLEMENTED();
#endif
}

void RenderThread::InformHostOfCacheStats() {
#if defined(OS_WIN) || defined(OS_LINUX)
  CacheManager::UsageStats stats;
  CacheManager::GetUsageStats(&stats);
  Send(new ViewHostMsg_UpdatedCacheStats(stats));
#else
  // TODO(port)
  NOTIMPLEMENTED();
#endif
}

void RenderThread::InformHostOfCacheStatsLater() {
  // Rate limit informing the host of our cache stats.
  if (!cache_stats_factory_->empty())
    return;

  MessageLoop::current()->PostDelayedTask(FROM_HERE,
      cache_stats_factory_->NewRunnableMethod(
          &RenderThread::InformHostOfCacheStats),
      kCacheStatsDelayMS);
}
<|endoftext|>


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

#include "base/command_line.h"
#include "base/histogram.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/scoped_nsautorelease_pool.h"
#include "base/string_util.h"
#include "base/system_monitor.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_counters.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/main_function_params.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/renderer/renderer_main_platform_delegate.h"
#include "chrome/renderer/render_process.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"

#if defined(OS_LINUX)
#include <gtk/gtk.h>
#endif

// This function provides some ways to test crash and assertion handling
// behavior of the renderer.
static void HandleRendererErrorTestParameters(const CommandLine& command_line) {
  // This parameter causes an assertion.
  if (command_line.HasSwitch(switches::kRendererAssertTest)) {
    DCHECK(false);
  }

  // This parameter causes a null pointer crash (crash reporter trigger).
  if (command_line.HasSwitch(switches::kRendererCrashTest)) {
    int* bad_pointer = NULL;
    *bad_pointer = 0;
  }

  if (command_line.HasSwitch(switches::kRendererStartupDialog)) {
#if defined(OS_WIN)
    std::wstring title = l10n_util::GetString(IDS_PRODUCT_NAME);
    title += L" renderer";  // makes attaching to process easier
    ::MessageBox(NULL, L"renderer starting...", title.c_str(),
                 MB_OK | MB_SETFOREGROUND);
#elif defined(OS_LINUX)
    // TODO(port): create an abstraction layer for dialog boxes and use it here.
    GtkWidget* dialog = gtk_message_dialog_new(
        NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, GTK_BUTTONS_OK,
        "Attach to renderer at pid %d.", getpid());
    gtk_window_set_title(GTK_WINDOW(dialog), "Renderer starting...");
    gtk_dialog_run(GTK_DIALOG(dialog));  // Runs a nested message loop.
    gtk_widget_destroy(dialog);
#elif defined(OS_MACOSX)
    // TODO(playmobil): In the long term, overriding this flag doesn't seem
    // right, either use our own flag or open a dialog we can use.
    // This is just to ease debugging in the interim.
    LOG(WARNING) << "Renderer ("
                 << getpid()
                 << ") paused waiting for debugger to attach @ pid";
    pause();
#endif  // defined(OS_MACOSX)
  }
}

// mainline routine for running as the Rendererer process
int RendererMain(const MainFunctionParams& parameters) {
  const CommandLine& parsed_command_line = parameters.command_line_;
  base::ScopedNSAutoreleasePool* pool = parameters.autorelease_pool_;

  // This function allows pausing execution using the --renderer-startup-dialog
  // flag allowing us to attach a debugger.
  // Do not move this function down since that would mean we can't easily debug
  // whatever occurs before it.
  HandleRendererErrorTestParameters(parsed_command_line);

  RendererMainPlatformDelegate platform(parameters);

  StatsScope<StatsCounterTimer>
      startup_timer(chrome::Counters::renderer_main());

  // The main thread of the renderer services IO.
  MessageLoopForIO main_message_loop;
  std::wstring app_name = chrome::kBrowserAppName;
  PlatformThread::SetName(WideToASCII(app_name + L"_RendererMain").c_str());

  // Initialize the SystemMonitor
  base::SystemMonitor::Start();

  platform.PlatformInitialize();

  bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox);
  platform.InitSandboxTests(no_sandbox);

  // Initialize histogram statistics gathering system.
  // Don't create StatisticsRecorde in the single process mode.
  scoped_ptr<StatisticsRecorder> statistics;
  if (!StatisticsRecorder::WasStarted()) {
    statistics.reset(new StatisticsRecorder());
  }

  {
    RenderProcess render_process;
    bool run_loop = true;
    if (!no_sandbox) {
      run_loop = platform.EnableSandbox();
    }

    platform.RunSandboxTests();

    startup_timer.Stop();  // End of Startup Time Measurement.

    if (run_loop) {
      // Load the accelerator table from the browser executable and tell the
      // message loop to use it when translating messages.
      if (pool) pool->Recycle();
      MessageLoop::current()->Run();
    }
  }
  platform.PlatformUninitialize();
  return 0;
}

<commit_msg>Get rid of renderer startup dialog implementation on linux.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/histogram.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/scoped_nsautorelease_pool.h"
#include "base/string_util.h"
#include "base/system_monitor.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_counters.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/main_function_params.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/renderer/renderer_main_platform_delegate.h"
#include "chrome/renderer/render_process.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"

// This function provides some ways to test crash and assertion handling
// behavior of the renderer.
static void HandleRendererErrorTestParameters(const CommandLine& command_line) {
  // This parameter causes an assertion.
  if (command_line.HasSwitch(switches::kRendererAssertTest)) {
    DCHECK(false);
  }

  // This parameter causes a null pointer crash (crash reporter trigger).
  if (command_line.HasSwitch(switches::kRendererCrashTest)) {
    int* bad_pointer = NULL;
    *bad_pointer = 0;
  }

  if (command_line.HasSwitch(switches::kRendererStartupDialog)) {
#if defined(OS_WIN)
    std::wstring title = l10n_util::GetString(IDS_PRODUCT_NAME);
    title += L" renderer";  // makes attaching to process easier
    ::MessageBox(NULL, L"renderer starting...", title.c_str(),
                 MB_OK | MB_SETFOREGROUND);
#elif defined(OS_MACOSX)
    // TODO(playmobil): In the long term, overriding this flag doesn't seem
    // right, either use our own flag or open a dialog we can use.
    // This is just to ease debugging in the interim.
    LOG(WARNING) << "Renderer ("
                 << getpid()
                 << ") paused waiting for debugger to attach @ pid";
    pause();
#endif  // defined(OS_MACOSX)
  }
}

// mainline routine for running as the Rendererer process
int RendererMain(const MainFunctionParams& parameters) {
  const CommandLine& parsed_command_line = parameters.command_line_;
  base::ScopedNSAutoreleasePool* pool = parameters.autorelease_pool_;

  // This function allows pausing execution using the --renderer-startup-dialog
  // flag allowing us to attach a debugger.
  // Do not move this function down since that would mean we can't easily debug
  // whatever occurs before it.
  HandleRendererErrorTestParameters(parsed_command_line);

  RendererMainPlatformDelegate platform(parameters);

  StatsScope<StatsCounterTimer>
      startup_timer(chrome::Counters::renderer_main());

  // The main thread of the renderer services IO.
  MessageLoopForIO main_message_loop;
  std::wstring app_name = chrome::kBrowserAppName;
  PlatformThread::SetName(WideToASCII(app_name + L"_RendererMain").c_str());

  // Initialize the SystemMonitor
  base::SystemMonitor::Start();

  platform.PlatformInitialize();

  bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox);
  platform.InitSandboxTests(no_sandbox);

  // Initialize histogram statistics gathering system.
  // Don't create StatisticsRecorde in the single process mode.
  scoped_ptr<StatisticsRecorder> statistics;
  if (!StatisticsRecorder::WasStarted()) {
    statistics.reset(new StatisticsRecorder());
  }

  {
    RenderProcess render_process;
    bool run_loop = true;
    if (!no_sandbox) {
      run_loop = platform.EnableSandbox();
    }

    platform.RunSandboxTests();

    startup_timer.Stop();  // End of Startup Time Measurement.

    if (run_loop) {
      // Load the accelerator table from the browser executable and tell the
      // message loop to use it when translating messages.
      if (pool) pool->Recycle();
      MessageLoop::current()->Run();
    }
  }
  platform.PlatformUninitialize();
  return 0;
}

<|endoftext|>