<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "TextEngine.h"

#include "../base/Logger.h"
#include "../base/OSHelper.h"
#include "../base/Exception.h"
#include "../base/FileHelper.h"
#include "../base/StringHelper.h"

#include <pango/pango.h>
#include <pango/pangoft2.h>
#include <fontconfig/fontconfig.h>

#include <assert.h>
#include <algorithm>

namespace avg {

using namespace std;

static void
text_subst_func(FcPattern *pattern, gpointer data)
{
//  GimpText *text = GIMP_TEXT (data);

  FcPatternAddBool(pattern, FC_HINTING, true);
  FcPatternAddInteger(pattern, FC_HINT_STYLE, FC_HINT_MEDIUM);
  FcPatternAddInteger(pattern, FC_RGBA, FC_RGBA_NONE);
  FcPatternAddBool(pattern, FC_ANTIALIAS, true);
}

TextEngine& TextEngine::get()
{
    static TextEngine s_Instance;
    return s_Instance;
}

TextEngine::TextEngine()
{
    m_sFontDirs.push_back("fonts/");
    init();
}

TextEngine::~TextEngine()
{
    deinit();
}

void TextEngine::init()
{
    pango_ft2_get_context(72, 72);

    PangoFT2FontMap *pFontMap;
    pFontMap = PANGO_FT2_FONT_MAP (pango_ft2_font_map_new());
    pango_ft2_font_map_set_resolution (pFontMap, 72, 72);
    pango_ft2_font_map_set_default_substitute (pFontMap, text_subst_func, 0, 0);
    m_pPangoContext = pango_ft2_font_map_create_context (pFontMap);
    g_object_unref (pFontMap);

    pango_context_set_language(m_pPangoContext,
            pango_language_from_string ("en_US"));
    pango_context_set_base_dir(m_pPangoContext, PANGO_DIRECTION_LTR);

    initFonts();

    string sOldLang = "";
    getEnv("LC_CTYPE", sOldLang);
    setEnv("LC_CTYPE", "en-us");
    pango_font_map_list_families(PANGO_FONT_MAP(pFontMap), &m_ppFontFamilies,
            &m_NumFontFamilies);
    setEnv("LC_CTYPE", sOldLang);
    for (int i=0; i<m_NumFontFamilies; ++i) {
        m_sFonts.push_back(pango_font_family_get_name(m_ppFontFamilies[i]));
    }
    sort(m_sFonts.begin(), m_sFonts.end());
}

void TextEngine::deinit()
{
    g_free(m_ppFontFamilies);
    g_object_unref(m_pPangoContext);
    m_sFonts.clear();
}

void TextEngine::addFontDir(const std::string& sDir)
{
    deinit();
    m_sFontDirs.push_back(sDir);
    init();
}

PangoContext * TextEngine::getPangoContext()
{
    return m_pPangoContext;
}

const vector<string>& TextEngine::getFontFamilies()
{
    return m_sFonts;
}

const vector<string>& TextEngine::getFontVariants(const string& sFontName)
{
    PangoFontFamily * pCurFamily = getFontFamily(sFontName);
    PangoFontFace ** ppFaces;
    int numFaces;
    pango_font_family_list_faces (pCurFamily, &ppFaces, &numFaces);
    static vector<string> sVariants;
    for (int i=0; i<numFaces; ++i) {
        sVariants.push_back(pango_font_face_get_face_name(ppFaces[i]));
    }
    g_free(ppFaces);
    return sVariants;
}

PangoFontDescription * TextEngine::getFontDescription(const string& sFamily,
        const string& sVariant)
{
    PangoFontDescription* pDescription;
    FontDescriptionCache::iterator it;
    it = m_FontDescriptionCache.find(pair<string, string>(sFamily, sVariant));
    if (it == m_FontDescriptionCache.end()) {
        PangoFontFamily * pFamily;
        bool bFamilyFound = true;
        try {
            pFamily = getFontFamily(sFamily);
        } catch (Exception&) {
            if (m_sFontsNotFound.find(sFamily) == m_sFontsNotFound.end()) {
                AVG_TRACE(Logger::WARNING, "Could not find font face " << sFamily <<
                        ". Using sans instead.");
                m_sFontsNotFound.insert(sFamily);
            }
            bFamilyFound = false;
            pFamily = getFontFamily("sans");
        }
        PangoFontFace ** ppFaces;
        int numFaces;
        pango_font_family_list_faces(pFamily, &ppFaces, &numFaces);
        PangoFontFace * pFace = 0;
        if (sVariant == "") {
            pFace = ppFaces[0];
        } else {
            for (int i=0; i<numFaces; ++i) {
                if (equalIgnoreCase(pango_font_face_get_face_name(ppFaces[i]), sVariant)) {
                    pFace = ppFaces[i];
                }
            }
        }
        if (!pFace) {
            pFace = ppFaces[0];
            if (bFamilyFound) {
                pair<string, string> variant(sFamily, sVariant);
                if (m_VariantsNotFound.find(variant) == m_VariantsNotFound.end()) {
                    m_VariantsNotFound.insert(variant);
                    AVG_TRACE(Logger::WARNING, "Could not find font variant "
                            << sFamily << ":" << sVariant << ". Using " <<
                            pango_font_face_get_face_name(pFace) << " instead.");
                }
            }
        }
        g_free(ppFaces);
        pDescription = pango_font_face_describe(pFace);
        m_FontDescriptionCache[pair<string, string>(sFamily, sVariant)] =
                pDescription;
    } else {
        pDescription = it->second;
    }
    return pango_font_description_copy(pDescription);
}

void GLibLogFunc(const gchar *log_domain, GLogLevelFlags log_level,
        const gchar *message, gpointer unused_data)
{
    string s = "Pango ";
    if (log_level & G_LOG_LEVEL_ERROR) {
        s += "error: ";
    } else if (log_level & G_LOG_LEVEL_CRITICAL) {
        s += string("critical: ")+message;
        AVG_TRACE(Logger::ERROR, s);
        assert(false);
    } else if (log_level & G_LOG_LEVEL_WARNING) {
        s += "warning: ";
    } else if (log_level & G_LOG_LEVEL_MESSAGE) {
        s += "message: ";
    } else if (log_level & G_LOG_LEVEL_INFO) {
        s += "info: ";
    } else if (log_level & G_LOG_LEVEL_DEBUG) {
        s += "debug: ";
    }
    s += message;
    AVG_TRACE(Logger::WARNING, s);
}

void TextEngine::initFonts()
{
    g_type_init();
    std::string sFontConfPath = "/etc/fonts/fonts.conf";
    if (!fileExists(sFontConfPath)) {
        sFontConfPath = getAvgLibPath()+"etc/fonts/fonts.conf";
    }
    FcConfig * pConfig = FcConfigCreate();
    int Ok = (int)FcConfigParseAndLoad(pConfig,
            (const FcChar8 *)(sFontConfPath.c_str()), true);
    checkFontError(Ok, string("Font error: could not load config file ")+sFontConfPath);
    Ok = (int)FcConfigBuildFonts(pConfig);
    checkFontError(Ok, string("Font error: FcConfigBuildFonts failed."));
    Ok = (int)FcConfigSetCurrent(pConfig);
    checkFontError(Ok, string("Font error: FcConfigSetCurrent failed."));
    for(std::vector<std::string>::const_iterator it = m_sFontDirs.begin();
            it != m_sFontDirs.end(); ++it) {
        Ok = (int)FcConfigAppFontAddDir(pConfig, (const FcChar8 *)it->c_str());
        checkFontError(Ok, string("Font error: FcConfigAppFontAddDir("
                    + *it + ") failed."));
    }
    /*
       FcStrList * pCacheDirs = FcConfigGetCacheDirs(pConfig);
       FcChar8 * pDir;
       do {
       pDir = FcStrListNext(pCacheDirs);
       if (pDir) {
       cerr << pDir << endl;
       }
       } while (pDir);
     */
    g_log_set_default_handler(GLibLogFunc, 0);
}

PangoFontFamily * TextEngine::getFontFamily(const string& sFamily)
{
    PangoFontFamily * pFamily = 0;
    assert(m_NumFontFamilies != 0);
    for (int i=0; i<m_NumFontFamilies; ++i) {
        if (equalIgnoreCase(pango_font_family_get_name(m_ppFontFamilies[i]), sFamily)) {
            pFamily = m_ppFontFamilies[i];
        }
    }
    if (!pFamily) {
        throw(Exception(AVG_ERR_INVALID_ARGS,
                "getFontFamily: Font family "+sFamily+" not found."));
    }
    return pFamily;
}

void TextEngine::checkFontError(int Ok, const string& sMsg)
{
    if (Ok == 0) {
        throw Exception(AVG_ERR_FONT_INIT_FAILED, sMsg);
    }
}

}
<commit_msg>Temporarily removed pango warnings from windows version.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "TextEngine.h"

#include "../base/Logger.h"
#include "../base/OSHelper.h"
#include "../base/Exception.h"
#include "../base/FileHelper.h"
#include "../base/StringHelper.h"

#include <pango/pango.h>
#include <pango/pangoft2.h>
#include <fontconfig/fontconfig.h>

#include <assert.h>
#include <algorithm>

namespace avg {

using namespace std;

static void
text_subst_func(FcPattern *pattern, gpointer data)
{
//  GimpText *text = GIMP_TEXT (data);

  FcPatternAddBool(pattern, FC_HINTING, true);
  FcPatternAddInteger(pattern, FC_HINT_STYLE, FC_HINT_MEDIUM);
  FcPatternAddInteger(pattern, FC_RGBA, FC_RGBA_NONE);
  FcPatternAddBool(pattern, FC_ANTIALIAS, true);
}

TextEngine& TextEngine::get()
{
    static TextEngine s_Instance;
    return s_Instance;
}

TextEngine::TextEngine()
{
    m_sFontDirs.push_back("fonts/");
    init();
}

TextEngine::~TextEngine()
{
    deinit();
}

void TextEngine::init()
{
    pango_ft2_get_context(72, 72);

    PangoFT2FontMap *pFontMap;
    pFontMap = PANGO_FT2_FONT_MAP (pango_ft2_font_map_new());
    pango_ft2_font_map_set_resolution (pFontMap, 72, 72);
    pango_ft2_font_map_set_default_substitute (pFontMap, text_subst_func, 0, 0);
    m_pPangoContext = pango_ft2_font_map_create_context (pFontMap);
    g_object_unref (pFontMap);

    pango_context_set_language(m_pPangoContext,
            pango_language_from_string ("en_US"));
    pango_context_set_base_dir(m_pPangoContext, PANGO_DIRECTION_LTR);

    initFonts();

    string sOldLang = "";
    getEnv("LC_CTYPE", sOldLang);
    setEnv("LC_CTYPE", "en-us");
    pango_font_map_list_families(PANGO_FONT_MAP(pFontMap), &m_ppFontFamilies,
            &m_NumFontFamilies);
    setEnv("LC_CTYPE", sOldLang);
    for (int i=0; i<m_NumFontFamilies; ++i) {
        m_sFonts.push_back(pango_font_family_get_name(m_ppFontFamilies[i]));
    }
    sort(m_sFonts.begin(), m_sFonts.end());
}

void TextEngine::deinit()
{
    g_free(m_ppFontFamilies);
    g_object_unref(m_pPangoContext);
    m_sFonts.clear();
}

void TextEngine::addFontDir(const std::string& sDir)
{
    deinit();
    m_sFontDirs.push_back(sDir);
    init();
}

PangoContext * TextEngine::getPangoContext()
{
    return m_pPangoContext;
}

const vector<string>& TextEngine::getFontFamilies()
{
    return m_sFonts;
}

const vector<string>& TextEngine::getFontVariants(const string& sFontName)
{
    PangoFontFamily * pCurFamily = getFontFamily(sFontName);
    PangoFontFace ** ppFaces;
    int numFaces;
    pango_font_family_list_faces (pCurFamily, &ppFaces, &numFaces);
    static vector<string> sVariants;
    for (int i=0; i<numFaces; ++i) {
        sVariants.push_back(pango_font_face_get_face_name(ppFaces[i]));
    }
    g_free(ppFaces);
    return sVariants;
}

PangoFontDescription * TextEngine::getFontDescription(const string& sFamily,
        const string& sVariant)
{
    PangoFontDescription* pDescription;
    FontDescriptionCache::iterator it;
    it = m_FontDescriptionCache.find(pair<string, string>(sFamily, sVariant));
    if (it == m_FontDescriptionCache.end()) {
        PangoFontFamily * pFamily;
        bool bFamilyFound = true;
        try {
            pFamily = getFontFamily(sFamily);
        } catch (Exception&) {
            if (m_sFontsNotFound.find(sFamily) == m_sFontsNotFound.end()) {
                AVG_TRACE(Logger::WARNING, "Could not find font face " << sFamily <<
                        ". Using sans instead.");
                m_sFontsNotFound.insert(sFamily);
            }
            bFamilyFound = false;
            pFamily = getFontFamily("sans");
        }
        PangoFontFace ** ppFaces;
        int numFaces;
        pango_font_family_list_faces(pFamily, &ppFaces, &numFaces);
        PangoFontFace * pFace = 0;
        if (sVariant == "") {
            pFace = ppFaces[0];
        } else {
            for (int i=0; i<numFaces; ++i) {
                if (equalIgnoreCase(pango_font_face_get_face_name(ppFaces[i]), sVariant)) {
                    pFace = ppFaces[i];
                }
            }
        }
        if (!pFace) {
            pFace = ppFaces[0];
            if (bFamilyFound) {
                pair<string, string> variant(sFamily, sVariant);
                if (m_VariantsNotFound.find(variant) == m_VariantsNotFound.end()) {
                    m_VariantsNotFound.insert(variant);
                    AVG_TRACE(Logger::WARNING, "Could not find font variant "
                            << sFamily << ":" << sVariant << ". Using " <<
                            pango_font_face_get_face_name(pFace) << " instead.");
                }
            }
        }
        g_free(ppFaces);
        pDescription = pango_font_face_describe(pFace);
        m_FontDescriptionCache[pair<string, string>(sFamily, sVariant)] =
                pDescription;
    } else {
        pDescription = it->second;
    }
    return pango_font_description_copy(pDescription);
}

void GLibLogFunc(const gchar *log_domain, GLogLevelFlags log_level,
        const gchar *message, gpointer unused_data)
{
#ifndef WIN32
    string s = "Pango ";
    if (log_level & G_LOG_LEVEL_ERROR) {
        s += "error: ";
    } else if (log_level & G_LOG_LEVEL_CRITICAL) {
        s += string("critical: ")+message;
        AVG_TRACE(Logger::ERROR, s);
        assert(false);
    } else if (log_level & G_LOG_LEVEL_WARNING) {
        s += "warning: ";
    } else if (log_level & G_LOG_LEVEL_MESSAGE) {
        s += "message: ";
    } else if (log_level & G_LOG_LEVEL_INFO) {
        s += "info: ";
    } else if (log_level & G_LOG_LEVEL_DEBUG) {
        s += "debug: ";
    }
    s += message;
    AVG_TRACE(Logger::WARNING, s);
#endif
}

void TextEngine::initFonts()
{
    g_type_init();
    std::string sFontConfPath = "/etc/fonts/fonts.conf";
    if (!fileExists(sFontConfPath)) {
        sFontConfPath = getAvgLibPath()+"etc/fonts/fonts.conf";
    }
    FcConfig * pConfig = FcConfigCreate();
    int Ok = (int)FcConfigParseAndLoad(pConfig,
            (const FcChar8 *)(sFontConfPath.c_str()), true);
    checkFontError(Ok, string("Font error: could not load config file ")+sFontConfPath);
    Ok = (int)FcConfigBuildFonts(pConfig);
    checkFontError(Ok, string("Font error: FcConfigBuildFonts failed."));
    Ok = (int)FcConfigSetCurrent(pConfig);
    checkFontError(Ok, string("Font error: FcConfigSetCurrent failed."));
    for(std::vector<std::string>::const_iterator it = m_sFontDirs.begin();
            it != m_sFontDirs.end(); ++it) {
        Ok = (int)FcConfigAppFontAddDir(pConfig, (const FcChar8 *)it->c_str());
        checkFontError(Ok, string("Font error: FcConfigAppFontAddDir("
                    + *it + ") failed."));
    }
    /*
       FcStrList * pCacheDirs = FcConfigGetCacheDirs(pConfig);
       FcChar8 * pDir;
       do {
       pDir = FcStrListNext(pCacheDirs);
       if (pDir) {
       cerr << pDir << endl;
       }
       } while (pDir);
     */
    g_log_set_default_handler(GLibLogFunc, 0);
}

PangoFontFamily * TextEngine::getFontFamily(const string& sFamily)
{
    PangoFontFamily * pFamily = 0;
    assert(m_NumFontFamilies != 0);
    for (int i=0; i<m_NumFontFamilies; ++i) {
        if (equalIgnoreCase(pango_font_family_get_name(m_ppFontFamilies[i]), sFamily)) {
            pFamily = m_ppFontFamilies[i];
        }
    }
    if (!pFamily) {
        throw(Exception(AVG_ERR_INVALID_ARGS,
                "getFontFamily: Font family "+sFamily+" not found."));
    }
    return pFamily;
}

void TextEngine::checkFontError(int Ok, const string& sMsg)
{
    if (Ok == 0) {
        throw Exception(AVG_ERR_FONT_INIT_FAILED, sMsg);
    }
}

}
<|endoftext|>


<commit_before>class Solution {
public:
    /**
     * @param A: An integers array.
     * @return: return any of peek positions.
     */
    int findPeak(vector<int> A) {
        // write your code here
        int l=0;
        int r=A.size();
        if(A.size()<3){
            return -1;
        }

        while(l<r){
            int mid=(l+r)>>1;

            if(A[mid]<A[mid-1]){
                //peak is in the left side
                r=mid;
            }else if(A[mid]<A[mid+1]){
                //peak is in the right side
                l=mid+1;
            }else{
                return mid;
            }
        }

    }
};

<commit_msg>add more<commit_after>class Solution {
public:
    /**
     * @param A: An integers array.
     * @return: return any of peek positions.
     */
    int findPeak(vector<int> A) {
        // write your code here
        int l=0;
        int r=A.size();
        if(A.size()<3){
            return -1;
        }

        while(l<r){
            int mid=l+((r-l)>>1);

            if(A[mid]<A[mid-1]){
                //peak is in the left side
                r=mid;
            }else if(A[mid]<A[mid+1]){
                //peak is in the right side
                l=mid+1;
            }else{
                return mid;
            }
        }

    }
};

<|endoftext|>


<commit_before><commit_msg>don't crash in LibraryLocal if the file cannot be found<commit_after><|endoftext|>


<commit_before>#include <algorithm>

#include "factory.hpp"

factory::interfaces::c_interface_manager g_factory;

NAMESPACE_REGION( factory )
NAMESPACE_REGION( interfaces )

c_interface_manager::c_interface_manager( ) {
	auto teb = reinterpret_cast< PTEB >( __readfsdword( uintptr_t( &static_cast< NT_TIB* >( nullptr )->Self ) ) );
	auto peb = teb->ProcessEnvironmentBlock;

	auto root = &peb->Ldr->InMemoryOrderModuleList;
	//iterate module list
	for ( auto entry = root->Flink->Flink->Flink->Flink; entry != root; entry = entry->Flink ) {
		PLDR_DATA_TABLE_ENTRY	data_table;
		HMODULE					module_base;
		uintptr_t				create_interface_export;
		uintptr_t				create_interface_;
		uintptr_t*				list_iterator_ptr;
		interface_iterator_t*	list_iterator;

		data_table = reinterpret_cast< PLDR_DATA_TABLE_ENTRY >( entry );
		module_base = reinterpret_cast< HMODULE >( data_table->Reserved2[ 0 ] );
		create_interface_export = uintptr_t( GetProcAddress( module_base, "CreateInterface" ) );

		if ( !create_interface_export || !is_createinterface_export( create_interface_export ) ) {
			continue;
		}

		//find the createinterface function
		create_interface_ = follow_createinterface_export( create_interface_export );
		if ( !is_createinterface_fn( create_interface_ ) ) {
			continue;
		}

		//find the list iterator
		list_iterator_ptr = find_list_ptr( create_interface_ );

		//iterate the interface list
		for ( list_iterator = reinterpret_cast< interface_iterator_t* >(
			list_iterator_ptr );
			!!list_iterator;
			list_iterator = list_iterator->m_next
			) {
			std::string name( list_iterator->m_name );
			std::string module_name( util::unicode_to_ascii(
				std::wstring( data_table->FullDllName.Buffer, data_table->FullDllName.Length ) ) );

			uintptr_t ptr = static_cast< uintptr_t( *)( ) >( list_iterator->m_create_fn )( );

			size_t version = [ & ]( ) {
				std::string ret( name );
				ret.erase( std::remove_if( ret.begin( ), ret.end( ),
					[ & ]( int i ) { return !::isdigit( i ); }
				), ret.end( ) );
				return atoi( ret.c_str( ) );
			}( );

			m_interfaces.push_back( interface_data_t{ name, module_name, version, ptr } );
		}
	}
}

END_REGION
END_REGION<commit_msg>formatting fix<commit_after>#include <algorithm>

#include "factory.hpp"

factory::interfaces::c_interface_manager g_factory;

NAMESPACE_REGION( factory )
NAMESPACE_REGION( interfaces )

c_interface_manager::c_interface_manager( ) {
	auto teb = reinterpret_cast< PTEB >( __readfsdword( uintptr_t( &static_cast< NT_TIB* >( nullptr )->Self ) ) );
	auto peb = teb->ProcessEnvironmentBlock;

	auto root = &peb->Ldr->InMemoryOrderModuleList;
	//iterate module list
	for ( auto entry = root->Flink->Flink->Flink->Flink; entry != root; entry = entry->Flink ) {
		PLDR_DATA_TABLE_ENTRY	data_table;
		HMODULE			module_base;
		uintptr_t		create_interface_export;
		uintptr_t		create_interface_;
		uintptr_t*		list_iterator_ptr;
		interface_iterator_t*	list_iterator;

		data_table = reinterpret_cast< PLDR_DATA_TABLE_ENTRY >( entry );
		module_base = reinterpret_cast< HMODULE >( data_table->Reserved2[ 0 ] );
		create_interface_export = uintptr_t( GetProcAddress( module_base, "CreateInterface" ) );

		if ( !create_interface_export || !is_createinterface_export( create_interface_export ) ) {
			continue;
		}

		//find the createinterface function
		create_interface_ = follow_createinterface_export( create_interface_export );
		if ( !is_createinterface_fn( create_interface_ ) ) {
			continue;
		}

		//find the list iterator
		list_iterator_ptr = find_list_ptr( create_interface_ );

		//iterate the interface list
		for ( list_iterator = reinterpret_cast< interface_iterator_t* >(
			list_iterator_ptr );
			!!list_iterator;
			list_iterator = list_iterator->m_next
			) {
			std::string name( list_iterator->m_name );
			std::string module_name( util::unicode_to_ascii(
				std::wstring( data_table->FullDllName.Buffer, data_table->FullDllName.Length ) ) );

			uintptr_t ptr = static_cast< uintptr_t( *)( ) >( list_iterator->m_create_fn )( );

			size_t version = [ & ]( ) {
				std::string ret( name );
				ret.erase( std::remove_if( ret.begin( ), ret.end( ),
					[ & ]( int i ) { return !::isdigit( i ); }
				), ret.end( ) );
				return atoi( ret.c_str( ) );
			}( );

			m_interfaces.push_back( interface_data_t{ name, module_name, version, ptr } );
		}
	}
}

END_REGION
END_REGION
<|endoftext|>


<commit_before><commit_msg>Erase carried element<commit_after><|endoftext|>


<commit_before>/*
 *  Copyright (c) 2015-present, Facebook, Inc.
 *
 *  This source code is licensed under the MIT license found in the LICENSE
 *  file in the root directory of this source tree.
 *
 */
#include "FifoReader.h"

#include <fcntl.h>

#include <algorithm>
#include <cstring>
#include <vector>

#include <boost/filesystem.hpp>
#include <boost/regex.hpp>

#include <folly/io/async/EventBase.h>

namespace fs = boost::filesystem;

namespace facebook {
namespace memcache {

namespace {

constexpr size_t kHeaderMagicSize = sizeof(MessageHeader().magic());

uint8_t getVersion(const folly::IOBufQueue& bufQueue) {
  const size_t kLength = kHeaderMagicSize + sizeof(MessageHeader().version());
  CHECK(bufQueue.chainLength() >= kLength)
      << "Buffer queue length is smaller than (magic + version) bytes.";

  size_t offset = 0;
  auto buf = bufQueue.front();
  while ((offset + buf->length()) < kLength) {
    offset += buf->length();
    buf = buf->next();
  }
  return buf->data()[kLength - offset - 1];
}

PacketHeader parsePacketHeader(folly::IOBufQueue& bufQueue) {
  CHECK(bufQueue.chainLength() >= sizeof(PacketHeader))
      << "Invalid packet header buffer size!";

  auto buf = bufQueue.split(sizeof(PacketHeader));
  auto bytes = buf->coalesce();

  PacketHeader header;
  std::memcpy(&header, bytes.data(), sizeof(PacketHeader));

  CHECK(header.packetSize() <= kFifoMaxPacketSize) << "Packet too large: "
                                                   << header.packetSize();

  return header;
}

MessageHeader parseMessageHeader(folly::IOBufQueue& bufQueue) {
  const size_t version = getVersion(bufQueue);
  const size_t messageHeaderSize = MessageHeader::size(version);

  CHECK(messageHeaderSize <= sizeof(MessageHeader))
      << "MessageHeader struct cannot hold message header data";
  CHECK(bufQueue.chainLength() >= messageHeaderSize)
      << "Invalid message header buffer size!";

  auto buf = bufQueue.split(messageHeaderSize);

  MessageHeader header;
  std::memcpy(&header, buf->coalesce().data(), messageHeaderSize);

  return header;
}

bool isMessageHeader(const folly::IOBufQueue& bufQueue) {
  CHECK(bufQueue.chainLength() >= kHeaderMagicSize)
      << "Buffer queue length is smaller than magic bytes.";

  uint32_t magic = 0;
  size_t i = 0;
  auto buf = bufQueue.front();
  while (i < sizeof(uint32_t)) {
    size_t j = 0;
    while (j < buf->length() && i < sizeof(uint32_t)) {
      // data is sent in little endian format.
      magic += (buf->data()[j] << (i * CHAR_BIT));
      ++i;
      ++j;
    }
    buf = buf->next();
  }
  magic = folly::Endian::little(magic);

  return magic == MessageHeader().magic();
}

} // anonymous namespace

FifoReadCallback::FifoReadCallback(
    std::string fifoName,
    const MessageReadyFn& messageReady) noexcept
    : fifoName_(std::move(fifoName)), messageReady_(messageReady) {}

void FifoReadCallback::getReadBuffer(void** bufReturn, size_t* lenReturn) {
  auto res = readBuffer_.preallocate(kMinSize, PIPE_BUF);
  *bufReturn = res.first;
  *lenReturn = res.second;
}

void FifoReadCallback::readDataAvailable(size_t len) noexcept {
  try {
    readBuffer_.postallocate(len);

    // Process any pending packet headers.
    if (pendingHeader_) {
      if (readBuffer_.chainLength() < pendingHeader_->packetSize()) {
        return;
      }
      forwardMessage(
          pendingHeader_.value(),
          readBuffer_.split(pendingHeader_->packetSize()));
      pendingHeader_.clear();
    }

    while (readBuffer_.chainLength() >= kHeaderMagicSize) {
      if (isMessageHeader(readBuffer_)) {
        if (readBuffer_.chainLength() < sizeof(MessageHeader)) {
          // Wait for more data
          return;
        }
        handleMessageHeader(parseMessageHeader(readBuffer_));
      }

      if (readBuffer_.chainLength() < sizeof(PacketHeader)) {
        // Wait for more data
        return;
      }
      auto packetHeader = parsePacketHeader(readBuffer_);
      if (packetHeader.packetSize() > readBuffer_.chainLength()) {
        // Wait for more data.
        pendingHeader_.assign(std::move(packetHeader));
        return;
      }

      forwardMessage(
          packetHeader, readBuffer_.split(packetHeader.packetSize()));
    }
  } catch (const std::exception& ex) {
    CHECK(false) << "Unexpected exception: " << ex.what();
  }
}

void FifoReadCallback::handleMessageHeader(MessageHeader msgHeader) noexcept {
  from_ = msgHeader.getLocalAddress();
  to_ = msgHeader.getPeerAddress();
  typeId_ = msgHeader.typeId();
  msgStartTime_ = msgHeader.timeUs();
  if (msgHeader.direction() == MessageDirection::Received) {
    std::swap(from_, to_);
  }
  if (!msgHeader.routerName()[0]) {
    carbonRouterName_ = facebook::memcache::MemcacheRouterInfo::name;
  } else {
    carbonRouterName_ = msgHeader.routerName();
  }
}

void FifoReadCallback::forwardMessage(
    const PacketHeader& header,
    std::unique_ptr<folly::IOBuf> buf) {
  auto data = buf->coalesce();
  CHECK(data.size() == header.packetSize()) << "Invalid header buffer size!";

  if (typeId_ != 0) {
    messageReady_(
        header.connectionId(),
        header.packetId(),
        std::move(from_),
        std::move(to_),
        typeId_,
        msgStartTime_,
        carbonRouterName_,
        data);
    typeId_ = 0;
  } else {
    VLOG(2) << "Type id is 0. Skipping message.";
  }
}

void FifoReadCallback::readEOF() noexcept {
  LOG(INFO) << "Fifo \"" << fifoName_ << "\" disconnected";
}

void FifoReadCallback::readErr(const folly::AsyncSocketException& e) noexcept {
  LOG(ERROR) << "Error reading fifo \"" << fifoName_ << "\": " << e.what();
}

FifoReaderManager::FifoReaderManager(
    folly::EventBase& evb,
    MessageReadyFn messageReady,
    std::string dir,
    std::unique_ptr<boost::regex> filenamePattern)
    : evb_(evb),
      messageReady_(std::move(messageReady)),
      directory_(std::move(dir)),
      filenamePattern_(std::move(filenamePattern)) {
  runScanDirectory();
}

std::vector<std::string> FifoReaderManager::getMatchedFiles() const {
  std::vector<std::string> fifos;

  try {
    if (!fs::exists(directory_)) {
      LOG(ERROR) << "Directory \"" << directory_ << "\" not found.";
    } else if (!fs::is_directory(directory_)) {
      LOG(ERROR) << "Path \"" << directory_ << "\" is not a directory.";
    } else {
      fs::directory_iterator endIt; // default construction = end iterator.
      for (fs::directory_iterator it(directory_); it != endIt; ++it) {
        if (fs::is_directory(it->status())) {
          continue;
        }
        auto& path = it->path();
        if (!filenamePattern_ || boost::regex_search(
                                     path.filename().string(),
                                     *filenamePattern_,
                                     boost::regex_constants::match_default)) {
          fifos.emplace_back(path.string());
        }
      }
    }
  } catch (const fs::filesystem_error& ex) {
    LOG(ERROR) << "Failed to find fifos: " << ex.what();
  }

  return fifos;
}

void FifoReaderManager::runScanDirectory() {
  auto fifos = getMatchedFiles();
  for (const auto& fifo : fifos) {
    if (fifoReaders_.find(fifo) != fifoReaders_.end()) {
      continue;
    }
    auto fd = ::open(fifo.c_str(), O_RDONLY | O_NONBLOCK);
    if (fd >= 0) {
      auto pipeReader = folly::AsyncPipeReader::UniquePtr(
          new folly::AsyncPipeReader(&evb_, fd));
      auto callback = std::make_unique<FifoReadCallback>(fifo, messageReady_);
      pipeReader->setReadCB(callback.get());
      fifoReaders_.emplace(
          fifo, FifoReader(std::move(pipeReader), std::move(callback)));
    } else {
      PLOG(WARNING) << "Error opening fifo: " << fifo;
    }
  }

  evb_.runAfterDelay(
      [this]() { runScanDirectory(); }, kPollDirectoryIntervalMs);
}

void FifoReaderManager::unregisterCallbacks() {
  for (auto& fifoReader : fifoReaders_) {
    fifoReader.second.first->setReadCB(nullptr);
  }
}

} // memcache
} // facebook
<commit_msg>Shift AsyncPipe to NetworkSocket<commit_after>/*
 *  Copyright (c) 2015-present, Facebook, Inc.
 *
 *  This source code is licensed under the MIT license found in the LICENSE
 *  file in the root directory of this source tree.
 *
 */
#include "FifoReader.h"

#include <fcntl.h>

#include <algorithm>
#include <cstring>
#include <vector>

#include <boost/filesystem.hpp>
#include <boost/regex.hpp>

#include <folly/io/async/EventBase.h>

namespace fs = boost::filesystem;

namespace facebook {
namespace memcache {

namespace {

constexpr size_t kHeaderMagicSize = sizeof(MessageHeader().magic());

uint8_t getVersion(const folly::IOBufQueue& bufQueue) {
  const size_t kLength = kHeaderMagicSize + sizeof(MessageHeader().version());
  CHECK(bufQueue.chainLength() >= kLength)
      << "Buffer queue length is smaller than (magic + version) bytes.";

  size_t offset = 0;
  auto buf = bufQueue.front();
  while ((offset + buf->length()) < kLength) {
    offset += buf->length();
    buf = buf->next();
  }
  return buf->data()[kLength - offset - 1];
}

PacketHeader parsePacketHeader(folly::IOBufQueue& bufQueue) {
  CHECK(bufQueue.chainLength() >= sizeof(PacketHeader))
      << "Invalid packet header buffer size!";

  auto buf = bufQueue.split(sizeof(PacketHeader));
  auto bytes = buf->coalesce();

  PacketHeader header;
  std::memcpy(&header, bytes.data(), sizeof(PacketHeader));

  CHECK(header.packetSize() <= kFifoMaxPacketSize) << "Packet too large: "
                                                   << header.packetSize();

  return header;
}

MessageHeader parseMessageHeader(folly::IOBufQueue& bufQueue) {
  const size_t version = getVersion(bufQueue);
  const size_t messageHeaderSize = MessageHeader::size(version);

  CHECK(messageHeaderSize <= sizeof(MessageHeader))
      << "MessageHeader struct cannot hold message header data";
  CHECK(bufQueue.chainLength() >= messageHeaderSize)
      << "Invalid message header buffer size!";

  auto buf = bufQueue.split(messageHeaderSize);

  MessageHeader header;
  std::memcpy(&header, buf->coalesce().data(), messageHeaderSize);

  return header;
}

bool isMessageHeader(const folly::IOBufQueue& bufQueue) {
  CHECK(bufQueue.chainLength() >= kHeaderMagicSize)
      << "Buffer queue length is smaller than magic bytes.";

  uint32_t magic = 0;
  size_t i = 0;
  auto buf = bufQueue.front();
  while (i < sizeof(uint32_t)) {
    size_t j = 0;
    while (j < buf->length() && i < sizeof(uint32_t)) {
      // data is sent in little endian format.
      magic += (buf->data()[j] << (i * CHAR_BIT));
      ++i;
      ++j;
    }
    buf = buf->next();
  }
  magic = folly::Endian::little(magic);

  return magic == MessageHeader().magic();
}

} // anonymous namespace

FifoReadCallback::FifoReadCallback(
    std::string fifoName,
    const MessageReadyFn& messageReady) noexcept
    : fifoName_(std::move(fifoName)), messageReady_(messageReady) {}

void FifoReadCallback::getReadBuffer(void** bufReturn, size_t* lenReturn) {
  auto res = readBuffer_.preallocate(kMinSize, PIPE_BUF);
  *bufReturn = res.first;
  *lenReturn = res.second;
}

void FifoReadCallback::readDataAvailable(size_t len) noexcept {
  try {
    readBuffer_.postallocate(len);

    // Process any pending packet headers.
    if (pendingHeader_) {
      if (readBuffer_.chainLength() < pendingHeader_->packetSize()) {
        return;
      }
      forwardMessage(
          pendingHeader_.value(),
          readBuffer_.split(pendingHeader_->packetSize()));
      pendingHeader_.clear();
    }

    while (readBuffer_.chainLength() >= kHeaderMagicSize) {
      if (isMessageHeader(readBuffer_)) {
        if (readBuffer_.chainLength() < sizeof(MessageHeader)) {
          // Wait for more data
          return;
        }
        handleMessageHeader(parseMessageHeader(readBuffer_));
      }

      if (readBuffer_.chainLength() < sizeof(PacketHeader)) {
        // Wait for more data
        return;
      }
      auto packetHeader = parsePacketHeader(readBuffer_);
      if (packetHeader.packetSize() > readBuffer_.chainLength()) {
        // Wait for more data.
        pendingHeader_.assign(std::move(packetHeader));
        return;
      }

      forwardMessage(
          packetHeader, readBuffer_.split(packetHeader.packetSize()));
    }
  } catch (const std::exception& ex) {
    CHECK(false) << "Unexpected exception: " << ex.what();
  }
}

void FifoReadCallback::handleMessageHeader(MessageHeader msgHeader) noexcept {
  from_ = msgHeader.getLocalAddress();
  to_ = msgHeader.getPeerAddress();
  typeId_ = msgHeader.typeId();
  msgStartTime_ = msgHeader.timeUs();
  if (msgHeader.direction() == MessageDirection::Received) {
    std::swap(from_, to_);
  }
  if (!msgHeader.routerName()[0]) {
    carbonRouterName_ = facebook::memcache::MemcacheRouterInfo::name;
  } else {
    carbonRouterName_ = msgHeader.routerName();
  }
}

void FifoReadCallback::forwardMessage(
    const PacketHeader& header,
    std::unique_ptr<folly::IOBuf> buf) {
  auto data = buf->coalesce();
  CHECK(data.size() == header.packetSize()) << "Invalid header buffer size!";

  if (typeId_ != 0) {
    messageReady_(
        header.connectionId(),
        header.packetId(),
        std::move(from_),
        std::move(to_),
        typeId_,
        msgStartTime_,
        carbonRouterName_,
        data);
    typeId_ = 0;
  } else {
    VLOG(2) << "Type id is 0. Skipping message.";
  }
}

void FifoReadCallback::readEOF() noexcept {
  LOG(INFO) << "Fifo \"" << fifoName_ << "\" disconnected";
}

void FifoReadCallback::readErr(const folly::AsyncSocketException& e) noexcept {
  LOG(ERROR) << "Error reading fifo \"" << fifoName_ << "\": " << e.what();
}

FifoReaderManager::FifoReaderManager(
    folly::EventBase& evb,
    MessageReadyFn messageReady,
    std::string dir,
    std::unique_ptr<boost::regex> filenamePattern)
    : evb_(evb),
      messageReady_(std::move(messageReady)),
      directory_(std::move(dir)),
      filenamePattern_(std::move(filenamePattern)) {
  runScanDirectory();
}

std::vector<std::string> FifoReaderManager::getMatchedFiles() const {
  std::vector<std::string> fifos;

  try {
    if (!fs::exists(directory_)) {
      LOG(ERROR) << "Directory \"" << directory_ << "\" not found.";
    } else if (!fs::is_directory(directory_)) {
      LOG(ERROR) << "Path \"" << directory_ << "\" is not a directory.";
    } else {
      fs::directory_iterator endIt; // default construction = end iterator.
      for (fs::directory_iterator it(directory_); it != endIt; ++it) {
        if (fs::is_directory(it->status())) {
          continue;
        }
        auto& path = it->path();
        if (!filenamePattern_ || boost::regex_search(
                                     path.filename().string(),
                                     *filenamePattern_,
                                     boost::regex_constants::match_default)) {
          fifos.emplace_back(path.string());
        }
      }
    }
  } catch (const fs::filesystem_error& ex) {
    LOG(ERROR) << "Failed to find fifos: " << ex.what();
  }

  return fifos;
}

void FifoReaderManager::runScanDirectory() {
  auto fifos = getMatchedFiles();
  for (const auto& fifo : fifos) {
    if (fifoReaders_.find(fifo) != fifoReaders_.end()) {
      continue;
    }
    auto fd = ::open(fifo.c_str(), O_RDONLY | O_NONBLOCK);
    if (fd >= 0) {
      auto pipeReader = folly::AsyncPipeReader::UniquePtr(
          new folly::AsyncPipeReader(&evb_, folly::NetworkSocket::fromFd(fd)));
      auto callback = std::make_unique<FifoReadCallback>(fifo, messageReady_);
      pipeReader->setReadCB(callback.get());
      fifoReaders_.emplace(
          fifo, FifoReader(std::move(pipeReader), std::move(callback)));
    } else {
      PLOG(WARNING) << "Error opening fifo: " << fifo;
    }
  }

  evb_.runAfterDelay(
      [this]() { runScanDirectory(); }, kPollDirectoryIntervalMs);
}

void FifoReaderManager::unregisterCallbacks() {
  for (auto& fifoReader : fifoReaders_) {
    fifoReader.second.first->setReadCB(nullptr);
  }
}

} // memcache
} // facebook
<|endoftext|>


<commit_before><commit_msg>Add FMU import test<commit_after><|endoftext|>


<commit_before><commit_msg>Fix Modelica test hopsan install path<commit_after><|endoftext|>


<commit_before>/*
 * This file is part of the LibreOffice project.
 *
 * Based on LLVM/Clang.
 *
 * This file is distributed under the University of Illinois Open Source
 * License. See LICENSE.TXT for details.
 *
 */

#include "unusedvariablecheck.hxx"

#include <clang/Basic/SourceManager.h>

namespace loplugin
{

/*
Check for unused classes where the compiler cannot decide (e.g. because of
non-trivial or extern ctors) if a variable is unused if only its ctor/dtor
are called and nothing else. For example std::vector is a class where
the ctor may call further functions, but an unused std::string variable
does nothing. On the other hand, std::auto_ptr instances are used
for their dtors and so are not unused even if not otherwise accessed.

Classes which are safe to be warned about need to be marked using
SAL_WARN_UNUSED (see e.g. OUString). For external classes such as std::vector
that cannot be edited there is a manual list below.
*/

UnusedVariableCheck::UnusedVariableCheck( ASTContext& context )
    : Plugin( context )
    {
    }

void UnusedVariableCheck::run()
    {
    TraverseDecl( context.getTranslationUnitDecl());
    }

bool UnusedVariableCheck::VisitNamedDecl( NamedDecl* declaration )
    {
    if( ignoreLocation( declaration ))
        return true;
    if( !isa< VarDecl >( declaration ))
        return true;
    const VarDecl* var = cast< VarDecl >( declaration );
    if( var->isReferenced() || var->isUsed())
        return true;
    if( CXXRecordDecl* type = var->getType()->getAsCXXRecordDecl())
        {
        bool warn_unused = false;
        if( type->hasAttrs())
            {
            // Clang currently has no support for custom attributes, but
            // the annotate attribute comes close, so check for __attribute__((annotate("lo_warn_unused")))
            for( specific_attr_iterator<AnnotateAttr> i = type->specific_attr_begin<AnnotateAttr>(),
                    e = type->specific_attr_end<AnnotateAttr>();
                 i != e;
                 ++i )
                {
                if( (*i)->getAnnotation() == "lo_warn_unused" )
                    {
                    warn_unused = true;
                    break;
                    }
                }
            }
        if( !warn_unused )
            {
            std::string n = type->getQualifiedNameAsString();
            // Check some common non-LO types.
            if( n == "std::string" || n == "std::basic_string"
                || n == "std::list" || n == "std::__debug::list"
                || n == "std::vector" || n == "std::__debug::vector" )
                warn_unused = true;
            }
        if( warn_unused )
            {
            if( const ParmVarDecl* param = dyn_cast< ParmVarDecl >( var ))
                {
                // If this declaration does not have a body, then the parameter is indeed not used,
                // so ignore.
                if( const FunctionDecl* func = dyn_cast< FunctionDecl >( param->getParentFunctionOrMethod()))
                    if( !func->doesThisDeclarationHaveABody())
                        return true;
                report( DiagnosticsEngine::Warning, "unused parameter %0 [loplugin]",
                    var->getLocStart()) << var->getDeclName();
                }
            else
                report( DiagnosticsEngine::Warning, "unused variable %0 [loplugin]",
                    var->getLocStart()) << var->getDeclName();
            }
        }
    return true;
    }

} // namespace
<commit_msg>do not report unnamed parameters as unused<commit_after>/*
 * This file is part of the LibreOffice project.
 *
 * Based on LLVM/Clang.
 *
 * This file is distributed under the University of Illinois Open Source
 * License. See LICENSE.TXT for details.
 *
 */

#include "unusedvariablecheck.hxx"

#include <clang/Basic/SourceManager.h>

namespace loplugin
{

/*
Check for unused classes where the compiler cannot decide (e.g. because of
non-trivial or extern ctors) if a variable is unused if only its ctor/dtor
are called and nothing else. For example std::vector is a class where
the ctor may call further functions, but an unused std::string variable
does nothing. On the other hand, std::auto_ptr instances are used
for their dtors and so are not unused even if not otherwise accessed.

Classes which are safe to be warned about need to be marked using
SAL_WARN_UNUSED (see e.g. OUString). For external classes such as std::vector
that cannot be edited there is a manual list below.
*/

UnusedVariableCheck::UnusedVariableCheck( ASTContext& context )
    : Plugin( context )
    {
    }

void UnusedVariableCheck::run()
    {
    TraverseDecl( context.getTranslationUnitDecl());
    }

bool UnusedVariableCheck::VisitNamedDecl( NamedDecl* declaration )
    {
    if( ignoreLocation( declaration ))
        return true;
    if( !isa< VarDecl >( declaration ))
        return true;
    const VarDecl* var = cast< VarDecl >( declaration );
    if( var->isReferenced() || var->isUsed())
        return true;
    if( CXXRecordDecl* type = var->getType()->getAsCXXRecordDecl())
        {
        bool warn_unused = false;
        if( type->hasAttrs())
            {
            // Clang currently has no support for custom attributes, but
            // the annotate attribute comes close, so check for __attribute__((annotate("lo_warn_unused")))
            for( specific_attr_iterator<AnnotateAttr> i = type->specific_attr_begin<AnnotateAttr>(),
                    e = type->specific_attr_end<AnnotateAttr>();
                 i != e;
                 ++i )
                {
                if( (*i)->getAnnotation() == "lo_warn_unused" )
                    {
                    warn_unused = true;
                    break;
                    }
                }
            }
        if( !warn_unused )
            {
            std::string n = type->getQualifiedNameAsString();
            // Check some common non-LO types.
            if( n == "std::string" || n == "std::basic_string"
                || n == "std::list" || n == "std::__debug::list"
                || n == "std::vector" || n == "std::__debug::vector" )
                warn_unused = true;
            }
        if( warn_unused )
            {
            if( const ParmVarDecl* param = dyn_cast< ParmVarDecl >( var ))
                {
                if( !param->getDeclName())
                    return true; // unnamed parameter -> unused
                // If this declaration does not have a body, then the parameter is indeed not used,
                // so ignore.
                if( const FunctionDecl* func = dyn_cast< FunctionDecl >( param->getParentFunctionOrMethod()))
                    if( !func->doesThisDeclarationHaveABody())
                        return true;
                report( DiagnosticsEngine::Warning, "unused parameter %0 [loplugin]",
                    var->getLocStart()) << var->getDeclName();
                }
            else
                report( DiagnosticsEngine::Warning, "unused variable %0 [loplugin]",
                    var->getLocStart()) << var->getDeclName();
            }
        }
    return true;
    }

} // namespace
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS changefileheader (1.19.216); FILE MERGED 2008/04/01 15:08:35 thb 1.19.216.3: #i85898# Stripping all external header guards 2008/04/01 10:52:48 thb 1.19.216.2: #i85898# Stripping all external header guards 2008/03/28 15:23:24 rt 1.19.216.1: #i87441# Change license header to LPGL v3.<commit_after><|endoftext|>


<commit_before><commit_msg>Try fix linux compile error.<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: dll.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: mhu $ $Date: 2001-10-15 06:56:37 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DLL_HXX
#define _DLL_HXX

#ifdef WIN

#ifndef _SVWIN_H
#include <svwin.h>
#endif

// ----------------------
// - Zugriffsfunktionen -
// ----------------------

struct SVDATA;

extern "C"
{
// IN APPDATA.ASM
SVDATA* FAR PASCAL GetSVData();
}

// IN TOOLSDLL.CXX
void SetSVData( SVDATA* pSVData );

#endif

// -------------------------------
// - Sonstige Funktionen fuer SV -
// -------------------------------

// Um Resourcen wieder freizugeben
inline void ImpDeInitWinTools() {}

#endif /* _DLL_HXX */
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.406); FILE MERGED 2005/09/05 13:59:44 rt 1.3.406.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dll.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 14:44:22 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _DLL_HXX
#define _DLL_HXX

#ifdef WIN

#ifndef _SVWIN_H
#include <svwin.h>
#endif

// ----------------------
// - Zugriffsfunktionen -
// ----------------------

struct SVDATA;

extern "C"
{
// IN APPDATA.ASM
SVDATA* FAR PASCAL GetSVData();
}

// IN TOOLSDLL.CXX
void SetSVData( SVDATA* pSVData );

#endif

// -------------------------------
// - Sonstige Funktionen fuer SV -
// -------------------------------

// Um Resourcen wieder freizugeben
inline void ImpDeInitWinTools() {}

#endif /* _DLL_HXX */
<|endoftext|>


<commit_before>/*
 * BloscPlugin.cpp
 *
 *  Created on: 22 Jan 2018
 *      Author: Ulrik Pedersen
 */
#include <cstdlib>
#include <blosc.h>
#include <version.h>
#include <BloscPlugin.h>

namespace FrameProcessor
{

/**
 * The constructor sets up logging used within the class.
 */
BloscPlugin::BloscPlugin()
{
  // Setup logging for the class
  logger_ = Logger::getLogger("FW.BloscPlugin");
  logger_->setLevel(Level::getAll());
  LOG4CXX_TRACE(logger_, "BloscPlugin constructor.");

  //blosc_init(); // not required for blosc >= v1.9
  LOG4CXX_TRACE(logger_, "Blosc Version: " << blosc_get_version_string());
  LOG4CXX_TRACE(logger_, "Blosc list available compressors: " << blosc_list_compressors());
  LOG4CXX_TRACE(logger_, "Blosc current compressor: " << blosc_get_compressor());
  LOG4CXX_TRACE(logger_, "Blosc # threads: " << blosc_get_nthreads());

}

/**
 * Destructor.
 */
BloscPlugin::~BloscPlugin()
{
  LOG4CXX_TRACE(logger_, "BloscPlugin destructor.");
}

/**
 * Compress one frame, return compressed frame.
 */
boost::shared_ptr<Frame> BloscPlugin::compress_frame(boost::shared_ptr<Frame> src_frame)
{
  int compressed_size = 0;
  boost::shared_ptr <Frame> dest_frame;

  const void* src_data_ptr = static_cast<const void*>(
      static_cast<const char*>(src_frame->get_data())
  );
  const size_t raw_data_size = src_frame->get_data_size();
  LOG4CXX_TRACE(logger_, "Frame data size: " << raw_data_size);

  try {
    size_t dest_data_size = src_frame->get_data_size() + BLOSC_MAX_OVERHEAD;
    // TODO: is this malloc really necessary? Can't we get writable DataBlocks somehow?
    void *dest_data_ptr = malloc(dest_data_size);
    // TODO: error check on the malloc here...

    LOG4CXX_TRACE(logger_, "Compressing frame no. " << src_frame->get_frame_number());
    // TODO: all args are hard-coded here and need to be turned into parameters
    compressed_size = blosc_compress(1, 1, src_frame->get_data_type_size(),
                                     raw_data_size, src_data_ptr, dest_data_ptr, dest_data_size);
    if (compressed_size > 0) {
      double factor = 0.;
      factor = (double)raw_data_size / (double)compressed_size;
      LOG4CXX_TRACE(logger_, "Compression factor of: " << factor);
    }

    dest_frame = boost::shared_ptr<Frame>(new Frame(src_frame->get_dataset_name()));

    LOG4CXX_TRACE(logger_, "Copying compressed data to output frame. (" << compressed_size << " bytes)");
    // I wish we had a pointer swap feature on the Frame class and avoid this unnecessary copy...
    dest_frame->copy_data(dest_data_ptr, compressed_size);
    free(dest_data_ptr);
    dest_data_ptr = NULL;

    // I wish we had a shallow-copy feature on the Frame class...
    dest_frame->set_data_type(src_frame->get_data_type());
    dest_frame->set_frame_number(src_frame->get_frame_number());
    dest_frame->set_acquisition_id(src_frame->get_acquisition_id());
    // TODO: is this the correct way to get and set dimensions?
    dest_frame->set_dimensions("data", src_frame->get_dimensions("data"));
  }
  catch (const std::exception& e) {
    LOG4CXX_ERROR(logger_, "Serious error in Blosc compression: " << e.what());
  }
  return dest_frame;
}

  /**
 * Perform compression on the frame and output a new, compressed Frame.
 *
 * \param[in] frame - Pointer to a Frame object.
 */
void BloscPlugin::process_frame(boost::shared_ptr<Frame> src_frame)
{
  LOG4CXX_TRACE(logger_, "Received a new frame...");
  boost::shared_ptr <Frame> compressed_frame = this->compress_frame(src_frame);
  LOG4CXX_TRACE(logger_, "Pushing compressed frame");
  this->push(compressed_frame);
}

int BloscPlugin::get_version_major()
{
  return ODIN_DATA_VERSION_MAJOR;
}

int BloscPlugin::get_version_minor()
{
  return ODIN_DATA_VERSION_MINOR;
}

int BloscPlugin::get_version_patch()
{
  return ODIN_DATA_VERSION_PATCH;
}

std::string BloscPlugin::get_version_short()
{
  return ODIN_DATA_VERSION_STR_SHORT;
}

std::string BloscPlugin::get_version_long()
{
  return ODIN_DATA_VERSION_STR;
}

} /* namespace FrameProcessor */
<commit_msg>BloscPlugin: tweaking malloc, free and error handling<commit_after>/*
 * BloscPlugin.cpp
 *
 *  Created on: 22 Jan 2018
 *      Author: Ulrik Pedersen
 */
#include <cstdlib>
#include <blosc.h>
#include <version.h>
#include <BloscPlugin.h>

namespace FrameProcessor
{

/**
 * The constructor sets up logging used within the class.
 */
BloscPlugin::BloscPlugin()
{
  // Setup logging for the class
  logger_ = Logger::getLogger("FW.BloscPlugin");
  logger_->setLevel(Level::getAll());
  LOG4CXX_TRACE(logger_, "BloscPlugin constructor.");

  //blosc_init(); // not required for blosc >= v1.9
  LOG4CXX_TRACE(logger_, "Blosc Version: " << blosc_get_version_string());
  LOG4CXX_TRACE(logger_, "Blosc list available compressors: " << blosc_list_compressors());
  LOG4CXX_TRACE(logger_, "Blosc current compressor: " << blosc_get_compressor());
  LOG4CXX_TRACE(logger_, "Blosc # threads: " << blosc_get_nthreads());

}

/**
 * Destructor.
 */
BloscPlugin::~BloscPlugin()
{
  LOG4CXX_TRACE(logger_, "BloscPlugin destructor.");
}

/**
 * Compress one frame, return compressed frame.
 */
boost::shared_ptr<Frame> BloscPlugin::compress_frame(boost::shared_ptr<Frame> src_frame)
{
  int compressed_size = 0;
  boost::shared_ptr <Frame> dest_frame;

  const void* src_data_ptr = static_cast<const void*>(
      static_cast<const char*>(src_frame->get_data())
  );
  const size_t raw_data_size = src_frame->get_data_size();
  LOG4CXX_TRACE(logger_, "Frame data size: " << raw_data_size);

  size_t dest_data_size = src_frame->get_data_size() + BLOSC_MAX_OVERHEAD;
  // TODO: is this malloc really necessary? Can't we get writable DataBlocks somehow?
  void *dest_data_ptr = malloc(dest_data_size);
  if (dest_data_ptr == NULL) {throw std::runtime_error("Failed to malloc buffer for Blosc compression output");}

  try {
    LOG4CXX_TRACE(logger_, "Compressing frame no. " << src_frame->get_frame_number());
    // TODO: all args are hard-coded here and need to be turned into parameters
    compressed_size = blosc_compress(1, 1, src_frame->get_data_type_size(),
                                     raw_data_size, src_data_ptr, dest_data_ptr, dest_data_size);
    if (compressed_size > 0) {
      double factor = 0.;
      factor = (double)raw_data_size / (double)compressed_size;
      LOG4CXX_TRACE(logger_, "Compression factor of: " << factor);
    }

    dest_frame = boost::shared_ptr<Frame>(new Frame(src_frame->get_dataset_name()));

    LOG4CXX_TRACE(logger_, "Copying compressed data to output frame. (" << compressed_size << " bytes)");
    // I wish we had a pointer swap feature on the Frame class and avoid this unnecessary copy...
    dest_frame->copy_data(dest_data_ptr, compressed_size);
    if (dest_data_ptr != NULL) {free(dest_data_ptr); dest_data_ptr = NULL;}

    // I wish we had a shallow-copy feature on the Frame class...
    dest_frame->set_data_type(src_frame->get_data_type());
    dest_frame->set_frame_number(src_frame->get_frame_number());
    dest_frame->set_acquisition_id(src_frame->get_acquisition_id());
    // TODO: is this the correct way to get and set dimensions?
    dest_frame->set_dimensions("data", src_frame->get_dimensions("data"));
  }
  catch (const std::exception& e) {
    LOG4CXX_ERROR(logger_, "Serious error in Blosc compression: " << e.what());
    if (dest_data_ptr != NULL) {free(dest_data_ptr); dest_data_ptr = NULL;}
  }
  return dest_frame;
}

  /**
 * Perform compression on the frame and output a new, compressed Frame.
 *
 * \param[in] frame - Pointer to a Frame object.
 */
void BloscPlugin::process_frame(boost::shared_ptr<Frame> src_frame)
{
  LOG4CXX_TRACE(logger_, "Received a new frame...");
  boost::shared_ptr <Frame> compressed_frame = this->compress_frame(src_frame);
  LOG4CXX_TRACE(logger_, "Pushing compressed frame");
  this->push(compressed_frame);
}

int BloscPlugin::get_version_major()
{
  return ODIN_DATA_VERSION_MAJOR;
}

int BloscPlugin::get_version_minor()
{
  return ODIN_DATA_VERSION_MINOR;
}

int BloscPlugin::get_version_patch()
{
  return ODIN_DATA_VERSION_PATCH;
}

std::string BloscPlugin::get_version_short()
{
  return ODIN_DATA_VERSION_STR_SHORT;
}

std::string BloscPlugin::get_version_long()
{
  return ODIN_DATA_VERSION_STR;
}

} /* namespace FrameProcessor */
<|endoftext|>


<commit_before>// Copyright (c) 2009 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 "config.h"

#include <wtf/HashSet.h>
#include <wtf/RefPtr.h>
#include <wtf/Vector.h>

#include "Document.h"
#include "Frame.h"
#include "Page.h"
#include "V8Binding.h"
#include "V8DOMWindow.h"
#include "V8Index.h"
#include "V8Proxy.h"
#undef LOG

#include "grit/webkit_resources.h"
#include "third_party/WebKit/WebKit/chromium/src/WebViewImpl.h"
#include "webkit/glue/devtools/debugger_agent_impl.h"
#include "webkit/glue/devtools/debugger_agent_manager.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webdevtoolsagent_impl.h"
#include "webkit/glue/webkit_glue.h"

using WebCore::DOMWindow;
using WebCore::Document;
using WebCore::Frame;
using WebCore::Page;
using WebCore::String;
using WebCore::V8ClassIndex;
using WebCore::V8Custom;
using WebCore::V8DOMWindow;
using WebCore::V8DOMWrapper;
using WebCore::V8Proxy;
using WebKit::WebViewImpl;

DebuggerAgentImpl::DebuggerAgentImpl(
    WebViewImpl* web_view_impl,
    DebuggerAgentDelegate* delegate,
    WebDevToolsAgentImpl* webdevtools_agent)
    : web_view_impl_(web_view_impl),
      delegate_(delegate),
      webdevtools_agent_(webdevtools_agent),
      auto_continue_on_exception_(false) {
  DebuggerAgentManager::DebugAttach(this);
}

DebuggerAgentImpl::~DebuggerAgentImpl() {
  DebuggerAgentManager::DebugDetach(this);
}

void DebuggerAgentImpl::GetContextId() {
  delegate_->SetContextId(webdevtools_agent_->host_id());
}

void DebuggerAgentImpl::DebuggerOutput(const String& command) {
  delegate_->DebuggerOutput(command);
  webdevtools_agent_->ForceRepaint();
}

// static
void DebuggerAgentImpl::CreateUtilityContext(
    Frame* frame,
    v8::Persistent<v8::Context>* context) {
  v8::HandleScope scope;

  // TODO(pfeldman): Validate against Soeren.
  // Set up the DOM window as the prototype of the new global object.
  v8::Handle<v8::Context> window_context =
      V8Proxy::context(frame);
  v8::Handle<v8::Object> window_global = window_context->Global();
  v8::Handle<v8::Object> window_wrapper =
      V8DOMWrapper::lookupDOMWrapper(V8ClassIndex::DOMWINDOW, window_global);

  ASSERT(V8DOMWrapper::convertDOMWrapperToNative<DOMWindow>(window_wrapper) ==
      frame->domWindow());

  v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();

  // TODO(yurys): provide a function in v8 bindings that would make the
  // utility context more like main world context of the inspected frame,
  // otherwise we need to manually make it satisfy various invariants
  // that V8Proxy::getEntered and some other V8Proxy methods expect to find
  // on v8 contexts on the contexts stack.
  // See V8Proxy::createNewContext.
  //
  // Install a security handler with V8.
  global_template->SetAccessCheckCallbacks(
      V8DOMWindow::namedSecurityCheck,
      V8DOMWindow::indexedSecurityCheck,
      v8::Integer::New(V8ClassIndex::DOMWINDOW));
  // We set number of internal fields to match that in V8DOMWindow wrapper.
  // See http://crbug.com/28961
  global_template->SetInternalFieldCount(
      V8Custom::kDOMWindowInternalFieldCount);

  *context = v8::Context::New(
      NULL /* no extensions */,
      global_template,
      v8::Handle<v8::Object>());
  v8::Context::Scope context_scope(*context);
  v8::Handle<v8::Object> global = (*context)->Global();

  v8::Handle<v8::String> implicit_proto_string = v8::String::New("__proto__");
  global->Set(implicit_proto_string, window_wrapper);

  // Give the code running in the new context a way to get access to the
  // original context.
  global->Set(v8::String::New("contentWindow"), window_global);

  // Inject javascript into the context.
  base::StringPiece injectjs_webkit =
      webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_WEBKIT_JS);
  v8::Script::Compile(
      v8::String::New(injectjs_webkit.as_string().c_str()))->Run();
  base::StringPiece inject_dispatchjs = webkit_glue::GetDataResource(
      IDR_DEVTOOLS_INJECT_DISPATCH_JS);
  v8::Script::Compile(v8::String::New(
      inject_dispatchjs.as_string().c_str()))->Run();
}

String DebuggerAgentImpl::ExecuteUtilityFunction(
    v8::Handle<v8::Context> context,
    int call_id,
    const char* object,
    const String &function_name,
    const String& json_args,
    bool async,
    String* exception) {
  v8::HandleScope scope;
  ASSERT(!context.IsEmpty());
  if (context.IsEmpty()) {
    *exception = "No window context.";
    return "";
  }
  v8::Context::Scope context_scope(context);

  DebuggerAgentManager::UtilityContextScope utility_scope;

  v8::Handle<v8::Object> dispatch_object = v8::Handle<v8::Object>::Cast(
      context->Global()->Get(v8::String::New(object)));

  v8::Handle<v8::Value> dispatch_function =
      dispatch_object->Get(v8::String::New("dispatch"));
  ASSERT(dispatch_function->IsFunction());
  v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(dispatch_function);

  v8::Handle<v8::String> function_name_wrapper = v8::Handle<v8::String>(
      v8::String::New(function_name.utf8().data()));
  v8::Handle<v8::String> json_args_wrapper = v8::Handle<v8::String>(
      v8::String::New(json_args.utf8().data()));
  v8::Handle<v8::Number> call_id_wrapper = v8::Handle<v8::Number>(
      v8::Number::New(async ? call_id : 0));

  v8::Handle<v8::Value> args[] = {
    function_name_wrapper,
    json_args_wrapper,
    call_id_wrapper
  };

  v8::TryCatch try_catch;
  v8::Handle<v8::Value> res_obj = function->Call(context->Global(), 3, args);
  if (try_catch.HasCaught()) {
    *exception = WebCore::toWebCoreString(try_catch.Message()->Get());
    return "";
  } else {
    return WebCore::toWebCoreStringWithNullCheck(res_obj);
  }
}

void DebuggerAgentImpl::ExecuteVoidJavaScript(v8::Handle<v8::Context> context) {
  v8::HandleScope scope;
  ASSERT(!context.IsEmpty());
  v8::Context::Scope context_scope(context);
  DebuggerAgentManager::UtilityContextScope utility_scope;

  v8::Handle<v8::Value> function =
      context->Global()->Get(v8::String::New("devtools$$void"));
  ASSERT(function->IsFunction());
  v8::Handle<v8::Value> args[] = {
    v8::Local<v8::Value>()
  };
  v8::Handle<v8::Function>::Cast(function)->Call(context->Global(), 0, args);
}

WebCore::Page* DebuggerAgentImpl::GetPage() {
  return web_view_impl_->page();
}
<commit_msg>DevTools: fix crash caused by dereferening empty handle<commit_after>// Copyright (c) 2009 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 "config.h"

#include <wtf/HashSet.h>
#include <wtf/RefPtr.h>
#include <wtf/Vector.h>

#include "Document.h"
#include "Frame.h"
#include "Page.h"
#include "V8Binding.h"
#include "V8DOMWindow.h"
#include "V8Index.h"
#include "V8Proxy.h"
#undef LOG

#include "grit/webkit_resources.h"
#include "third_party/WebKit/WebKit/chromium/src/WebViewImpl.h"
#include "webkit/glue/devtools/debugger_agent_impl.h"
#include "webkit/glue/devtools/debugger_agent_manager.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webdevtoolsagent_impl.h"
#include "webkit/glue/webkit_glue.h"

using WebCore::DOMWindow;
using WebCore::Document;
using WebCore::Frame;
using WebCore::Page;
using WebCore::String;
using WebCore::V8ClassIndex;
using WebCore::V8Custom;
using WebCore::V8DOMWindow;
using WebCore::V8DOMWrapper;
using WebCore::V8Proxy;
using WebKit::WebViewImpl;

DebuggerAgentImpl::DebuggerAgentImpl(
    WebViewImpl* web_view_impl,
    DebuggerAgentDelegate* delegate,
    WebDevToolsAgentImpl* webdevtools_agent)
    : web_view_impl_(web_view_impl),
      delegate_(delegate),
      webdevtools_agent_(webdevtools_agent),
      auto_continue_on_exception_(false) {
  DebuggerAgentManager::DebugAttach(this);
}

DebuggerAgentImpl::~DebuggerAgentImpl() {
  DebuggerAgentManager::DebugDetach(this);
}

void DebuggerAgentImpl::GetContextId() {
  delegate_->SetContextId(webdevtools_agent_->host_id());
}

void DebuggerAgentImpl::DebuggerOutput(const String& command) {
  delegate_->DebuggerOutput(command);
  webdevtools_agent_->ForceRepaint();
}

// static
void DebuggerAgentImpl::CreateUtilityContext(
    Frame* frame,
    v8::Persistent<v8::Context>* context) {
  v8::HandleScope scope;

  // TODO(pfeldman): Validate against Soeren.
  // Set up the DOM window as the prototype of the new global object.
  v8::Handle<v8::Context> window_context =
      V8Proxy::context(frame);
  v8::Handle<v8::Object> window_global = window_context->Global();
  v8::Handle<v8::Object> window_wrapper =
      V8DOMWrapper::lookupDOMWrapper(V8ClassIndex::DOMWINDOW, window_global);

  ASSERT(V8DOMWrapper::convertDOMWrapperToNative<DOMWindow>(window_wrapper) ==
      frame->domWindow());

  v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();

  // TODO(yurys): provide a function in v8 bindings that would make the
  // utility context more like main world context of the inspected frame,
  // otherwise we need to manually make it satisfy various invariants
  // that V8Proxy::getEntered and some other V8Proxy methods expect to find
  // on v8 contexts on the contexts stack.
  // See V8Proxy::createNewContext.
  //
  // Install a security handler with V8.
  global_template->SetAccessCheckCallbacks(
      V8DOMWindow::namedSecurityCheck,
      V8DOMWindow::indexedSecurityCheck,
      v8::Integer::New(V8ClassIndex::DOMWINDOW));
  // We set number of internal fields to match that in V8DOMWindow wrapper.
  // See http://crbug.com/28961
  global_template->SetInternalFieldCount(
      V8Custom::kDOMWindowInternalFieldCount);

  *context = v8::Context::New(
      NULL /* no extensions */,
      global_template,
      v8::Handle<v8::Object>());
  v8::Context::Scope context_scope(*context);
  v8::Handle<v8::Object> global = (*context)->Global();

  v8::Handle<v8::String> implicit_proto_string = v8::String::New("__proto__");
  global->Set(implicit_proto_string, window_wrapper);

  // Give the code running in the new context a way to get access to the
  // original context.
  global->Set(v8::String::New("contentWindow"), window_global);

  // Inject javascript into the context.
  base::StringPiece injectjs_webkit =
      webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_WEBKIT_JS);
  v8::Script::Compile(
      v8::String::New(injectjs_webkit.as_string().c_str()))->Run();
  base::StringPiece inject_dispatchjs = webkit_glue::GetDataResource(
      IDR_DEVTOOLS_INJECT_DISPATCH_JS);
  v8::Script::Compile(v8::String::New(
      inject_dispatchjs.as_string().c_str()))->Run();
}

String DebuggerAgentImpl::ExecuteUtilityFunction(
    v8::Handle<v8::Context> context,
    int call_id,
    const char* object,
    const String &function_name,
    const String& json_args,
    bool async,
    String* exception) {
  v8::HandleScope scope;
  ASSERT(!context.IsEmpty());
  if (context.IsEmpty()) {
    *exception = "No window context.";
    return "";
  }
  v8::Context::Scope context_scope(context);

  DebuggerAgentManager::UtilityContextScope utility_scope;

  v8::Handle<v8::Object> dispatch_object = v8::Handle<v8::Object>::Cast(
      context->Global()->Get(v8::String::New(object)));

  v8::Handle<v8::Value> dispatch_function =
      dispatch_object->Get(v8::String::New("dispatch"));
  ASSERT(dispatch_function->IsFunction());
  v8::Handle<v8::Function> function = v8::Handle<v8::Function>::Cast(dispatch_function);

  v8::Handle<v8::String> function_name_wrapper = v8::Handle<v8::String>(
      v8::String::New(function_name.utf8().data()));
  v8::Handle<v8::String> json_args_wrapper = v8::Handle<v8::String>(
      v8::String::New(json_args.utf8().data()));
  v8::Handle<v8::Number> call_id_wrapper = v8::Handle<v8::Number>(
      v8::Number::New(async ? call_id : 0));

  v8::Handle<v8::Value> args[] = {
    function_name_wrapper,
    json_args_wrapper,
    call_id_wrapper
  };

  v8::TryCatch try_catch;
  v8::Handle<v8::Value> res_obj = function->Call(context->Global(), 3, args);
  if (try_catch.HasCaught()) {
    v8::Local<v8::Message> message = try_catch.Message();
    if (message.IsEmpty())
      *exception = "Unknown exception";
    else
      *exception = WebCore::toWebCoreString(message->Get());
    return "";
  } else {
    return WebCore::toWebCoreStringWithNullCheck(res_obj);
  }
}

void DebuggerAgentImpl::ExecuteVoidJavaScript(v8::Handle<v8::Context> context) {
  v8::HandleScope scope;
  ASSERT(!context.IsEmpty());
  v8::Context::Scope context_scope(context);
  DebuggerAgentManager::UtilityContextScope utility_scope;

  v8::Handle<v8::Value> function =
      context->Global()->Get(v8::String::New("devtools$$void"));
  ASSERT(function->IsFunction());
  v8::Handle<v8::Value> args[] = {
    v8::Local<v8::Value>()
  };
  v8::Handle<v8::Function>::Cast(function)->Call(context->Global(), 0, args);
}

WebCore::Page* DebuggerAgentImpl::GetPage() {
  return web_view_impl_->page();
}
<|endoftext|>


<commit_before><commit_msg>move quit of paint message_loop into callback of pipeline stop to guarantee message loop will not quit till paint is deinit'ed. BUG=none TEST=dev platform and desktop<commit_after><|endoftext|>


<commit_before><commit_msg>No longer pulls display out of DirectMode when the config file says to.<commit_after><|endoftext|>


<commit_before>/*
 *
 * MIT License
 *
 * Copyright (c) 2016-2018 The Cats Project
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

#ifndef CATS_CORECAT_DATA_ARRAY_HPP
#define CATS_CORECAT_DATA_ARRAY_HPP

#include <cstddef>

#include <iterator>
#include <memory>
#include <utility>

#include "Allocator/DefaultAllocator.hpp"
#include "../Util/Iterator.hpp"

namespace Cats {
namespace Corecat {
inline namespace Data {

template <typename T>
class ArrayView;

template <typename T, typename A = DefaultAllocator>
class Array {

public:

    using Type = T;
    using AllocatorType = A;

    using Iterator = Type*;
    using ConstIterator = const Type*;
    using ReverseIterator = Corecat::ReverseIterator<Iterator>;
    using ConstReverseIterator = Corecat::ReverseIterator<ConstIterator>;

    using ArrayViewType = ArrayView<T>;
    using ConstArrayViewType = ArrayView<const T>;

private:

    A allocator;
    Type* data = nullptr;
    std::size_t size = 0;
    std::size_t capacity = 0;

public:

    Array() = default;
    Array(std::size_t size_) { resize(size_); }
    Array(const Array& src) = delete;
    Array(Array&& src) { swap(src); }
    ~Array() {

        clear();
        if(data) allocator.deallocate(data, capacity * sizeof(T));

    }

    Array& operator =(const Array& src) = delete;
    Array& operator =(Array&& src) { swap(*this, src); return *this; }

    operator ConstArrayViewType() const noexcept { return getView(); }
    operator ArrayViewType() noexcept { return getView(); }

    const Type& operator [](std::size_t index) const noexcept { return data[index]; }
    Type& operator [](std::size_t index) noexcept { return data[index]; }

    const Type* getData() const noexcept { return data; }
    Type* getData() noexcept { return data; }
    std::size_t getSize() const noexcept { return size; }
    std::size_t getCapacity() const noexcept { return capacity; }

    ConstArrayViewType getView() const noexcept { return {data, size}; }
    ArrayViewType getView() noexcept { return {data, size}; }

    bool isEmpty() const noexcept { return !size; }

    void clear() noexcept { resize(0); }

    void reserve(std::size_t capacity_) {

        if(capacity >= capacity_) return;
        T* data_ = static_cast<T*>(allocator.allocate(capacity_ * sizeof(T)));
        std::size_t i = 0;
        try {

            for(; i < size; ++i) new(data_ + i) T(data[i]);

        } catch(...) {

            for(--i; i != std::size_t(-1); --i) data_[i].~T();
            allocator.deallocate(data_, capacity_ * sizeof(T));
            std::rethrow_exception(std::current_exception());

        }
        if(data) {

            for(std::size_t i = size - 1; i != std::size_t(-1); --i) data[i].~T();
            allocator.deallocate(data, capacity * sizeof(T));

        }
        data = data_;
        capacity = capacity_;

    }

    void resize(std::size_t size_) {

        if(size_ < size) {

            for(std::size_t i = size_ - 1; i != size_ - 1; --i)
                data[i].~T();

        } else if(size_ > size) {

            if(size_ <= capacity) {

                std::size_t i = size;
                try {

                    for(; i < size_; ++i) new(data + i) T();

                } catch(...) {

                    for(--i; i != size - 1; --i) data[i].~T();
                    std::rethrow_exception(std::current_exception());

                }

            } else {

                T* data_ = static_cast<T*>(allocator.allocate(size_ * sizeof(T)));
                std::size_t i = 0;
                try {

                    for(; i < size; ++i) new(data_ + i) T(data[i]);
                    for(; i < size_; ++i) new(data_ + i) T();

                } catch(...) {

                    for(--i; i != std::size_t(-1); --i) data_[i].~T();
                    allocator.deallocate(data_, size_ * sizeof(T));
                    std::rethrow_exception(std::current_exception());

                }
                if(data) {

                    for(std::size_t i = size - 1; i != std::size_t(-1); --i) data[i].~T();
                    allocator.deallocate(data, capacity * sizeof(T));

                }
                data = data_;
                capacity = size_;

            }

        }
        size = size_;

    }

    void append(const T& t) {

        if(size < capacity) {

            new(data + size) T(t);

        } else {

            std::size_t newSize = size + 1;
            T* newData = static_cast<T*>(allocator.allocate(newSize * sizeof(T)));
            std::size_t i = 0;
            try {

                for(; i < size; ++i) new(newData + i) T(data[i]);
                new(newData + size) T(t);

            } catch(...) {

                for(--i; i != std::size_t(-1); --i) newData[i].~T();
                allocator.deallocate(newData, newSize * sizeof(T));
                std::rethrow_exception(std::current_exception());

            }
            if(data) {

                for(std::size_t i = size - 1; i != std::size_t(-1); --i) data[i].~T();
                allocator.deallocate(data, capacity * sizeof(T));

            }
            data = newData;
            capacity = newSize;

        }
        ++size;

    }

    void swap(Array& src) noexcept {

        std::swap(allocator, src.allocator);
        std::swap(data, src.data);
        std::swap(size, src.size);
        std::swap(capacity, src.capacity);

    }

    Iterator begin() const noexcept { return data; }
    Iterator end() const noexcept { return data + size; }

    ConstIterator cbegin() const noexcept { return begin(); }
    ConstIterator cend() const noexcept { return end(); }

    ReverseIterator rbegin() const noexcept { return ReverseIterator(end()); }
    ReverseIterator rend() const noexcept { return ReverseIterator(begin()); }

    ConstReverseIterator crbegin() const noexcept { return ConstReverseIterator(cend()); }
    ConstReverseIterator crend() const noexcept { return ConstReverseIterator(cbegin()); }

};

template <typename T>
class ArrayView {

public:

    using Type = T;

    using Iterator = Type*;
    using ConstIterator = const Type*;
    using ReverseIterator = Corecat::ReverseIterator<Iterator>;
    using ConstReverseIterator = Corecat::ReverseIterator<ConstIterator>;

private:

    Type* data = nullptr;
    std::size_t size = 0;

public:

    ArrayView() = default;
    ArrayView(std::nullptr_t) noexcept {}
    ArrayView(Type* data_, std::size_t size_) noexcept : data(data_), size(size_) {}
    template <std::size_t S>
    ArrayView(Type (&array)[S]) noexcept : data(array), size(S) {}
    ArrayView(const ArrayView& src) = default;

    ArrayView& operator =(const ArrayView& src) = default;

    operator ArrayView<const Type>() noexcept { return {data, size}; }

    Type& operator [](std::size_t index) const noexcept { return data[index]; }

    Type* getData() const noexcept { return data; }
    std::size_t getSize() const noexcept { return size; }

    bool isEmpty() const noexcept { return !size; }

    Iterator begin() const noexcept { return data; }
    Iterator end() const noexcept { return data + size; }

    ConstIterator cbegin() const noexcept { return begin(); }
    ConstIterator cend() const noexcept { return end(); }

    ReverseIterator rbegin() const noexcept { return ReverseIterator(end()); }
    ReverseIterator rend() const noexcept { return ReverseIterator(begin()); }

    ConstReverseIterator crbegin() const noexcept { return ConstReverseIterator(cend()); }
    ConstReverseIterator crend() const noexcept { return ConstReverseIterator(cbegin()); }

};

}
}
}

#endif
<commit_msg>Update Array<commit_after>/*
 *
 * MIT License
 *
 * Copyright (c) 2016-2018 The Cats Project
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

#ifndef CATS_CORECAT_DATA_ARRAY_HPP
#define CATS_CORECAT_DATA_ARRAY_HPP

#include <cstddef>

#include <iterator>
#include <memory>
#include <utility>

#include "Allocator/DefaultAllocator.hpp"
#include "../Util/Iterator.hpp"

namespace Cats {
namespace Corecat {
inline namespace Data {

template <typename T>
class ArrayView;

template <typename T, typename A = DefaultAllocator>
class Array {

public:

    using Type = T;
    using AllocatorType = A;

    using Iterator = Type*;
    using ConstIterator = const Type*;
    using ReverseIterator = Corecat::ReverseIterator<Iterator>;
    using ConstReverseIterator = Corecat::ReverseIterator<ConstIterator>;

    using ArrayViewType = ArrayView<T>;
    using ConstArrayViewType = ArrayView<const T>;

private:

    A allocator;
    Type* data = nullptr;
    std::size_t size = 0;
    std::size_t capacity = 0;

public:

    Array() = default;
    Array(std::size_t size_) { resize(size_); }
    Array(const Array& src) = delete;
    Array(Array&& src) { swap(src); }
    ~Array() {

        clear();
        if(data) allocator.deallocate(data, capacity * sizeof(T));

    }

    Array& operator =(const Array& src) = delete;
    Array& operator =(Array&& src) { swap(*this, src); return *this; }

    operator ConstArrayViewType() const noexcept { return getView(); }
    operator ArrayViewType() noexcept { return getView(); }

    const Type& operator [](std::size_t index) const noexcept { return data[index]; }
    Type& operator [](std::size_t index) noexcept { return data[index]; }

    const Type* getData() const noexcept { return data; }
    Type* getData() noexcept { return data; }
    std::size_t getSize() const noexcept { return size; }
    std::size_t getCapacity() const noexcept { return capacity; }

    ConstArrayViewType getView() const noexcept { return {data, size}; }
    ArrayViewType getView() noexcept { return {data, size}; }

    bool isEmpty() const noexcept { return !size; }

    void clear() noexcept { resize(0); }

    void reserve(std::size_t capacity_) {

        if(capacity >= capacity_) return;
        T* data_ = static_cast<T*>(allocator.allocate(capacity_ * sizeof(T)));
        std::size_t i = 0;
        try {

            for(; i < size; ++i) new(data_ + i) T(data[i]);

        } catch(...) {

            for(--i; i != std::size_t(-1); --i) data_[i].~T();
            allocator.deallocate(data_, capacity_ * sizeof(T));
            std::rethrow_exception(std::current_exception());

        }
        if(data) {

            for(std::size_t i = size - 1; i != std::size_t(-1); --i) data[i].~T();
            allocator.deallocate(data, capacity * sizeof(T));

        }
        data = data_;
        capacity = capacity_;

    }

    void resize(std::size_t size_) {

        if(size_ < size) {

            for(std::size_t i = size_ - 1; i != size_ - 1; --i)
                data[i].~T();

        } else if(size_ > size) {

            if(size_ <= capacity) {

                std::size_t i = size;
                try {

                    for(; i < size_; ++i) new(data + i) T();

                } catch(...) {

                    for(--i; i != size - 1; --i) data[i].~T();
                    std::rethrow_exception(std::current_exception());

                }

            } else {

                T* data_ = static_cast<T*>(allocator.allocate(size_ * sizeof(T)));
                std::size_t i = 0;
                try {

                    for(; i < size; ++i) new(data_ + i) T(data[i]);
                    for(; i < size_; ++i) new(data_ + i) T();

                } catch(...) {

                    for(--i; i != std::size_t(-1); --i) data_[i].~T();
                    allocator.deallocate(data_, size_ * sizeof(T));
                    std::rethrow_exception(std::current_exception());

                }
                if(data) {

                    for(std::size_t i = size - 1; i != std::size_t(-1); --i) data[i].~T();
                    allocator.deallocate(data, capacity * sizeof(T));

                }
                data = data_;
                capacity = size_;

            }

        }
        size = size_;

    }

    template <typename... Arg>
    void append(Arg&&... arg) {

        if(size < capacity) {

            new(data + size) T(std::forward<Arg>(arg)...);

        } else {

            std::size_t newSize = size + 1;
            T* newData = static_cast<T*>(allocator.allocate(newSize * sizeof(T)));
            std::size_t i = 0;
            try {

                for(; i < size; ++i) new(newData + i) T(data[i]);
                new(newData + size) T(std::forward<Arg>(arg)...);

            } catch(...) {

                for(--i; i != std::size_t(-1); --i) newData[i].~T();
                allocator.deallocate(newData, newSize * sizeof(T));
                std::rethrow_exception(std::current_exception());

            }
            if(data) {

                for(std::size_t i = size - 1; i != std::size_t(-1); --i) data[i].~T();
                allocator.deallocate(data, capacity * sizeof(T));

            }
            data = newData;
            capacity = newSize;

        }
        ++size;

    }

    void swap(Array& src) noexcept {

        std::swap(allocator, src.allocator);
        std::swap(data, src.data);
        std::swap(size, src.size);
        std::swap(capacity, src.capacity);

    }

    Iterator begin() const noexcept { return data; }
    Iterator end() const noexcept { return data + size; }

    ConstIterator cbegin() const noexcept { return begin(); }
    ConstIterator cend() const noexcept { return end(); }

    ReverseIterator rbegin() const noexcept { return ReverseIterator(end()); }
    ReverseIterator rend() const noexcept { return ReverseIterator(begin()); }

    ConstReverseIterator crbegin() const noexcept { return ConstReverseIterator(cend()); }
    ConstReverseIterator crend() const noexcept { return ConstReverseIterator(cbegin()); }

};

template <typename T>
class ArrayView {

public:

    using Type = T;

    using Iterator = Type*;
    using ConstIterator = const Type*;
    using ReverseIterator = Corecat::ReverseIterator<Iterator>;
    using ConstReverseIterator = Corecat::ReverseIterator<ConstIterator>;

private:

    Type* data = nullptr;
    std::size_t size = 0;

public:

    ArrayView() = default;
    ArrayView(std::nullptr_t) noexcept {}
    ArrayView(Type* data_, std::size_t size_) noexcept : data(data_), size(size_) {}
    template <std::size_t S>
    ArrayView(Type (&array)[S]) noexcept : data(array), size(S) {}
    ArrayView(const ArrayView& src) = default;

    ArrayView& operator =(const ArrayView& src) = default;

    operator ArrayView<const Type>() noexcept { return {data, size}; }

    Type& operator [](std::size_t index) const noexcept { return data[index]; }

    Type* getData() const noexcept { return data; }
    std::size_t getSize() const noexcept { return size; }

    bool isEmpty() const noexcept { return !size; }

    Iterator begin() const noexcept { return data; }
    Iterator end() const noexcept { return data + size; }

    ConstIterator cbegin() const noexcept { return begin(); }
    ConstIterator cend() const noexcept { return end(); }

    ReverseIterator rbegin() const noexcept { return ReverseIterator(end()); }
    ReverseIterator rend() const noexcept { return ReverseIterator(begin()); }

    ConstReverseIterator crbegin() const noexcept { return ConstReverseIterator(cend()); }
    ConstReverseIterator crend() const noexcept { return ConstReverseIterator(cbegin()); }

};

}
}
}

#endif
<|endoftext|>