<commit_before>/*

Copyright (c) 2007, Jonathan Wayne Parrott.

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.

*/

#include "PhTexture.h"

using namespace phoenix;

////////////////////////////////////////////////////////////////////////////////
// Construct and Destruct
////////////////////////////////////////////////////////////////////////////////

PhTexture::PhTexture(PhTextureManager* t)
	: texture(0), txtmgr(t), width(0), height(0), name("")
{
    txtmgr->addTexture(this);
}

PhTexture::PhTexture(PhTextureManager* t, int a, int b)
	: txtmgr(t), width(a), height(b), name("")
{

    txtmgr = t;
    txtmgr->addTexture(this);

    //make some room for the texture's data
    data = (unsigned char*)malloc(a*b*4);

    //make all the pixels white and fully opaque
    for (int i = 0; i<(a*b*4); i++)
    {
        *(data+i) = 255;
    }

    //Generate 1 texture
    glGenTextures(1,&texture);

    //Load the texture
    glBindTexture(GL_TEXTURE_2D, texture);

    //write the texture
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, a, b, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);

    //set the parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    //clear the data (not needed until the texture is locked agian)
    free(data);
    data = NULL;

}

PhTexture::~PhTexture()
{
    if (glIsTexture(texture))
    {
        glDeleteTextures(1, &texture);
    }

    if (data!=NULL)
    {
        free(data);
    }

    txtmgr->removeTexture(this);

}

////////////////////////////////////////////////////////////////////////////////
// set and get the texture ID
////////////////////////////////////////////////////////////////////////////////

void PhTexture::setTexture(GLuint text)
{
    texture=text;
}

GLuint PhTexture::getTexture()
{
    return texture;
}

////////////////////////////////////////////////////////////////////////////////
// set and get the texture name
////////////////////////////////////////////////////////////////////////////////

void PhTexture::setName(std::string nm)
{
    name=nm;
}

std::string PhTexture::getName()
{
    return name;
}

////////////////////////////////////////////////////////////////////////////////
// get and set width and height
////////////////////////////////////////////////////////////////////////////////

int PhTexture::getWidth()
{
    return width;
}

int PhTexture::getHeight()
{
    return height;
}

void PhTexture::setWidth(int var)
{
    width = var;
}

void PhTexture::setHeight(int var)
{
    height = var;
}

////////////////////////////////////////////////////////////////////////////////
// write and read pixel functions
// follows naming conventions, get and set pixel as of v0.1b
////////////////////////////////////////////////////////////////////////////////

void PhTexture::setPixel(int x, int y, PhColor col)
{

    if (data!=NULL)
    {

        *(data+(((y*width)+x)*4)) = col.getRed();
        *(data+(((y*width)+x)*4)+1) = col.getGreen();
        *(data+(((y*width)+x)*4)+2) = col.getBlue();
        *(data+(((y*width)+x)*4)+3) = col.getAlpha();

    }

}

PhColor PhTexture::getPixel(int x, int y)
{

    if (data!=NULL)
    {

        PhColor col;
        col.setRed(*(data+(((y*width)+x)*4)));
        col.setGreen(*(data+(((y*width)+x)*4)+1));
        col.setBlue(*(data+(((y*width)+x)*4)+2));
        col.setAlpha(*(data+(((y*width)+x)*4)+3));
        return col;

    }
    else
    {

        return PhColor(255,255,255,255);

    }

}

////////////////////////////////////////////////////////////////////////////////
// lock and unlock texture
////////////////////////////////////////////////////////////////////////////////

void PhTexture::unlockTexture()
{

    if (data!=NULL)
    {

        glBindTexture(GL_TEXTURE_2D, texture);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);

        free(data);

        data = NULL;

    }
}

bool PhTexture::lockTexture()
{

    data = (unsigned char*)malloc(width*height*4);

    if (data!=NULL)
    {

        glGetTexImage( GL_TEXTURE_2D , 0 , GL_RGBA , GL_UNSIGNED_BYTE, data );
        return true;

    }
    else
    {
        return false;
    }

}

////////////////////////////////////////////////////////////////////////////////
// Bind texture
////////////////////////////////////////////////////////////////////////////////

bool PhTexture::bindTexture()
{
    if (glIsTexture(texture)) //make sure this is a texture
    {
        glBindTexture(GL_TEXTURE_2D, texture); //set the texture
        return true;
    }
    return false;
}
<commit_msg>CRITICAL: Fixed a major bug that causes a segfault on program exit. When textures are constructed using the default constructor the "data" member was not initialized to NULL but instead a random value, thus causing the class to try and free() the data member, and causing a segfault.<commit_after>/*

Copyright (c) 2007, Jonathan Wayne Parrott.

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.

*/

#include "PhTexture.h"

using namespace phoenix;

////////////////////////////////////////////////////////////////////////////////
// Construct and Destruct
////////////////////////////////////////////////////////////////////////////////

PhTexture::PhTexture(PhTextureManager* t)
	: texture(0), txtmgr(t), width(0), height(0), data(NULL), name("")
{
    txtmgr->addTexture(this);
}

PhTexture::PhTexture(PhTextureManager* t, int a, int b)
	: txtmgr(t), width(a), height(b), name("")
{

    txtmgr = t;
    txtmgr->addTexture(this);

    //make some room for the texture's data
    data = (unsigned char*)malloc(a*b*4);

    //make all the pixels white and fully opaque
    for (int i = 0; i<(a*b*4); i++)
    {
        *(data+i) = 255;
    }

    //Generate 1 texture
    glGenTextures(1,&texture);

    //Load the texture
    glBindTexture(GL_TEXTURE_2D, texture);

    //write the texture
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, a, b, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);

    //set the parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    //clear the data (not needed until the texture is locked agian)
    free(data);
    data = NULL;

}

PhTexture::~PhTexture()
{
    if (glIsTexture(texture))
    {
        glDeleteTextures(1, &texture);
    }

    if (data!=NULL)
    {
        free(data);
    }

    txtmgr->removeTexture(this);

}

////////////////////////////////////////////////////////////////////////////////
// set and get the texture ID
////////////////////////////////////////////////////////////////////////////////

void PhTexture::setTexture(GLuint text)
{
    texture=text;
}

GLuint PhTexture::getTexture()
{
    return texture;
}

////////////////////////////////////////////////////////////////////////////////
// set and get the texture name
////////////////////////////////////////////////////////////////////////////////

void PhTexture::setName(std::string nm)
{
    name=nm;
}

std::string PhTexture::getName()
{
    return name;
}

////////////////////////////////////////////////////////////////////////////////
// get and set width and height
////////////////////////////////////////////////////////////////////////////////

int PhTexture::getWidth()
{
    return width;
}

int PhTexture::getHeight()
{
    return height;
}

void PhTexture::setWidth(int var)
{
    width = var;
}

void PhTexture::setHeight(int var)
{
    height = var;
}

////////////////////////////////////////////////////////////////////////////////
// write and read pixel functions
// follows naming conventions, get and set pixel as of v0.1b
////////////////////////////////////////////////////////////////////////////////

void PhTexture::setPixel(int x, int y, PhColor col)
{

    if (data!=NULL)
    {

        *(data+(((y*width)+x)*4)) = col.getRed();
        *(data+(((y*width)+x)*4)+1) = col.getGreen();
        *(data+(((y*width)+x)*4)+2) = col.getBlue();
        *(data+(((y*width)+x)*4)+3) = col.getAlpha();

    }

}

PhColor PhTexture::getPixel(int x, int y)
{

    if (data!=NULL)
    {

        PhColor col;
        col.setRed(*(data+(((y*width)+x)*4)));
        col.setGreen(*(data+(((y*width)+x)*4)+1));
        col.setBlue(*(data+(((y*width)+x)*4)+2));
        col.setAlpha(*(data+(((y*width)+x)*4)+3));
        return col;

    }
    else
    {

        return PhColor(255,255,255,255);

    }

}

////////////////////////////////////////////////////////////////////////////////
// lock and unlock texture
////////////////////////////////////////////////////////////////////////////////

void PhTexture::unlockTexture()
{

    if (data!=NULL)
    {

        glBindTexture(GL_TEXTURE_2D, texture);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);

        free(data);

        data = NULL;

    }
}

bool PhTexture::lockTexture()
{

    data = (unsigned char*)malloc(width*height*4);

    if (data!=NULL)
    {

        glGetTexImage( GL_TEXTURE_2D , 0 , GL_RGBA , GL_UNSIGNED_BYTE, data );
        return true;

    }
    else
    {
        return false;
    }

}

////////////////////////////////////////////////////////////////////////////////
// Bind texture
////////////////////////////////////////////////////////////////////////////////

bool PhTexture::bindTexture()
{
    if (glIsTexture(texture)) //make sure this is a texture
    {
        glBindTexture(GL_TEXTURE_2D, texture); //set the texture
        return true;
    }
    return false;
}
<|endoftext|>


<commit_before>//---------------------------------------------------------------------------
/// \file   es/storage.hpp
/// \brief  The entity/component data store
//
// Copyright 2013, nocte@hippie.nu            Released under the MIT License.
//---------------------------------------------------------------------------
#include "storage.hpp"

namespace es {

storage::storage()
    : next_id_(0)
{
    component_offsets_.push_back(0);
}

storage::component_id
storage::find_component (const std::string& name) const
{
    auto found (std::find(components_.begin(), components_.end(), name));
    if (found == components_.end())
        throw std::logic_error("component does not exist");

    return std::distance(components_.begin(), found);
}

entity
storage::new_entity()
{
    entities_[next_id_++];
    return next_id_ - 1;
}

storage::iterator
storage::make (uint32_t id)
{
    if (next_id_ <= id)
        next_id_ = id + 1;

    return entities_.insert(entities_.end(), std::make_pair(id, elem()));
}

std::pair<entity, entity>
storage::new_entities (size_t count)
{
    auto range_begin (next_id_);
    for (; count > 0; --count)
        entities_[next_id_++];

    return std::make_pair(range_begin, next_id_);
}

entity
storage::clone_entity (iterator f)
{
    elem& e (f->second);
    entities_[next_id_++] = e;

    // Quick check if we need to make deep copies
    if ((e.components & flat_mask_).any())
    {
        size_t off (0);
        for (int c_id (0); c_id < 64 && off < e.data.size(); ++c_id)
        {
            if (e.components[c_id])
            {
                if (!components_[c_id].is_flat())
                {
                    auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
                    ptr = ptr->clone();
                }
                off += components_[c_id].size();
            }
        }
    }
    return next_id_ - 1;
}

storage::iterator
storage::find (entity en)
{
    auto found (entities_.find(en));
    if (found == entities_.end())
        throw std::logic_error("unknown entity");

    return found;
}

storage::const_iterator
storage::find (entity en) const
{
    auto found (entities_.find(en));
    if (found == entities_.end())
        throw std::logic_error("unknown entity");

    return found;
}

size_t
storage::size() const
{
    return entities_.size();
}

bool
storage::delete_entity (entity en)
{
    auto found (find(en));
    if (found != entities_.end())
    {
        delete_entity(found);
        return true;
    }
    return false;
}

void
storage::delete_entity (iterator f)
{
    elem& e (f->second);

    // Quick check if we'll have to call any destructors.
    if ((e.components & flat_mask_).any())
    {
        size_t off (0);
        for (int search (0); search < 64 && off < e.data.size(); ++search)
        {
            if (e.components[search])
            {
                if (!components_[search].is_flat())
                {
                    auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
                    ptr->~placeholder();
                }
                off += components_[search].size();
            }
        }
    }

    entities_.erase(f);
}

void
storage::remove_component_from_entity (iterator en, component_id c)
{
    auto& e (en->second);
    if (!e.components[c])
        return;

    size_t off (offset(e, c));
    auto& comp_info (components_[c]);
    if (!comp_info.is_flat())
    {
        auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
        if (ptr)
            ptr->~placeholder();
    }
    auto o (e.data.begin() + off);
    e.data.erase(o, o + comp_info.size());
    e.components.reset(c);
}

size_t
storage::offset (const elem& e, component_id c) const
{
    assert(c < components_.size());
    assert((c & cache_mask) < component_offsets_.size());

    size_t result (component_offsets_[((1 << c) - 1) & e.components.to_ulong() & cache_mask]);

    for (component_id search (cache_size); search < c; ++search)
    {
        if (e.components[search])
            result += components_[search].size();
    }

    return result;
}

bool
storage::check_dirty (iterator en)
{
    return en->second.dirty.any();
}

bool
storage::check_dirty_and_clear (iterator en)
{
    bool result (check_dirty(en));
    en->second.dirty.reset();
    return result;
}

bool
storage::check_dirty_flag (iterator en, component_id c_id)
{
    return en->second.dirty[c_id];
}

bool
storage::check_dirty_flag_and_clear (iterator en, component_id c_id)
{
    bool result (check_dirty_flag(en, c_id));
    en->second.dirty.reset(c_id);
    return result;
}

} // namespace es
<commit_msg>Fixed a memory leak on destruction<commit_after>//---------------------------------------------------------------------------
/// \file   es/storage.hpp
/// \brief  The entity/component data store
//
// Copyright 2013, nocte@hippie.nu            Released under the MIT License.
//---------------------------------------------------------------------------
#include "storage.hpp"

namespace es {

storage::storage()
    : next_id_(0)
{
    component_offsets_.push_back(0);
}

storage::~storage()
{
    for (auto i (entities_.begin()); i != entities_.end(); ++i)
        call_destructors(i);
}

storage::component_id
storage::find_component (const std::string& name) const
{
    auto found (std::find(components_.begin(), components_.end(), name));
    if (found == components_.end())
        throw std::logic_error("component does not exist");

    return std::distance(components_.begin(), found);
}

entity
storage::new_entity()
{
    entities_[next_id_++];
    return next_id_ - 1;
}

storage::iterator
storage::make (uint32_t id)
{
    if (next_id_ <= id)
        next_id_ = id + 1;

    return entities_.insert(entities_.end(), std::make_pair(id, elem()));
}

std::pair<entity, entity>
storage::new_entities (size_t count)
{
    auto range_begin (next_id_);
    for (; count > 0; --count)
        entities_[next_id_++];

    return std::make_pair(range_begin, next_id_);
}

entity
storage::clone_entity (iterator f)
{
    elem& e (f->second);
    entities_[next_id_++] = e;

    // Quick check if we need to make deep copies
    if ((e.components & flat_mask_).any())
    {
        size_t off (0);
        for (int c_id (0); c_id < 64 && off < e.data.size(); ++c_id)
        {
            if (e.components[c_id])
            {
                if (!components_[c_id].is_flat())
                {
                    auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
                    ptr = ptr->clone();
                }
                off += components_[c_id].size();
            }
        }
    }
    return next_id_ - 1;
}

storage::iterator
storage::find (entity en)
{
    auto found (entities_.find(en));
    if (found == entities_.end())
        throw std::logic_error("unknown entity");

    return found;
}

storage::const_iterator
storage::find (entity en) const
{
    auto found (entities_.find(en));
    if (found == entities_.end())
        throw std::logic_error("unknown entity");

    return found;
}

size_t
storage::size() const
{
    return entities_.size();
}

bool
storage::delete_entity (entity en)
{
    auto found (find(en));
    if (found != entities_.end())
    {
        delete_entity(found);
        return true;
    }
    return false;
}

void
storage::delete_entity (iterator f)
{
    call_destructors(f);
    entities_.erase(f);
}

void
storage::remove_component_from_entity (iterator en, component_id c)
{
    auto& e (en->second);
    if (!e.components[c])
        return;

    size_t off (offset(e, c));
    auto& comp_info (components_[c]);
    if (!comp_info.is_flat())
    {
        auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
        if (ptr)
            ptr->~placeholder();
    }
    auto o (e.data.begin() + off);
    e.data.erase(o, o + comp_info.size());
    e.components.reset(c);
}

bool
storage::entity_has_component (iterator en, component_id c) const
{
    return c < components_.size() && en->second.components.test(c);
}

size_t
storage::offset (const elem& e, component_id c) const
{
    assert(c < components_.size());
    assert((c & cache_mask) < component_offsets_.size());

    size_t result (component_offsets_[((1 << c) - 1) & e.components.to_ulong() & cache_mask]);

    for (component_id search (cache_size); search < c; ++search)
    {
        if (e.components[search])
            result += components_[search].size();
    }

    return result;
}

bool
storage::check_dirty (iterator en)
{
    return en->second.dirty.any();
}

bool
storage::check_dirty_and_clear (iterator en)
{
    bool result (check_dirty(en));
    en->second.dirty.reset();
    return result;
}

bool
storage::check_dirty_flag (iterator en, component_id c_id)
{
    return en->second.dirty[c_id];
}

bool
storage::check_dirty_flag_and_clear (iterator en, component_id c_id)
{
    bool result (check_dirty_flag(en, c_id));
    en->second.dirty.reset(c_id);
    return result;
}

void
storage::call_destructors(iterator i) const
{
    elem& e (i->second);

    // Quick check if we'll have to call any destructors.
    if ((e.components & flat_mask_).any())
    {
        size_t off (0);
        for (int search (0); search < 64 && off < e.data.size(); ++search)
        {
            if (e.components[search])
            {
                if (!components_[search].is_flat())
                {
                    auto ptr (reinterpret_cast<placeholder*>(&*e.data.begin() + off));
                    ptr->~placeholder();
                }
                off += components_[search].size();
            }
        }
    }
}

} // namespace es
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: lngmerge.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hjs $ $Date: 2004-06-25 12:39:26 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
// local includes
#include "export.hxx"

DECLARE_LIST( LngLineList, ByteString * );

#define LNG_OK              0x0000
#define LNG_FILE_NOTFOUND   0x0001
#define LNG_COULD_NOT_OPEN  0x0002
#define SDF_OK              0x0003
#define SDF_FILE_NOTFOUND   0x0004
#define SDF_COULD_NOT_OPEN  0x0005

//
// class LngParser
//

class LngParser
{
private:
    USHORT nError;
    LngLineList *pLines;
    ByteString sSource;
    BOOL bDBIsUTF8;
    BOOL bULF;
    std::vector<ByteString> aLanguages;

    void FillInFallbacks( ByteStringHashMap Text );
    bool isNextGroup(  ByteString &sGroup_out , ByteString &sLine_in);
    void ReadLine( const ByteString &sLine_in , ByteStringHashMap &rText_inout );
    void WriteSDF( SvFileStream &aSDFStream , ByteStringHashMap &rText_inout ,
                    const ByteString &rSDFFile, const ByteString &rPrj ,
                    const ByteString &rRoot , const ByteString &sActFileName , const ByteString &sID );
public:
    LngParser( const ByteString &rLngFile, BOOL bUTF8, BOOL bULFFormat );
    ~LngParser();

    BOOL CreateSDF( const ByteString &rSDFFile, const ByteString &rPrj, const ByteString &rRoot );
    BOOL Merge( const ByteString &rSDFFile, const ByteString &rDestinationFile );
};
<commit_msg>INTEGRATION: CWS isocodefix1 (1.3.2); FILE MERGED 2004/07/08 17:25:23 ihi 1.3.2.2: Quite -> Quiet 2004/07/06 14:16:25 ihi 1.3.2.1: #i8252# Quite mode added<commit_after>/*************************************************************************
 *
 *  $RCSfile: lngmerge.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-13 13:50:26 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
// local includes
#include "export.hxx"

DECLARE_LIST( LngLineList, ByteString * );

#define LNG_OK              0x0000
#define LNG_FILE_NOTFOUND   0x0001
#define LNG_COULD_NOT_OPEN  0x0002
#define SDF_OK              0x0003
#define SDF_FILE_NOTFOUND   0x0004
#define SDF_COULD_NOT_OPEN  0x0005

//
// class LngParser
//

class LngParser
{
private:
    USHORT nError;
    LngLineList *pLines;
    ByteString sSource;
    BOOL bDBIsUTF8;
    BOOL bULF;
    bool bQuiet;
    std::vector<ByteString> aLanguages;

    void FillInFallbacks( ByteStringHashMap Text );
    bool isNextGroup(  ByteString &sGroup_out , ByteString &sLine_in);
    void ReadLine( const ByteString &sLine_in , ByteStringHashMap &rText_inout );
    void WriteSDF( SvFileStream &aSDFStream , ByteStringHashMap &rText_inout ,
                    const ByteString &rSDFFile, const ByteString &rPrj ,
                    const ByteString &rRoot , const ByteString &sActFileName , const ByteString &sID );
public:
    LngParser( const ByteString &rLngFile, BOOL bUTF8, BOOL bULFFormat, bool bQuiet_in );
    ~LngParser();

    BOOL CreateSDF( const ByteString &rSDFFile, const ByteString &rPrj, const ByteString &rRoot );
    BOOL Merge( const ByteString &rSDFFile, const ByteString &rDestinationFile );
};
<|endoftext|>


<commit_before>// http://ideveloperworld.blogspot.com.au/2011/02/epub-reader.html

// #include "tidy.h"
// #include "tidybuffio.h"

#include <algorithm>
#include <fstream>
#include <iostream>
#include <cmath>
#include <numeric>

#include "gui.h" // includes book.h
#include "TextVisitor.h"

using namespace tinyxml2;

Book::~Book()
{
	manifest.clear();
	spine.clear();
	alltext.clear();
}

void Book::CloseBook()
{
	manifest.clear();
	spine.clear();
	alltext.clear();

	book = "";
	opf = "";
}

void Book::LoadBook(const std::string& epub)
{
	book = epub;
	BLUnZip zp(book);

	ParseContainer(zp);
	ParseOPF(zp);
	ParsePages(zp);
}

void Book::ParseContainer(BLUnZip& zipfile)
{
	std::string unclean( zipfile.ExtractToString("META-INF/container.xml") );

	XMLDocument doc;
    doc.Parse( unclean.c_str() );

    XMLElement* container = doc.FirstChildElement( "container" );
    XMLElement* rootfiles = container->FirstChildElement( "rootfiles" );
    XMLElement* rootfile = rootfiles->FirstChildElement( "rootfile" );

    opf = rootfile->Attribute("full-path");
}

void Book::ParseOPF(BLUnZip& zipfile)
{
	std::string unclean( zipfile.ExtractToString( opf ) );

	XMLDocument doc;
    doc.Parse( unclean.c_str() );

    XMLElement* package = doc.FirstChildElement("package");
    XMLElement* manifest_ = package->FirstChildElement("manifest");
    XMLElement* item = manifest_->FirstChildElement("item");

	for(XMLElement* rfe = item; rfe != nullptr; rfe = rfe->NextSiblingElement("item"))
	{
    	manifest.emplace(rfe->Attribute("id"), rfe->Attribute("href"));
	}

	XMLElement* spine_ = package->FirstChildElement("spine");
	XMLElement* itemref = spine_->FirstChildElement("itemref");

	for (XMLElement* rfe = itemref; rfe != nullptr; rfe = rfe->NextSiblingElement("itemref"))
	{
		spine.push_back(rfe->Attribute("idref"));
	}
}

void Book::ParsePages(BLUnZip& zipfile)
{
	std::vector<char> filter(std::numeric_limits<unsigned char>::max(), 1);
	for (unsigned char c : valid)
	{
    	filter[c] = 0;
	}

	// spine.size();
	for (unsigned int i = 0; i != 7; i++)
	{
		TextVisitor tv;

		std::string page ( zipfile.ExtractToString( manifest[spine[i]]) );

		XMLDocument doc;
		doc.Parse(page.c_str());
		XMLElement* body = doc.FirstChildElement("html")->FirstChildElement("body");
		body->Accept(&tv);

		for (auto& v : tv.GetText())
		{
			alltext.push_back(v);
		}

		// clean up text, remove any random / corrupt characters
		// https://github.com/dietmarkuehl/cputube/blob/master/cpu/test/replace.cpp
		for (auto& text : alltext)
		{/*
			text.erase(std::remove_if(text.begin(), text.end(),
									  [&](unsigned char c)
									  { return filter[c]; }
									 ), text.end());
									 */
			std::replace_if(text.begin(), text.end(), [&](unsigned char c) { return filter[c]; }, '\'');
		}
	}
}

std::string Book::GetBook()
{
	return book;
}

void Book::Reader(Gui& gui)
{
	int ypos = 20;

	// 57 character limit using fixed width font, start at y = 20, 12 pixels spacing per line..., 18 lines per page top screen, max looping is 236
	// bottom screen is same, except only 46 characters per line.
	for (int i = (gui.getBookPage() * 18); i < ((gui.getBookPage() * 18) + 18); i++)
	{
		sftd_draw_text(gui.getTextFont(), 0, ypos, RGBA8(0, 0, 0, 255), 12, alltext[i].c_str());
		ypos += 12;
	}
}	<commit_msg>fixed not parsing whole book<commit_after>// http://ideveloperworld.blogspot.com.au/2011/02/epub-reader.html

// #include "tidy.h"
// #include "tidybuffio.h"

#include <algorithm>
#include <fstream>
#include <iostream>
#include <cmath>
#include <numeric>

#include "gui.h" // includes book.h
#include "TextVisitor.h"

using namespace tinyxml2;

Book::~Book()
{
	manifest.clear();
	spine.clear();
	alltext.clear();
}

void Book::CloseBook()
{
	manifest.clear();
	spine.clear();
	alltext.clear();

	book = "";
	opf = "";
}

void Book::LoadBook(const std::string& epub)
{
	book = epub;
	BLUnZip zp(book);

	ParseContainer(zp);
	ParseOPF(zp);
	ParsePages(zp);
}

void Book::ParseContainer(BLUnZip& zipfile)
{
	std::string unclean( zipfile.ExtractToString("META-INF/container.xml") );

	XMLDocument doc;
    doc.Parse( unclean.c_str() );

    XMLElement* container = doc.FirstChildElement( "container" );
    XMLElement* rootfiles = container->FirstChildElement( "rootfiles" );
    XMLElement* rootfile = rootfiles->FirstChildElement( "rootfile" );

    opf = rootfile->Attribute("full-path");
}

void Book::ParseOPF(BLUnZip& zipfile)
{
	std::string unclean( zipfile.ExtractToString( opf ) );

	XMLDocument doc;
    doc.Parse( unclean.c_str() );

    XMLElement* package = doc.FirstChildElement("package");
    XMLElement* manifest_ = package->FirstChildElement("manifest");
    XMLElement* item = manifest_->FirstChildElement("item");

	for(XMLElement* rfe = item; rfe != nullptr; rfe = rfe->NextSiblingElement("item"))
	{
    	manifest.emplace(rfe->Attribute("id"), rfe->Attribute("href"));
	}

	XMLElement* spine_ = package->FirstChildElement("spine");
	XMLElement* itemref = spine_->FirstChildElement("itemref");

	for (XMLElement* rfe = itemref; rfe != nullptr; rfe = rfe->NextSiblingElement("itemref"))
	{
		spine.push_back(rfe->Attribute("idref"));
	}
}

void Book::ParsePages(BLUnZip& zipfile)
{
	std::vector<char> filter(std::numeric_limits<unsigned char>::max(), 1);
	for (unsigned char c : valid)
	{
    	filter[c] = 0;
	}

	// spine.size(); or 7
	for (unsigned int i = 0; i != spine.size(); i++)
	{
		TextVisitor tv;

		std::string page ( zipfile.ExtractToString( manifest[spine[i]]) );

		XMLDocument doc;
		doc.Parse(page.c_str());
		XMLElement* body = doc.FirstChildElement("html")->FirstChildElement("body");
		body->Accept(&tv);

		for (auto& v : tv.GetText())
		{
			alltext.push_back(v);
		}

		// clean up text, remove any random / corrupt characters
		// https://github.com/dietmarkuehl/cputube/blob/master/cpu/test/replace.cpp
		for (auto& text : alltext)
		{/*
			text.erase(std::remove_if(text.begin(), text.end(),
									  [&](unsigned char c)
									  { return filter[c]; }
									 ), text.end());
									 */
			std::replace_if(text.begin(), text.end(), [&](unsigned char c) { return filter[c]; }, '\'');
		}
	}
}

std::string Book::GetBook()
{
	return book;
}

void Book::Reader(Gui& gui)
{
	int ypos = 20;

	// 57 character limit using fixed width font, start at y = 20, 12 pixels spacing per line..., 18 lines per page top screen, max looping is 236
	// bottom screen is same, except only 46 characters per line.
	for (int i = (gui.getBookPage() * 18); i < ((gui.getBookPage() * 18) + 18); i++)
	{
		sftd_draw_text(gui.getTextFont(), 0, ypos, RGBA8(0, 0, 0, 255), 12, alltext[i].c_str());
		ypos += 12;
	}
}	<|endoftext|>


<commit_before>#ifndef EBITEN_GRAPHICS_DETAIL_OPENGL_GRAPHICS_CONTEXT_HPP
#define EBITEN_GRAPHICS_DETAIL_OPENGL_GRAPHICS_CONTEXT_HPP

#include "ebiten/graphics/detail/opengl/device.hpp"
#include "ebiten/graphics/color_matrix.hpp"
#include "ebiten/graphics/drawing_region.hpp"
#include "ebiten/graphics/geometry_matrix.hpp"
#include "ebiten/graphics/texture.hpp"
#include "ebiten/util/noncopyable.hpp"
#include <OpenGL/gl.h>
#include <array>
#include <algorithm>
#include <cassert>
#include <iostream>
#include <type_traits>

namespace ebiten {
namespace graphics {
namespace detail {

class graphics_context : private ebiten::util::noncopyable {
  friend class device;
private:
  GLuint shader_program;
private:
  graphics_context()
    : shader_program(0) {
  }
public:
  template<class Drawable>
  void
  draw(Drawable const& drawable) {
    drawable.draw(*this);
  }
  template<class DrawingRegions>
  void
  draw_textures(graphics::texture const& texture,
                DrawingRegions const& drawing_regions,
                graphics::geometry_matrix const& geo_mat,
                graphics::color_matrix const& color_mat) {
    if (!this->shader_program) {
      this->shader_program = compile_shader_program();
      assert(this->shader_program);
    }
    if (!color_mat.is_identity()) {
      ::glUseProgram(this->shader_program);
      ::glUniform1i(glGetUniformLocation(this->shader_program, "texture"), 0);
      float const gl_color_mat[] = {
        static_cast<float>(color_mat.element<0, 0>()),
        static_cast<float>(color_mat.element<0, 1>()),
        static_cast<float>(color_mat.element<0, 2>()),
        static_cast<float>(color_mat.element<0, 3>()),
        static_cast<float>(color_mat.element<1, 0>()),
        static_cast<float>(color_mat.element<1, 1>()),
        static_cast<float>(color_mat.element<1, 2>()),
        static_cast<float>(color_mat.element<1, 3>()),
        static_cast<float>(color_mat.element<2, 0>()),
        static_cast<float>(color_mat.element<2, 1>()),
        static_cast<float>(color_mat.element<2, 2>()),
        static_cast<float>(color_mat.element<2, 3>()),
        static_cast<float>(color_mat.element<3, 0>()),
        static_cast<float>(color_mat.element<3, 1>()),
        static_cast<float>(color_mat.element<3, 2>()),
        static_cast<float>(color_mat.element<3, 3>()),
      };
      ::glUniformMatrix4fv(glGetUniformLocation(this->shader_program, "color_matrix"),
                           1, GL_FALSE, gl_color_mat);
      float const gl_color_mat_translation[] = {
        static_cast<float>(color_mat.element<0, 4>()),
        static_cast<float>(color_mat.element<1, 4>()),
        static_cast<float>(color_mat.element<2, 4>()),
        static_cast<float>(color_mat.element<3, 4>()),
      };
      ::glUniform4fv(glGetUniformLocation(this->shader_program, "color_matrix_translation"),
                     4, gl_color_mat_translation);
    }
    float const gl_geo_mat[] = {geo_mat.a(),  geo_mat.c(),  0, 0,
                                geo_mat.b(),  geo_mat.d(),  0, 0,
                                0,            0,            1, 0,
                                geo_mat.tx(), geo_mat.ty(), 0, 1};
    ::glMatrixMode(GL_MODELVIEW);
    ::glLoadMatrixf(gl_geo_mat);
    ::glBindTexture(GL_TEXTURE_2D, texture.id());
    ::glBegin(GL_QUADS);
    float const texture_width  = texture.texture_width();
    float const texture_height = texture.texture_height();
    for (auto const& dr : drawing_regions) {
      float const tu1 = dr.src_x()                 / texture_width;
      float const tu2 = (dr.src_x() + dr.width())  / texture_width;
      float const tv1 = dr.src_y()                 / texture_height;
      float const tv2 = (dr.src_y() + dr.height()) / texture_height;
      float const x1 = dr.dst_x();
      float const x2 = dr.dst_x() + dr.width();
      float const y1 = dr.dst_y();
      float const y2 = dr.dst_y() + dr.height();
      float const vertex[4][3] = {{x1, y1},
                                  {x2, y1},
                                  {x2, y2},
                                  {x1, y2}};
      // TODO: use glDrawArrays?
      ::glTexCoord2f(tu1, tv1);
      ::glVertex2fv(vertex[0]);
      ::glTexCoord2f(tu2, tv1);
      ::glVertex2fv(vertex[1]);
      ::glTexCoord2f(tu2, tv2);
      ::glVertex2fv(vertex[2]);
      ::glTexCoord2f(tu1, tv2);
      ::glVertex2fv(vertex[3]);
    };
    ::glEnd();
    ::glBindTexture(GL_TEXTURE_2D, 0);
    ::glUseProgram(0);
  }
private:
  GLuint
  compile_shader_program() {
    static std::string const sharder_source("uniform sampler2D texture;\n"
                                            "uniform mat4 color_matrix;\n"
                                            "uniform vec4 color_matrix_translation;\n"
                                            "\n"
                                            "void main(void) {\n"
                                            "  vec4 color = texture2DProj(texture, gl_TexCoord[0]);\n"
                                            "  gl_FragColor = color_matrix * color + color_matrix_translation;\n"
                                            "}\n");
    // TODO: ARB?
    GLuint fragment_shader;
    fragment_shader = ::glCreateShader(GL_FRAGMENT_SHADER);
    assert(fragment_shader);
    char const* shader_source_p = sharder_source.c_str();
    ::glShaderSource(fragment_shader, 1, &shader_source_p, 0);
    ::glCompileShader(fragment_shader);
    // check status
    GLint compiled;
    ::glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &compiled);
    this->show_shader_log(fragment_shader);
    if (compiled == GL_FALSE) {
      throw std::runtime_error("shader compile error");
    }

    GLuint program;
    program = ::glCreateProgram();
    assert(program);
    ::glAttachShader(program, fragment_shader);
    ::glDeleteShader(fragment_shader);
    ::glLinkProgram(program);
    // check status
    GLint linked;
    ::glGetProgramiv(program, GL_LINK_STATUS, &linked);
    if (linked == GL_FALSE) {
      throw std::runtime_error("program error");
    }

    return program;
  }
  // TODO: Debug Mode
  void
  show_shader_log(GLuint shader) {
    int log_size = 0;
    ::glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_size);
    if (log_size) {
      int length = 0;
      // TODO: 動的確保のほうがよい?
      std::array<char, 1024> buffer;
      // TODO: バッファ確認
      ::glGetShaderInfoLog(shader, buffer.size(), &length, buffer.data());
      std::cerr << buffer.data() << std::endl;
    }
  }
  // TODO: show_program_log
};

}
}
}

#endif
<commit_msg>Added TODO<commit_after>#ifndef EBITEN_GRAPHICS_DETAIL_OPENGL_GRAPHICS_CONTEXT_HPP
#define EBITEN_GRAPHICS_DETAIL_OPENGL_GRAPHICS_CONTEXT_HPP

#include "ebiten/graphics/detail/opengl/device.hpp"
#include "ebiten/graphics/color_matrix.hpp"
#include "ebiten/graphics/drawing_region.hpp"
#include "ebiten/graphics/geometry_matrix.hpp"
#include "ebiten/graphics/texture.hpp"
#include "ebiten/util/noncopyable.hpp"
#include <OpenGL/gl.h>
#include <array>
#include <algorithm>
#include <cassert>
#include <iostream>
#include <type_traits>

namespace ebiten {
namespace graphics {
namespace detail {

class graphics_context : private ebiten::util::noncopyable {
  friend class device;
private:
  GLuint shader_program;
private:
  graphics_context()
    : shader_program(0) {
  }
public:
  template<class Drawable>
  void
  draw(Drawable const& drawable) {
    drawable.draw(*this);
  }
  template<class DrawingRegions>
  void
  draw_textures(graphics::texture const& texture,
                DrawingRegions const& drawing_regions,
                graphics::geometry_matrix const& geo_mat,
                graphics::color_matrix const& color_mat) {
    if (!this->shader_program) {
      this->shader_program = compile_shader_program();
      assert(this->shader_program);
    }
    if (!color_mat.is_identity()) {
      ::glUseProgram(this->shader_program);
      ::glUniform1i(glGetUniformLocation(this->shader_program, "texture"), 0);
      float const gl_color_mat[] = {
        static_cast<float>(color_mat.element<0, 0>()),
        static_cast<float>(color_mat.element<0, 1>()),
        static_cast<float>(color_mat.element<0, 2>()),
        static_cast<float>(color_mat.element<0, 3>()),
        static_cast<float>(color_mat.element<1, 0>()),
        static_cast<float>(color_mat.element<1, 1>()),
        static_cast<float>(color_mat.element<1, 2>()),
        static_cast<float>(color_mat.element<1, 3>()),
        static_cast<float>(color_mat.element<2, 0>()),
        static_cast<float>(color_mat.element<2, 1>()),
        static_cast<float>(color_mat.element<2, 2>()),
        static_cast<float>(color_mat.element<2, 3>()),
        static_cast<float>(color_mat.element<3, 0>()),
        static_cast<float>(color_mat.element<3, 1>()),
        static_cast<float>(color_mat.element<3, 2>()),
        static_cast<float>(color_mat.element<3, 3>()),
      };
      ::glUniformMatrix4fv(glGetUniformLocation(this->shader_program, "color_matrix"),
                           1, GL_FALSE, gl_color_mat);
      float const gl_color_mat_translation[] = {
        static_cast<float>(color_mat.element<0, 4>()),
        static_cast<float>(color_mat.element<1, 4>()),
        static_cast<float>(color_mat.element<2, 4>()),
        static_cast<float>(color_mat.element<3, 4>()),
      };
      ::glUniform4fv(glGetUniformLocation(this->shader_program, "color_matrix_translation"),
                     4, gl_color_mat_translation);
    }
    float const gl_geo_mat[] = {geo_mat.a(),  geo_mat.c(),  0, 0,
                                geo_mat.b(),  geo_mat.d(),  0, 0,
                                0,            0,            1, 0,
                                geo_mat.tx(), geo_mat.ty(), 0, 1};
    ::glMatrixMode(GL_MODELVIEW);
    ::glLoadMatrixf(gl_geo_mat);
    // TODO: cache?
    ::glBindTexture(GL_TEXTURE_2D, texture.id());
    ::glBegin(GL_QUADS);
    // TODO: replace float to short?
    // http://objective-audio.jp/2009/07/ngmoco-opengl.html
    float const texture_width  = texture.texture_width();
    float const texture_height = texture.texture_height();
    for (auto const& dr : drawing_regions) {
      float const tu1 = dr.src_x()                 / texture_width;
      float const tu2 = (dr.src_x() + dr.width())  / texture_width;
      float const tv1 = dr.src_y()                 / texture_height;
      float const tv2 = (dr.src_y() + dr.height()) / texture_height;
      float const x1 = dr.dst_x();
      float const x2 = dr.dst_x() + dr.width();
      float const y1 = dr.dst_y();
      float const y2 = dr.dst_y() + dr.height();
      float const vertex[4][3] = {{x1, y1},
                                  {x2, y1},
                                  {x2, y2},
                                  {x1, y2}};
      // TODO: use glDrawArrays?
      ::glTexCoord2f(tu1, tv1);
      ::glVertex2fv(vertex[0]);
      ::glTexCoord2f(tu2, tv1);
      ::glVertex2fv(vertex[1]);
      ::glTexCoord2f(tu2, tv2);
      ::glVertex2fv(vertex[2]);
      ::glTexCoord2f(tu1, tv2);
      ::glVertex2fv(vertex[3]);
    };
    ::glEnd();
    ::glBindTexture(GL_TEXTURE_2D, 0);
    ::glUseProgram(0);
  }
private:
  GLuint
  compile_shader_program() {
    static std::string const sharder_source("uniform sampler2D texture;\n"
                                            "uniform mat4 color_matrix;\n"
                                            "uniform vec4 color_matrix_translation;\n"
                                            "\n"
                                            "void main(void) {\n"
                                            "  vec4 color = texture2DProj(texture, gl_TexCoord[0]);\n"
                                            "  gl_FragColor = color_matrix * color + color_matrix_translation;\n"
                                            "}\n");
    // TODO: ARB?
    GLuint fragment_shader;
    fragment_shader = ::glCreateShader(GL_FRAGMENT_SHADER);
    assert(fragment_shader);
    char const* shader_source_p = sharder_source.c_str();
    ::glShaderSource(fragment_shader, 1, &shader_source_p, 0);
    ::glCompileShader(fragment_shader);
    // check status
    GLint compiled;
    ::glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &compiled);
    this->show_shader_log(fragment_shader);
    if (compiled == GL_FALSE) {
      throw std::runtime_error("shader compile error");
    }

    GLuint program;
    program = ::glCreateProgram();
    assert(program);
    ::glAttachShader(program, fragment_shader);
    ::glDeleteShader(fragment_shader);
    ::glLinkProgram(program);
    // check status
    GLint linked;
    ::glGetProgramiv(program, GL_LINK_STATUS, &linked);
    if (linked == GL_FALSE) {
      throw std::runtime_error("program error");
    }

    return program;
  }
  // TODO: Debug Mode
  void
  show_shader_log(GLuint shader) {
    int log_size = 0;
    ::glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_size);
    if (log_size) {
      int length = 0;
      // TODO: 動的確保のほうがよい?
      std::array<char, 1024> buffer;
      // TODO: バッファ確認
      ::glGetShaderInfoLog(shader, buffer.size(), &length, buffer.data());
      std::cerr << buffer.data() << std::endl;
    }
  }
  // TODO: show_program_log
};

}
}
}

#endif
<|endoftext|>


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

#include "config.h"
#include "FontUtilsChromiumWin.h"

#include <limits>

#include "PlatformString.h"
#include "StringHash.h"
#include "UniscribeHelper.h"
#include <unicode/locid.h>
#include <unicode/uchar.h>
#include <wtf/HashMap.h>

namespace WebCore {

namespace {

// A simple mapping from UScriptCode to family name.  This is a sparse array,
// which works well since the range of UScriptCode values is small.
typedef const UChar* ScriptToFontMap[USCRIPT_CODE_LIMIT];

void InitializeScriptFontMap(ScriptToFontMap& scriptFontMap)
{
    struct FontMap {
        UScriptCode script;
        const UChar* family;
    };

    const static FontMap fontMap[] = {
        {USCRIPT_LATIN, L"times new roman"},
        {USCRIPT_GREEK, L"times new roman"},
        {USCRIPT_CYRILLIC, L"times new roman"},
        {USCRIPT_SIMPLIFIED_HAN, L"simsun"},
        //{USCRIPT_TRADITIONAL_HAN, L"pmingliu"},
        {USCRIPT_HIRAGANA, L"ms pgothic"},
        {USCRIPT_KATAKANA, L"ms pgothic"},
        {USCRIPT_KATAKANA_OR_HIRAGANA, L"ms pgothic"},
        {USCRIPT_HANGUL, L"gulim"},
        {USCRIPT_THAI, L"tahoma"},
        {USCRIPT_HEBREW, L"david"},
        {USCRIPT_ARABIC, L"tahoma"},
        {USCRIPT_DEVANAGARI, L"mangal"},
        {USCRIPT_BENGALI, L"vrinda"},
        {USCRIPT_GURMUKHI, L"raavi"},
        {USCRIPT_GUJARATI, L"shruti"},
        {USCRIPT_ORIYA, L"kalinga"},
        {USCRIPT_TAMIL, L"latha"},
        {USCRIPT_TELUGU, L"gautami"},
        {USCRIPT_KANNADA, L"tunga"},
        {USCRIPT_MALAYALAM, L"kartika"},
        {USCRIPT_LAO, L"dokchampa"},
        {USCRIPT_TIBETAN, L"microsoft himalaya"},
        {USCRIPT_GEORGIAN, L"sylfaen"},
        {USCRIPT_ARMENIAN, L"sylfaen"},
        {USCRIPT_ETHIOPIC, L"nyala"},
        {USCRIPT_CANADIAN_ABORIGINAL, L"euphemia"},
        {USCRIPT_CHEROKEE, L"plantagenet cherokee"},
        {USCRIPT_YI, L"microsoft yi balti"},
        {USCRIPT_SINHALA, L"iskoola pota"},
        {USCRIPT_SYRIAC, L"estrangelo edessa"},
        {USCRIPT_KHMER, L"daunpenh"},
        {USCRIPT_THAANA, L"mv boli"},
        {USCRIPT_MONGOLIAN, L"mongolian balti"},
        {USCRIPT_MYANMAR, L"padauk"},
        // For USCRIPT_COMMON, we map blocks to scripts when
        // that makes sense.
    };

    for (int i = 0; i < sizeof(fontMap) / sizeof(fontMap[0]); ++i)
        scriptFontMap[fontMap[i].script] = fontMap[i].family;

    // Initialize the locale-dependent mapping.
    // Since Chrome synchronizes the ICU default locale with its UI locale,
    // this ICU locale tells the current UI locale of Chrome.
    Locale locale = Locale::getDefault();
    const UChar* localeFamily = NULL;
    if (locale == Locale::getJapanese()) {
        localeFamily = scriptFontMap[USCRIPT_HIRAGANA];
    } else if (locale == Locale::getKorean()) {
        localeFamily = scriptFontMap[USCRIPT_HANGUL];
    } else {
        // Use Simplified Chinese font for all other locales including
        // Traditional Chinese because Simsun (SC font) has a wider
        // coverage (covering both SC and TC) than PMingLiu (TC font).
        // This also speeds up the TC version of Chrome when rendering SC
        // pages.
        localeFamily = scriptFontMap[USCRIPT_SIMPLIFIED_HAN];
    }
    if (localeFamily)
        scriptFontMap[USCRIPT_HAN] = localeFamily;
}

const int kUndefinedAscent = std::numeric_limits<int>::min();

// Given an HFONT, return the ascent. If GetTextMetrics fails,
// kUndefinedAscent is returned, instead.
int GetAscent(HFONT hfont)
{
    HDC dc = GetDC(NULL);
    HGDIOBJ oldFont = SelectObject(dc, hfont);
    TEXTMETRIC tm;
    BOOL got_metrics = GetTextMetrics(dc, &tm);
    SelectObject(dc, oldFont);
    ReleaseDC(NULL, dc);
    return got_metrics ? tm.tmAscent : kUndefinedAscent;
}

struct FontData {
    FontData() : hfont(NULL), ascent(kUndefinedAscent), scriptCache(NULL) {}
    HFONT hfont;
    int ascent;
    mutable SCRIPT_CACHE scriptCache;
};

// Again, using hash_map does not earn us much here.  page_cycler_test intl2
// gave us a 'better' result with map than with hash_map even though they're
// well-within 1-sigma of each other so that the difference is not significant.
// On the other hand, some pages in intl2 seem to take longer to load with map
// in the 1st pass. Need to experiment further.
typedef HashMap<String, FontData*> FontDataCache;

}  // namespace

// TODO(jungshik) : this is font fallback code version 0.1
//  - Cover all the scripts
//  - Get the default font for each script/generic family from the
//    preference instead of hardcoding in the source.
//    (at least, read values from the registry for IE font settings).
//  - Support generic families (from FontDescription)
//  - If the default font for a script is not available,
//    try some more fonts known to support it. Finally, we can
//    use EnumFontFamilies or similar APIs to come up with a list of
//    fonts supporting the script and cache the result.
//  - Consider using UnicodeSet (or UnicodeMap) converted from
//    GLYPHSET (BMP) or directly read from truetype cmap tables to
//    keep track of which character is supported by which font
//  - Update script_font_cache in response to WM_FONTCHANGE

const UChar* GetFontFamilyForScript(UScriptCode script,
                                    GenericFamilyType generic) {
    static ScriptToFontMap scriptFontMap;
    static bool initialized = false;
    if (!initialized) {
        InitializeScriptFontMap(scriptFontMap);
        initialized = true;
    }
    if (script == USCRIPT_INVALID_CODE)
        return NULL;
    ASSERT(script < USCRIPT_CODE_LIMIT);
    return scriptFontMap[script];
}

// TODO(jungshik)
//  - Handle 'Inherited', 'Common' and 'Unknown'
//    (see http://www.unicode.org/reports/tr24/#Usage_Model )
//    For 'Inherited' and 'Common', perhaps we need to
//    accept another parameter indicating the previous family
//    and just return it.
//  - All the characters (or characters up to the point a single
//    font can cover) need to be taken into account
const UChar* GetFallbackFamily(const UChar *characters,
                               int length,
                               GenericFamilyType generic,
                               UChar32 *charChecked,
                               UScriptCode *scriptChecked)
{
    ASSERT(characters && characters[0] && length > 0);
    UScriptCode script = USCRIPT_COMMON;

    // Sometimes characters common to script (e.g. space) is at
    // the beginning of a string so that we need to skip them
    // to get a font required to render the string.
    int i = 0;
    UChar32 ucs4 = 0;
    while (i < length && script == USCRIPT_COMMON ||
           script == USCRIPT_INVALID_CODE) {
        U16_NEXT(characters, i, length, ucs4);
        UErrorCode err = U_ZERO_ERROR;
        script = uscript_getScript(ucs4, &err);
        // silently ignore the error
    }

    // hack for full width ASCII. For the full-width ASCII, use the font
    // for Han (which is locale-dependent).
    if (0xFF00 < ucs4 && ucs4 < 0xFF5F)
        script = USCRIPT_HAN;

    // There are a lot of characters in USCRIPT_COMMON that can be covered
    // by fonts for scripts closely related to them. See
    // http://unicode.org/cldr/utility/list-unicodeset.jsp?a=[:Script=Common:]
    // TODO(jungshik): make this more efficient with a wider coverage
    if (script == USCRIPT_COMMON || script == USCRIPT_INHERITED) {
        UBlockCode block = ublock_getCode(ucs4);
        switch (block) {
        case UBLOCK_BASIC_LATIN:
            script = USCRIPT_LATIN;
            break;
        case UBLOCK_CJK_SYMBOLS_AND_PUNCTUATION:
            script = USCRIPT_HAN;
            break;
        case UBLOCK_HIRAGANA:
        case UBLOCK_KATAKANA:
            script = USCRIPT_HIRAGANA;
            break;
        case UBLOCK_ARABIC:
            script = USCRIPT_ARABIC;
            break;
        case UBLOCK_GREEK:
            script = USCRIPT_GREEK;
            break;
        case UBLOCK_DEVANAGARI:
            // For Danda and Double Danda (U+0964, U+0965), use a Devanagari
            // font for now although they're used by other scripts as well.
            // Without a context, we can't do any better.
            script = USCRIPT_DEVANAGARI;
            break;
        case UBLOCK_ARMENIAN:
            script = USCRIPT_ARMENIAN;
            break;
        case UBLOCK_GEORGIAN:
            script = USCRIPT_GEORGIAN;
            break;
        case UBLOCK_KANNADA:
            script = USCRIPT_KANNADA;
            break;
        }
    }

    // Another lame work-around to cover non-BMP characters.
    const UChar* family = GetFontFamilyForScript(script, generic);
    if (!family) {
        int plane = ucs4 >> 16;
        switch (plane) {
        case 1:
            family = L"code2001";
            break;
        case 2:
            family = L"simsun-extb";
            break;
        default:
            family = L"lucida sans unicode";
        }
    }

    if (charChecked)
        *charChecked = ucs4;
    if (scriptChecked)
        *scriptChecked = script;
    return family;
}

// Be aware that this is not thread-safe.
bool GetDerivedFontData(const UChar *family,
                        int style,
                        LOGFONT *logfont,
                        int *ascent,
                        HFONT *hfont,
                        SCRIPT_CACHE **scriptCache) {
    ASSERT(logfont && family && *family);

    // It does not matter that we leak font data when we exit.
    static FontDataCache fontDataCache;

    // TODO(jungshik) : This comes up pretty high in the profile so that
    // we need to measure whether using SHA256 (after coercing all the
    // fields to char*) is faster than String::format.
    String fontKey = String::format("%1d:%d:%ls", style, logfont->lfHeight, family);
    FontDataCache::iterator iter = fontDataCache.find(fontKey);
    FontData *derived;
    if (iter == fontDataCache.end()) {
        ASSERT(wcslen(family) < LF_FACESIZE);
        wcscpy_s(logfont->lfFaceName, LF_FACESIZE, family);
        // TODO(jungshik): CreateFontIndirect always comes up with
        // a font even if there's no font matching the name. Need to
        // check it against what we actually want (as is done in
        // FontCacheWin.cpp)
        derived = new FontData;
        derived->hfont = CreateFontIndirect(logfont);
        // GetAscent may return kUndefinedAscent, but we still want to
        // cache it so that we won't have to call CreateFontIndirect once
        // more for HFONT next time.
        derived->ascent = GetAscent(derived->hfont);
        fontDataCache.add(fontKey, derived);
    } else {
        derived = iter->second;
        // Last time, GetAscent failed so that only HFONT was
        // cached. Try once more assuming that TryPreloadFont
        // was called by a caller between calls.
        if (kUndefinedAscent == derived->ascent)
            derived->ascent = GetAscent(derived->hfont);
    }
    *hfont = derived->hfont;
    *ascent = derived->ascent;
    *scriptCache = &(derived->scriptCache);
    return *ascent != kUndefinedAscent;
}

int GetStyleFromLogfont(const LOGFONT* logfont) {
    // TODO(jungshik) : consider defining UNDEFINED or INVALID for style and
    //                  returning it when logfont is NULL
    if (!logfont) {
        ASSERT_NOT_REACHED();
        return FONT_STYLE_NORMAL;
    }
    return (logfont->lfItalic ? FONT_STYLE_ITALIC : FONT_STYLE_NORMAL) |
           (logfont->lfUnderline ? FONT_STYLE_UNDERLINED : FONT_STYLE_NORMAL) |
           (logfont->lfWeight >= 700 ? FONT_STYLE_BOLD : FONT_STYLE_NORMAL);
}

}  // namespace WebCore
<commit_msg>Fix purify complaint about FontData structs being leaked.  These are held in a cache that never evicts anything, so they are not real leaks.  We just used to free them before to probably make purify happy, and I didn't realize that when I made recent changes to the file.  Now we clean up the FontData structs again.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"
#include "FontUtilsChromiumWin.h"

#include <limits>

#include "PlatformString.h"
#include "StringHash.h"
#include "UniscribeHelper.h"
#include <unicode/locid.h>
#include <unicode/uchar.h>
#include <wtf/HashMap.h>

namespace WebCore {

namespace {

// A simple mapping from UScriptCode to family name.  This is a sparse array,
// which works well since the range of UScriptCode values is small.
typedef const UChar* ScriptToFontMap[USCRIPT_CODE_LIMIT];

void InitializeScriptFontMap(ScriptToFontMap& scriptFontMap)
{
    struct FontMap {
        UScriptCode script;
        const UChar* family;
    };

    const static FontMap fontMap[] = {
        {USCRIPT_LATIN, L"times new roman"},
        {USCRIPT_GREEK, L"times new roman"},
        {USCRIPT_CYRILLIC, L"times new roman"},
        {USCRIPT_SIMPLIFIED_HAN, L"simsun"},
        //{USCRIPT_TRADITIONAL_HAN, L"pmingliu"},
        {USCRIPT_HIRAGANA, L"ms pgothic"},
        {USCRIPT_KATAKANA, L"ms pgothic"},
        {USCRIPT_KATAKANA_OR_HIRAGANA, L"ms pgothic"},
        {USCRIPT_HANGUL, L"gulim"},
        {USCRIPT_THAI, L"tahoma"},
        {USCRIPT_HEBREW, L"david"},
        {USCRIPT_ARABIC, L"tahoma"},
        {USCRIPT_DEVANAGARI, L"mangal"},
        {USCRIPT_BENGALI, L"vrinda"},
        {USCRIPT_GURMUKHI, L"raavi"},
        {USCRIPT_GUJARATI, L"shruti"},
        {USCRIPT_ORIYA, L"kalinga"},
        {USCRIPT_TAMIL, L"latha"},
        {USCRIPT_TELUGU, L"gautami"},
        {USCRIPT_KANNADA, L"tunga"},
        {USCRIPT_MALAYALAM, L"kartika"},
        {USCRIPT_LAO, L"dokchampa"},
        {USCRIPT_TIBETAN, L"microsoft himalaya"},
        {USCRIPT_GEORGIAN, L"sylfaen"},
        {USCRIPT_ARMENIAN, L"sylfaen"},
        {USCRIPT_ETHIOPIC, L"nyala"},
        {USCRIPT_CANADIAN_ABORIGINAL, L"euphemia"},
        {USCRIPT_CHEROKEE, L"plantagenet cherokee"},
        {USCRIPT_YI, L"microsoft yi balti"},
        {USCRIPT_SINHALA, L"iskoola pota"},
        {USCRIPT_SYRIAC, L"estrangelo edessa"},
        {USCRIPT_KHMER, L"daunpenh"},
        {USCRIPT_THAANA, L"mv boli"},
        {USCRIPT_MONGOLIAN, L"mongolian balti"},
        {USCRIPT_MYANMAR, L"padauk"},
        // For USCRIPT_COMMON, we map blocks to scripts when
        // that makes sense.
    };

    for (int i = 0; i < sizeof(fontMap) / sizeof(fontMap[0]); ++i)
        scriptFontMap[fontMap[i].script] = fontMap[i].family;

    // Initialize the locale-dependent mapping.
    // Since Chrome synchronizes the ICU default locale with its UI locale,
    // this ICU locale tells the current UI locale of Chrome.
    Locale locale = Locale::getDefault();
    const UChar* localeFamily = NULL;
    if (locale == Locale::getJapanese()) {
        localeFamily = scriptFontMap[USCRIPT_HIRAGANA];
    } else if (locale == Locale::getKorean()) {
        localeFamily = scriptFontMap[USCRIPT_HANGUL];
    } else {
        // Use Simplified Chinese font for all other locales including
        // Traditional Chinese because Simsun (SC font) has a wider
        // coverage (covering both SC and TC) than PMingLiu (TC font).
        // This also speeds up the TC version of Chrome when rendering SC
        // pages.
        localeFamily = scriptFontMap[USCRIPT_SIMPLIFIED_HAN];
    }
    if (localeFamily)
        scriptFontMap[USCRIPT_HAN] = localeFamily;
}

const int kUndefinedAscent = std::numeric_limits<int>::min();

// Given an HFONT, return the ascent. If GetTextMetrics fails,
// kUndefinedAscent is returned, instead.
int GetAscent(HFONT hfont)
{
    HDC dc = GetDC(NULL);
    HGDIOBJ oldFont = SelectObject(dc, hfont);
    TEXTMETRIC tm;
    BOOL got_metrics = GetTextMetrics(dc, &tm);
    SelectObject(dc, oldFont);
    ReleaseDC(NULL, dc);
    return got_metrics ? tm.tmAscent : kUndefinedAscent;
}

struct FontData {
    FontData() : hfont(NULL), ascent(kUndefinedAscent), scriptCache(NULL) {}
    HFONT hfont;
    int ascent;
    mutable SCRIPT_CACHE scriptCache;
};

// Again, using hash_map does not earn us much here.  page_cycler_test intl2
// gave us a 'better' result with map than with hash_map even though they're
// well-within 1-sigma of each other so that the difference is not significant.
// On the other hand, some pages in intl2 seem to take longer to load with map
// in the 1st pass. Need to experiment further.
typedef HashMap<String, FontData> FontDataCache;

}  // namespace

// TODO(jungshik) : this is font fallback code version 0.1
//  - Cover all the scripts
//  - Get the default font for each script/generic family from the
//    preference instead of hardcoding in the source.
//    (at least, read values from the registry for IE font settings).
//  - Support generic families (from FontDescription)
//  - If the default font for a script is not available,
//    try some more fonts known to support it. Finally, we can
//    use EnumFontFamilies or similar APIs to come up with a list of
//    fonts supporting the script and cache the result.
//  - Consider using UnicodeSet (or UnicodeMap) converted from
//    GLYPHSET (BMP) or directly read from truetype cmap tables to
//    keep track of which character is supported by which font
//  - Update script_font_cache in response to WM_FONTCHANGE

const UChar* GetFontFamilyForScript(UScriptCode script,
                                    GenericFamilyType generic) {
    static ScriptToFontMap scriptFontMap;
    static bool initialized = false;
    if (!initialized) {
        InitializeScriptFontMap(scriptFontMap);
        initialized = true;
    }
    if (script == USCRIPT_INVALID_CODE)
        return NULL;
    ASSERT(script < USCRIPT_CODE_LIMIT);
    return scriptFontMap[script];
}

// TODO(jungshik)
//  - Handle 'Inherited', 'Common' and 'Unknown'
//    (see http://www.unicode.org/reports/tr24/#Usage_Model )
//    For 'Inherited' and 'Common', perhaps we need to
//    accept another parameter indicating the previous family
//    and just return it.
//  - All the characters (or characters up to the point a single
//    font can cover) need to be taken into account
const UChar* GetFallbackFamily(const UChar *characters,
                               int length,
                               GenericFamilyType generic,
                               UChar32 *charChecked,
                               UScriptCode *scriptChecked)
{
    ASSERT(characters && characters[0] && length > 0);
    UScriptCode script = USCRIPT_COMMON;

    // Sometimes characters common to script (e.g. space) is at
    // the beginning of a string so that we need to skip them
    // to get a font required to render the string.
    int i = 0;
    UChar32 ucs4 = 0;
    while (i < length && script == USCRIPT_COMMON ||
           script == USCRIPT_INVALID_CODE) {
        U16_NEXT(characters, i, length, ucs4);
        UErrorCode err = U_ZERO_ERROR;
        script = uscript_getScript(ucs4, &err);
        // silently ignore the error
    }

    // hack for full width ASCII. For the full-width ASCII, use the font
    // for Han (which is locale-dependent).
    if (0xFF00 < ucs4 && ucs4 < 0xFF5F)
        script = USCRIPT_HAN;

    // There are a lot of characters in USCRIPT_COMMON that can be covered
    // by fonts for scripts closely related to them. See
    // http://unicode.org/cldr/utility/list-unicodeset.jsp?a=[:Script=Common:]
    // TODO(jungshik): make this more efficient with a wider coverage
    if (script == USCRIPT_COMMON || script == USCRIPT_INHERITED) {
        UBlockCode block = ublock_getCode(ucs4);
        switch (block) {
        case UBLOCK_BASIC_LATIN:
            script = USCRIPT_LATIN;
            break;
        case UBLOCK_CJK_SYMBOLS_AND_PUNCTUATION:
            script = USCRIPT_HAN;
            break;
        case UBLOCK_HIRAGANA:
        case UBLOCK_KATAKANA:
            script = USCRIPT_HIRAGANA;
            break;
        case UBLOCK_ARABIC:
            script = USCRIPT_ARABIC;
            break;
        case UBLOCK_GREEK:
            script = USCRIPT_GREEK;
            break;
        case UBLOCK_DEVANAGARI:
            // For Danda and Double Danda (U+0964, U+0965), use a Devanagari
            // font for now although they're used by other scripts as well.
            // Without a context, we can't do any better.
            script = USCRIPT_DEVANAGARI;
            break;
        case UBLOCK_ARMENIAN:
            script = USCRIPT_ARMENIAN;
            break;
        case UBLOCK_GEORGIAN:
            script = USCRIPT_GEORGIAN;
            break;
        case UBLOCK_KANNADA:
            script = USCRIPT_KANNADA;
            break;
        }
    }

    // Another lame work-around to cover non-BMP characters.
    const UChar* family = GetFontFamilyForScript(script, generic);
    if (!family) {
        int plane = ucs4 >> 16;
        switch (plane) {
        case 1:
            family = L"code2001";
            break;
        case 2:
            family = L"simsun-extb";
            break;
        default:
            family = L"lucida sans unicode";
        }
    }

    if (charChecked)
        *charChecked = ucs4;
    if (scriptChecked)
        *scriptChecked = script;
    return family;
}

// Be aware that this is not thread-safe.
bool GetDerivedFontData(const UChar *family,
                        int style,
                        LOGFONT *logfont,
                        int *ascent,
                        HFONT *hfont,
                        SCRIPT_CACHE **scriptCache) {
    ASSERT(logfont && family && *family);

    // It does not matter that we leak font data when we exit.
    static FontDataCache fontDataCache;

    // TODO(jungshik) : This comes up pretty high in the profile so that
    // we need to measure whether using SHA256 (after coercing all the
    // fields to char*) is faster than String::format.
    String fontKey = String::format("%1d:%d:%ls", style, logfont->lfHeight, family);
    FontDataCache::iterator iter = fontDataCache.find(fontKey);
    FontData *derived;
    if (iter == fontDataCache.end()) {
        ASSERT(wcslen(family) < LF_FACESIZE);
        wcscpy_s(logfont->lfFaceName, LF_FACESIZE, family);
        // TODO(jungshik): CreateFontIndirect always comes up with
        // a font even if there's no font matching the name. Need to
        // check it against what we actually want (as is done in
        // FontCacheWin.cpp)
        pair<FontDataCache::iterator, bool> entry = fontDataCache.add(fontKey, FontData());
        derived = &entry.first->second;
        derived->hfont = CreateFontIndirect(logfont);
        // GetAscent may return kUndefinedAscent, but we still want to
        // cache it so that we won't have to call CreateFontIndirect once
        // more for HFONT next time.
        derived->ascent = GetAscent(derived->hfont);
    } else {
        derived = &iter->second;
        // Last time, GetAscent failed so that only HFONT was
        // cached. Try once more assuming that TryPreloadFont
        // was called by a caller between calls.
        if (kUndefinedAscent == derived->ascent)
            derived->ascent = GetAscent(derived->hfont);
    }
    *hfont = derived->hfont;
    *ascent = derived->ascent;
    *scriptCache = &(derived->scriptCache);
    return *ascent != kUndefinedAscent;
}

int GetStyleFromLogfont(const LOGFONT* logfont) {
    // TODO(jungshik) : consider defining UNDEFINED or INVALID for style and
    //                  returning it when logfont is NULL
    if (!logfont) {
        ASSERT_NOT_REACHED();
        return FONT_STYLE_NORMAL;
    }
    return (logfont->lfItalic ? FONT_STYLE_ITALIC : FONT_STYLE_NORMAL) |
           (logfont->lfUnderline ? FONT_STYLE_UNDERLINED : FONT_STYLE_NORMAL) |
           (logfont->lfWeight >= 700 ? FONT_STYLE_BOLD : FONT_STYLE_NORMAL);
}

}  // namespace WebCore
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
#include "webrtc/modules/audio_processing/aec3/render_delay_controller.h"

#include <algorithm>
#include <memory>
#include <string>
#include <vector>

#include "webrtc/base/atomicops.h"
#include "webrtc/base/constructormagic.h"
#include "webrtc/modules/audio_processing/aec3/aec3_common.h"
#include "webrtc/modules/audio_processing/aec3/echo_path_delay_estimator.h"
#include "webrtc/modules/audio_processing/aec3/render_delay_controller_metrics.h"

namespace webrtc {

namespace {

class RenderDelayControllerImpl final : public RenderDelayController {
 public:
  RenderDelayControllerImpl(int sample_rate_hz);
  ~RenderDelayControllerImpl() override;
  void Reset() override;
  void SetDelay(size_t render_delay) override;
  size_t GetDelay(const DownsampledRenderBuffer& render_buffer,
                  rtc::ArrayView<const float> capture) override;
  rtc::Optional<size_t> AlignmentHeadroomSamples() const override {
    return headroom_samples_;
  }

 private:
  static int instance_count_;
  std::unique_ptr<ApmDataDumper> data_dumper_;
  size_t delay_ = 0;
  EchoPathDelayEstimator delay_estimator_;
  size_t blocks_since_last_delay_estimate_ = 300000;
  int echo_path_delay_samples_ = 0;
  size_t align_call_counter_ = 0;
  rtc::Optional<size_t> headroom_samples_;
  RenderDelayControllerMetrics metrics_;
  RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(RenderDelayControllerImpl);
};

size_t ComputeNewBufferDelay(size_t current_delay,
                             size_t echo_path_delay_samples) {
  // The below division is not exact and the truncation is intended.
  const int echo_path_delay_blocks = echo_path_delay_samples / kBlockSize;
  constexpr int kDelayHeadroomBlocks = 1;

  // Compute the buffer delay increase required to achieve the desired latency.
  size_t new_delay = std::max(echo_path_delay_blocks - kDelayHeadroomBlocks, 0);

  // Add hysteresis.
  if (new_delay == current_delay + 1 || new_delay + 1 == current_delay) {
    new_delay = current_delay;
  }

  return new_delay;
}

int RenderDelayControllerImpl::instance_count_ = 0;

RenderDelayControllerImpl::RenderDelayControllerImpl(int sample_rate_hz)
    : data_dumper_(
          new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
      delay_estimator_(data_dumper_.get()) {
  RTC_DCHECK(ValidFullBandRate(sample_rate_hz));
}

RenderDelayControllerImpl::~RenderDelayControllerImpl() = default;

void RenderDelayControllerImpl::Reset() {
  delay_ = 0;
  blocks_since_last_delay_estimate_ = 300000;
  echo_path_delay_samples_ = 0;
  align_call_counter_ = 0;
  headroom_samples_ = rtc::Optional<size_t>();

  delay_estimator_.Reset();
}

void RenderDelayControllerImpl::SetDelay(size_t render_delay) {
  if (delay_ != render_delay) {
    // If a the delay set does not match the actual delay, reset the delay
    // controller.
    Reset();
    delay_ = render_delay;
  }
}

size_t RenderDelayControllerImpl::GetDelay(
    const DownsampledRenderBuffer& render_buffer,
    rtc::ArrayView<const float> capture) {
  RTC_DCHECK_EQ(kBlockSize, capture.size());

  ++align_call_counter_;
  rtc::Optional<size_t> echo_path_delay_samples =
      delay_estimator_.EstimateDelay(render_buffer, capture);
  if (echo_path_delay_samples) {
    echo_path_delay_samples_ = *echo_path_delay_samples;

    // Compute and set new render delay buffer delay.
    const size_t new_delay =
        ComputeNewBufferDelay(delay_, echo_path_delay_samples_);
    if (new_delay != delay_ && align_call_counter_ > kNumBlocksPerSecond) {
      delay_ = new_delay;
    }

    // Update render delay buffer headroom.
    blocks_since_last_delay_estimate_ = 0;
    const int headroom = echo_path_delay_samples_ - delay_ * kBlockSize;
    RTC_DCHECK_LE(0, headroom);
    headroom_samples_ = rtc::Optional<size_t>(headroom);
  } else if (++blocks_since_last_delay_estimate_ > 20 * kNumBlocksPerSecond) {
    headroom_samples_ = rtc::Optional<size_t>();
  }

  metrics_.Update(echo_path_delay_samples, delay_);

  data_dumper_->DumpRaw("aec3_render_delay_controller_delay", 1,
                        &echo_path_delay_samples_);
  data_dumper_->DumpRaw("aec3_render_delay_controller_buffer_delay", delay_);

  return delay_;
}

}  // namespace

RenderDelayController* RenderDelayController::Create(int sample_rate_hz) {
  return new RenderDelayControllerImpl(sample_rate_hz);
}

}  // namespace webrtc
<commit_msg>Corrected the computation of the headroom in the AEC3 buffer alignment<commit_after>/*
 *  Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
#include "webrtc/modules/audio_processing/aec3/render_delay_controller.h"

#include <algorithm>
#include <memory>
#include <string>
#include <vector>

#include "webrtc/base/atomicops.h"
#include "webrtc/base/constructormagic.h"
#include "webrtc/modules/audio_processing/aec3/aec3_common.h"
#include "webrtc/modules/audio_processing/aec3/echo_path_delay_estimator.h"
#include "webrtc/modules/audio_processing/aec3/render_delay_controller_metrics.h"

namespace webrtc {

namespace {

class RenderDelayControllerImpl final : public RenderDelayController {
 public:
  RenderDelayControllerImpl(int sample_rate_hz);
  ~RenderDelayControllerImpl() override;
  void Reset() override;
  void SetDelay(size_t render_delay) override;
  size_t GetDelay(const DownsampledRenderBuffer& render_buffer,
                  rtc::ArrayView<const float> capture) override;
  rtc::Optional<size_t> AlignmentHeadroomSamples() const override {
    return headroom_samples_;
  }

 private:
  static int instance_count_;
  std::unique_ptr<ApmDataDumper> data_dumper_;
  size_t delay_ = 0;
  EchoPathDelayEstimator delay_estimator_;
  size_t blocks_since_last_delay_estimate_ = 300000;
  int echo_path_delay_samples_ = 0;
  size_t align_call_counter_ = 0;
  rtc::Optional<size_t> headroom_samples_;
  RenderDelayControllerMetrics metrics_;
  RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(RenderDelayControllerImpl);
};

size_t ComputeNewBufferDelay(size_t current_delay,
                             size_t echo_path_delay_samples) {
  // The below division is not exact and the truncation is intended.
  const int echo_path_delay_blocks = echo_path_delay_samples / kBlockSize;
  constexpr int kDelayHeadroomBlocks = 1;

  // Compute the buffer delay increase required to achieve the desired latency.
  size_t new_delay = std::max(echo_path_delay_blocks - kDelayHeadroomBlocks, 0);

  // Add hysteresis.
  if (new_delay == current_delay + 1 || new_delay + 1 == current_delay) {
    new_delay = current_delay;
  }

  return new_delay;
}

int RenderDelayControllerImpl::instance_count_ = 0;

RenderDelayControllerImpl::RenderDelayControllerImpl(int sample_rate_hz)
    : data_dumper_(
          new ApmDataDumper(rtc::AtomicOps::Increment(&instance_count_))),
      delay_estimator_(data_dumper_.get()) {
  RTC_DCHECK(ValidFullBandRate(sample_rate_hz));
}

RenderDelayControllerImpl::~RenderDelayControllerImpl() = default;

void RenderDelayControllerImpl::Reset() {
  delay_ = 0;
  blocks_since_last_delay_estimate_ = 300000;
  echo_path_delay_samples_ = 0;
  align_call_counter_ = 0;
  headroom_samples_ = rtc::Optional<size_t>();

  delay_estimator_.Reset();
}

void RenderDelayControllerImpl::SetDelay(size_t render_delay) {
  if (delay_ != render_delay) {
    // If a the delay set does not match the actual delay, reset the delay
    // controller.
    Reset();
    delay_ = render_delay;
  }
}

size_t RenderDelayControllerImpl::GetDelay(
    const DownsampledRenderBuffer& render_buffer,
    rtc::ArrayView<const float> capture) {
  RTC_DCHECK_EQ(kBlockSize, capture.size());

  ++align_call_counter_;
  rtc::Optional<size_t> echo_path_delay_samples =
      delay_estimator_.EstimateDelay(render_buffer, capture);
  if (echo_path_delay_samples) {
    blocks_since_last_delay_estimate_ = 0;
    echo_path_delay_samples_ = *echo_path_delay_samples;

    // Compute and set new render delay buffer delay.
    const size_t new_delay =
        ComputeNewBufferDelay(delay_, echo_path_delay_samples_);
    if (align_call_counter_ > kNumBlocksPerSecond) {
      delay_ = new_delay;

      // Update render delay buffer headroom.
      const int headroom = echo_path_delay_samples_ - delay_ * kBlockSize;
      RTC_DCHECK_LE(0, headroom);
      headroom_samples_ = rtc::Optional<size_t>(headroom);
    }
  } else if (++blocks_since_last_delay_estimate_ > 20 * kNumBlocksPerSecond) {
    headroom_samples_ = rtc::Optional<size_t>();
  }

  metrics_.Update(echo_path_delay_samples, delay_);

  data_dumper_->DumpRaw("aec3_render_delay_controller_delay", 1,
                        &echo_path_delay_samples_);
  data_dumper_->DumpRaw("aec3_render_delay_controller_buffer_delay", delay_);

  return delay_;
}

}  // namespace

RenderDelayController* RenderDelayController::Create(int sample_rate_hz) {
  return new RenderDelayControllerImpl(sample_rate_hz);
}

}  // namespace webrtc
<|endoftext|>


<commit_before>#include <3ds.h>
#include <stdio.h>
#include <string>
#include <unistd.h>

using namespace std;

int main(void)
{
	string menu[3] = {"Server1", "Server2", "Server3"};
	int pointer = 0;

	// Initialize services
	gfxInitDefault();
	consoleInit(GFX_TOP, NULL);  //TODO: Change to Bottom

	u32 kDownOld = 0; //In these variables there will be information about keys detected in the previous frame

	printf("Menu\n\n");
	printf(("\x1b[31m" + menu[0] + "\x1b[0m\n").c_str());

	for (int i=1; i<3; i++)
		printf((menu[i] + "\n").c_str());

	while (aptMainLoop())
	{
	    printf("\x1b[30;1H%i", pointer);
		//Scan all the inputs. This should be done once for each frame
		hidScanInput();

		//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
		u32 kDown = hidKeysDown();

		if (kDown & KEY_START) break; // break in order to return to hbmenu

		//Do the keys printing only if keys have changed
		if (kDown & KEY_DUP || kDown & KEY_DDOWN){
			if (kDown & KEY_DUP){
				pointer -= 1;
				if (pointer == -1){
					pointer = 2;
				}
			}
			else if (kDown & KEY_DDOWN){
				pointer += 1;
				if(pointer == 3){
					pointer = 0;
				}
			}
			consoleClear();
			printf("Menu\n\n");

			for (int i=0; i<3; ++i){
				if (i == pointer)
					printf(("\x1b[31m" + menu[i] + "\x1b[0m\n").c_str());
				else{
					printf((menu[i] + "\n").c_str());
				}
			}

		}

		//Set keys old values for the next frame
		kDownOld = kDown;

		// Flush and swap framebuffers
		gfxFlushBuffers();
		gfxSwapBuffers();

		//Wait for VBlank
		gspWaitForVBlank();
	}
	// Exit services
	gfxExit();
	return 0;
}
<commit_msg>Modulable server list<commit_after>#include <3ds.h>
#include <stdio.h>
#include <string>
#include <unistd.h>

using namespace std;

// Get length of an array
template <typename T,unsigned S>
inline unsigned arraysize(const T (&v)[S]) { return S; }

int main(void)
{
	string menu[] = {"Server1", "Server2", "Server3", "Server4", "Server5", "Server6", "Server7", "Server8", "Server9", "Server10", "Server11", "Server12", "Server13", "Server14", "Server15", "Server16", "Server17", "Server18", "Server19", "Server20"};
	unsigned int pointer = 0;

	// Initialize services
	gfxInitDefault();
	consoleInit(GFX_TOP, NULL);  //TODO: Change to Bottom

	printf("Menu\n\n");
	printf(("\x1b[31m" + menu[0] + "\x1b[0m\n").c_str());

	for (unsigned int i=1; i< arraysize(menu); i++)
		printf((menu[i] + "\n").c_str());

	while (aptMainLoop())
	{
	    printf("\x1b[30;1H%i", pointer);
		//Scan all the inputs. This should be done once for each frame
		hidScanInput();

		//hidKeysDown returns information about which buttons have been just pressed (and they weren't in the previous frame)
		u32 kDown = hidKeysDown();

		if (kDown & KEY_START) break; // break in order to return to hbmenu

		//Do the keys printing only if keys have changed
		if (kDown & KEY_DUP || kDown & KEY_DDOWN){
			if (kDown & KEY_DUP){
				pointer -= 1;
				if (pointer == (unsigned) -1){
					pointer = arraysize(menu) - 1;
				}
			}
			else if (kDown & KEY_DDOWN){
				pointer += 1;
				if(pointer == arraysize(menu)){
					pointer = 0;
				}
			}
			consoleClear();
			printf("Menu\n\n");

			for (unsigned int i=0; i< arraysize(menu); ++i){
				if (i == pointer)
					printf(("\x1b[31m" + menu[i] + "\x1b[0m\n").c_str());
				else{
					printf((menu[i] + "\n").c_str());
				}
			}

		}

		// Flush and swap framebuffers
		gfxFlushBuffers();
		gfxSwapBuffers();

		//Wait for VBlank
		gspWaitForVBlank();
	}
	// Exit services
	gfxExit();
	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include "TrelScript.h"

///////////////////////////////////////////////////////////
// Main function                                         //
///////////////////////////////////////////////////////////
int main()
{
	TrelScript *ts	= new TrelScript("testfile.trole");
	ts->runScript();
	delete ts;

	system("pause");
	return 0;
}<commit_msg>changed to cin.get() because *nix<commit_after>#include <iostream>
#include <string>
#include "TrelScript.h"

///////////////////////////////////////////////////////////
// Main function                                         //
///////////////////////////////////////////////////////////
int main()
{
	TrelScript *ts	= new TrelScript("testfile.trole");
	ts->runScript();
	delete ts;

	std::cin.get();
	return 0;
}<|endoftext|>


<commit_before>#include <ctrcommon/common.hpp>

#include <sstream>
#include <iomanip>
#include <stdio.h>

typedef enum {
    INSTALL,
    DELETE
} Mode;

int main(int argc, char **argv) {
    if(!platform_init()) {
        return 0;
    }

    std::vector<std::string> extensions;
    extensions.push_back("cia");

    MediaType destination = SD;
    Mode mode = INSTALL;
    bool netInstall = false;
    u64 freeSpace = fs_get_free_space(destination);
    auto onLoop = [&]() {
        bool breakLoop = false;
        if(input_is_pressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fs_get_free_space(destination);
            if(mode == DELETE) {
                breakLoop = true;
            }
        }

        if(input_is_pressed(BUTTON_R)) {
            if(mode == INSTALL) {
                mode = DELETE;
            } else {
                mode = INSTALL;
            }

            breakLoop = true;
        }

        if(input_is_pressed(BUTTON_Y)) {
            netInstall = true;
            breakLoop = true;
        }

        std::stringstream stream;
        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        stream << "Y - Receive an app over the network" << "\n";

        std::string str = stream.str();
        screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);

        return breakLoop;
    };

    auto onProgress = [&](int progress) {
        ui_display_progress("Installing", "Press B to cancel.", true, progress);
        input_poll();
        return !input_is_pressed(BUTTON_B);
    };

    while(platform_is_running()) {
        std::string targetInstall;
        App targetDelete;
        bool obtained = false;
        if(mode == INSTALL) {
            obtained = ui_select_file(&targetInstall, "sdmc:", extensions, onLoop);
        } else if(mode == DELETE) {
            obtained = ui_select_app(&targetDelete, destination, onLoop);
        }

        if(netInstall) {
            netInstall = false;

            // Clear bottom screen on both buffers.
            screen_begin_draw(BOTTOM_SCREEN);
            screen_clear(0, 0, 0);
            screen_end_draw();
            screen_swap_buffers();

            screen_begin_draw(BOTTOM_SCREEN);
            screen_clear(0, 0, 0);
            screen_end_draw();
            screen_swap_buffers();

            RemoteFile file = ui_accept_remote_file();
            if(file.fd == NULL) {
                continue;
            }

            std::stringstream confirmStream;
            confirmStream << "Install the received application?" << "\n";
            confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
            if(ui_prompt(confirmStream.str(), true)) {
                int ret = app_install(destination, file.fd, file.fileSize, onProgress);
                std::stringstream resultMsg;
                resultMsg << "Install ";
                if(ret == 0) {
                    resultMsg << "succeeded!";
                } else if(ret == -2) {
                    resultMsg << "cancelled!";
                } else {
                    resultMsg << "failed! Error: 0x" << std::hex << ret;
                }

                ui_prompt(resultMsg.str(), false);
            }

            fclose(file.fd);
            continue;
        }

        if(obtained) {
            std::stringstream prompt;
            if(mode == INSTALL) {
                prompt << "Install ";
            } else if(mode == DELETE) {
                prompt << "Delete ";
            }

            prompt << "the selected title?";
            if(ui_prompt(prompt.str(), true)) {
                int ret = 0;
                if(mode == INSTALL) {
                    ret = app_install_file(destination, targetInstall, onProgress);
                } else if(mode == DELETE) {
                    ui_display_message("Deleting title...");
                    ret = app_delete(targetDelete);
                }

                std::stringstream resultMsg;
                if(mode == INSTALL) {
                    resultMsg << "Install ";
                } else if(mode == DELETE) {
                    resultMsg << "Delete ";
                }

                if(ret == 0) {
                    resultMsg << "succeeded!";
                } else if(ret == -2) {
                    resultMsg << "cancelled!";
                } else {
                    resultMsg << "failed! Error: 0x" << std::hex << ret;
                }

                ui_prompt(resultMsg.str(), false);

                freeSpace = fs_get_free_space(destination);
            }
        }
    }

    platform_cleanup();
    return 0;
}
<commit_msg>Make use of enhanced app result reporting.<commit_after>#include <ctrcommon/common.hpp>

#include <sstream>
#include <iomanip>
#include <stdio.h>
#include <sys/errno.h>

typedef enum {
    INSTALL,
    DELETE
} Mode;

int main(int argc, char **argv) {
    if(!platform_init()) {
        return 0;
    }

    std::vector<std::string> extensions;
    extensions.push_back("cia");

    MediaType destination = SD;
    Mode mode = INSTALL;
    bool netInstall = false;
    u64 freeSpace = fs_get_free_space(destination);
    auto onLoop = [&]() {
        bool breakLoop = false;
        if(input_is_pressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fs_get_free_space(destination);
            if(mode == DELETE) {
                breakLoop = true;
            }
        }

        if(input_is_pressed(BUTTON_R)) {
            if(mode == INSTALL) {
                mode = DELETE;
            } else {
                mode = INSTALL;
            }

            breakLoop = true;
        }

        if(input_is_pressed(BUTTON_Y)) {
            netInstall = true;
            breakLoop = true;
        }

        std::stringstream stream;
        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        stream << "Y - Receive an app over the network" << "\n";

        std::string str = stream.str();
        screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);

        return breakLoop;
    };

    auto onProgress = [&](int progress) {
        ui_display_progress("Installing", "Press B to cancel.", true, progress);
        input_poll();
        return !input_is_pressed(BUTTON_B);
    };

    while(platform_is_running()) {
        std::string targetInstall;
        App targetDelete;
        bool obtained = false;
        if(mode == INSTALL) {
            obtained = ui_select_file(&targetInstall, "sdmc:", extensions, onLoop);
        } else if(mode == DELETE) {
            obtained = ui_select_app(&targetDelete, destination, onLoop);
        }

        if(netInstall) {
            netInstall = false;

            // Clear bottom screen on both buffers.
            screen_begin_draw(BOTTOM_SCREEN);
            screen_clear(0, 0, 0);
            screen_end_draw();
            screen_swap_buffers();

            screen_begin_draw(BOTTOM_SCREEN);
            screen_clear(0, 0, 0);
            screen_end_draw();
            screen_swap_buffers();

            RemoteFile file = ui_accept_remote_file();
            if(file.fd == NULL) {
                continue;
            }

            std::stringstream confirmStream;
            confirmStream << "Install the received application?" << "\n";
            confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n";
            if(ui_prompt(confirmStream.str(), true)) {
                int ret = app_install(destination, file.fd, file.fileSize, onProgress);
                std::stringstream resultMsg;
                if(mode == INSTALL) {
                    resultMsg << "Install ";
                } else if(mode == DELETE) {
                    resultMsg << "Delete ";
                }

                if(ret == APP_SUCCESS) {
                    resultMsg << "succeeded!";
                } else {
                    resultMsg << "failed!" << "\n";
                    resultMsg << app_get_result_string(ret);
                }

                ui_prompt(resultMsg.str(), false);
            }

            fclose(file.fd);
            continue;
        }

        if(obtained) {
            std::stringstream prompt;
            if(mode == INSTALL) {
                prompt << "Install ";
            } else if(mode == DELETE) {
                prompt << "Delete ";
            }

            prompt << "the selected title?";
            if(ui_prompt(prompt.str(), true)) {
                int ret = 0;
                if(mode == INSTALL) {
                    ret = app_install_file(destination, targetInstall, onProgress);
                } else if(mode == DELETE) {
                    ui_display_message("Deleting title...");
                    ret = app_delete(targetDelete);
                }

                std::stringstream resultMsg;
                if(mode == INSTALL) {
                    resultMsg << "Install ";
                } else if(mode == DELETE) {
                    resultMsg << "Delete ";
                }

                if(ret == APP_SUCCESS) {
                    resultMsg << "succeeded!";
                } else {
                    resultMsg << "failed!" << "\n";
                    resultMsg << app_get_result_string(ret);
                }

                ui_prompt(resultMsg.str(), false);

                freeSpace = fs_get_free_space(destination);
            }
        }
    }

    platform_cleanup();
    return 0;
}
<|endoftext|>