<commit_before>/***********************************************************************
    created:    8/7/2004
    author:     James '_mental_' O'Sullivan
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
 *
 *   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 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.
 ***************************************************************************/
#include "CEGUI/DefaultResourceProvider.h"
#include "CEGUI/Exceptions.h"

#include <stdio.h>

#if defined(__WIN32__) || defined(_WIN32)
#   include "CEGUI/System.h"
#   include <io.h>
#   include <windows.h>
#   include <string>
#else
#   include <sys/types.h>
#   include <sys/stat.h>
#   include <dirent.h>
#   include <fnmatch.h>
#endif

// Start of CEGUI namespace section
namespace CEGUI
{

//----------------------------------------------------------------------------//
void DefaultResourceProvider::loadRawDataContainer(const String& filename,
                                                   RawDataContainer& output,
                                                   const String& resourceGroup)
{
    if (filename.empty())
        CEGUI_THROW(InvalidRequestException(
            "Filename supplied for data loading must be valid"));

    const String final_filename(getFinalFilename(filename, resourceGroup));

#if defined(__WIN32__) || defined(_WIN32)
    FILE* file = _wfopen(System::getStringTranscoder().stringToStdWString(final_filename).c_str(), L"rb");
#else
    FILE* file = fopen(final_filename.c_str(), "rb");
#endif

    if (file == 0)
        CEGUI_THROW(FileIOException(final_filename + " does not exist"));

    fseek(file, 0, SEEK_END);
    const size_t size = ftell(file);
    fseek(file, 0, SEEK_SET);

    unsigned char* const buffer = CEGUI_NEW_ARRAY_PT(unsigned char, size, RawDataContainer);

    const size_t size_read = fread(buffer, sizeof(char), size, file);
    fclose(file);

    if (size_read != size)
    {
        CEGUI_DELETE_ARRAY_PT(buffer, unsigned char, size, BufferAllocator);

        CEGUI_THROW(FileIOException(
            "A problem occurred while reading file: " + final_filename));
    }

    output.setData(buffer);
    output.setSize(size);
}

//----------------------------------------------------------------------------//
void DefaultResourceProvider::unloadRawDataContainer(RawDataContainer& data)
{
    data.release();
}

//----------------------------------------------------------------------------//
void DefaultResourceProvider::setResourceGroupDirectory(
                                                const String& resourceGroup,
                                                const String& directory)
{
    if (directory.length() == 0)
        return;

#if defined(_WIN32) || defined(__WIN32__)
    // while we rarely use the unportable '\', the user may have
    const String separators("\\/");
#else
    const String separators("/");
#endif

    if (String::npos == separators.find(directory[directory.length() - 1]))
        d_resourceGroups[resourceGroup] = directory + '/';
    else
        d_resourceGroups[resourceGroup] = directory;
}

//----------------------------------------------------------------------------//
const String& DefaultResourceProvider::getResourceGroupDirectory(
                                                const String& resourceGroup)
{
    return d_resourceGroups[resourceGroup];
}

//----------------------------------------------------------------------------//
void DefaultResourceProvider::clearResourceGroupDirectory(
                                                const String& resourceGroup)
{
    ResourceGroupMap::iterator iter = d_resourceGroups.find(resourceGroup);

    if (iter != d_resourceGroups.end())
        d_resourceGroups.erase(iter);
}

//----------------------------------------------------------------------------//
String DefaultResourceProvider::getFinalFilename(
                                            const String& filename,
                                            const String& resourceGroup) const
{
    String final_filename;

    // look up resource group directory
    ResourceGroupMap::const_iterator iter =
        d_resourceGroups.find(resourceGroup.empty() ?
            d_defaultResourceGroup :
            resourceGroup);

    // if there was an entry for this group, use it's directory as the
    // first part of the filename
    if (iter != d_resourceGroups.end())
        final_filename = (*iter).second;

    // append the filename part that we were passed
    final_filename += filename;

    // return result
    return final_filename;
}

//----------------------------------------------------------------------------//
size_t DefaultResourceProvider::getResourceGroupFileNames(
    std::vector<String>& out_vec,
    const String& file_pattern,
    const String& resource_group)
{
    // look-up resource group name
    ResourceGroupMap::const_iterator iter =
        d_resourceGroups.find(resource_group.empty() ? d_defaultResourceGroup :
                              resource_group);
    // get directory that's set for the resource group
    const String dir_name(
        iter != d_resourceGroups.end() ? (*iter).second : "./");

    size_t entries = 0;

// Win32 code.
#if defined(__WIN32__) || defined(_WIN32)
    intptr_t f;
    struct _wfinddata_t fd;

    if ((f = _wfindfirst(System::getStringTranscoder().stringToStdWString(
            dir_name + file_pattern).c_str(), &fd)) != -1)
    {
        do
        {
            if ((fd.attrib & _A_SUBDIR))
                continue;

            out_vec.push_back(System::getStringTranscoder().stringFromStdWString(fd.name));
            ++entries;
        }
        while (_wfindnext(f, &fd) == 0);

        _findclose(f);
    }

// Everybody else
#else
    DIR* dirp;

    if ((dirp = opendir(dir_name.c_str())))
    {
        struct dirent* dp;

        while ((dp = readdir(dirp)))
        {
            const String filename(dir_name + dp->d_name);
            struct stat s;

            if ((stat(filename.c_str(), &s) == 0) &&
                    S_ISREG(s.st_mode) &&
                    (fnmatch(file_pattern.c_str(), dp->d_name, 0) == 0))
            {
                out_vec.push_back(dp->d_name);
                ++entries;
            }
        }

        closedir(dirp);
    }
#endif

    return entries;
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section

<commit_msg>MOD: Fixing mingw build<commit_after>/***********************************************************************
    created:    8/7/2004
    author:     James '_mental_' O'Sullivan
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
 *
 *   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 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.
 ***************************************************************************/
#include "CEGUI/DefaultResourceProvider.h"
#include "CEGUI/Exceptions.h"

#include <stdio.h>

#if defined(__WIN32__) || defined(_WIN32)
#   include "CEGUI/System.h"
#   include <io.h>
#   include <windows.h>
#   include <string>
#   include <cstdio>
#else
#   include <sys/types.h>
#   include <sys/stat.h>
#   include <dirent.h>
#   include <fnmatch.h>
#endif

// Start of CEGUI namespace section
namespace CEGUI
{

//----------------------------------------------------------------------------//
void DefaultResourceProvider::loadRawDataContainer(const String& filename,
                                                   RawDataContainer& output,
                                                   const String& resourceGroup)
{
    if (filename.empty())
        CEGUI_THROW(InvalidRequestException(
            "Filename supplied for data loading must be valid"));

    const String final_filename(getFinalFilename(filename, resourceGroup));

#if defined(__WIN32__) || defined(_WIN32)
    FILE* file = _wfopen(System::getStringTranscoder().stringToStdWString(final_filename).c_str(), L"rb");
#else
    FILE* file = fopen(final_filename.c_str(), "rb");
#endif

    if (file == 0)
        CEGUI_THROW(FileIOException(final_filename + " does not exist"));

    fseek(file, 0, SEEK_END);
    const size_t size = ftell(file);
    fseek(file, 0, SEEK_SET);

    unsigned char* const buffer = CEGUI_NEW_ARRAY_PT(unsigned char, size, RawDataContainer);

    const size_t size_read = fread(buffer, sizeof(char), size, file);
    fclose(file);

    if (size_read != size)
    {
        CEGUI_DELETE_ARRAY_PT(buffer, unsigned char, size, BufferAllocator);

        CEGUI_THROW(FileIOException(
            "A problem occurred while reading file: " + final_filename));
    }

    output.setData(buffer);
    output.setSize(size);
}

//----------------------------------------------------------------------------//
void DefaultResourceProvider::unloadRawDataContainer(RawDataContainer& data)
{
    data.release();
}

//----------------------------------------------------------------------------//
void DefaultResourceProvider::setResourceGroupDirectory(
                                                const String& resourceGroup,
                                                const String& directory)
{
    if (directory.length() == 0)
        return;

#if defined(_WIN32) || defined(__WIN32__)
    // while we rarely use the unportable '\', the user may have
    const String separators("\\/");
#else
    const String separators("/");
#endif

    if (String::npos == separators.find(directory[directory.length() - 1]))
        d_resourceGroups[resourceGroup] = directory + '/';
    else
        d_resourceGroups[resourceGroup] = directory;
}

//----------------------------------------------------------------------------//
const String& DefaultResourceProvider::getResourceGroupDirectory(
                                                const String& resourceGroup)
{
    return d_resourceGroups[resourceGroup];
}

//----------------------------------------------------------------------------//
void DefaultResourceProvider::clearResourceGroupDirectory(
                                                const String& resourceGroup)
{
    ResourceGroupMap::iterator iter = d_resourceGroups.find(resourceGroup);

    if (iter != d_resourceGroups.end())
        d_resourceGroups.erase(iter);
}

//----------------------------------------------------------------------------//
String DefaultResourceProvider::getFinalFilename(
                                            const String& filename,
                                            const String& resourceGroup) const
{
    String final_filename;

    // look up resource group directory
    ResourceGroupMap::const_iterator iter =
        d_resourceGroups.find(resourceGroup.empty() ?
            d_defaultResourceGroup :
            resourceGroup);

    // if there was an entry for this group, use it's directory as the
    // first part of the filename
    if (iter != d_resourceGroups.end())
        final_filename = (*iter).second;

    // append the filename part that we were passed
    final_filename += filename;

    // return result
    return final_filename;
}

//----------------------------------------------------------------------------//
size_t DefaultResourceProvider::getResourceGroupFileNames(
    std::vector<String>& out_vec,
    const String& file_pattern,
    const String& resource_group)
{
    // look-up resource group name
    ResourceGroupMap::const_iterator iter =
        d_resourceGroups.find(resource_group.empty() ? d_defaultResourceGroup :
                              resource_group);
    // get directory that's set for the resource group
    const String dir_name(
        iter != d_resourceGroups.end() ? (*iter).second : "./");

    size_t entries = 0;

// Win32 code.
#if defined(__WIN32__) || defined(_WIN32)
    intptr_t f;
    struct _wfinddata_t fd;

    if ((f = _wfindfirst(System::getStringTranscoder().stringToStdWString(
            dir_name + file_pattern).c_str(), &fd)) != -1)
    {
        do
        {
            if ((fd.attrib & _A_SUBDIR))
                continue;

            out_vec.push_back(System::getStringTranscoder().stringFromStdWString(fd.name));
            ++entries;
        }
        while (_wfindnext(f, &fd) == 0);

        _findclose(f);
    }

// Everybody else
#else
    DIR* dirp;

    if ((dirp = opendir(dir_name.c_str())))
    {
        struct dirent* dp;

        while ((dp = readdir(dirp)))
        {
            const String filename(dir_name + dp->d_name);
            struct stat s;

            if ((stat(filename.c_str(), &s) == 0) &&
                    S_ISREG(s.st_mode) &&
                    (fnmatch(file_pattern.c_str(), dp->d_name, 0) == 0))
            {
                out_vec.push_back(dp->d_name);
                ++entries;
            }
        }

        closedir(dirp);
    }
#endif

    return entries;
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section

<|endoftext|>


<commit_before>/********************************************************************************
 File name: monster.cpp
 Written by: Daniel Nguyen
 Written on 08/27/2016
 Purpose: This is a c++ file containing monster class.

 Class: CPSC 362
 *********************************************************************************/
#include <sstream>
#include <string>
#include "enum.h"

/*********************************************************************
 This is the monster class. It only uses Health, Experience, Attack,
 Defense, ActionCoo
 *********************************************************************/
class Enemy{
protected:
    std::string name;
    int StatTable[2][9];
    const int Current = 0;
    const int Maximum = 1;
    std::string description;
public:
    //Accessor functions for hp
    int GetStat (Stats Stat, bool Max){
        return StatTable[Max ? Maximum : Current][(int) Stat];
    }

    void AlterStat (Stats Stat, bool Max, int Amount){
        StatTable[Max ? Maximum : Current][(int) Stat] += Amount;
    }

    void SetStatToMax (Stats Stat){
        StatTable[Current][(int) Stat] = StatTable[Maximum][(int)Stat];
    }
    //Accessor function for name
    std::string get_name(){return name;}

    //Accessor function for description
    std::string get_description(){ return description;}

    //Stores length of name and name, hp, exp, min atk, max atk, length of description
    //and description
    void write_to_stream(std::ostream & str)
    {
        //Write length and data for name
        int name_length = name.length();
        str.write(reinterpret_cast<char *>(&name_length),sizeof(int));
        str.write(name.data(), name_length);

        //Write hp
        str.write(reinterpret_cast<char *>(&hp),sizeof(hp));

        //Write exp
        str.write(reinterpret_cast<char *>(&exp),sizeof(exp));

        //write min_atk
        str.write(reinterpret_cast<char *>(&min_atk),sizeof(min_atk));

        //write max atk
        str.write(reinterpret_cast<char *>(&max_atk),sizeof(max_atk));

        //write length and data for description
        int description_length = description.length();
        str.write(reinterpret_cast<char *>(&description_length),sizeof(int));
        str.write(description.data(), description_length);
    }

    //Reads the data in the format written by Monster::pack
    void read_from_file(std::istream & str)
    {
        const int BUFFER_SIZE = 256;
        static char buffer[256];

        //Getting name's length, read the data into a local buffer and assign to name
        int name_length;
        str.read(reinterpret_cast<char *>(&name_length),sizeof(int));
        str.read(buffer, name_length);
        buffer[name_length] = '\0';
        name = buffer;

        //Getting hp
        str.read(reinterpret_cast<char *>(&hp),sizeof(hp));

        //Getting exp
        str.read(reinterpret_cast<char *> (&exp),sizeof(exp));

        //Getting min_atk
        str.read(reinterpret_cast<char *> (&min_atk),sizeof(min_atk));

        //Getting max atk
        str.read(reinterpret_cast<char *> (&max_atk),sizeof(max_atk));

        //Getting description's length, read the data into a local buffer and assign
        //to description
        int description_length;
        str.read(reinterpret_cast<char *>(&description_length),sizeof(int));
        str.read(buffer, description_length);
        buffer[description_length] = '\0';
        description = buffer;

    }

    //This function converts a template data type to a string and add
    //a '/' to end of string as delimiter.
    template<typename T> std::string convert_to_string(T data){
        std::stringstream stream;
        std::string str;
        stream << data;
        stream >> str;
        str += '/';
        return str;
    }

    //Pack() function packs every single member variable using the
    //convert_to_string function and return a string containing all
    //the stats
    std::string pack(){
        std::string retVal = "";
        //Add name and '/' following it to retVal string
        retVal += name;
        retVal += '/';

        //Convert Stat Table to String
        for(int row = 0; row < 2; row ++){
            for(int col = 0; col < 2; col++){
                retVal += convert_to_string(StatTable[row][col]);
            }
        }

        //Add description to retVal string
        retVal+= description;
        retVal+='/';

        return retVal;
    }

    //Unpack() function converts str to corresponding data type. It uses count
    //as a counter to store the correct member variable
    void unpack(std::string str)
    {
        int row;
        int col;
        std::string token;
        std::istringstream ss(str);
        int count = 1;
        while(std::getline(ss, token, '/'))
        {
            std::istringstream stream(token);
            if (count == 1){
                stream >> name;
                count ++;
            }
            else if (count =2){
                stream >> StatTable[row][col++];
                if (col = 8){
                    count++;
                    row++;
                    col = 0;
                }
            }
            else if(count == 3){
                stream >> StatTable[row][col++];
                if(col = 8){
                    count++;
                }
            }

            else if( count ==4){
                stream >> description;
                break;
            }
        }
    }
};

<commit_msg>remove write_to_stream() and read_to_stream()<commit_after>/********************************************************************************
 File name: monster.cpp
 Written by: Daniel Nguyen
 Written on 08/27/2016
 Purpose: This is a c++ file containing monster class.

 Class: CPSC 362
 *********************************************************************************/
#include <sstream>
#include <string>
#include "enum.h"

/*********************************************************************
 This is the monster class. It only uses Health, Experience, Attack,
 Defense, ActionCoolDown
 *********************************************************************/
class Enemy{
private:
    std::string name;
    int StatTable[2][9];
    const int Current = 0;
    const int Maximum = 1;
    std::string description;
public:
    //Accessor functions for hp
    int GetStat (Stats Stat, bool Max){
        return StatTable[Max ? Maximum : Current][(int) Stat];
    }

    void AlterStat (Stats Stat, bool Max, int Amount){
        StatTable[Max ? Maximum : Current][(int) Stat] += Amount;
    }

    void SetStatToMax (Stats Stat){
        StatTable[Current][(int) Stat] = StatTable[Maximum][(int)Stat];
    }
    //Accessor function for name
    std::string get_name(){return name;}

    //Accessor function for description
    std::string get_description(){ return description;}

    //This function converts a template data type to a string and add
    //a '/' to end of string as delimiter.
    template<typename T> std::string convert_to_string(T data){
        std::stringstream stream;
        std::string str;
        stream << data;
        stream >> str;
        str += '/';
        return str;
    }

    //Pack() function packs every single member variable using the
    //convert_to_string function and return a string containing all
    //the stats
    std::string pack(){
        std::string retVal = "";
        //Add name and '/' following it to retVal string
        retVal += name;
        retVal += '/';

        //Convert Stat Table to String
        for(int row = 0; row < 2; row ++){
            for(int col = 0; col < 2; col++){
                retVal += convert_to_string(StatTable[row][col]);
            }
        }

        //Add description to retVal string
        retVal+= description;
        retVal+='/';

        return retVal;
    }

    //Unpack() function converts str to corresponding data type. It uses count
    //as a counter to store the correct member variable
    void unpack(std::string str)
    {
        int row;
        int col;
        std::string token;
        std::istringstream ss(str);
        int count = 1;
        while(std::getline(ss, token, '/'))
        {
            std::istringstream stream(token);
            if (count == 1){
                stream >> name;
                count ++;
            }
            else if (count =2){
                stream >> StatTable[row][col++];
                if (col = 8){
                    count++;
                    row++;
                    col = 0;
                }
            }
            else if(count == 3){
                stream >> StatTable[row][col++];
                if(col = 8){
                    count++;
                }
            }

            else if( count ==4){
                stream >> description;
                break;
            }
        }
    }
};

<|endoftext|>


<commit_before><commit_msg>Refactor getAvailablePosAndSizeForDiagram() to use CreateShapeParam2D.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2010 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 "chrome/browser/cookie_modal_dialog.h"

#include "chrome/browser/host_content_settings_map.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/cookie_prompt_view.h"
#include "chrome/common/pref_names.h"

// Cookies
CookiePromptModalDialog::CookiePromptModalDialog(
    TabContents* tab_contents,
    const GURL& origin,
    const std::string& cookie_line,
    CookiePromptModalDialogDelegate* delegate)
    : AppModalDialog(tab_contents, std::wstring()),
      dialog_type_(DIALOG_TYPE_COOKIE),
      origin_(origin),
      cookie_line_(cookie_line),
      delegate_(delegate) {
}

// LocalStorage
CookiePromptModalDialog::CookiePromptModalDialog(
    TabContents* tab_contents,
    const GURL& origin,
    const string16& key,
    const string16& value,
    CookiePromptModalDialogDelegate* delegate)
    : AppModalDialog(tab_contents, std::wstring()),
      dialog_type_(DIALOG_TYPE_LOCAL_STORAGE),
      origin_(origin),
      local_storage_key_(key),
      local_storage_value_(value),
      delegate_(delegate) {
}

// Database
CookiePromptModalDialog::CookiePromptModalDialog(
    TabContents* tab_contents,
    const GURL& origin,
    const string16& database_name,
    CookiePromptModalDialogDelegate* delegate)
    : AppModalDialog(tab_contents, std::wstring()),
      dialog_type_(DIALOG_TYPE_DATABASE),
      origin_(origin),
      database_name_(database_name),
      delegate_(delegate) {
}

bool CookiePromptModalDialog::IsValid() {
  HostContentSettingsMap* host_content_settings_map =
      tab_contents()->profile()->GetHostContentSettingsMap();
  ContentSetting content_setting =
      host_content_settings_map->GetContentSetting(
          origin(),
          CONTENT_SETTINGS_TYPE_COOKIES);
  if (content_setting != CONTENT_SETTING_ASK) {
    if (content_setting == CONTENT_SETTING_ALLOW) {
      AllowSiteData(false, false);
    } else {
      DCHECK(content_setting == CONTENT_SETTING_BLOCK);
      BlockSiteData(false);
    }
    return false;
  }
  return true;
}

void CookiePromptModalDialog::AllowSiteData(bool remember,
                                            bool session_expire) {
  delegate_->AllowSiteData(remember, session_expire);
  delegate_ = NULL;  // It can be deleted at any point now.
}

void CookiePromptModalDialog::BlockSiteData(bool remember) {
  delegate_->BlockSiteData(remember);
  delegate_ = NULL;  // It can be deleted at any point now.
}

// static
void CookiePromptModalDialog::RegisterPrefs(PrefService* prefs) {
  prefs->RegisterBooleanPref(prefs::kCookiePromptExpanded, false);
}
<commit_msg>Speculative crash fix.<commit_after>// Copyright (c) 2010 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 "chrome/browser/cookie_modal_dialog.h"

#include "chrome/browser/host_content_settings_map.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/cookie_prompt_view.h"
#include "chrome/common/pref_names.h"

// Cookies
CookiePromptModalDialog::CookiePromptModalDialog(
    TabContents* tab_contents,
    const GURL& origin,
    const std::string& cookie_line,
    CookiePromptModalDialogDelegate* delegate)
    : AppModalDialog(tab_contents, std::wstring()),
      dialog_type_(DIALOG_TYPE_COOKIE),
      origin_(origin),
      cookie_line_(cookie_line),
      delegate_(delegate) {
}

// LocalStorage
CookiePromptModalDialog::CookiePromptModalDialog(
    TabContents* tab_contents,
    const GURL& origin,
    const string16& key,
    const string16& value,
    CookiePromptModalDialogDelegate* delegate)
    : AppModalDialog(tab_contents, std::wstring()),
      dialog_type_(DIALOG_TYPE_LOCAL_STORAGE),
      origin_(origin),
      local_storage_key_(key),
      local_storage_value_(value),
      delegate_(delegate) {
}

// Database
CookiePromptModalDialog::CookiePromptModalDialog(
    TabContents* tab_contents,
    const GURL& origin,
    const string16& database_name,
    CookiePromptModalDialogDelegate* delegate)
    : AppModalDialog(tab_contents, std::wstring()),
      dialog_type_(DIALOG_TYPE_DATABASE),
      origin_(origin),
      database_name_(database_name),
      delegate_(delegate) {
}

bool CookiePromptModalDialog::IsValid() {
  HostContentSettingsMap* host_content_settings_map =
      tab_contents()->profile()->GetHostContentSettingsMap();
  ContentSetting content_setting =
      host_content_settings_map->GetContentSetting(
          origin(),
          CONTENT_SETTINGS_TYPE_COOKIES);
  if (content_setting != CONTENT_SETTING_ASK) {
    if (content_setting == CONTENT_SETTING_ALLOW) {
      AllowSiteData(false, false);
    } else {
      DCHECK(content_setting == CONTENT_SETTING_BLOCK);
      BlockSiteData(false);
    }
    return false;
  }
  return true;
}

void CookiePromptModalDialog::AllowSiteData(bool remember,
                                            bool session_expire) {
  if (delegate_) {
    delegate_->AllowSiteData(remember, session_expire);
    delegate_ = NULL;  // It can be deleted at any point now.
  }
}

void CookiePromptModalDialog::BlockSiteData(bool remember) {
  if (delegate_) {
    delegate_->BlockSiteData(remember);
    delegate_ = NULL;  // It can be deleted at any point now.
  }
}

// static
void CookiePromptModalDialog::RegisterPrefs(PrefService* prefs) {
  prefs->RegisterBooleanPref(prefs::kCookiePromptExpanded, false);
}
<|endoftext|>


<commit_before><commit_msg>coverity: Pass strings by reference.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011 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 "chrome/browser/ui/webui/crashes_ui.h"

#include "base/i18n/time_formatting.h"
#include "base/ref_counted_memory.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/crash_upload_list.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/webui/chrome_url_data_manager.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"

namespace {

///////////////////////////////////////////////////////////////////////////////
//
// CrashesUIHTMLSource
//
///////////////////////////////////////////////////////////////////////////////

class CrashesUIHTMLSource : public ChromeURLDataManager::DataSource {
 public:
  CrashesUIHTMLSource()
      : DataSource(chrome::kChromeUICrashesHost, MessageLoop::current()) {}

  // Called when the network layer has requested a resource underneath
  // the path we registered.
  virtual void StartDataRequest(const std::string& path,
                                bool is_off_the_record,
                                int request_id);
  virtual std::string GetMimeType(const std::string&) const {
    return "text/html";
  }

 private:
  ~CrashesUIHTMLSource() {}

  DISALLOW_COPY_AND_ASSIGN(CrashesUIHTMLSource);
};

void CrashesUIHTMLSource::StartDataRequest(const std::string& path,
                                           bool is_off_the_record,
                                           int request_id) {
  DictionaryValue localized_strings;
  localized_strings.SetString("crashesTitle",
      l10n_util::GetStringUTF16(IDS_CRASHES_TITLE));
  localized_strings.SetString("crashCountFormat",
      l10n_util::GetStringUTF16(IDS_CRASHES_CRASH_COUNT_BANNER_FORMAT));
  localized_strings.SetString("crashHeaderFormat",
      l10n_util::GetStringUTF16(IDS_CRASHES_CRASH_HEADER_FORMAT));
  localized_strings.SetString("crashTimeFormat",
      l10n_util::GetStringUTF16(IDS_CRASHES_CRASH_TIME_FORMAT));
  localized_strings.SetString("bugLinkText",
      l10n_util::GetStringUTF16(IDS_CRASHES_BUG_LINK_LABEL));
  localized_strings.SetString("noCrashesMessage",
      l10n_util::GetStringUTF16(IDS_CRASHES_NO_CRASHES_MESSAGE));
  localized_strings.SetString("disabledHeader",
      l10n_util::GetStringUTF16(IDS_CRASHES_DISABLED_HEADER));
  localized_strings.SetString("disabledMessage",
      l10n_util::GetStringUTF16(IDS_CRASHES_DISABLED_MESSAGE));

  ChromeURLDataManager::DataSource::SetFontAndTextDirection(&localized_strings);

  static const base::StringPiece crashes_html(
      ResourceBundle::GetSharedInstance().GetRawDataResource(IDR_CRASHES_HTML));
  std::string full_html =
      jstemplate_builder::GetI18nTemplateHtml(crashes_html, &localized_strings);
  jstemplate_builder::AppendJsTemplateSourceHtml(&full_html);

  scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes);
  html_bytes->data.resize(full_html.size());
  std::copy(full_html.begin(), full_html.end(), html_bytes->data.begin());

  SendResponse(request_id, html_bytes);
}

////////////////////////////////////////////////////////////////////////////////
//
// CrashesDOMHandler
//
////////////////////////////////////////////////////////////////////////////////

// The handler for Javascript messages for the chrome://crashes/ page.
class CrashesDOMHandler : public WebUIMessageHandler,
                          public CrashUploadList::Delegate {
 public:
  explicit CrashesDOMHandler();
  virtual ~CrashesDOMHandler();

  // WebUIMessageHandler implementation.
  virtual WebUIMessageHandler* Attach(WebUI* web_ui);
  virtual void RegisterMessages();

  // CrashUploadList::Delegate implemenation.
  virtual void OnCrashListAvailable();

 private:
  // Asynchronously fetches the list of crashes. Called from JS.
  void HandleRequestCrashes(const ListValue* args);

  // Sends the recent crashes list JS.
  void UpdateUI();

  // Returns whether or not crash reporting is enabled.
  bool CrashReportingEnabled() const;

  scoped_refptr<CrashUploadList> upload_list_;
  bool list_available_;
  bool js_request_pending_;

  DISALLOW_COPY_AND_ASSIGN(CrashesDOMHandler);
};

CrashesDOMHandler::CrashesDOMHandler()
    : list_available_(false), js_request_pending_(false) {
  upload_list_ = new CrashUploadList(this);
}

CrashesDOMHandler::~CrashesDOMHandler() {
  upload_list_->ClearDelegate();
}

WebUIMessageHandler* CrashesDOMHandler::Attach(WebUI* web_ui) {
  upload_list_->LoadCrashListAsynchronously();
  return WebUIMessageHandler::Attach(web_ui);
}

void CrashesDOMHandler::RegisterMessages() {
  web_ui_->RegisterMessageCallback("requestCrashList",
      NewCallback(this, &CrashesDOMHandler::HandleRequestCrashes));
}

void CrashesDOMHandler::HandleRequestCrashes(const ListValue* args) {
  if (!CrashReportingEnabled() || list_available_)
    UpdateUI();
  else
    js_request_pending_ = true;
}

void CrashesDOMHandler::OnCrashListAvailable() {
  list_available_ = true;
  if (js_request_pending_)
    UpdateUI();
}

void CrashesDOMHandler::UpdateUI() {
  bool crash_reporting_enabled = CrashReportingEnabled();
  ListValue crash_list;

  if (crash_reporting_enabled) {
    std::vector<CrashUploadList::CrashInfo> crashes;
    upload_list_->GetUploadedCrashes(50, &crashes);

    for (std::vector<CrashUploadList::CrashInfo>::iterator i = crashes.begin();
         i != crashes.end(); ++i) {
      DictionaryValue* crash = new DictionaryValue();
      crash->SetString("id", i->crash_id);
      crash->SetString("time",
                       base::TimeFormatFriendlyDateAndTime(i->crash_time));
      crash_list.Append(crash);
    }
  }

  FundamentalValue enabled(crash_reporting_enabled);

  web_ui_->CallJavascriptFunction(L"updateCrashList", enabled, crash_list);
}

bool CrashesDOMHandler::CrashReportingEnabled() const {
#if defined(GOOGLE_CHROME_BUILD)
  PrefService* prefs = web_ui_->GetProfile()->GetPrefs();
  return prefs->GetBoolean(prefs::kMetricsReportingEnabled);
#else
  return false;
#endif
}

}  // namespace

///////////////////////////////////////////////////////////////////////////////
//
// CrashesUI
//
///////////////////////////////////////////////////////////////////////////////

CrashesUI::CrashesUI(TabContents* contents) : WebUI(contents) {
  AddMessageHandler((new CrashesDOMHandler())->Attach(this));

  CrashesUIHTMLSource* html_source = new CrashesUIHTMLSource();

  // Set up the chrome://crashes/ source.
  contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source);
}

// static
RefCountedMemory* CrashesUI::GetFaviconResourceBytes() {
  return ResourceBundle::GetSharedInstance().
      LoadDataResourceBytes(IDR_SAD_FAVICON);
}
<commit_msg>Fix chrome://crashes to check the right pref.<commit_after>// Copyright (c) 2011 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 "chrome/browser/ui/webui/crashes_ui.h"

#include "base/i18n/time_formatting.h"
#include "base/ref_counted_memory.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/crash_upload_list.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/ui/webui/chrome_url_data_manager.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"

namespace {

///////////////////////////////////////////////////////////////////////////////
//
// CrashesUIHTMLSource
//
///////////////////////////////////////////////////////////////////////////////

class CrashesUIHTMLSource : public ChromeURLDataManager::DataSource {
 public:
  CrashesUIHTMLSource()
      : DataSource(chrome::kChromeUICrashesHost, MessageLoop::current()) {}

  // Called when the network layer has requested a resource underneath
  // the path we registered.
  virtual void StartDataRequest(const std::string& path,
                                bool is_off_the_record,
                                int request_id);
  virtual std::string GetMimeType(const std::string&) const {
    return "text/html";
  }

 private:
  ~CrashesUIHTMLSource() {}

  DISALLOW_COPY_AND_ASSIGN(CrashesUIHTMLSource);
};

void CrashesUIHTMLSource::StartDataRequest(const std::string& path,
                                           bool is_off_the_record,
                                           int request_id) {
  DictionaryValue localized_strings;
  localized_strings.SetString("crashesTitle",
      l10n_util::GetStringUTF16(IDS_CRASHES_TITLE));
  localized_strings.SetString("crashCountFormat",
      l10n_util::GetStringUTF16(IDS_CRASHES_CRASH_COUNT_BANNER_FORMAT));
  localized_strings.SetString("crashHeaderFormat",
      l10n_util::GetStringUTF16(IDS_CRASHES_CRASH_HEADER_FORMAT));
  localized_strings.SetString("crashTimeFormat",
      l10n_util::GetStringUTF16(IDS_CRASHES_CRASH_TIME_FORMAT));
  localized_strings.SetString("bugLinkText",
      l10n_util::GetStringUTF16(IDS_CRASHES_BUG_LINK_LABEL));
  localized_strings.SetString("noCrashesMessage",
      l10n_util::GetStringUTF16(IDS_CRASHES_NO_CRASHES_MESSAGE));
  localized_strings.SetString("disabledHeader",
      l10n_util::GetStringUTF16(IDS_CRASHES_DISABLED_HEADER));
  localized_strings.SetString("disabledMessage",
      l10n_util::GetStringUTF16(IDS_CRASHES_DISABLED_MESSAGE));

  ChromeURLDataManager::DataSource::SetFontAndTextDirection(&localized_strings);

  static const base::StringPiece crashes_html(
      ResourceBundle::GetSharedInstance().GetRawDataResource(IDR_CRASHES_HTML));
  std::string full_html =
      jstemplate_builder::GetI18nTemplateHtml(crashes_html, &localized_strings);
  jstemplate_builder::AppendJsTemplateSourceHtml(&full_html);

  scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes);
  html_bytes->data.resize(full_html.size());
  std::copy(full_html.begin(), full_html.end(), html_bytes->data.begin());

  SendResponse(request_id, html_bytes);
}

////////////////////////////////////////////////////////////////////////////////
//
// CrashesDOMHandler
//
////////////////////////////////////////////////////////////////////////////////

// The handler for Javascript messages for the chrome://crashes/ page.
class CrashesDOMHandler : public WebUIMessageHandler,
                          public CrashUploadList::Delegate {
 public:
  explicit CrashesDOMHandler();
  virtual ~CrashesDOMHandler();

  // WebUIMessageHandler implementation.
  virtual WebUIMessageHandler* Attach(WebUI* web_ui);
  virtual void RegisterMessages();

  // CrashUploadList::Delegate implemenation.
  virtual void OnCrashListAvailable();

 private:
  // Asynchronously fetches the list of crashes. Called from JS.
  void HandleRequestCrashes(const ListValue* args);

  // Sends the recent crashes list JS.
  void UpdateUI();

  // Returns whether or not crash reporting is enabled.
  bool CrashReportingEnabled() const;

  scoped_refptr<CrashUploadList> upload_list_;
  bool list_available_;
  bool js_request_pending_;

  DISALLOW_COPY_AND_ASSIGN(CrashesDOMHandler);
};

CrashesDOMHandler::CrashesDOMHandler()
    : list_available_(false), js_request_pending_(false) {
  upload_list_ = new CrashUploadList(this);
}

CrashesDOMHandler::~CrashesDOMHandler() {
  upload_list_->ClearDelegate();
}

WebUIMessageHandler* CrashesDOMHandler::Attach(WebUI* web_ui) {
  upload_list_->LoadCrashListAsynchronously();
  return WebUIMessageHandler::Attach(web_ui);
}

void CrashesDOMHandler::RegisterMessages() {
  web_ui_->RegisterMessageCallback("requestCrashList",
      NewCallback(this, &CrashesDOMHandler::HandleRequestCrashes));
}

void CrashesDOMHandler::HandleRequestCrashes(const ListValue* args) {
  if (!CrashReportingEnabled() || list_available_)
    UpdateUI();
  else
    js_request_pending_ = true;
}

void CrashesDOMHandler::OnCrashListAvailable() {
  list_available_ = true;
  if (js_request_pending_)
    UpdateUI();
}

void CrashesDOMHandler::UpdateUI() {
  bool crash_reporting_enabled = CrashReportingEnabled();
  ListValue crash_list;

  if (crash_reporting_enabled) {
    std::vector<CrashUploadList::CrashInfo> crashes;
    upload_list_->GetUploadedCrashes(50, &crashes);

    for (std::vector<CrashUploadList::CrashInfo>::iterator i = crashes.begin();
         i != crashes.end(); ++i) {
      DictionaryValue* crash = new DictionaryValue();
      crash->SetString("id", i->crash_id);
      crash->SetString("time",
                       base::TimeFormatFriendlyDateAndTime(i->crash_time));
      crash_list.Append(crash);
    }
  }

  FundamentalValue enabled(crash_reporting_enabled);

  web_ui_->CallJavascriptFunction(L"updateCrashList", enabled, crash_list);
}

bool CrashesDOMHandler::CrashReportingEnabled() const {
#if defined(GOOGLE_CHROME_BUILD)
  PrefService* prefs = g_browser_process->local_state();
  return prefs->GetBoolean(prefs::kMetricsReportingEnabled);
#else
  return false;
#endif
}

}  // namespace

///////////////////////////////////////////////////////////////////////////////
//
// CrashesUI
//
///////////////////////////////////////////////////////////////////////////////

CrashesUI::CrashesUI(TabContents* contents) : WebUI(contents) {
  AddMessageHandler((new CrashesDOMHandler())->Attach(this));

  CrashesUIHTMLSource* html_source = new CrashesUIHTMLSource();

  // Set up the chrome://crashes/ source.
  contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source);
}

// static
RefCountedMemory* CrashesUI::GetFaviconResourceBytes() {
  return ResourceBundle::GetSharedInstance().
      LoadDataResourceBytes(IDR_SAD_FAVICON);
}
<|endoftext|>


<commit_before><commit_msg>Remove LOG(INFO) spam.<commit_after><|endoftext|>


<commit_before>#ifndef MUNCHAR_LEXEMES
#define MUNCHAR_LEXEMES

#include "munchar.hpp"
#include <cctype>

namespace Munchar {
  namespace Lexemes {

    constexpr auto null          = '\0'_lit;
    constexpr auto tab           = '\t'_lit;
    constexpr auto newline       = '\n'_lit;
    constexpr auto linefeed      = newline;
    constexpr auto cr            = '\r'_lit;
    constexpr auto crlf          = "\r\n"_lit;

    constexpr auto space         = ' '_lit;
    constexpr auto exclamation   = '!'_lit;
    constexpr auto double_quote  = '"'_lit;
    constexpr auto quote         = double_quote;
    constexpr auto pound         = '#'_lit;
    constexpr auto hash          = pound;
    constexpr auto octothorpe    = pound;
    constexpr auto dollar        = '$'_lit;
    constexpr auto percent       = '%'_lit;
    constexpr auto ampersand     = '&'_lit;
    constexpr auto apostrophe    = '\''_lit;
    constexpr auto single_quote  = apostrophe;
    constexpr auto left_paren    = '('_lit;
    constexpr auto right_paren   = ')'_lit;
    constexpr auto asterisk      = '*'_lit;
    constexpr auto plus          = '+'_lit;
    constexpr auto comma         = ','_lit;
    constexpr auto hyphen        = '-'_lit;
    constexpr auto minus         = hyphen;
    constexpr auto period        = '.'_lit;
    constexpr auto dot           = period;
    constexpr auto slash         = '/'_lit;
    constexpr auto divide        = slash;
    constexpr auto colon         = ':'_lit;
    constexpr auto semicolon     = ';'_lit;
    constexpr auto less_than     = '<'_lit;
    constexpr auto lt            = less_than;
    constexpr auto lte           = "<="_lit;
    constexpr auto equals        = '='_lit;
    constexpr auto eq            = equals;
    constexpr auto greater_than  = '>'_lit;
    constexpr auto gt            = greater_than;
    constexpr auto gte           = ">="_lit;
    constexpr auto question      = '?'_lit;
    constexpr auto at            = '@'_lit;
    constexpr auto left_bracket  = '['_lit;
    constexpr auto backslash     = '\\';
    constexpr auto right_bracket = ']'_lit;
    constexpr auto caret         = '^'_lit;
    constexpr auto circumflex    = caret;
    constexpr auto underscore    = '_'_lit;
    constexpr auto backquote     = '`'_lit;
    constexpr auto left_brace    = '{'_lit;
    constexpr auto vertical_bar  = '|'_lit;
    constexpr auto pipe          = vertical_bar;
    constexpr auto right_brace   = '}'_lit;
    constexpr auto tilde         = '~'_lit;

    constexpr auto _             = Any_Char { };
    constexpr auto letter        = MUNCHAR_STATIC_PREDICATE(std::isalpha);
    constexpr auto alphanumeric  = MUNCHAR_STATIC_PREDICATE(std::isalnum);
    constexpr auto digit         = MUNCHAR_STATIC_PREDICATE(std::isdigit);
    constexpr auto hex_digit     = MUNCHAR_STATIC_PREDICATE(std::isxdigit);
    constexpr auto ws_char       = MUNCHAR_STATIC_PREDICATE(std::isspace);
    constexpr auto whitespace    = *ws_char;
    constexpr auto sign          = "+-"_cls;
    constexpr auto id_start      = letter | underscore;
    constexpr auto id_body       = alphanumeric | underscore;
    constexpr auto identifier    = id_start^*id_body;
    constexpr auto integer       = ~sign ^ +digit;
    constexpr auto real          = (integer|sign)^dot^+digit^~('e'_lit^integer);
    constexpr auto number        = real | integer;

  }
}

#endif<commit_msg>tweking some predefined patterns<commit_after>#ifndef MUNCHAR_LEXEMES
#define MUNCHAR_LEXEMES

#include "munchar.hpp"
#include <cctype>

namespace Munchar {
  namespace Lexemes {

    constexpr auto null          = '\0'_lit;
    constexpr auto tab           = '\t'_lit;
    constexpr auto newline       = '\n'_lit;
    constexpr auto linefeed      = newline;
    constexpr auto cr            = '\r'_lit;
    constexpr auto crlf          = "\r\n"_lit;

    constexpr auto space         = ' '_lit;
    constexpr auto exclamation   = '!'_lit;
    constexpr auto double_quote  = '"'_lit;
    constexpr auto quote         = double_quote;
    constexpr auto pound         = '#'_lit;
    constexpr auto hash          = pound;
    constexpr auto octothorpe    = pound;
    constexpr auto dollar        = '$'_lit;
    constexpr auto percent       = '%'_lit;
    constexpr auto ampersand     = '&'_lit;
    constexpr auto apostrophe    = '\''_lit;
    constexpr auto single_quote  = apostrophe;
    constexpr auto left_paren    = '('_lit;
    constexpr auto right_paren   = ')'_lit;
    constexpr auto asterisk      = '*'_lit;
    constexpr auto plus          = '+'_lit;
    constexpr auto comma         = ','_lit;
    constexpr auto hyphen        = '-'_lit;
    constexpr auto minus         = hyphen;
    constexpr auto period        = '.'_lit;
    constexpr auto dot           = period;
    constexpr auto slash         = '/'_lit;
    constexpr auto divide        = slash;
    constexpr auto colon         = ':'_lit;
    constexpr auto semicolon     = ';'_lit;
    constexpr auto less_than     = '<'_lit;
    constexpr auto lt            = less_than;
    constexpr auto lte           = "<="_lit;
    constexpr auto equals        = '='_lit;
    constexpr auto eq            = equals;
    constexpr auto greater_than  = '>'_lit;
    constexpr auto gt            = greater_than;
    constexpr auto gte           = ">="_lit;
    constexpr auto question      = '?'_lit;
    constexpr auto at            = '@'_lit;
    constexpr auto left_bracket  = '['_lit;
    constexpr auto backslash     = '\\';
    constexpr auto right_bracket = ']'_lit;
    constexpr auto caret         = '^'_lit;
    constexpr auto circumflex    = caret;
    constexpr auto underscore    = '_'_lit;
    constexpr auto backquote     = '`'_lit;
    constexpr auto left_brace    = '{'_lit;
    constexpr auto vertical_bar  = '|'_lit;
    constexpr auto pipe          = vertical_bar;
    constexpr auto right_brace   = '}'_lit;
    constexpr auto tilde         = '~'_lit;

    constexpr auto _             = Any_Char { };
    constexpr auto letter        = MUNCHAR_STATIC_PREDICATE(std::isalpha);
    constexpr auto alphanumeric  = MUNCHAR_STATIC_PREDICATE(std::isalnum);
    constexpr auto digit         = MUNCHAR_STATIC_PREDICATE(std::isdigit);
    constexpr auto hex_digit     = MUNCHAR_STATIC_PREDICATE(std::isxdigit);
    constexpr auto ws_char       = MUNCHAR_STATIC_PREDICATE(std::isspace);
    constexpr auto whitespace    = *ws_char;
    constexpr auto sign          = "+-"_cls;
    constexpr auto id_start      = letter | underscore;
    constexpr auto id_body       = alphanumeric | underscore;
    constexpr auto identifier    = id_start^*id_body;
    constexpr auto integer       = ~sign ^ +digit;
    constexpr auto number_ne     = (~sign ^ *digit ^ dot ^ +digit) | +digit;
    constexpr auto number        = number_ne ^ ~("eE"_cls ^ ~sign ^ +digit);

  }
}

#endif<|endoftext|>


<commit_before>/*
 * Copyright (C) 2018 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "partition_version.hh"
#include "partition_version_list.hh"

#include "utils/logalloc.hh"

class mutation_cleaner_impl final {
    using snapshot_list = boost::intrusive::slist<partition_snapshot,
        boost::intrusive::member_hook<partition_snapshot, boost::intrusive::slist_member_hook<>, &partition_snapshot::_cleaner_hook>>;
    struct worker {
        condition_variable cv;
        snapshot_list snapshots;
        logalloc::allocating_section alloc_section;
        bool done = false; // true means the worker was abandoned and cannot access the mutation_cleaner_impl instance.
    };
private:
    logalloc::region& _region;
    cache_tracker* _tracker;
    partition_version_list _versions;
    lw_shared_ptr<worker> _worker_state;
    seastar::scheduling_group _scheduling_group;
private:
    stop_iteration merge_some(partition_snapshot& snp) noexcept;
    stop_iteration merge_some() noexcept;
    void start_worker();
public:
    mutation_cleaner_impl(logalloc::region& r, cache_tracker* t, seastar::scheduling_group sg = seastar::current_scheduling_group())
        : _region(r)
        , _tracker(t)
        , _worker_state(make_lw_shared<worker>())
        , _scheduling_group(sg)
    {
        start_worker();
    }
    ~mutation_cleaner_impl();
    stop_iteration clear_gently() noexcept;
    memory::reclaiming_result clear_some() noexcept;
    void clear() noexcept;
    void destroy_later(partition_version& v) noexcept;
    void destroy_gently(partition_version& v) noexcept;
    void merge(mutation_cleaner_impl& other) noexcept;
    bool empty() const noexcept { return _versions.empty(); }
    future<> drain();
    void merge_and_destroy(partition_snapshot&) noexcept;
    void set_scheduling_group(seastar::scheduling_group sg) {
        _scheduling_group = sg;
        _worker_state->cv.broadcast();
    }
};

inline
void mutation_cleaner_impl::destroy_later(partition_version& v) noexcept {
    _versions.push_back(v);
}

inline
void mutation_cleaner_impl::destroy_gently(partition_version& v) noexcept {
    if (v.clear_gently(_tracker) == stop_iteration::no) {
        destroy_later(v);
    } else {
        current_allocator().destroy(&v);
    }
}

inline
void mutation_cleaner_impl::merge_and_destroy(partition_snapshot& ps) noexcept {
    if (ps.slide_to_oldest() == stop_iteration::yes || merge_some(ps) == stop_iteration::yes) {
        lw_shared_ptr<partition_snapshot>::dispose(&ps);
    } else {
        // The snapshot must not be reachable by partitino_entry::read() after this,
        // which is ensured by slide_to_oldest() == stop_iteration::no.
        _worker_state->snapshots.push_front(ps);
        _worker_state->cv.signal();
    }
}

// Container for garbage partition_version objects, used for freeing them incrementally.
//
// Mutation cleaner extends the lifetime of mutation_partition without doing
// the same for its schema. This means that the destruction of mutation_partition
// as well as any LSA migrators it may use cannot depend on the schema. Moreover,
// all used LSA migrators need remain alive and registered as long as
// mutation_cleaner is alive. In particular, this means that the instances of
// mutation_cleaner should not be thread local objects (or members of thread
// local objects).
class mutation_cleaner final {
    lw_shared_ptr<mutation_cleaner_impl> _impl;
public:
    mutation_cleaner(logalloc::region& r, cache_tracker* t, seastar::scheduling_group sg = seastar::current_scheduling_group())
        : _impl(make_lw_shared<mutation_cleaner_impl>(r, t, sg)) {
    }

    void set_scheduling_group(seastar::scheduling_group sg) {
        _impl->set_scheduling_group(sg);
    }

    // Frees some of the data. Returns stop_iteration::yes iff all was freed.
    // Must be invoked under owning allocator.
    stop_iteration clear_gently() noexcept {
        return _impl->clear_gently();
    }

    // Must be invoked under owning allocator.
    memory::reclaiming_result clear_some() noexcept {
        return _impl->clear_some();
    }

    // Must be invoked under owning allocator.
    void clear() noexcept {
        _impl->clear();
    }

    // Enqueues v for destruction.
    // The object must not be part of any list, and must not be accessed externally any more.
    // In particular, it must not be attached, even indirectly, to any snapshot or partition_entry,
    // and must not be evicted from.
    // Must be invoked under owning allocator.
    void destroy_later(partition_version& v) noexcept {
        return _impl->destroy_later(v);
    }

    // Destroys v now or later.
    // Same requirements as destroy_later().
    // Must be invoked under owning allocator.
    void destroy_gently(partition_version& v) noexcept {
        return _impl->destroy_gently(v);
    }

    // Transfers objects from other to this.
    // This and other must belong to the same logalloc::region, and the same cache_tracker.
    // After the call other will refer to this cleaner.
    void merge(mutation_cleaner& other) noexcept {
        _impl->merge(*other._impl);
        other._impl = _impl;
    }

    // Returns true iff contains no unfreed objects
    bool empty() const noexcept {
        return _impl->empty();
    }

    // Forces cleaning and returns a future which resolves when there is nothing to clean.
    future<> drain() {
        return _impl->drain();
    }

    // Will merge given snapshot using partition_snapshot::merge_partition_versions() and then destroys it
    // using destroy_from_this(), possibly deferring in between.
    // This instance becomes the sole owner of the partition_snapshot object, the caller should not destroy it
    // nor access it after calling this.
    void merge_and_destroy(partition_snapshot& ps) {
        return _impl->merge_and_destroy(ps);
    }
};
<commit_msg>mutation_cleaner: impl: Store a back-reference to the owning mutation_cleaner<commit_after>/*
 * Copyright (C) 2018 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "partition_version.hh"
#include "partition_version_list.hh"

#include "utils/logalloc.hh"

class mutation_cleaner;

class mutation_cleaner_impl final {
    using snapshot_list = boost::intrusive::slist<partition_snapshot,
        boost::intrusive::member_hook<partition_snapshot, boost::intrusive::slist_member_hook<>, &partition_snapshot::_cleaner_hook>>;
    struct worker {
        condition_variable cv;
        snapshot_list snapshots;
        logalloc::allocating_section alloc_section;
        bool done = false; // true means the worker was abandoned and cannot access the mutation_cleaner_impl instance.
    };
private:
    logalloc::region& _region;
    cache_tracker* _tracker;
    mutation_cleaner* _cleaner;
    partition_version_list _versions;
    lw_shared_ptr<worker> _worker_state;
    seastar::scheduling_group _scheduling_group;
private:
    stop_iteration merge_some(partition_snapshot& snp) noexcept;
    stop_iteration merge_some() noexcept;
    void start_worker();
public:
    mutation_cleaner_impl(logalloc::region& r, cache_tracker* t, mutation_cleaner* cleaner, seastar::scheduling_group sg = seastar::current_scheduling_group())
        : _region(r)
        , _tracker(t)
        , _cleaner(cleaner)
        , _worker_state(make_lw_shared<worker>())
        , _scheduling_group(sg)
    {
        start_worker();
    }
    ~mutation_cleaner_impl();
    stop_iteration clear_gently() noexcept;
    memory::reclaiming_result clear_some() noexcept;
    void clear() noexcept;
    void destroy_later(partition_version& v) noexcept;
    void destroy_gently(partition_version& v) noexcept;
    void merge(mutation_cleaner_impl& other) noexcept;
    bool empty() const noexcept { return _versions.empty(); }
    future<> drain();
    void merge_and_destroy(partition_snapshot&) noexcept;
    void set_scheduling_group(seastar::scheduling_group sg) {
        _scheduling_group = sg;
        _worker_state->cv.broadcast();
    }
};

inline
void mutation_cleaner_impl::destroy_later(partition_version& v) noexcept {
    _versions.push_back(v);
}

inline
void mutation_cleaner_impl::destroy_gently(partition_version& v) noexcept {
    if (v.clear_gently(_tracker) == stop_iteration::no) {
        destroy_later(v);
    } else {
        current_allocator().destroy(&v);
    }
}

inline
void mutation_cleaner_impl::merge_and_destroy(partition_snapshot& ps) noexcept {
    if (ps.slide_to_oldest() == stop_iteration::yes || merge_some(ps) == stop_iteration::yes) {
        lw_shared_ptr<partition_snapshot>::dispose(&ps);
    } else {
        // The snapshot must not be reachable by partitino_entry::read() after this,
        // which is ensured by slide_to_oldest() == stop_iteration::no.
        _worker_state->snapshots.push_front(ps);
        _worker_state->cv.signal();
    }
}

// Container for garbage partition_version objects, used for freeing them incrementally.
//
// Mutation cleaner extends the lifetime of mutation_partition without doing
// the same for its schema. This means that the destruction of mutation_partition
// as well as any LSA migrators it may use cannot depend on the schema. Moreover,
// all used LSA migrators need remain alive and registered as long as
// mutation_cleaner is alive. In particular, this means that the instances of
// mutation_cleaner should not be thread local objects (or members of thread
// local objects).
class mutation_cleaner final {
    lw_shared_ptr<mutation_cleaner_impl> _impl;
public:
    mutation_cleaner(logalloc::region& r, cache_tracker* t, seastar::scheduling_group sg = seastar::current_scheduling_group())
        : _impl(make_lw_shared<mutation_cleaner_impl>(r, t, this, sg)) {
    }

    mutation_cleaner(mutation_cleaner&&) = delete;
    mutation_cleaner(const mutation_cleaner&) = delete;

    void set_scheduling_group(seastar::scheduling_group sg) {
        _impl->set_scheduling_group(sg);
    }

    // Frees some of the data. Returns stop_iteration::yes iff all was freed.
    // Must be invoked under owning allocator.
    stop_iteration clear_gently() noexcept {
        return _impl->clear_gently();
    }

    // Must be invoked under owning allocator.
    memory::reclaiming_result clear_some() noexcept {
        return _impl->clear_some();
    }

    // Must be invoked under owning allocator.
    void clear() noexcept {
        _impl->clear();
    }

    // Enqueues v for destruction.
    // The object must not be part of any list, and must not be accessed externally any more.
    // In particular, it must not be attached, even indirectly, to any snapshot or partition_entry,
    // and must not be evicted from.
    // Must be invoked under owning allocator.
    void destroy_later(partition_version& v) noexcept {
        return _impl->destroy_later(v);
    }

    // Destroys v now or later.
    // Same requirements as destroy_later().
    // Must be invoked under owning allocator.
    void destroy_gently(partition_version& v) noexcept {
        return _impl->destroy_gently(v);
    }

    // Transfers objects from other to this.
    // This and other must belong to the same logalloc::region, and the same cache_tracker.
    // After the call other will refer to this cleaner.
    void merge(mutation_cleaner& other) noexcept {
        _impl->merge(*other._impl);
        other._impl = _impl;
    }

    // Returns true iff contains no unfreed objects
    bool empty() const noexcept {
        return _impl->empty();
    }

    // Forces cleaning and returns a future which resolves when there is nothing to clean.
    future<> drain() {
        return _impl->drain();
    }

    // Will merge given snapshot using partition_snapshot::merge_partition_versions() and then destroys it
    // using destroy_from_this(), possibly deferring in between.
    // This instance becomes the sole owner of the partition_snapshot object, the caller should not destroy it
    // nor access it after calling this.
    void merge_and_destroy(partition_snapshot& ps) {
        return _impl->merge_and_destroy(ps);
    }
};
<|endoftext|>


<commit_before>#include <cmath>

#include "factorization.hpp"

VU
factor(UL n)
{
    VU factors;

    UL limit = sqrtl(n);
    for (UL x = 2;;) {
        if (x > limit) break;

        while (n % x == 0) {
            n /= x;
            limit = sqrtl(n);
            factors.push_back(x);
        }

        if (x > 2)
            x += 2;
        else
            ++x;
    }
    if (n > 1)
        factors.push_back(n);

    return factors;
}

<commit_msg>2.5% better time<commit_after>#include <cmath>

#include "factorization.hpp"

VU
factor(UL n)
{
    VU factors;

    UL limit = sqrtl(n);
    for (UL x = 2;;) {
        if (x > limit) break;

        if (n % x == 0) {
            do {
                n /= x;
                factors.push_back(x);
            } while (n % x == 0);
            limit = sqrtl(n);
        }

        if (x > 2)
            x += 2;
        else
            ++x;
    }
    if (n > 1)
        factors.push_back(n);

    return factors;
}

<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
//  winInputMgr.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "winInputMgr.h"
#include "Core/Core.h"
#include "Core/RunLoop.h"
#include "Gfx/win/winDisplayMgr.h"

namespace Oryol {
namespace _priv {

winInputMgr* winInputMgr::self = nullptr;

static Key::Code keyTable[ORYOL_WIN_KEY_LAST + 1];

//------------------------------------------------------------------------------
winInputMgr::winInputMgr() :
    runLoopId(RunLoop::InvalidId) {
    o_assert(nullptr == self);
    self = this;
}

//------------------------------------------------------------------------------
winInputMgr::~winInputMgr() {
    o_assert(nullptr != self);
    self = nullptr;
}

//------------------------------------------------------------------------------
void
winInputMgr::setup(const InputSetup& setup) {

    inputMgrBase::setup(setup);
    this->keyboard.attached = true;
    this->mouse.attached = true;

    // first check that the Gfx module has already been initialized
    // (directly access the 'private' interface of winDisplayMgr,
    // better don't do this in regular code!)
    if (!winDisplayMgr::self && winDisplayMgr::self->IsDisplayValid()) {
        o_error("winInputMgr: Gfx::Setup() must be called before Input::Setup!\n");
        return;
    }
    this->setupKeyTable();
    this->setupCallbacks();

    // attach our reset callback to the global runloop
    this->runLoopId = Core::PostRunLoop()->Add([this]() { this->reset(); });
}

//------------------------------------------------------------------------------
void
winInputMgr::discard() {
    this->discardCallbacks();
    Core::PostRunLoop()->Remove(this->runLoopId);
    this->runLoopId = RunLoop::InvalidId;
    inputMgrBase::discard();
}

//------------------------------------------------------------------------------
void
winInputMgr::setupCallbacks() {
    o_assert(winDisplayMgr::self);
    winDisplayMgr::callbackTable& cb = winDisplayMgr::self->callbacks;
    cb.key = keyCallback;
    cb.character = charCallback;
    cb.mouseButton = mouseButtonCallback;
    cb.cursorPos = cursorPosCallback;
    cb.cursorEnter = cursorEnterCallback;
    cb.scroll = scrollCallback;
}

//------------------------------------------------------------------------------
void
winInputMgr::discardCallbacks() {
    o_assert(winDisplayMgr::self);
    winDisplayMgr::callbackTable& cb = winDisplayMgr::self->callbacks;
    cb.key = nullptr;
    cb.character = nullptr;
    cb.mouseButton = nullptr;
    cb.cursorPos = nullptr;
    cb.cursorEnter = nullptr;
    cb.scroll = nullptr;
}

//------------------------------------------------------------------------------
void
winInputMgr::keyCallback(int winKey, int /*winScancode*/, int winAction, int /*winMods*/) {
    if (nullptr != self) {
        Key::Code key = self->mapKey(winKey);
        if (Key::InvalidKey != key) {
            if (winAction == ORYOL_WIN_PRESS) {
                self->keyboard.onKeyDown(key);
            }
            else if (winAction == ORYOL_WIN_RELEASE) {
                self->keyboard.onKeyUp(key);
            }
            else {
                self->keyboard.onKeyRepeat(key);
            }
        }
    }
}

//------------------------------------------------------------------------------
void
winInputMgr::charCallback(unsigned int unicode) {
    if (nullptr != self) {
        self->keyboard.onChar((wchar_t)unicode);
    }
}

//------------------------------------------------------------------------------
void
winInputMgr::mouseButtonCallback(int winButton, int winAction, int winMods) {
    if (nullptr != self) {
        MouseButton::Code btn;
        switch (winButton) {
            case ORYOL_WIN_MOUSE_BUTTON_LEFT:    btn = MouseButton::Left; break;
            case ORYOL_WIN_MOUSE_BUTTON_RIGHT:   btn = MouseButton::Right; break;
            case ORYOL_WIN_MOUSE_BUTTON_MIDDLE:  btn = MouseButton::Middle; break;
            default:                             btn = MouseButton::InvalidMouseButton; break;
        }
        if (btn != MouseButton::InvalidMouseButton) {
            PointerLockMode::Code lockMode = PointerLockMode::DontCare;
            if (winAction == ORYOL_WIN_PRESS) {
                lockMode = self->mouse.onButtonDown(btn);
            }
            else if (winAction == ORYOL_WIN_RELEASE) {
                lockMode = self->mouse.onButtonUp(btn);
            }
            if (PointerLockMode::Enable == lockMode) {
                winDisplayMgr::self->setInputMode(ORYOL_WIN_CURSOR, ORYOL_WIN_CURSOR_DISABLED);
            }
            else if (PointerLockMode::Disable == lockMode) {
                winDisplayMgr::self->setInputMode(ORYOL_WIN_CURSOR, ORYOL_WIN_CURSOR_NORMAL);
            }
        }
    }
}

//------------------------------------------------------------------------------
void
winInputMgr::cursorPosCallback(double winX, double winY) {
    if (nullptr != self) {
        const glm::vec2 pos((float)winX, (float)winY);
        self->mouse.onPosMov(pos);
    }
}

//------------------------------------------------------------------------------
void
winInputMgr::scrollCallback(double winX, double winY) {
    if (nullptr != self) {
        const glm::vec2 scroll((float)winX, (float)winY);
        self->mouse.scroll = scroll;
    }
}

//------------------------------------------------------------------------------
void
winInputMgr::cursorEnterCallback(int entered) {
    // empty
}

//------------------------------------------------------------------------------
Key::Code
winInputMgr::mapKey(int winKey) const {
    if ((winKey >= 0) && (winKey <= ORYOL_WIN_KEY_LAST)) {
        return keyTable[winKey];
    }
    else {
        return Key::InvalidKey;
    }
}

//------------------------------------------------------------------------------
void
winInputMgr::setupKeyTable() {

    for (int i = 0; i <= ORYOL_WIN_KEY_LAST; i++) {
        keyTable[i] = Key::InvalidKey;
    }

    keyTable[ORYOL_WIN_KEY_SPACE] = Key::Space;
    keyTable[ORYOL_WIN_KEY_APOSTROPHE] = Key::Apostrophe;
    keyTable[ORYOL_WIN_KEY_COMMA] = Key::Comma;
    keyTable[ORYOL_WIN_KEY_MINUS] = Key::Minus;
    keyTable[ORYOL_WIN_KEY_PERIOD] = Key::Period;
    keyTable[ORYOL_WIN_KEY_SLASH] = Key::Slash;
    keyTable[ORYOL_WIN_KEY_0] = Key::N0;
    keyTable[ORYOL_WIN_KEY_1] = Key::N1;
    keyTable[ORYOL_WIN_KEY_2] = Key::N2;
    keyTable[ORYOL_WIN_KEY_3] = Key::N3;
    keyTable[ORYOL_WIN_KEY_4] = Key::N4;
    keyTable[ORYOL_WIN_KEY_5] = Key::N5;
    keyTable[ORYOL_WIN_KEY_6] = Key::N6;
    keyTable[ORYOL_WIN_KEY_7] = Key::N7;
    keyTable[ORYOL_WIN_KEY_8] = Key::N8;
    keyTable[ORYOL_WIN_KEY_9] = Key::N9;
    keyTable[ORYOL_WIN_KEY_SEMICOLON] = Key::Semicolon;
    keyTable[ORYOL_WIN_KEY_EQUAL] = Key::Equal;
    keyTable[ORYOL_WIN_KEY_A] = Key::A;
    keyTable[ORYOL_WIN_KEY_B] = Key::B;
    keyTable[ORYOL_WIN_KEY_C] = Key::C;
    keyTable[ORYOL_WIN_KEY_D] = Key::D;
    keyTable[ORYOL_WIN_KEY_E] = Key::E;
    keyTable[ORYOL_WIN_KEY_F] = Key::F;
    keyTable[ORYOL_WIN_KEY_G] = Key::G;
    keyTable[ORYOL_WIN_KEY_H] = Key::H;
    keyTable[ORYOL_WIN_KEY_I] = Key::I;
    keyTable[ORYOL_WIN_KEY_J] = Key::J;
    keyTable[ORYOL_WIN_KEY_K] = Key::K;
    keyTable[ORYOL_WIN_KEY_L] = Key::L;
    keyTable[ORYOL_WIN_KEY_M] = Key::M;
    keyTable[ORYOL_WIN_KEY_N] = Key::N;
    keyTable[ORYOL_WIN_KEY_O] = Key::O;
    keyTable[ORYOL_WIN_KEY_P] = Key::P;
    keyTable[ORYOL_WIN_KEY_Q] = Key::Q;
    keyTable[ORYOL_WIN_KEY_R] = Key::R;
    keyTable[ORYOL_WIN_KEY_S] = Key::S;
    keyTable[ORYOL_WIN_KEY_T] = Key::T;
    keyTable[ORYOL_WIN_KEY_U] = Key::U;
    keyTable[ORYOL_WIN_KEY_V] = Key::V;
    keyTable[ORYOL_WIN_KEY_W] = Key::W;
    keyTable[ORYOL_WIN_KEY_X] = Key::X;
    keyTable[ORYOL_WIN_KEY_Y] = Key::Y;
    keyTable[ORYOL_WIN_KEY_Z] = Key::Z;
    keyTable[ORYOL_WIN_KEY_LEFT_BRACKET] = Key::LeftBracket;
    keyTable[ORYOL_WIN_KEY_BACKSLASH] = Key::BackSlash;
    keyTable[ORYOL_WIN_KEY_RIGHT_BRACKET] = Key::RightBracket;
    keyTable[ORYOL_WIN_KEY_GRAVE_ACCENT] = Key::GraveAccent;
    keyTable[ORYOL_WIN_KEY_WORLD_1] = Key::World1;
    keyTable[ORYOL_WIN_KEY_WORLD_2] = Key::World2;
    keyTable[ORYOL_WIN_KEY_ESCAPE] = Key::Escape;
    keyTable[ORYOL_WIN_KEY_ENTER] = Key::Enter;
    keyTable[ORYOL_WIN_KEY_TAB] = Key::Tab;
    keyTable[ORYOL_WIN_KEY_BACKSPACE] = Key::BackSpace;
    keyTable[ORYOL_WIN_KEY_INSERT] = Key::Insert;
    keyTable[ORYOL_WIN_KEY_DELETE] = Key::Delete;
    keyTable[ORYOL_WIN_KEY_RIGHT] = Key::Right;
    keyTable[ORYOL_WIN_KEY_LEFT] = Key::Left;
    keyTable[ORYOL_WIN_KEY_DOWN] = Key::Down;
    keyTable[ORYOL_WIN_KEY_UP] = Key::Up;
    keyTable[ORYOL_WIN_KEY_PAGE_UP] = Key::PageUp;
    keyTable[ORYOL_WIN_KEY_PAGE_DOWN] = Key::PageDown;
    keyTable[ORYOL_WIN_KEY_HOME] = Key::Home;
    keyTable[ORYOL_WIN_KEY_END] = Key::End;
    keyTable[ORYOL_WIN_KEY_CAPS_LOCK] = Key::CapsLock;
    keyTable[ORYOL_WIN_KEY_SCROLL_LOCK] = Key::ScrollLock;
    keyTable[ORYOL_WIN_KEY_NUM_LOCK] = Key::NumLock;
    keyTable[ORYOL_WIN_KEY_PRINT_SCREEN] = Key::PrintScreen;
    keyTable[ORYOL_WIN_KEY_PAUSE] = Key::Pause;
    keyTable[ORYOL_WIN_KEY_F1] = Key::F1;
    keyTable[ORYOL_WIN_KEY_F2] = Key::F2;
    keyTable[ORYOL_WIN_KEY_F3] = Key::F3;
    keyTable[ORYOL_WIN_KEY_F4] = Key::F4;
    keyTable[ORYOL_WIN_KEY_F5] = Key::F5;
    keyTable[ORYOL_WIN_KEY_F6] = Key::F6;
    keyTable[ORYOL_WIN_KEY_F7] = Key::F7;
    keyTable[ORYOL_WIN_KEY_F8] = Key::F8;
    keyTable[ORYOL_WIN_KEY_F9] = Key::F9;
    keyTable[ORYOL_WIN_KEY_F10] = Key::F10;
    keyTable[ORYOL_WIN_KEY_F11] = Key::F11;
    keyTable[ORYOL_WIN_KEY_F12] = Key::F12;
    keyTable[ORYOL_WIN_KEY_F13] = Key::F13;
    keyTable[ORYOL_WIN_KEY_F14] = Key::F14;
    keyTable[ORYOL_WIN_KEY_F15] = Key::F15;
    keyTable[ORYOL_WIN_KEY_F16] = Key::F16;
    keyTable[ORYOL_WIN_KEY_F17] = Key::F17;
    keyTable[ORYOL_WIN_KEY_F18] = Key::F18;
    keyTable[ORYOL_WIN_KEY_F19] = Key::F19;
    keyTable[ORYOL_WIN_KEY_F20] = Key::F20;
    keyTable[ORYOL_WIN_KEY_F21] = Key::F21;
    keyTable[ORYOL_WIN_KEY_F22] = Key::F22;
    keyTable[ORYOL_WIN_KEY_F23] = Key::F23;
    keyTable[ORYOL_WIN_KEY_F24] = Key::F24;
    keyTable[ORYOL_WIN_KEY_F25] = Key::F25;
    keyTable[ORYOL_WIN_KEY_KP_0] = Key::Num0;
    keyTable[ORYOL_WIN_KEY_KP_1] = Key::Num1;
    keyTable[ORYOL_WIN_KEY_KP_2] = Key::Num2;
    keyTable[ORYOL_WIN_KEY_KP_3] = Key::Num3;
    keyTable[ORYOL_WIN_KEY_KP_4] = Key::Num4;
    keyTable[ORYOL_WIN_KEY_KP_5] = Key::Num5;
    keyTable[ORYOL_WIN_KEY_KP_6] = Key::Num6;
    keyTable[ORYOL_WIN_KEY_KP_7] = Key::Num7;
    keyTable[ORYOL_WIN_KEY_KP_8] = Key::Num8;
    keyTable[ORYOL_WIN_KEY_KP_9] = Key::Num9;
    keyTable[ORYOL_WIN_KEY_KP_DECIMAL] = Key::NumDecimal;
    keyTable[ORYOL_WIN_KEY_KP_DIVIDE] = Key::NumDivide;
    keyTable[ORYOL_WIN_KEY_KP_MULTIPLY] = Key::NumMultiply;
    keyTable[ORYOL_WIN_KEY_KP_SUBTRACT] = Key::NumSubtract;
    keyTable[ORYOL_WIN_KEY_KP_ADD] = Key::NumAdd;
    keyTable[ORYOL_WIN_KEY_KP_ENTER] = Key::NumEnter;
    keyTable[ORYOL_WIN_KEY_KP_EQUAL] = Key::NumEqual;
    keyTable[ORYOL_WIN_KEY_LEFT_SHIFT] = Key::LeftShift;
    keyTable[ORYOL_WIN_KEY_LEFT_CONTROL] = Key::LeftControl;
    keyTable[ORYOL_WIN_KEY_LEFT_ALT] = Key::LeftAlt;
    keyTable[ORYOL_WIN_KEY_LEFT_SUPER] = Key::LeftSuper;
    keyTable[ORYOL_WIN_KEY_RIGHT_SHIFT] = Key::RightShift;
    keyTable[ORYOL_WIN_KEY_RIGHT_CONTROL] = Key::RightControl;
    keyTable[ORYOL_WIN_KEY_RIGHT_ALT] = Key::RightAlt;
    keyTable[ORYOL_WIN_KEY_RIGHT_SUPER] = Key::RightSuper;
    keyTable[ORYOL_WIN_KEY_MENU] = Key::Menu;
}

} // namespace _priv
} // namespace Oryol
<commit_msg>winInputMgr: minor intendation fix<commit_after>//------------------------------------------------------------------------------
//  winInputMgr.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "winInputMgr.h"
#include "Core/Core.h"
#include "Core/RunLoop.h"
#include "Gfx/win/winDisplayMgr.h"

namespace Oryol {
namespace _priv {

winInputMgr* winInputMgr::self = nullptr;

static Key::Code keyTable[ORYOL_WIN_KEY_LAST + 1];

//------------------------------------------------------------------------------
winInputMgr::winInputMgr() :
runLoopId(RunLoop::InvalidId) {
    o_assert(nullptr == self);
    self = this;
}

//------------------------------------------------------------------------------
winInputMgr::~winInputMgr() {
    o_assert(nullptr != self);
    self = nullptr;
}

//------------------------------------------------------------------------------
void
winInputMgr::setup(const InputSetup& setup) {

    inputMgrBase::setup(setup);
    this->keyboard.attached = true;
    this->mouse.attached = true;

    // first check that the Gfx module has already been initialized
    // (directly access the 'private' interface of winDisplayMgr,
    // better don't do this in regular code!)
    if (!winDisplayMgr::self && winDisplayMgr::self->IsDisplayValid()) {
        o_error("winInputMgr: Gfx::Setup() must be called before Input::Setup!\n");
        return;
    }
    this->setupKeyTable();
    this->setupCallbacks();

    // attach our reset callback to the global runloop
    this->runLoopId = Core::PostRunLoop()->Add([this]() { this->reset(); });
}

//------------------------------------------------------------------------------
void
winInputMgr::discard() {
    this->discardCallbacks();
    Core::PostRunLoop()->Remove(this->runLoopId);
    this->runLoopId = RunLoop::InvalidId;
    inputMgrBase::discard();
}

//------------------------------------------------------------------------------
void
winInputMgr::setupCallbacks() {
    o_assert(winDisplayMgr::self);
    winDisplayMgr::callbackTable& cb = winDisplayMgr::self->callbacks;
    cb.key = keyCallback;
    cb.character = charCallback;
    cb.mouseButton = mouseButtonCallback;
    cb.cursorPos = cursorPosCallback;
    cb.cursorEnter = cursorEnterCallback;
    cb.scroll = scrollCallback;
}

//------------------------------------------------------------------------------
void
winInputMgr::discardCallbacks() {
    o_assert(winDisplayMgr::self);
    winDisplayMgr::callbackTable& cb = winDisplayMgr::self->callbacks;
    cb.key = nullptr;
    cb.character = nullptr;
    cb.mouseButton = nullptr;
    cb.cursorPos = nullptr;
    cb.cursorEnter = nullptr;
    cb.scroll = nullptr;
}

//------------------------------------------------------------------------------
void
winInputMgr::keyCallback(int winKey, int /*winScancode*/, int winAction, int /*winMods*/) {
    if (nullptr != self) {
        Key::Code key = self->mapKey(winKey);
        if (Key::InvalidKey != key) {
            if (winAction == ORYOL_WIN_PRESS) {
                self->keyboard.onKeyDown(key);
            }
            else if (winAction == ORYOL_WIN_RELEASE) {
                self->keyboard.onKeyUp(key);
            }
            else {
                self->keyboard.onKeyRepeat(key);
            }
        }
    }
}

//------------------------------------------------------------------------------
void
winInputMgr::charCallback(unsigned int unicode) {
    if (nullptr != self) {
        self->keyboard.onChar((wchar_t)unicode);
    }
}

//------------------------------------------------------------------------------
void
winInputMgr::mouseButtonCallback(int winButton, int winAction, int winMods) {
    if (nullptr != self) {
        MouseButton::Code btn;
        switch (winButton) {
            case ORYOL_WIN_MOUSE_BUTTON_LEFT:    btn = MouseButton::Left; break;
            case ORYOL_WIN_MOUSE_BUTTON_RIGHT:   btn = MouseButton::Right; break;
            case ORYOL_WIN_MOUSE_BUTTON_MIDDLE:  btn = MouseButton::Middle; break;
            default:                             btn = MouseButton::InvalidMouseButton; break;
        }
        if (btn != MouseButton::InvalidMouseButton) {
            PointerLockMode::Code lockMode = PointerLockMode::DontCare;
            if (winAction == ORYOL_WIN_PRESS) {
                lockMode = self->mouse.onButtonDown(btn);
            }
            else if (winAction == ORYOL_WIN_RELEASE) {
                lockMode = self->mouse.onButtonUp(btn);
            }
            if (PointerLockMode::Enable == lockMode) {
                winDisplayMgr::self->setInputMode(ORYOL_WIN_CURSOR, ORYOL_WIN_CURSOR_DISABLED);
            }
            else if (PointerLockMode::Disable == lockMode) {
                winDisplayMgr::self->setInputMode(ORYOL_WIN_CURSOR, ORYOL_WIN_CURSOR_NORMAL);
            }
        }
    }
}

//------------------------------------------------------------------------------
void
winInputMgr::cursorPosCallback(double winX, double winY) {
    if (nullptr != self) {
        const glm::vec2 pos((float)winX, (float)winY);
        self->mouse.onPosMov(pos);
    }
}

//------------------------------------------------------------------------------
void
winInputMgr::scrollCallback(double winX, double winY) {
    if (nullptr != self) {
        const glm::vec2 scroll((float)winX, (float)winY);
        self->mouse.scroll = scroll;
    }
}

//------------------------------------------------------------------------------
void
winInputMgr::cursorEnterCallback(int entered) {
    // empty
}

//------------------------------------------------------------------------------
Key::Code
winInputMgr::mapKey(int winKey) const {
    if ((winKey >= 0) && (winKey <= ORYOL_WIN_KEY_LAST)) {
        return keyTable[winKey];
    }
    else {
        return Key::InvalidKey;
    }
}

//------------------------------------------------------------------------------
void
winInputMgr::setupKeyTable() {

    for (int i = 0; i <= ORYOL_WIN_KEY_LAST; i++) {
        keyTable[i] = Key::InvalidKey;
    }

    keyTable[ORYOL_WIN_KEY_SPACE] = Key::Space;
    keyTable[ORYOL_WIN_KEY_APOSTROPHE] = Key::Apostrophe;
    keyTable[ORYOL_WIN_KEY_COMMA] = Key::Comma;
    keyTable[ORYOL_WIN_KEY_MINUS] = Key::Minus;
    keyTable[ORYOL_WIN_KEY_PERIOD] = Key::Period;
    keyTable[ORYOL_WIN_KEY_SLASH] = Key::Slash;
    keyTable[ORYOL_WIN_KEY_0] = Key::N0;
    keyTable[ORYOL_WIN_KEY_1] = Key::N1;
    keyTable[ORYOL_WIN_KEY_2] = Key::N2;
    keyTable[ORYOL_WIN_KEY_3] = Key::N3;
    keyTable[ORYOL_WIN_KEY_4] = Key::N4;
    keyTable[ORYOL_WIN_KEY_5] = Key::N5;
    keyTable[ORYOL_WIN_KEY_6] = Key::N6;
    keyTable[ORYOL_WIN_KEY_7] = Key::N7;
    keyTable[ORYOL_WIN_KEY_8] = Key::N8;
    keyTable[ORYOL_WIN_KEY_9] = Key::N9;
    keyTable[ORYOL_WIN_KEY_SEMICOLON] = Key::Semicolon;
    keyTable[ORYOL_WIN_KEY_EQUAL] = Key::Equal;
    keyTable[ORYOL_WIN_KEY_A] = Key::A;
    keyTable[ORYOL_WIN_KEY_B] = Key::B;
    keyTable[ORYOL_WIN_KEY_C] = Key::C;
    keyTable[ORYOL_WIN_KEY_D] = Key::D;
    keyTable[ORYOL_WIN_KEY_E] = Key::E;
    keyTable[ORYOL_WIN_KEY_F] = Key::F;
    keyTable[ORYOL_WIN_KEY_G] = Key::G;
    keyTable[ORYOL_WIN_KEY_H] = Key::H;
    keyTable[ORYOL_WIN_KEY_I] = Key::I;
    keyTable[ORYOL_WIN_KEY_J] = Key::J;
    keyTable[ORYOL_WIN_KEY_K] = Key::K;
    keyTable[ORYOL_WIN_KEY_L] = Key::L;
    keyTable[ORYOL_WIN_KEY_M] = Key::M;
    keyTable[ORYOL_WIN_KEY_N] = Key::N;
    keyTable[ORYOL_WIN_KEY_O] = Key::O;
    keyTable[ORYOL_WIN_KEY_P] = Key::P;
    keyTable[ORYOL_WIN_KEY_Q] = Key::Q;
    keyTable[ORYOL_WIN_KEY_R] = Key::R;
    keyTable[ORYOL_WIN_KEY_S] = Key::S;
    keyTable[ORYOL_WIN_KEY_T] = Key::T;
    keyTable[ORYOL_WIN_KEY_U] = Key::U;
    keyTable[ORYOL_WIN_KEY_V] = Key::V;
    keyTable[ORYOL_WIN_KEY_W] = Key::W;
    keyTable[ORYOL_WIN_KEY_X] = Key::X;
    keyTable[ORYOL_WIN_KEY_Y] = Key::Y;
    keyTable[ORYOL_WIN_KEY_Z] = Key::Z;
    keyTable[ORYOL_WIN_KEY_LEFT_BRACKET] = Key::LeftBracket;
    keyTable[ORYOL_WIN_KEY_BACKSLASH] = Key::BackSlash;
    keyTable[ORYOL_WIN_KEY_RIGHT_BRACKET] = Key::RightBracket;
    keyTable[ORYOL_WIN_KEY_GRAVE_ACCENT] = Key::GraveAccent;
    keyTable[ORYOL_WIN_KEY_WORLD_1] = Key::World1;
    keyTable[ORYOL_WIN_KEY_WORLD_2] = Key::World2;
    keyTable[ORYOL_WIN_KEY_ESCAPE] = Key::Escape;
    keyTable[ORYOL_WIN_KEY_ENTER] = Key::Enter;
    keyTable[ORYOL_WIN_KEY_TAB] = Key::Tab;
    keyTable[ORYOL_WIN_KEY_BACKSPACE] = Key::BackSpace;
    keyTable[ORYOL_WIN_KEY_INSERT] = Key::Insert;
    keyTable[ORYOL_WIN_KEY_DELETE] = Key::Delete;
    keyTable[ORYOL_WIN_KEY_RIGHT] = Key::Right;
    keyTable[ORYOL_WIN_KEY_LEFT] = Key::Left;
    keyTable[ORYOL_WIN_KEY_DOWN] = Key::Down;
    keyTable[ORYOL_WIN_KEY_UP] = Key::Up;
    keyTable[ORYOL_WIN_KEY_PAGE_UP] = Key::PageUp;
    keyTable[ORYOL_WIN_KEY_PAGE_DOWN] = Key::PageDown;
    keyTable[ORYOL_WIN_KEY_HOME] = Key::Home;
    keyTable[ORYOL_WIN_KEY_END] = Key::End;
    keyTable[ORYOL_WIN_KEY_CAPS_LOCK] = Key::CapsLock;
    keyTable[ORYOL_WIN_KEY_SCROLL_LOCK] = Key::ScrollLock;
    keyTable[ORYOL_WIN_KEY_NUM_LOCK] = Key::NumLock;
    keyTable[ORYOL_WIN_KEY_PRINT_SCREEN] = Key::PrintScreen;
    keyTable[ORYOL_WIN_KEY_PAUSE] = Key::Pause;
    keyTable[ORYOL_WIN_KEY_F1] = Key::F1;
    keyTable[ORYOL_WIN_KEY_F2] = Key::F2;
    keyTable[ORYOL_WIN_KEY_F3] = Key::F3;
    keyTable[ORYOL_WIN_KEY_F4] = Key::F4;
    keyTable[ORYOL_WIN_KEY_F5] = Key::F5;
    keyTable[ORYOL_WIN_KEY_F6] = Key::F6;
    keyTable[ORYOL_WIN_KEY_F7] = Key::F7;
    keyTable[ORYOL_WIN_KEY_F8] = Key::F8;
    keyTable[ORYOL_WIN_KEY_F9] = Key::F9;
    keyTable[ORYOL_WIN_KEY_F10] = Key::F10;
    keyTable[ORYOL_WIN_KEY_F11] = Key::F11;
    keyTable[ORYOL_WIN_KEY_F12] = Key::F12;
    keyTable[ORYOL_WIN_KEY_F13] = Key::F13;
    keyTable[ORYOL_WIN_KEY_F14] = Key::F14;
    keyTable[ORYOL_WIN_KEY_F15] = Key::F15;
    keyTable[ORYOL_WIN_KEY_F16] = Key::F16;
    keyTable[ORYOL_WIN_KEY_F17] = Key::F17;
    keyTable[ORYOL_WIN_KEY_F18] = Key::F18;
    keyTable[ORYOL_WIN_KEY_F19] = Key::F19;
    keyTable[ORYOL_WIN_KEY_F20] = Key::F20;
    keyTable[ORYOL_WIN_KEY_F21] = Key::F21;
    keyTable[ORYOL_WIN_KEY_F22] = Key::F22;
    keyTable[ORYOL_WIN_KEY_F23] = Key::F23;
    keyTable[ORYOL_WIN_KEY_F24] = Key::F24;
    keyTable[ORYOL_WIN_KEY_F25] = Key::F25;
    keyTable[ORYOL_WIN_KEY_KP_0] = Key::Num0;
    keyTable[ORYOL_WIN_KEY_KP_1] = Key::Num1;
    keyTable[ORYOL_WIN_KEY_KP_2] = Key::Num2;
    keyTable[ORYOL_WIN_KEY_KP_3] = Key::Num3;
    keyTable[ORYOL_WIN_KEY_KP_4] = Key::Num4;
    keyTable[ORYOL_WIN_KEY_KP_5] = Key::Num5;
    keyTable[ORYOL_WIN_KEY_KP_6] = Key::Num6;
    keyTable[ORYOL_WIN_KEY_KP_7] = Key::Num7;
    keyTable[ORYOL_WIN_KEY_KP_8] = Key::Num8;
    keyTable[ORYOL_WIN_KEY_KP_9] = Key::Num9;
    keyTable[ORYOL_WIN_KEY_KP_DECIMAL] = Key::NumDecimal;
    keyTable[ORYOL_WIN_KEY_KP_DIVIDE] = Key::NumDivide;
    keyTable[ORYOL_WIN_KEY_KP_MULTIPLY] = Key::NumMultiply;
    keyTable[ORYOL_WIN_KEY_KP_SUBTRACT] = Key::NumSubtract;
    keyTable[ORYOL_WIN_KEY_KP_ADD] = Key::NumAdd;
    keyTable[ORYOL_WIN_KEY_KP_ENTER] = Key::NumEnter;
    keyTable[ORYOL_WIN_KEY_KP_EQUAL] = Key::NumEqual;
    keyTable[ORYOL_WIN_KEY_LEFT_SHIFT] = Key::LeftShift;
    keyTable[ORYOL_WIN_KEY_LEFT_CONTROL] = Key::LeftControl;
    keyTable[ORYOL_WIN_KEY_LEFT_ALT] = Key::LeftAlt;
    keyTable[ORYOL_WIN_KEY_LEFT_SUPER] = Key::LeftSuper;
    keyTable[ORYOL_WIN_KEY_RIGHT_SHIFT] = Key::RightShift;
    keyTable[ORYOL_WIN_KEY_RIGHT_CONTROL] = Key::RightControl;
    keyTable[ORYOL_WIN_KEY_RIGHT_ALT] = Key::RightAlt;
    keyTable[ORYOL_WIN_KEY_RIGHT_SUPER] = Key::RightSuper;
    keyTable[ORYOL_WIN_KEY_MENU] = Key::Menu;
}

} // namespace _priv
} // namespace Oryol
<|endoftext|>


<commit_before>#include "rpi.h"
#include "bcm2835.h"

//#include <cstdlib> //for atexit
#include "scheduler.h"

namespace drv {
namespace rpi {

bool wasBcmInit = false;

void atexit_bcm2835_close() {
	bcm2835_close(); //return value is int. Must be wrapped as void function for std::atexit to be used.
}

void initIO() {
	if (!wasBcmInit) { //it's OK to double-init (or double-free), but just wastes CPU, and we only really want 1 exit handler.
		wasBcmInit = true;
		if (bcm2835_init()) {
			Scheduler::registerExitHandler(atexit_bcm2835_close, SCHED_MEM_EXIT_LEVEL);
			//std::atexit(atexit_bcm2835_close);
		}
	}
}

}
}
<commit_msg>Log on rpi unload<commit_after>#include "rpi.h"
#include "bcm2835.h"

//#include <cstdlib> //for atexit
#include "scheduler.h"
#include "logging.h"

namespace drv {
namespace rpi {

bool wasBcmInit = false;

void atexit_bcm2835_close() {
	LOG("freeing bcm2835 memmaps\n");
	bcm2835_close(); //return value is int. Must be wrapped as void function for std::atexit to be used.
}

void initIO() {
	if (!wasBcmInit) { //it's OK to double-init (or double-free), but just wastes CPU, and we only really want 1 exit handler.
		wasBcmInit = true;
		if (bcm2835_init()) {
			Scheduler::registerExitHandler(atexit_bcm2835_close, SCHED_MEM_EXIT_LEVEL);
			//std::atexit(atexit_bcm2835_close);
		}
	}
}

}
}
<|endoftext|>