<commit_before>//
//  download_manager.cpp
//  Cooloi_Assets_Downloader
//
//  Created by ESoragoto on 11/17/15.
//
//

#include "download_manager.hpp"
#include "assets_downloader.hpp"

#include "SimpleAudioEngine.h"

#include <iostream>
#include <string>
#include <fstream>
#include <regex>
#include <stdio.h>

#include "json/rapidjson.h"
#include "json/document.h"
#include "json/writer.h"
#include "json/stringbuffer.h"

using namespace cocos2d;
using namespace CocosDenshion;

#pragma mark - Initialization
DownloadManager::DownloadManager():
downloader_(nullptr),
stage_(DownloadStage ::kNull),
conf_(),
finished_(),
update_(),
now_downloading_(""),
now_number_(0)
{
} // DownloadManager

DownloadManager::~DownloadManager()
{
    if (downloader_)
        CC_SAFE_DELETE(downloader_);
} // ~DownloadManager

// on "init" you need to initialize your instance
bool DownloadManager::init()
{
    if ( !Scene::init() )
    {
        return false;
    }

    LoadConfig();

    InitDownloader();

    LoadUpdate();

    return true;
} // init

DownloadManager* DownloadManager::Create()
{
    auto d = new DownloadManager();
    if(d->init())
        return d;
    CC_SAFE_DELETE(d);
    return nullptr;
} // Create

void DownloadManager::update(float dt)
{
    if (downloader_->downloading()) return;

    unscheduleUpdate();

    switch (downloader()->status())
    {
//        case AssetsManager::ErrorCode::CREATE_FILE:
//        {
//            return;
//        }
//            break;

        case AssetsManager::ErrorCode::UNCOMPRESS:
        {
            set_stage(DownloadStage::kNull);
            return;
        }
            break;

        case AssetsManager::ErrorCode::NETWORK:
        {
            set_stage(DownloadStage::kNull);
            return;
        }
            break;

        default:
            break;
    }

    switch (stage())
    {
        case DownloadStage ::kLoadUpdate:
        {
            CheckUpdate();
        }
            break;

        case DownloadStage ::kGetUpdate:
        {
            GetUpdate();
        }
            break;

        default:
            break;
    }
} // update

#pragma mark - Member Function
#pragma mark -stage

int DownloadManager::LoadConfig()
{
    log("\nStage : Load config info.\n");
    set_stage(DownloadStage::kLoadConfig);
    auto ret = 0;
    std::string file_name = "";
//#if COCOS2D_DEBUG
//    file_name = "Cooloi_ASDL_DEBUG.conf";
////    file_name = "Cooloi_ASDL.conf";
//#else
//    file_name = "Cooloi_ASDL.conf";
//#endif
//    ret = ReadConf(file_name,
//                   conf_);

#if COCOS2D_DEBUG
    file_name = "Cooloi_ASDL_DEBUG.json";
    //    file_name = "Cooloi_ASDL.json";
#else
    file_name = "Cooloi_ASDL.json";
#endif
    ret = ReadConfigFromJson(file_name,
                             conf_);

    if (0 != ret)
    {
        set_stage(DownloadStage::kNull);
    }
    return ret;
} // LoadConfig

int DownloadManager::InitDownloader()
{
    log("\nStage : Initialization Downloader.\n");
    set_stage(DownloadStage::kInitDownloader);
    downloader_ = new AssetsDownloader(conf_["URL"],
                                       conf_["VER"],
                                       conf_["DIR"],
                                       std::stoi(conf_["TRY"]));
    downloader_->Init();
    return 0;
} // InitDownloader

int DownloadManager::LoadUpdate()
{
    log("\nStage : Download update info.\n");
    set_stage(DownloadStage::kLoadUpdate);
    Download(conf_["URL"]);
    return 0;
} // LoadUpdate

int DownloadManager::CheckUpdate()
{
    log("\nStage : Check update info.\n");
    set_stage(DownloadStage::kCheckUpdate);
    auto ret = 0;
    if ("" != now_downloading_) push_finished(now_downloading());
//    ret = ReadConf(conf_["NAME"], pkg_map_);
//    ret = ReadConf(conf_["LOCAL_NAME"], loc_map_);

    ret = ReadConfigFromJson(conf_["NAME"], pkg_map_);
    ret = ReadConfigFromJson(conf_["LOCAL_NAME"], loc_map_);

    for (auto p : pkg_map())
    {
        if (p.second != loc_map_[p.first])
        {
            push_update(p.first);
        }
    }

    if (update().empty())
    {
        set_stage(DownloadStage::kFinished);
    }
    else
    {
        log("New package find!");
//        GetUpdate();
    }
    return ret;
} // CheckUpdate

int DownloadManager::GetUpdate()
{
    log("\nStage : Get update package.\n");
    set_stage(DownloadStage::kGetUpdate);
    auto ret = 0;
    if ("" != now_downloading_) push_finished(now_downloading());

    for (auto u : update())
    {
        auto jump = false;
        for (auto f : finished())
        {
            if (u == f)
            {
                jump = true;
                break;
            }
        }
        if (jump) continue;

        set_now_downloading(u);
        Download(conf().at("SER") + pkg_map_[u]);
        break;
    }

    if (update().size() == finished().size())
    {
        std::string content = "#loacl list\n";
        for (auto p : pkg_map())
        {
            content += (p.first + " = " + p.second + "\n");
        }
        WriteFile(conf_["LOCAL_NAME"], content);
        auto s = FileUtils::getInstance()->getStringFromFile(conf_["LOCAL_NAME"]);
        log("%s", s.c_str());
        set_stage(DownloadStage::kFinished);
    }

    return ret;
} // GetUpdate

void DownloadManager::Close()
{
    Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
} // Close

#pragma mark -other

int DownloadManager::Download(const std::string pkg_url)
{
    log("Request to download resource : %s", pkg_url.c_str());
    downloader_->Download(pkg_url);

    scheduleUpdate();
    return 0;
} // Download

int DownloadManager::ReadConf(const std::string file_name,
                              std::map<std::string, std::string> &conf_map)
{
    log("Read config file : %s", file_name.c_str());
    std::string path_with_file = "";
    FindPathWithFile(file_name, path_with_file);
    if ("" == path_with_file)
    {
        WriteFile(file_name, "");
        return 1;
    }

    auto str = FileUtils::getInstance()->getStringFromFile(file_name);
    log("getStringFromFile\n%s",str.c_str());

    std::ifstream in_file(path_with_file);
    if(in_file.fail())
        return 1001;

    std::string str_by_line = "";
    while (std::getline(in_file, str_by_line))
    {
        std::string arg;
        std::string value;
        ConfRegex(str_by_line, arg, value);
        conf_map[arg] = value;
    }
    return 0;
} // ReadConf

int DownloadManager::ConfRegex(const std::string str,
                               std::string &arg,
                               std::string &value)
{
    log("Regex line : %s", str.c_str());
    std::regex rgx("^(\\w+)\\s*\\=\\s*([^\\s]+)$");
    std::smatch match;

    if (std::regex_search(str.begin(), str.end(), match, rgx))
    {
        for(auto q : match)
        {
            log("\t%s", q.str().c_str());
        }
        log("----");
        arg = match[1].str();
        value = match[2].str();
    }
    return 0;
} // ConfRegex

int DownloadManager::ReadConfigFromJson(const std::string file_name,
                                        std::map<std::string, std::string> &conf_map)
{
    std::string file_with_path = "";
    FindPathWithFile(file_name, file_with_path);
    auto str = FileUtils::getInstance()->getStringFromFile(file_with_path.c_str());
    log("getStringFromFile : %s", str.c_str());
    rapidjson::Document d;
    d.Parse<0>(str.c_str());
    if(!d.IsObject())
    {
        set_stage(DownloadStage::kFileNotFound);
        return 1404;
    }
    for (auto iter = d.MemberBegin() ; iter != d.MemberEnd() ; iter++)
    {
        log("\tKey\t : %s\n\tValue : %s\n\t----",
            iter->name.GetString(),
            iter->value.GetString());
        conf_map[iter->name.GetString()] = iter->value.GetString();
    }
    return 0;
}

int DownloadManager::WriteConfigToJson(const std::string file_name,
                                       std::map<std::string, std::string> &conf_map)
{
    std::string file_with_path = "";
    FindPathWithFile(file_name, file_with_path);

    rapidjson::Document d;
    d.SetObject();
    for(auto c : conf_map)
    {
        log("write config name is %s, value is %s", c.first.c_str(), c.second.c_str());
        rapidjson::Value name(rapidjson::kStringType);
        name.SetString(c.first.c_str(), (int)c.first.length());

        rapidjson::Value value(rapidjson::kStringType);
        value.SetString(c.second.c_str(), (int)c.second.length());

        d.AddMember(name, value, d.GetAllocator());
    }

    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> write(buffer);
    d.Accept(write);

    log("now write config is %s", buffer.GetString());

    if ("" == file_with_path)
    {
        file_with_path = FileUtils::getInstance()->getWritablePath() + file_name;
    }

    FILE* file = fopen(file_with_path.c_str(), "wb");
    if (file)
    {
        fputs(buffer.GetString(), file);
        fclose(file);
    }
    return 0;
}

int DownloadManager::ReadFile(const std::string file_name,
                              std::string &content)
{
    log("Preparing Read file : %s", file_name.c_str());
    std::string file_with_path = "";
    FindPathWithFile(file_name, file_with_path);
    if ("" == file_with_path)
        return 1404;

    log("Full path: %s", file_with_path.c_str());
    auto file = FileUtils::getInstance()->getStringFromFile(file_with_path);

    if ("" == file)
    {
        std::ifstream infile(file_with_path);

        if (infile.fail())
        {
            log("Open file fail, file name: %s", file_name.c_str());
            return 1001;
        }

        std::string str((std::istreambuf_iterator<char>(infile)),
                        std::istreambuf_iterator<char>());
        file = str.c_str();
        infile.close();
    }

    log("open file:\n----\n%s\n----", file.c_str());
    content = file;
    return 0;
} // ReadFile

int DownloadManager::WriteFile(const std::string file_name,
                               const std::string content)
{
    log("Preparing write file : %s", file_name.c_str());
    std::string file_to_write = "";
    FindPathWithFile(file_name, file_to_write);
    if ("" == file_to_write)
    {
        file_to_write = FileUtils::getInstance()->getWritablePath();
//        file_to_write += conf_["Dir"];
        file_to_write += file_name;
    }

    log("Write path : %s", file_to_write.c_str());
    std::ofstream outfile;
    outfile.open(file_to_write);
    if (outfile.fail())
    {
        log("Open file fail, file name: %s", file_name.c_str());
        return 1001;
    }
    std::string str = "#" + file_name + "\n" + content;
    outfile << str;
    log("write file with fstream : \n----\n%s\n----", str.c_str());
    outfile.close();
    return 0;
} // WriteFile

int DownloadManager::AppendFile(const std::string file_name,
                                const std::string content)
{
    auto ret = 0;
    std::string path_with_file = "";
    FindPathWithFile(file_name, path_with_file);

    if ("" == path_with_file)
    {
        return 1404;
    }
    log("Full path: %s", path_with_file.c_str());

    std::string front_content = "";
    ret = ReadFile(file_name,
                   front_content);
    if (0 != ret)
        return ret;

    ret = WriteFile(file_name, front_content + "\n" + content);
    return ret;
} // AppendFile

int DownloadManager::FindPathWithFile(const std::string file_name,
                                      std::string &path_with_file)
{
    auto path = FileUtils::getInstance()->fullPathForFilename(file_name);
    if ("" == path)
    {
        auto temp_name = FileUtils::getInstance()->getWritablePath() + file_name;
        path = FileUtils::getInstance()->fullPathForFilename(temp_name);
        if ("" == path) log("File not exist!");
    }
    if ("" != path)
        log("Find file with : %s", path.c_str());
    path_with_file = path;
    return 0;
} // FindPathWithFile
<commit_msg>some fix<commit_after>//
//  download_manager.cpp
//  Cooloi_Assets_Downloader
//
//  Created by ESoragoto on 11/17/15.
//
//

#include "download_manager.hpp"
#include "assets_downloader.hpp"

#include "SimpleAudioEngine.h"

#include <iostream>
#include <string>
#include <fstream>
#include <regex>
#include <stdio.h>

#include "json/rapidjson.h"
#include "json/document.h"
#include "json/writer.h"
#include "json/stringbuffer.h"

using namespace cocos2d;
using namespace CocosDenshion;

#pragma mark - Initialization
DownloadManager::DownloadManager():
downloader_(nullptr),
stage_(DownloadStage ::kNull),
conf_(),
finished_(),
update_(),
now_downloading_(""),
now_number_(0)
{
} // DownloadManager

DownloadManager::~DownloadManager()
{
    if (downloader_)
        CC_SAFE_DELETE(downloader_);
} // ~DownloadManager

// on "init" you need to initialize your instance
bool DownloadManager::init()
{
    if ( !Scene::init() )
    {
        return false;
    }

    LoadConfig();

    InitDownloader();

    LoadUpdate();

    return true;
} // init

DownloadManager* DownloadManager::Create()
{
    auto d = new DownloadManager();
    if(d->init())
        return d;
    CC_SAFE_DELETE(d);
    return nullptr;
} // Create

void DownloadManager::update(float dt)
{
    if (downloader_->downloading()) return;

    unscheduleUpdate();

    switch (downloader()->status())
    {
//        case AssetsManager::ErrorCode::CREATE_FILE:
//        {
//            return;
//        }
//            break;

        case AssetsManager::ErrorCode::UNCOMPRESS:
        {
            set_stage(DownloadStage::kNull);
            return;
        }
            break;

        case AssetsManager::ErrorCode::NETWORK:
        {
            set_stage(DownloadStage::kNull);
            return;
        }
            break;

        default:
            break;
    }

    switch (stage())
    {
        case DownloadStage ::kLoadUpdate:
        {
            CheckUpdate();
        }
            break;

        case DownloadStage ::kGetUpdate:
        {
            GetUpdate();
        }
            break;

        default:
            break;
    }
} // update

#pragma mark - Member Function
#pragma mark -stage

int DownloadManager::LoadConfig()
{
    log("\nStage : Load config info.\n");
    set_stage(DownloadStage::kLoadConfig);
    auto ret = 0;
    std::string file_name = "";
//#if COCOS2D_DEBUG
//    file_name = "Cooloi_ASDL_DEBUG.conf";
////    file_name = "Cooloi_ASDL.conf";
//#else
//    file_name = "Cooloi_ASDL.conf";
//#endif
//    ret = ReadConf(file_name,
//                   conf_);

#if COCOS2D_DEBUG
    file_name = "Cooloi_ASDL_DEBUG.json";
    //    file_name = "Cooloi_ASDL.json";
#else
    file_name = "Cooloi_ASDL.json";
#endif
    ret = ReadConfigFromJson(file_name,
                             conf_);

    if (0 != ret)
    {
        set_stage(DownloadStage::kNull);
    }
    return ret;
} // LoadConfig

int DownloadManager::InitDownloader()
{
    log("\nStage : Initialization Downloader.\n");
    set_stage(DownloadStage::kInitDownloader);
    downloader_ = new AssetsDownloader(conf_["URL"],
                                       conf_["VER"],
                                       conf_["DIR"],
                                       std::stoi(conf_["TRY"]));
    downloader_->Init();
    return 0;
} // InitDownloader

int DownloadManager::LoadUpdate()
{
    log("\nStage : Download update info.\n");
    set_stage(DownloadStage::kLoadUpdate);
    Download(conf_["URL"]);
    return 0;
} // LoadUpdate

int DownloadManager::CheckUpdate()
{
    log("\nStage : Check update info.\n");
    set_stage(DownloadStage::kCheckUpdate);
    auto ret = 0;
    if ("" != now_downloading_) push_finished(now_downloading());
//    ret = ReadConf(conf_["NAME"], pkg_map_);
//    ret = ReadConf(conf_["LOCAL_NAME"], loc_map_);

    ret = ReadConfigFromJson(conf_["NAME"], pkg_map_);
    ret = ReadConfigFromJson(conf_["LOCAL_NAME"], loc_map_);

    for (auto p : pkg_map())
    {
        if (p.second != loc_map_[p.first])
        {
            push_update(p.first);
        }
    }

    if (update().empty())
    {
        set_stage(DownloadStage::kFinished);
    }
    else
    {
        log("New package find!");
//        GetUpdate();
    }
    return ret;
} // CheckUpdate

int DownloadManager::GetUpdate()
{
    log("\nStage : Get update package.\n");
    set_stage(DownloadStage::kGetUpdate);
    auto ret = 0;
    if ("" != now_downloading_) push_finished(now_downloading());

    for (auto u : update())
    {
        auto jump = false;
        for (auto f : finished())
        {
            if (u == f)
            {
                jump = true;
                break;
            }
        }
        if (jump) continue;

        set_now_downloading(u);
        Download(conf().at("SER") + pkg_map_[u]);
        break;
    }

    if (update().size() == finished().size())
    {
        std::string content = "";
        for (auto p : pkg_map())
        {
            content += (p.first + " = " + p.second + "\n");
        }
        WriteFile(conf_["LOCAL_NAME"], content);
        auto s = FileUtils::getInstance()->getStringFromFile(conf_["LOCAL_NAME"]);
        log("%s", s.c_str());
        set_stage(DownloadStage::kFinished);
    }

    return ret;
} // GetUpdate

void DownloadManager::Close()
{
    Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
} // Close

#pragma mark -other

int DownloadManager::Download(const std::string pkg_url)
{
    log("Request to download resource : %s", pkg_url.c_str());
    downloader_->Download(pkg_url);

    scheduleUpdate();
    return 0;
} // Download

int DownloadManager::ReadConf(const std::string file_name,
                              std::map<std::string, std::string> &conf_map)
{
    log("Read config file : %s", file_name.c_str());
    std::string path_with_file = "";
    FindPathWithFile(file_name, path_with_file);
    if ("" == path_with_file)
    {
        WriteFile(file_name, "");
        return 1;
    }

    auto str = FileUtils::getInstance()->getStringFromFile(file_name);
    log("getStringFromFile\n%s",str.c_str());

    std::ifstream in_file(path_with_file);
    if(in_file.fail())
        return 1001;

    std::string str_by_line = "";
    while (std::getline(in_file, str_by_line))
    {
        std::string arg;
        std::string value;
        ConfRegex(str_by_line, arg, value);
        conf_map[arg] = value;
    }
    return 0;
} // ReadConf

int DownloadManager::ConfRegex(const std::string str,
                               std::string &arg,
                               std::string &value)
{
    log("Regex line : %s", str.c_str());
    std::regex rgx("^(\\w+)\\s*\\=\\s*([^\\s]+)$");
    std::smatch match;

    if (std::regex_search(str.begin(), str.end(), match, rgx))
    {
        for(auto q : match)
        {
            log("\t%s", q.str().c_str());
        }
        log("----");
        arg = match[1].str();
        value = match[2].str();
    }
    return 0;
} // ConfRegex

int DownloadManager::ReadConfigFromJson(const std::string file_name,
                                        std::map<std::string, std::string> &conf_map)
{
    std::string file_with_path = "";
    FindPathWithFile(file_name, file_with_path);
    auto str = FileUtils::getInstance()->getStringFromFile(file_with_path.c_str());
    log("getStringFromFile : %s", str.c_str());
    rapidjson::Document d;
    d.Parse<0>(str.c_str());
    if(!d.IsObject())
    {
        set_stage(DownloadStage::kFileNotFound);
        return 1404;
    }
    for (auto iter = d.MemberBegin() ; iter != d.MemberEnd() ; iter++)
    {
        log("\tKey\t : %s\n\tValue : %s\n\t----",
            iter->name.GetString(),
            iter->value.GetString());
        conf_map[iter->name.GetString()] = iter->value.GetString();
    }
    return 0;
}

int DownloadManager::WriteConfigToJson(const std::string file_name,
                                       std::map<std::string, std::string> &conf_map)
{
    std::string file_with_path = "";
    FindPathWithFile(file_name, file_with_path);

    rapidjson::Document d;
    d.SetObject();
    for(auto c : conf_map)
    {
        log("write config name is %s, value is %s", c.first.c_str(), c.second.c_str());
        rapidjson::Value name(rapidjson::kStringType);
        name.SetString(c.first.c_str(), (int)c.first.length());

        rapidjson::Value value(rapidjson::kStringType);
        value.SetString(c.second.c_str(), (int)c.second.length());

        d.AddMember(name, value, d.GetAllocator());
    }

    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> write(buffer);
    d.Accept(write);

    log("now write config is %s", buffer.GetString());

    if ("" == file_with_path)
    {
        file_with_path = FileUtils::getInstance()->getWritablePath() + file_name;
    }

    FILE* file = fopen(file_with_path.c_str(), "wb");
    if (file)
    {
        fputs(buffer.GetString(), file);
        fclose(file);
    }
    return 0;
}

int DownloadManager::ReadFile(const std::string file_name,
                              std::string &content)
{
    log("Preparing Read file : %s", file_name.c_str());
    std::string file_with_path = "";
    FindPathWithFile(file_name, file_with_path);
    if ("" == file_with_path)
        return 1404;

    log("Full path: %s", file_with_path.c_str());
    auto file = FileUtils::getInstance()->getStringFromFile(file_with_path);

    if ("" == file)
    {
        std::ifstream infile(file_with_path);

        if (infile.fail())
        {
            log("Open file fail, file name: %s", file_name.c_str());
            return 1001;
        }

        std::string str((std::istreambuf_iterator<char>(infile)),
                        std::istreambuf_iterator<char>());
        file = str.c_str();
        infile.close();
    }

    log("open file:\n----\n%s\n----", file.c_str());
    content = file;
    return 0;
} // ReadFile

int DownloadManager::WriteFile(const std::string file_name,
                               const std::string content)
{
    log("Preparing write file : %s", file_name.c_str());
    std::string file_to_write = "";
    FindPathWithFile(file_name, file_to_write);
    if ("" == file_to_write)
    {
        file_to_write = FileUtils::getInstance()->getWritablePath();
//        file_to_write += conf_["Dir"];
        file_to_write += file_name;
    }

    log("Write path : %s", file_to_write.c_str());
    std::ofstream outfile;
    outfile.open(file_to_write);
    if (outfile.fail())
    {
        log("Open file fail, file name: %s", file_name.c_str());
        return 1001;
    }
    std::string str = "";
//    str += "#" + file_name + "\n";
    str += content;
    outfile << str;
    log("write file with fstream : \n----\n%s\n----", str.c_str());
    outfile.close();
    return 0;
} // WriteFile

int DownloadManager::AppendFile(const std::string file_name,
                                const std::string content)
{
    auto ret = 0;
    std::string path_with_file = "";
    FindPathWithFile(file_name, path_with_file);

    if ("" == path_with_file)
    {
        return 1404;
    }
    log("Full path: %s", path_with_file.c_str());

    std::string front_content = "";
    ret = ReadFile(file_name,
                   front_content);
    if (0 != ret)
        return ret;

    ret = WriteFile(file_name, front_content + "\n" + content);
    return ret;
} // AppendFile

int DownloadManager::FindPathWithFile(const std::string file_name,
                                      std::string &path_with_file)
{
    auto path = FileUtils::getInstance()->fullPathForFilename(file_name);
    if ("" == path)
    {
        auto temp_name = FileUtils::getInstance()->getWritablePath() + file_name;
        path = FileUtils::getInstance()->fullPathForFilename(temp_name);
        if ("" == path) log("File not exist!");
    }
    if ("" != path)
        log("Find file with : %s", path.c_str());
    path_with_file = path;
    return 0;
} // FindPathWithFile
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sstream>

#include <map>
#include <vector>
#include <utility>

using namespace std;

typedef pair<string,double> P;

struct node
{
	std::vector<struct node *> parents; //for 0 or N-parents; if the vector is empty, the event is Independient
	std::map<string, double> probabilityTable;  //key is X in P(X)
};

int main(int argc, char *argv[])
{
	std::map<string, struct node*> nodes;

	string buffer, builder, aux;

	char devourer;

	double readerProb;

	int sect = 0;
	cout << "STARTING...\n";
	while(sect < 3){
		getline(cin,buffer);
		//cout << "Reading std\n";
		if(buffer.compare("[Nodes]")==0){
			cout << "Nodes:\n";
			getline(cin,buffer);
			for(int i=0;i < buffer.length();i++){
				if(buffer[i]==','){
					nodes[builder] = new node;
					cout << builder << "\n";
				}else if(i==(buffer.length()-1)){
					builder+=buffer[i];
					cout << builder << "\n";
					nodes[builder] = new node;
				}else if(buffer[i]==' '){
					builder="";
				}else{
					builder+=buffer[i];
				}
			}
			cout << '\n';
			sect++;
		}else if(buffer.compare("[Probabilities]")==0){
			cout << "Probabilities:\n";
			while(buffer.compare("")!=0){
				getline(cin,buffer);
				builder="";
				//link nodes with their parents
				//cout << "----\n";
				bool indexNode=false;
				for(int i=0;i < buffer.length();i++){
					if(buffer[i]=='|'){
						indexNode = true; //the node have a parent
						aux = builder;
						builder="";
						cout << "\nNode is: " << aux <<'\n';
						cout << "Its parents are: ";
					}
					if(buffer[i]=='+'||buffer[i]=='-'||buffer[i]==' '||buffer[i]=='='||buffer[i]==','||buffer[i]=='|'||(buffer[i]>=48&&buffer[i]<=57));
					else{
						builder+=buffer[i]; //construct the string key for the map of nodes
						//cout << '.';
					}
					if(indexNode){ //to make the conection in base of the dependece
						if(buffer[i]==','){
							(nodes[aux])->parents.push_back(nodes[builder]); //to create N parents
							cout << builder <<' ';
							builder="";
						}else if (buffer[i]=='=')
						{
							(nodes[aux])->parents.push_back(nodes[builder]); //if there is only one parent
							cout << builder <<' ';
							builder="";
						}
					}

					if(buffer[i]=='='){
						if(!indexNode){
							aux=builder; //the node is root P(X) is independient
							cout << "\nNode: " << aux <<" is a root\n";
						}
						break; //finish the creation of the edges
					}
				}
				cout << '\n';
				//probability table
				builder="";
				for(int i=0;i < buffer.length();i++){
					if(buffer[i]=='='){
						break;
					}else if(buffer[i]==' '&&buffer[i+1]=='=');
					else{
						builder+=buffer[i];
					}
				}

				if(builder.compare("")!=0){
					stringstream extract(buffer);

					do{
						extract >> devourer; //eats all chars
					}while(devourer!='=');

					extract >> readerProb;

					(nodes[aux])->probabilityTable[builder]=readerProb;

					cout << "P("<< builder << ")= " << (nodes[aux])->probabilityTable[builder] << "\n";
				}
			}
			sect++;
		}else if (buffer.compare("[Queries]")==0){
			cout << "Queries:\n";
			sect++;
		}
	}

	return 0;
}<commit_msg>No duplications in the vector of parents<commit_after>#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sstream>

#include <algorithm>
#include <map>
#include <vector>
#include <utility>

using namespace std;

typedef pair<string,double> P;

struct node
{
	std::vector<struct node *> parents; //for 0 or N-parents; if the vector is empty, the event is Independient
	std::map<string, double> probabilityTable;  //key is X in P(X)
};

void createNodes(map<string, struct node*> &nodes,string buffer){
	string builder;
	getline(cin,buffer);
	for(int i=0;i < buffer.length();i++){
		if(buffer[i]==','){
			nodes[builder] = new node;
			cout << builder << "\n";
		}else if(i==(buffer.length()-1)){
			builder+=buffer[i];
			cout << builder << "\n";
			nodes[builder] = new node;
		}else if(buffer[i]==' '){
			builder="";
		}else{
			builder+=buffer[i];
		}
	}
}

void createBayesNetwork(map<string, struct node*> &nodes,string buffer){
	string builder, aux;
	char devourer;
	double readerProb;

	while(buffer.compare("")!=0){
		getline(cin,buffer);
		builder="";
		//link nodes with their parents
		//cout << "----\n";
		bool indexNode=false;
		for(int i=0;i < buffer.length();i++){
			if(buffer[i]=='|'){
				indexNode = true; //the node have a parent
				aux = builder;
				builder="";
				cout << "\nNode is: " << aux <<'\n';
				cout << "Its parents are: ";
			}
			if(buffer[i]=='+'||buffer[i]=='-'||buffer[i]==' '||buffer[i]=='='||buffer[i]==','||buffer[i]=='|'||(buffer[i]>=48&&buffer[i]<=57));
			else{
				builder+=buffer[i]; //construct the string key for the map of nodes
				//cout << '.';
			}
			if(indexNode){ //to make the conection in base of the dependece
				if(find((nodes[aux])->parents.begin(),(nodes[aux])->parents.end(),nodes[builder])!=(nodes[aux])->parents.end()){
					cout << " [A.K.] ";
					builder = "";
				}
				else{
					if(buffer[i]==','){
						(nodes[aux])->parents.push_back(nodes[builder]); //to create N parents
						cout << builder <<' ';
						builder="";
					}else if (buffer[i]=='=')
					{
						(nodes[aux])->parents.push_back(nodes[builder]); //if there is only one parent
						cout << builder <<' ';
						builder="";
					}
				}
			}

			if(buffer[i]=='='){
				if(!indexNode){
					aux=builder; //the node is root P(X) is independient
					cout << "\nNode: " << aux <<" is a root\n";
				}
				break; //finish the creation of the edges
			}
		}
		cout << '\n';
		//probability table
		builder="";
		for(int i=0;i < buffer.length();i++){
			if(buffer[i]=='='){
				break;
			}else if(buffer[i]==' '&&buffer[i+1]=='='); //to ignore the last blank space " ="
			else{
				builder+=buffer[i];
			}
		}

		if(builder.compare("")!=0){
			stringstream extract(buffer);

			do{
				extract >> devourer; //eats all chars
			}while(devourer!='=');

			extract >> readerProb;

			(nodes[aux])->probabilityTable[builder]=readerProb; //store the true values P(+X|Y)

			cout << "P("<< builder << ")= " << (nodes[aux])->probabilityTable[builder] << "\n";
		}

	}
}

int main(int argc, char *argv[])
{
	std::map<string, struct node*> nodes;

	string buffer, builder, aux;

	char devourer;

	double readerProb;

	int sect = 0;
	cout << "STARTING...\n";
	while(sect < 3){
		getline(cin,buffer);
		//cout << "Reading std\n";
		if(buffer.compare("[Nodes]")==0){
			cout << "Nodes:\n";
			/*
			getline(cin,buffer);
			for(int i=0;i < buffer.length();i++){
				if(buffer[i]==','){
					nodes[builder] = new node;
					cout << builder << "\n";
				}else if(i==(buffer.length()-1)){
					builder+=buffer[i];
					cout << builder << "\n";
					nodes[builder] = new node;
				}else if(buffer[i]==' '){
					builder="";
				}else{
					builder+=buffer[i];
				}
			}
			*/
			createNodes(nodes,buffer);
			cout << '\n';
			sect++;
		}else if(buffer.compare("[Probabilities]")==0){
			cout << "Probabilities:\n";
			/*
			while(buffer.compare("")!=0){
				getline(cin,buffer);
				builder="";
				//link nodes with their parents
				//cout << "----\n";
				bool indexNode=false;
				for(int i=0;i < buffer.length();i++){
					if(buffer[i]=='|'){
						indexNode = true; //the node have a parent
						aux = builder;
						builder="";
						cout << "\nNode is: " << aux <<'\n';
						cout << "Its parents are: ";
					}
					if(buffer[i]=='+'||buffer[i]=='-'||buffer[i]==' '||buffer[i]=='='||buffer[i]==','||buffer[i]=='|'||(buffer[i]>=48&&buffer[i]<=57));
					else{
						builder+=buffer[i]; //construct the string key for the map of nodes
						//cout << '.';
					}
					if(indexNode){ //to make the conection in base of the dependece
						if(find((nodes[aux])->parents.begin(),(nodes[aux])->parents.end(),nodes[builder])!=(nodes[aux])->parents.end()){
							cout << " [A.K.] ";
							builder = "";
						}
						else{
							if(buffer[i]==','){
								(nodes[aux])->parents.push_back(nodes[builder]); //to create N parents
								cout << builder <<' ';
								builder="";
							}else if (buffer[i]=='=')
							{
								(nodes[aux])->parents.push_back(nodes[builder]); //if there is only one parent
								cout << builder <<' ';
								builder="";
							}
						}
					}

					if(buffer[i]=='='){
						if(!indexNode){
							aux=builder; //the node is root P(X) is independient
							cout << "\nNode: " << aux <<" is a root\n";
						}
						break; //finish the creation of the edges
					}
				}
				cout << '\n';
				//probability table
				builder="";
				for(int i=0;i < buffer.length();i++){
					if(buffer[i]=='='){
						break;
					}else if(buffer[i]==' '&&buffer[i+1]=='='); //to ignore the last blank space " ="
					else{
						builder+=buffer[i];
					}
				}

				if(builder.compare("")!=0){
					stringstream extract(buffer);

					do{
						extract >> devourer; //eats all chars
					}while(devourer!='=');

					extract >> readerProb;

					(nodes[aux])->probabilityTable[builder]=readerProb; //store the true values P(+X|Y)

					cout << "P("<< builder << ")= " << (nodes[aux])->probabilityTable[builder] << "\n";
				}

			}*/
			createBayesNetwork(nodes,buffer);
			sect++;
		}else if (buffer.compare("[Queries]")==0){
			cout << "Queries:\n";
			getline(cin,buffer);
			sect++;
		}
	}

	return 0;
}<|endoftext|>


<commit_before><commit_msg>restore missing frame borders<commit_after><|endoftext|>


<commit_before>// Always goes first
#define _CUSTOM_UINT64
#include "stdint.h"
// ROS
#include <ros/ros.h>
// bCAP (Always last)
#include "bcap_client.h"

#define PERIOD		(100)	/* Period Cycle */
#define AMPLITUDE	(10)	/* Amplitude */

#define E_BUF_FULL	(0x83201483)

int main(void)
{
	int i, fd;
	long *plData;
	uint32_t hCtrl, hRob;
	double *pdData, dAng[8];
	BSTR bstr1, bstr2, bstr3, bstr4;
	VARIANT vntParam, vntRet;
	HRESULT hr;

	/* Open connection */
	hr = bCap_Open_Client("tcp:192.168.0.1:5007", 1000, 3, &fd);

	if(SUCCEEDED(hr)){
		bstr1 = SysAllocString(L",WDT=400");

		/* Send SERVICE_START packet */
		bCap_ServiceStart(fd, NULL);

		SysFreeString(bstr1);

		bstr1 = SysAllocString(L"RC8");					// Name
		bstr2 = SysAllocString(L"CaoProv.DENSO.VRC");	// Provider
		bstr3 = SysAllocString(L"localhost");			// Machine
		bstr4 = SysAllocString(L"");					// Option

		/* Connect RC8 */
		hr = bCap_ControllerConnect(fd, bstr1, bstr2, bstr3, bstr4, &hCtrl);

		SysFreeString(bstr1);
		SysFreeString(bstr2);
		SysFreeString(bstr3);
		SysFreeString(bstr4);

		if(SUCCEEDED(hr)){
			bstr1 = SysAllocString(L"Robot");	// Name
			bstr2 = SysAllocString(L"");		// Option

			/* Get robot handle */
			hr = bCap_ControllerGetRobot(fd, hCtrl, bstr1, bstr2, &hRob);

			SysFreeString(bstr1);
			SysFreeString(bstr2);

			if(SUCCEEDED(hr)){
				bstr1 = SysAllocString(L"Takearm");

				VariantInit(&vntParam);
				vntParam.vt = (VT_I4 | VT_ARRAY);
				vntParam.parray = SafeArrayCreateVector(VT_I4, 0, 2);
				SafeArrayAccessData(vntParam.parray, (void **)&plData);
				plData[0] = 0; plData[1] = 1;
				SafeArrayUnaccessData(vntParam.parray);

				/* Get arm control authority */
				hr = bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);

				SysFreeString(bstr1);

				VariantClear(&vntParam);
				VariantClear(&vntRet);

				if(SUCCEEDED(hr)){
					bstr1 = SysAllocString(L"Motor");

					VariantInit(&vntParam);
					vntParam.vt = VT_I4;
					vntParam.lVal = 1;

					/* Motor on */
					bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);

					SysFreeString(bstr1);

					VariantClear(&vntParam);
					VariantClear(&vntRet);

					VariantInit(&vntParam);
					vntParam.vt = VT_BSTR;
					vntParam.bstrVal = SysAllocString(L"@E J1");

					/* Move to first pose */
					bCap_RobotMove(fd, hRob, 1, vntParam, NULL);

					VariantClear(&vntParam);

					bstr1 = SysAllocString(L"CurJnt");

					VariantInit(&vntParam);
					vntParam.vt = VT_EMPTY;

					/* Get current angle */
					bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);

					SafeArrayAccessData(vntRet.parray, (void **)&pdData);
					memcpy(dAng, pdData, 8 * sizeof(double));
					SafeArrayUnaccessData(vntRet.parray);

					SysFreeString(bstr1);

					VariantClear(&vntParam);
					VariantClear(&vntRet);

					bstr1 = SysAllocString(L"slvChangeMode");

					VariantInit(&vntParam);
					vntParam.vt = VT_I4;
					vntParam.lVal = 2;

					/* Start slave mode (Mode 0, J Type) */
					bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);

					SysFreeString(bstr1);

					VariantClear(&vntParam);
					VariantClear(&vntRet);

					bstr1 = SysAllocString(L"slvMove");

					VariantInit(&vntParam);
					vntParam.vt = (VT_R8 | VT_ARRAY);
					vntParam.parray = SafeArrayCreateVector(VT_R8, 0, 8);

					for(i = 0; i < PERIOD; i++){
						SafeArrayAccessData(vntParam.parray, (void **)&pdData);
						memcpy(pdData, dAng, 8 * sizeof(double));
						pdData[0] = dAng[0] + i / 10.0;
						pdData[1] = dAng[1] + AMPLITUDE * sin(2*M_PI*i/PERIOD);
						SafeArrayUnaccessData(vntParam.parray);

						hr = bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
						VariantClear(&vntRet);

						/* if return code is not S_OK, then keep the message sending process waiting for 8 msec */
						if(hr != S_OK){
							usleep(8000);

							/* if return code is E_BUF_FULL, then retry previous packet */
							if(FAILED(hr)){
								if(hr == E_BUF_FULL){
									i--;
								}else{
									break;
								}
							}
						}
					}

					/* Stop robot */
					bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);

					SysFreeString(bstr1);

					VariantClear(&vntParam);
					VariantClear(&vntRet);

					bstr1 = SysAllocString(L"slvChangeMode");

					VariantInit(&vntParam);
					vntParam.vt = VT_I4;
					vntParam.lVal = 0;

					/* Stop slave mode */
					bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);

					SysFreeString(bstr1);

					VariantClear(&vntParam);
					VariantClear(&vntRet);

					bstr1 = SysAllocString(L"Motor");

					VariantInit(&vntParam);
					vntParam.vt = VT_I4;
					vntParam.lVal = 0;

					/* Motor off */
					bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);

					SysFreeString(bstr1);

					VariantClear(&vntParam);
					VariantClear(&vntRet);

					bstr1 = SysAllocString(L"Givearm");

					VariantInit(&vntParam);
					vntParam.vt = VT_EMPTY;

					/* Release arm control authority */
					bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);

					SysFreeString(bstr1);

					VariantClear(&vntParam);
					VariantClear(&vntRet);
				}

				/* Release robot handle */
				bCap_RobotRelease(fd, &hRob);
			}

			/* Disconnect RC8 */
			bCap_ControllerDisconnect(fd, &hCtrl);
		}

		/* Send SERVICE_STOP packet */
		bCap_ServiceStop(fd);

		/* Close connection */
		bCap_Close_Client(&fd);
	}

	return 0;
};
<commit_msg>Cleaned-up slave_mode.cpp<commit_after>// Always goes first
#define _CUSTOM_UINT64
#include "stdint.h"
// ROS
#include <ros/ros.h>
// bCAP (Always last)
#include "bcap_client.h"

#define E_BUF_FULL  (0x83201483)

namespace SlaveMode
{
  enum Modes
  {
    P0 = 0x001,
    J0 = 0x002,
    T0 = 0x003,
    P1 = 0x101,
    J1 = 0x102,
    T1 = 0x103,
    P2 = 0x201,
    J2 = 0x202,
    T2 = 0x203
  };
  enum Formats
  {
    None          = 0x0000,
    HandIO        = 0x0020,
    Electric      = 0x0020,
    MiniIO        = 0x0100,
    MiniAndHandIO = 0x0120,
    UserIO        = 0x0200,
    UserAndHandIO = 0x0220,
    Ptype         = 0x0001,
    Jtype         = 0x0002,
    Ttype         = 0x0003,
    PJtypes       = 0x0004,
    TJtypes       = 0x0005,
    Timestamp     = 0x0010
  };
}

int main(int argc, char **argv)
{
  ros::init (argc, argv, "slave_mode");
  ros::NodeHandle nh_;
  int i, fd;
  long *plData;
  uint32_t hCtrl, hRob;
  double *pdData, dAng[8], dElectric[16];
  BSTR bstr1, bstr2, bstr3, bstr4;
  VARIANT vntParam, vntRet;
  HRESULT hr;

  // Open connection
  hr = bCap_Open_Client("tcp:192.168.0.21:5007", 1000, 3, &fd);

  if(SUCCEEDED(hr)){
    // Send SERVICE_START packet
    bstr1 = SysAllocString(L",WDT=400");
    bCap_ServiceStart(fd, NULL);
    SysFreeString(bstr1);

    // Connect to RC8
    bstr1 = SysAllocString(L"RC8");               // Name
    bstr2 = SysAllocString(L"CaoProv.DENSO.VRC"); // Provider
    bstr3 = SysAllocString(L"localhost");         // Machine
    bstr4 = SysAllocString(L"");                  // Options
    hr = bCap_ControllerConnect(fd, bstr1, bstr2, bstr3, bstr4, &hCtrl);
    SysFreeString(bstr1);
    SysFreeString(bstr2);
    SysFreeString(bstr3);
    SysFreeString(bstr4);

    if(SUCCEEDED(hr)){
      // Get robot handle
      bstr1 = SysAllocString(L"Robot"); // Name
      bstr2 = SysAllocString(L"");    // Option
      hr = bCap_ControllerGetRobot(fd, hCtrl, bstr1, bstr2, &hRob);
      SysFreeString(bstr1);
      SysFreeString(bstr2);

      if(SUCCEEDED(hr)){
        // Get arm control authority
        bstr1 = SysAllocString(L"Takearm");
        VariantInit(&vntParam);
        vntParam.vt = (VT_I4 | VT_ARRAY);
        vntParam.parray = SafeArrayCreateVector(VT_I4, 0, 2);
        SafeArrayAccessData(vntParam.parray, (void **)&plData);
        plData[0] = 0; plData[1] = 1;
        SafeArrayUnaccessData(vntParam.parray);
        hr = bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
        SysFreeString(bstr1);
        VariantClear(&vntParam);
        VariantClear(&vntRet);

        if(SUCCEEDED(hr)){
          // Motor ON
          bstr1 = SysAllocString(L"Motor");
          VariantInit(&vntParam);
          vntParam.vt = VT_I4;
          vntParam.lVal = 1;
          bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
          SysFreeString(bstr1);
          VariantClear(&vntParam);
          VariantClear(&vntRet);

          // Get current angles
          bstr1 = SysAllocString(L"CurJnt");
          VariantInit(&vntParam);
          vntParam.vt = VT_EMPTY;
          bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
          SafeArrayAccessData(vntRet.parray, (void **)&pdData);
          memcpy(dAng, pdData, 8 * sizeof(double));
          SafeArrayUnaccessData(vntRet.parray);
          SysFreeString(bstr1);
          VariantClear(&vntParam);
          VariantClear(&vntRet);

          // Change slvRecvFormat
          bstr1 = SysAllocString(L"slvRecvFormat");
          VariantInit(&vntParam);
          vntParam.vt = (VT_I4 | VT_ARRAY);
          vntParam.parray = SafeArrayCreateVector(VT_I4, 0, 2);
          SafeArrayAccessData(vntParam.parray, (void **)&plData);
          plData[0] = SlaveMode::Ptype;
          plData[1] = 0;
          bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
          SysFreeString(bstr1);
          VariantClear(&vntParam);
          VariantClear(&vntRet);

          // Start slave mode
          bstr1 = SysAllocString(L"slvChangeMode");
          VariantInit(&vntParam);
          vntParam.vt = VT_I4;
          vntParam.lVal = SlaveMode::J1;
          bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
          SysFreeString(bstr1);
          VariantClear(&vntParam);
          VariantClear(&vntRet);

          // Send commands
          bstr1 = SysAllocString(L"slvMove");
          VariantInit(&vntParam);
          vntParam.vt = (VT_R8 | VT_ARRAY);
          vntParam.parray = SafeArrayCreateVector(VT_R8, 0, 8);
          ros::Rate rate(125);
          while (ros::ok())
          {
            SafeArrayAccessData(vntParam.parray, (void **)&pdData);
            memcpy(pdData, dAng, 8 * sizeof(double));
            SafeArrayUnaccessData(vntParam.parray);
            hr = bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
            VariantClear(&vntRet);
            // Sleep
            rate.sleep();
          }

          // Stop robot
          bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
          SysFreeString(bstr1);
          VariantClear(&vntParam);
          VariantClear(&vntRet);

          // Stop slave mode
          bstr1 = SysAllocString(L"slvChangeMode");
          VariantInit(&vntParam);
          vntParam.vt = VT_I4;
          vntParam.lVal = 0;
          bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
          SysFreeString(bstr1);
          VariantClear(&vntParam);
          VariantClear(&vntRet);

          // Motor off
          bstr1 = SysAllocString(L"Motor");
          VariantInit(&vntParam);
          vntParam.vt = VT_I4;
          vntParam.lVal = 0;
          bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
          SysFreeString(bstr1);
          VariantClear(&vntParam);
          VariantClear(&vntRet);

          // Release arm control authority
          bstr1 = SysAllocString(L"Givearm");
          VariantInit(&vntParam);
          vntParam.vt = VT_EMPTY;
          bCap_RobotExecute(fd, hRob, bstr1, vntParam, &vntRet);
          SysFreeString(bstr1);
          VariantClear(&vntParam);
          VariantClear(&vntRet);
        }
        // Release robot handle
        bCap_RobotRelease(fd, &hRob);
      }
      // Disconnect RC8
      bCap_ControllerDisconnect(fd, &hCtrl);
    }
    // Send SERVICE_STOP packet
    bCap_ServiceStop(fd);
    // Close connection
    bCap_Close_Client(&fd);
  }

  return 0;
};
<|endoftext|>


<commit_before>//===-- ElimAvailExtern.cpp - DCE unreachable internal functions ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This transform is designed to eliminate available external global
// definitions from the program, turning them into declarations.
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/IPO.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/Utils/CtorUtils.h"
#include "llvm/Transforms/Utils/GlobalStatus.h"
#include "llvm/Pass.h"
using namespace llvm;

#define DEBUG_TYPE "elim-avail-extern"

STATISTIC(NumAliases  , "Number of global aliases removed");
STATISTIC(NumFunctions, "Number of functions removed");
STATISTIC(NumVariables, "Number of global variables removed");

namespace {
  struct EliminateAvailableExternally : public ModulePass {
    static char ID; // Pass identification, replacement for typeid
    EliminateAvailableExternally() : ModulePass(ID) {
      initializeEliminateAvailableExternallyPass(
          *PassRegistry::getPassRegistry());
    }

    // run - Do the EliminateAvailableExternally pass on the specified module,
    // optionally updating the specified callgraph to reflect the changes.
    //
    bool runOnModule(Module &M) override;
  };
}

char EliminateAvailableExternally::ID = 0;
INITIALIZE_PASS(EliminateAvailableExternally, "elim-avail-extern",
                "Eliminate Available Externally Globals", false, false)

ModulePass *llvm::createEliminateAvailableExternallyPass() {
  return new EliminateAvailableExternally();
}

bool EliminateAvailableExternally::runOnModule(Module &M) {
  bool Changed = false;

  // Drop initializers of available externally global variables.
  for (Module::global_iterator I = M.global_begin(), E = M.global_end();
       I != E; ++I) {
    if (!I->hasAvailableExternallyLinkage())
      continue;
    if (I->hasInitializer()) {
      Constant *Init = I->getInitializer();
      I->setInitializer(nullptr);
      if (isSafeToDestroyConstant(Init))
        Init->destroyConstant();
    }
    I->removeDeadConstantUsers();
    I->setLinkage(GlobalValue::ExternalLinkage);
    NumVariables++;
  }

  // Drop the bodies of available externally functions.
  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
    if (!I->hasAvailableExternallyLinkage())
      continue;
    if (!I->isDeclaration())
      // This will set the linkage to external
      I->deleteBody();
    I->removeDeadConstantUsers();
    NumFunctions++;
  }

  // Drop targets of available externally aliases.
  for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); I != E;
       ++I) {
    if (!I->hasAvailableExternallyLinkage())
      continue;
    I->setAliasee(nullptr);
    I->removeDeadConstantUsers();
    I->setLinkage(GlobalValue::ExternalLinkage);
    NumAliases++;
  }

  return Changed;
}
<commit_msg>Aliases don't have available_externally linkage.<commit_after>//===-- ElimAvailExtern.cpp - DCE unreachable internal functions ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This transform is designed to eliminate available external global
// definitions from the program, turning them into declarations.
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/IPO.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/Utils/CtorUtils.h"
#include "llvm/Transforms/Utils/GlobalStatus.h"
#include "llvm/Pass.h"
using namespace llvm;

#define DEBUG_TYPE "elim-avail-extern"

STATISTIC(NumAliases  , "Number of global aliases removed");
STATISTIC(NumFunctions, "Number of functions removed");
STATISTIC(NumVariables, "Number of global variables removed");

namespace {
  struct EliminateAvailableExternally : public ModulePass {
    static char ID; // Pass identification, replacement for typeid
    EliminateAvailableExternally() : ModulePass(ID) {
      initializeEliminateAvailableExternallyPass(
          *PassRegistry::getPassRegistry());
    }

    // run - Do the EliminateAvailableExternally pass on the specified module,
    // optionally updating the specified callgraph to reflect the changes.
    //
    bool runOnModule(Module &M) override;
  };
}

char EliminateAvailableExternally::ID = 0;
INITIALIZE_PASS(EliminateAvailableExternally, "elim-avail-extern",
                "Eliminate Available Externally Globals", false, false)

ModulePass *llvm::createEliminateAvailableExternallyPass() {
  return new EliminateAvailableExternally();
}

bool EliminateAvailableExternally::runOnModule(Module &M) {
  bool Changed = false;

  // Drop initializers of available externally global variables.
  for (Module::global_iterator I = M.global_begin(), E = M.global_end();
       I != E; ++I) {
    if (!I->hasAvailableExternallyLinkage())
      continue;
    if (I->hasInitializer()) {
      Constant *Init = I->getInitializer();
      I->setInitializer(nullptr);
      if (isSafeToDestroyConstant(Init))
        Init->destroyConstant();
    }
    I->removeDeadConstantUsers();
    I->setLinkage(GlobalValue::ExternalLinkage);
    NumVariables++;
  }

  // Drop the bodies of available externally functions.
  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
    if (!I->hasAvailableExternallyLinkage())
      continue;
    if (!I->isDeclaration())
      // This will set the linkage to external
      I->deleteBody();
    I->removeDeadConstantUsers();
    NumFunctions++;
  }

  return Changed;
}
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Fangfang Bai, fangfang@multicorewareinc.com
//    Jin Ma,       jin@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other oclMaterials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors as is and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "perf_precomp.hpp"
using namespace perf;
using namespace std;
using namespace cv::ocl;
using namespace cv;
#if defined(HAVE_XINE)         || \
    defined(HAVE_GSTREAMER)    || \
    defined(HAVE_QUICKTIME)    || \
    defined(HAVE_AVFOUNDATION) || \
    defined(HAVE_FFMPEG)       || \
    defined(WIN32)

#  define BUILD_WITH_VIDEO_INPUT_SUPPORT 1
#else
#  define BUILD_WITH_VIDEO_INPUT_SUPPORT 0
#endif

static void cvtFrameFmt(vector<Mat>& input, vector<Mat>& output, int output_cn)
{
    for(int i = 0; i< (int)(input.size()); i++)
    {
        if(output_cn == 1)
            cvtColor(input[i], output[i], COLOR_RGB2GRAY);
        else
            cvtColor(input[i], output[i], COLOR_RGB2RGBA);
    }
}

static void prepareData(VideoCapture& cap, int cn, vector<Mat>& frame_buffer, vector<oclMat>& frame_buffer_ocl)
{
    cv::Mat frame;
    std::vector<Mat> frame_buffer_init;
    int nFrame = (int)frame_buffer.size();
    for(int i = 0; i < nFrame; i++)
    {
        cap >> frame;
        ASSERT_FALSE(frame.empty());
        frame_buffer_init.push_back(frame);
    }

    if(cn == 1)
        cvtFrameFmt(frame_buffer_init, frame_buffer, 1);
    else
        frame_buffer = frame_buffer_init;

    for(int i = 0; i < nFrame; i++)
        frame_buffer_ocl.push_back(cv::ocl::oclMat(frame_buffer[i]));
}

///////////// MOG ////////////////////////
#if BUILD_WITH_VIDEO_INPUT_SUPPORT

typedef tuple<string, int, double> VideoMOGParamType;
typedef TestBaseWithParam<VideoMOGParamType> VideoMOGFixture;

PERF_TEST_P(VideoMOGFixture, MOG,
            ::testing::Combine(::testing::Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"),
            ::testing::Values(1, 3),
            ::testing::Values(0.0, 0.01)))
{
    VideoMOGParamType params = GetParam();

    const string inputFile = perf::TestBase::getDataPath(get<0>(params));
    const int cn = get<1>(params);
    const float learningRate = static_cast<float>(get<2>(params));

    const int nFrame = 5;

    Mat foreground_cpu;
    std::vector<Mat> frame_buffer(nFrame);
    std::vector<oclMat> frame_buffer_ocl;

    cv::VideoCapture cap(inputFile);
    ASSERT_TRUE(cap.isOpened());

    prepareData(cap, cn, frame_buffer, frame_buffer_ocl);

    if(RUN_PLAIN_IMPL)
    {
        cv::BackgroundSubtractorMOG mog;
        cv::Mat foreground;

        TEST_CYCLE()
        {
            for (int i = 0; i < nFrame; i++)
            {
                mog(frame_buffer[i], foreground, learningRate);
            }
        }
        SANITY_CHECK(foreground);
    }else if(RUN_OCL_IMPL)
    {
        cv::ocl::MOG d_mog;
        cv::ocl::oclMat foreground;
        cv::Mat foreground_h;
        OCL_TEST_CYCLE()
        {
            for (int i = 0; i < nFrame; ++i)
            {
                d_mog(frame_buffer_ocl[i], foreground, learningRate);
            }
        }
        foreground.download(foreground_h);
        SANITY_CHECK(foreground_h);
    }else
        OCL_PERF_ELSE
}
#endif

///////////// MOG2 ////////////////////////
#if BUILD_WITH_VIDEO_INPUT_SUPPORT

typedef tuple<string, int> VideoMOG2ParamType;
typedef TestBaseWithParam<VideoMOG2ParamType> VideoMOG2Fixture;

PERF_TEST_P(VideoMOG2Fixture, MOG2,
            ::testing::Combine(::testing::Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"),
            ::testing::Values(1, 3)))
{
    VideoMOG2ParamType params = GetParam();

    const string inputFile = perf::TestBase::getDataPath(get<0>(params));
    const int cn = get<1>(params);
    int nFrame = 5;

    std::vector<cv::Mat> frame_buffer(nFrame);
    std::vector<cv::ocl::oclMat> frame_buffer_ocl;

    cv::VideoCapture cap(inputFile);
    ASSERT_TRUE(cap.isOpened());

    prepareData(cap, cn, frame_buffer, frame_buffer_ocl);

    if(RUN_PLAIN_IMPL)
    {
        cv::BackgroundSubtractorMOG2 mog2;
        cv::Mat foreground;

        mog2.set("detectShadows", false);

        TEST_CYCLE()
        {
            for (int i = 0; i < nFrame; i++)
            {
                mog2(frame_buffer[i], foreground);
            }
        }
        SANITY_CHECK(foreground);
    }else if(RUN_OCL_IMPL)
    {
        cv::ocl::MOG2 d_mog2;
        cv::ocl::oclMat foreground;
        cv::Mat foreground_h;

        OCL_TEST_CYCLE()
        {
            for (int i = 0; i < nFrame; i++)
            {
                d_mog2(frame_buffer_ocl[i], foreground);
            }
        }
        foreground.download(foreground_h);
        SANITY_CHECK(foreground_h);
    }else
        OCL_PERF_ELSE
}
#endif

///////////// MOG2_GetBackgroundImage //////////////////
#if BUILD_WITH_VIDEO_INPUT_SUPPORT

typedef TestBaseWithParam<VideoMOG2ParamType> Video_MOG2GetBackgroundImage;

PERF_TEST_P(Video_MOG2GetBackgroundImage, MOG2,
            ::testing::Combine(::testing::Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"),
            ::testing::Values(1, 3)))
{
    VideoMOG2ParamType params = GetParam();

    const string inputFile = perf::TestBase::getDataPath(get<0>(params));
    const int cn = get<1>(params);
    int nFrame = 5;

    std::vector<cv::Mat> frame_buffer(nFrame);
    std::vector<cv::ocl::oclMat> frame_buffer_ocl;

    cv::VideoCapture cap(inputFile);
    ASSERT_TRUE(cap.isOpened());

    prepareData(cap, cn, frame_buffer, frame_buffer_ocl);

    if(RUN_PLAIN_IMPL)
    {
        cv::BackgroundSubtractorMOG2 mog2;
        cv::Mat foreground;
        cv::Mat background;
        mog2.set("detectShadows", false);
        TEST_CYCLE()
        {
            for (int i = 0; i < nFrame; i++)
            {
                mog2(frame_buffer[i], foreground);
            }
            mog2.getBackgroundImage(background);
        }
        SANITY_CHECK(background);
    }else if(RUN_OCL_IMPL)
    {
        cv::ocl::MOG2 d_mog2;
        cv::ocl::oclMat foreground;
        cv::Mat background_h;
        cv::ocl::oclMat background;

        OCL_TEST_CYCLE()
        {
            for (int i = 0; i < nFrame; i++)
            {
                d_mog2(frame_buffer_ocl[i], foreground);
            }
            d_mog2.getBackgroundImage(background);
        }
        background.download(background_h);
        SANITY_CHECK(background_h);
    }else
        OCL_PERF_ELSE
}
#endif<commit_msg>Revised performance test according to the feedback of the community.<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Fangfang Bai, fangfang@multicorewareinc.com
//    Jin Ma,       jin@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other oclMaterials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors as is and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "perf_precomp.hpp"
using namespace perf;
using namespace std;
using namespace cv::ocl;
using namespace cv;
using std::tr1::tuple;
using std::tr1::get;
#if defined(HAVE_XINE)         || \
    defined(HAVE_GSTREAMER)    || \
    defined(HAVE_QUICKTIME)    || \
    defined(HAVE_AVFOUNDATION) || \
    defined(HAVE_FFMPEG)       || \
    defined(WIN32)

#  define BUILD_WITH_VIDEO_INPUT_SUPPORT 1
#else
#  define BUILD_WITH_VIDEO_INPUT_SUPPORT 0
#endif

#if BUILD_WITH_VIDEO_INPUT_SUPPORT
static void cvtFrameFmt(vector<Mat>& input, vector<Mat>& output, int output_cn)
{
    for(int i = 0; i< (int)(input.size()); i++)
    {
        if(output_cn == 1)
            cvtColor(input[i], output[i], COLOR_RGB2GRAY);
        else
            cvtColor(input[i], output[i], COLOR_RGB2RGBA);
    }
}
//prepare data for CPU
static void prepareData(VideoCapture& cap, int cn, vector<Mat>& frame_buffer)
{
    cv::Mat frame;
    std::vector<Mat> frame_buffer_init;
    int nFrame = (int)frame_buffer.size();
    for(int i = 0; i < nFrame; i++)
    {
        cap >> frame;
        ASSERT_FALSE(frame.empty());
        frame_buffer_init.push_back(frame);
    }

    if(cn == 1)
        cvtFrameFmt(frame_buffer_init, frame_buffer, 1);
    else
        frame_buffer = frame_buffer_init;
}
//copy CPU data to GPU
static void prepareData(vector<Mat>& frame_buffer, vector<oclMat>& frame_buffer_ocl)
{
    for(int i = 0; i < (int)frame_buffer.size(); i++)
        frame_buffer_ocl.push_back(cv::ocl::oclMat(frame_buffer[i]));
}
#endif
///////////// MOG ////////////////////////
#if BUILD_WITH_VIDEO_INPUT_SUPPORT

typedef tuple<string, int, double> VideoMOGParamType;
typedef TestBaseWithParam<VideoMOGParamType> VideoMOGFixture;

PERF_TEST_P(VideoMOGFixture, MOG,
            ::testing::Combine(::testing::Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"),
            ::testing::Values(1, 3),
            ::testing::Values(0.0, 0.01)))
{
    VideoMOGParamType params = GetParam();

    const string inputFile = perf::TestBase::getDataPath(get<0>(params));
    const int cn = get<1>(params);
    const float learningRate = static_cast<float>(get<2>(params));

    const int nFrame = 5;

    Mat foreground_cpu;
    std::vector<Mat> frame_buffer(nFrame);
    std::vector<oclMat> frame_buffer_ocl;

    cv::VideoCapture cap(inputFile);
    ASSERT_TRUE(cap.isOpened());

    prepareData(cap, cn, frame_buffer);

    cv::Mat foreground;
    cv::ocl::oclMat foreground_d;
    if(RUN_PLAIN_IMPL)
    {
        TEST_CYCLE()
        {
            cv::BackgroundSubtractorMOG mog;
            foreground.release();
            for (int i = 0; i < nFrame; i++)
            {
                mog(frame_buffer[i], foreground, learningRate);
            }
        }
        SANITY_CHECK(foreground);
    }else if(RUN_OCL_IMPL)
    {
        prepareData(frame_buffer, frame_buffer_ocl);
        CV_Assert((int)(frame_buffer_ocl.size()) == nFrame);
        OCL_TEST_CYCLE()
        {
            cv::ocl::MOG d_mog;
            foreground_d.release();
            for (int i = 0; i < nFrame; ++i)
            {
                d_mog(frame_buffer_ocl[i], foreground_d, learningRate);
            }
        }
        foreground_d.download(foreground);
        SANITY_CHECK(foreground);
    }else
        OCL_PERF_ELSE
}
#endif

///////////// MOG2 ////////////////////////
#if BUILD_WITH_VIDEO_INPUT_SUPPORT

typedef tuple<string, int> VideoMOG2ParamType;
typedef TestBaseWithParam<VideoMOG2ParamType> VideoMOG2Fixture;

PERF_TEST_P(VideoMOG2Fixture, MOG2,
            ::testing::Combine(::testing::Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"),
            ::testing::Values(1, 3)))
{
    VideoMOG2ParamType params = GetParam();

    const string inputFile = perf::TestBase::getDataPath(get<0>(params));
    const int cn = get<1>(params);
    int nFrame = 5;

    std::vector<cv::Mat> frame_buffer(nFrame);
    std::vector<cv::ocl::oclMat> frame_buffer_ocl;

    cv::VideoCapture cap(inputFile);
    ASSERT_TRUE(cap.isOpened());
    prepareData(cap, cn, frame_buffer);
    cv::Mat foreground;
    cv::ocl::oclMat foreground_d;

    if(RUN_PLAIN_IMPL)
    {
        TEST_CYCLE()
        {
            cv::BackgroundSubtractorMOG2 mog2;
            mog2.set("detectShadows", false);
            foreground.release();

            for (int i = 0; i < nFrame; i++)
            {
                mog2(frame_buffer[i], foreground);
            }
        }
        SANITY_CHECK(foreground);
    }else if(RUN_OCL_IMPL)
    {
        prepareData(frame_buffer, frame_buffer_ocl);
        CV_Assert((int)(frame_buffer_ocl.size()) == nFrame);
        OCL_TEST_CYCLE()
        {
            cv::ocl::MOG2 d_mog2;
            foreground_d.release();
            for (int i = 0; i < nFrame; i++)
            {
                d_mog2(frame_buffer_ocl[i], foreground_d);
            }
        }
        foreground_d.download(foreground);
        SANITY_CHECK(foreground);
    }else
        OCL_PERF_ELSE
}
#endif

///////////// MOG2_GetBackgroundImage //////////////////
#if BUILD_WITH_VIDEO_INPUT_SUPPORT

typedef TestBaseWithParam<VideoMOG2ParamType> Video_MOG2GetBackgroundImage;

PERF_TEST_P(Video_MOG2GetBackgroundImage, MOG2,
            ::testing::Combine(::testing::Values("gpu/video/768x576.avi", "gpu/video/1920x1080.avi"),
            ::testing::Values(3)))
{
    VideoMOG2ParamType params = GetParam();

    const string inputFile = perf::TestBase::getDataPath(get<0>(params));
    const int cn = get<1>(params);
    int nFrame = 5;

    std::vector<cv::Mat> frame_buffer(nFrame);
    std::vector<cv::ocl::oclMat> frame_buffer_ocl;

    cv::VideoCapture cap(inputFile);
    ASSERT_TRUE(cap.isOpened());

    prepareData(cap, cn, frame_buffer);

    cv::Mat foreground;
    cv::Mat background;
    cv::ocl::oclMat foreground_d;
    cv::ocl::oclMat background_d;

    if(RUN_PLAIN_IMPL)
    {
        TEST_CYCLE()
        {
            cv::BackgroundSubtractorMOG2 mog2;
            mog2.set("detectShadows", false);
            foreground.release();
            background.release();
            for (int i = 0; i < nFrame; i++)
            {
                mog2(frame_buffer[i], foreground);
            }
            mog2.getBackgroundImage(background);
        }
        SANITY_CHECK(background);
    }else if(RUN_OCL_IMPL)
    {
        prepareData(frame_buffer, frame_buffer_ocl);
        CV_Assert((int)(frame_buffer_ocl.size()) == nFrame);
        OCL_TEST_CYCLE()
        {
            cv::ocl::MOG2 d_mog2;
            foreground_d.release();
            background_d.release();
            for (int i = 0; i < nFrame; i++)
            {
                d_mog2(frame_buffer_ocl[i], foreground_d);
            }
            d_mog2.getBackgroundImage(background_d);
        }
        background_d.download(background);
        SANITY_CHECK(background);
    }else
        OCL_PERF_ELSE
}
#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: mnemonic.cxx,v $
 *
 *  $Revision: 1.21 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 20:32:25 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#include <string.h>
#include <vcl/svapp.hxx>
#include <vcl/settings.hxx>
#include <vcl/mnemonic.hxx>

#include <vcl/unohelp.hxx>

#ifndef _COM_SUN_STAR_I18N_XCHARACTERCLASSIFICATION_HPP_
#include <com/sun/star/i18n/XCharacterClassification.hpp>
#endif

using namespace ::com::sun::star;

// =======================================================================

MnemonicGenerator::MnemonicGenerator()
{
    memset( maMnemonics, 1, sizeof( maMnemonics ) );
}

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

USHORT MnemonicGenerator::ImplGetMnemonicIndex( sal_Unicode c )
{
    static USHORT const aImplMnemonicRangeTab[MNEMONIC_RANGES*2] =
    {
        MNEMONIC_RANGE_1_START, MNEMONIC_RANGE_1_END,
        MNEMONIC_RANGE_2_START, MNEMONIC_RANGE_2_END,
        MNEMONIC_RANGE_3_START, MNEMONIC_RANGE_3_END,
        MNEMONIC_RANGE_4_START, MNEMONIC_RANGE_4_END
    };

    USHORT nMnemonicIndex = 0;
    for ( USHORT i = 0; i < MNEMONIC_RANGES; i++ )
    {
        if ( (c >= aImplMnemonicRangeTab[i*2]) &&
             (c <= aImplMnemonicRangeTab[i*2+1]) )
            return nMnemonicIndex+c-aImplMnemonicRangeTab[i*2];

        nMnemonicIndex += aImplMnemonicRangeTab[i*2+1]-aImplMnemonicRangeTab[i*2];
    }

    return MNEMONIC_INDEX_NOTFOUND;
}

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

sal_Unicode MnemonicGenerator::ImplFindMnemonic( const XubString& rKey )
{
    xub_StrLen nIndex = 0;
    while ( (nIndex = rKey.Search( MNEMONIC_CHAR, nIndex )) != STRING_NOTFOUND )
    {
        sal_Unicode cMnemonic = rKey.GetChar( nIndex+1 );
        if ( cMnemonic != MNEMONIC_CHAR )
            return cMnemonic;
        nIndex += 2;
    }

    return 0;
}

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

void MnemonicGenerator::RegisterMnemonic( const XubString& rKey )
{
    const ::com::sun::star::lang::Locale& rLocale = Application::GetSettings().GetUILocale();
    uno::Reference < i18n::XCharacterClassification > xCharClass = GetCharClass();

    // Don't crash even when we don't have access to i18n service
    if ( !xCharClass.is() )
        return;

    XubString aKey = xCharClass->toUpper( rKey, 0, rKey.Len(), rLocale );

    // If we find a Mnemonic, set the flag. In other case count the
    // characters, because we need this to set most as possible
    // Mnemonics
    sal_Unicode cMnemonic = ImplFindMnemonic( aKey );
    if ( cMnemonic )
    {
        USHORT nMnemonicIndex = ImplGetMnemonicIndex( cMnemonic );
        if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
            maMnemonics[nMnemonicIndex] = 0;
    }
    else
    {
        xub_StrLen nIndex = 0;
        xub_StrLen nLen = aKey.Len();
        while ( nIndex < nLen )
        {
            sal_Unicode c = aKey.GetChar( nIndex );

            USHORT nMnemonicIndex = ImplGetMnemonicIndex( c );
            if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
            {
                if ( maMnemonics[nMnemonicIndex] && (maMnemonics[nMnemonicIndex] < 0xFF) )
                    maMnemonics[nMnemonicIndex]++;
            }

            nIndex++;
        }
    }
}

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

BOOL MnemonicGenerator::CreateMnemonic( XubString& rKey )
{
    if ( !rKey.Len() || ImplFindMnemonic( rKey ) )
        return FALSE;

    const ::com::sun::star::lang::Locale& rLocale = Application::GetSettings().GetUILocale();
    uno::Reference < i18n::XCharacterClassification > xCharClass = GetCharClass();

    // Don't crash even when we don't have access to i18n service
    if ( !xCharClass.is() )
        return FALSE;

    XubString aKey = xCharClass->toUpper( rKey, 0, rKey.Len(), rLocale );

    BOOL bChanged = FALSE;
    xub_StrLen nLen = aKey.Len();

    BOOL bCJK = FALSE;
    switch( Application::GetSettings().GetUILanguage() )
    {
        case LANGUAGE_JAPANESE:
        case LANGUAGE_CHINESE_TRADITIONAL:
        case LANGUAGE_CHINESE_SIMPLIFIED:
        case LANGUAGE_CHINESE_HONGKONG:
        case LANGUAGE_CHINESE_SINGAPORE:
        case LANGUAGE_CHINESE_MACAU:
        case LANGUAGE_KOREAN:
        case LANGUAGE_KOREAN_JOHAB:
            bCJK = TRUE;
            break;
        default:
            break;
    }
    // #107889# in CJK versions ALL strings (even those that contain latin characters)
    // will get mnemonics in the form: xyz (M)
    // thus steps 1) and 2) are skipped for CJK locales

    // #110720#, avoid CJK-style mnemonics for latin-only strings that do not contain useful mnemonic chars
    if( bCJK )
    {
        BOOL bLatinOnly = TRUE;
        BOOL bMnemonicIndexFound = FALSE;
        sal_Unicode     c;
        xub_StrLen      nIndex;

        for( nIndex=0; nIndex < nLen; nIndex++ )
        {
            c = aKey.GetChar( nIndex );
            if ( ((c >= 0x3000) && (c <= 0xD7FF)) ||    // cjk
                 ((c >= 0xFF61) && (c <= 0xFFDC)) )     // halfwidth forms
            {
                bLatinOnly = FALSE;
                break;
            }
            if( ImplGetMnemonicIndex( c ) != MNEMONIC_INDEX_NOTFOUND )
                bMnemonicIndexFound = TRUE;
        }
        if( bLatinOnly && !bMnemonicIndexFound )
            return FALSE;
    }

    int             nCJK = 0;
    USHORT          nMnemonicIndex;
    sal_Unicode     c;
    xub_StrLen      nIndex = 0;
    if( !bCJK )
    {
        // 1) first try the first character of a word
        do
        {
            c = aKey.GetChar( nIndex );

            if ( nCJK != 2 )
            {
                if ( ((c >= 0x3000) && (c <= 0xD7FF)) ||    // cjk
                    ((c >= 0xFF61) && (c <= 0xFFDC)) )     // halfwidth forms
                    nCJK = 1;
                else if ( ((c >= 0x0030) && (c <= 0x0039)) || // digits
                        ((c >= 0x0041) && (c <= 0x005A)) || // latin capitals
                        ((c >= 0x0061) && (c <= 0x007A)) || // latin small
                        ((c >= 0x0370) && (c <= 0x037F)) || // greek numeral signs
                        ((c >= 0x0400) && (c <= 0x04FF)) )  // cyrillic
                    nCJK = 2;
            }

            nMnemonicIndex = ImplGetMnemonicIndex( c );
            if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
            {
                if ( maMnemonics[nMnemonicIndex] )
                {
                    maMnemonics[nMnemonicIndex] = 0;
                    rKey.Insert( MNEMONIC_CHAR, nIndex );
                    bChanged = TRUE;
                    break;
                }
            }

            // Search for next word
            do
            {
                nIndex++;
                c = aKey.GetChar( nIndex );
                if ( c == ' ' )
                    break;
            }
            while ( nIndex < nLen );
            nIndex++;
        }
        while ( nIndex < nLen );

        // 2) search for a unique/uncommon character
        if ( !bChanged )
        {
            USHORT      nBestCount = 0xFFFF;
            USHORT      nBestMnemonicIndex = 0;
            xub_StrLen  nBestIndex = 0;
            nIndex = 0;
            do
            {
                c = aKey.GetChar( nIndex );
                nMnemonicIndex = ImplGetMnemonicIndex( c );
                if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
                {
                    if ( maMnemonics[nMnemonicIndex] )
                    {
                        if ( maMnemonics[nMnemonicIndex] < nBestCount )
                        {
                            nBestCount = maMnemonics[nMnemonicIndex];
                            nBestIndex = nIndex;
                            nBestMnemonicIndex = nMnemonicIndex;
                            if ( nBestCount == 2 )
                                break;
                        }
                    }
                }

                nIndex++;
            }
            while ( nIndex < nLen );

            if ( nBestCount != 0xFFFF )
            {
                maMnemonics[nBestMnemonicIndex] = 0;
                rKey.Insert( MNEMONIC_CHAR, nBestIndex );
                bChanged = TRUE;
            }
        }
    }
    else
        nCJK = 1;

    // 3) Add English Mnemonic for CJK Text
    if ( !bChanged && (nCJK == 1) && rKey.Len() )
    {
        // Append Ascii Mnemonic
        for ( c = MNEMONIC_RANGE_2_START; c <= MNEMONIC_RANGE_2_END; c++ )
        {
            nMnemonicIndex = ImplGetMnemonicIndex( c );
            if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
            {
                if ( maMnemonics[nMnemonicIndex] )
                {
                    maMnemonics[nMnemonicIndex] = 0;
                    UniString aStr( '(' );
                    aStr += MNEMONIC_CHAR;
                    aStr += c;
                    aStr += ')';
                    nIndex = rKey.Len();
                    if( nIndex >= 2 )
                    {
                        static sal_Unicode cGreaterGreater[] = { 0xFF1E, 0xFF1E };
                        if ( rKey.EqualsAscii( ">>", nIndex-2, 2 ) ||
                            rKey.Equals( cGreaterGreater, nIndex-2, 2 ) )
                            nIndex -= 2;
                    }
                    if( nIndex >= 3 )
                    {
                        static sal_Unicode cDotDotDot[] = { 0xFF0E, 0xFF0E, 0xFF0E };
                        if ( rKey.EqualsAscii( "...", nIndex-3, 3 ) ||
                            rKey.Equals( cDotDotDot, nIndex-3, 3 ) )
                            nIndex -= 3;
                    }
                    if( nIndex >= 1)
                    {
                        sal_Unicode cLastChar = rKey.GetChar( nIndex-1 );
                        if ( (cLastChar == ':') || (cLastChar == 0xFF1A) ||
                            (cLastChar == '.') || (cLastChar == 0xFF0E) ||
                            (cLastChar == '?') || (cLastChar == 0xFF1F) ||
                            (cLastChar == ' ') )
                            nIndex--;
                    }
                    rKey.Insert( aStr, nIndex );
                    bChanged = TRUE;
                    break;
                }
            }
        }
    }

    if( ! bChanged )
    {
        /*
         *  #97809# if all else fails use the first character of a word
         *  anyway and live with duplicate mnemonics
         */
        nIndex = 0;
        do
        {
            c = aKey.GetChar( nIndex );

            nMnemonicIndex = ImplGetMnemonicIndex( c );
            if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
            {
                maMnemonics[nMnemonicIndex] = 0;
                rKey.Insert( MNEMONIC_CHAR, nIndex );
                bChanged = TRUE;
                break;
            }

            // Search for next word
            do
            {
                nIndex++;
                c = aKey.GetChar( nIndex );
                if ( c == ' ' )
                    break;
            }
            while ( nIndex < nLen );
            nIndex++;
        }
        while ( nIndex < nLen );
    }

    return bChanged;
}

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

uno::Reference< i18n::XCharacterClassification > MnemonicGenerator::GetCharClass()
{
    if ( !mxCharClass.is() )
        mxCharClass = vcl::unohelper::CreateCharacterClassification();
    return mxCharClass;
}

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

String MnemonicGenerator::EraseAllMnemonicChars( const String& rStr )
{
    String      aStr = rStr;
    xub_StrLen  nLen = aStr.Len();
    xub_StrLen  i    = 0;

    while ( i < nLen )
    {
        if ( aStr.GetChar( i ) == '~' )
        {
            // check for CJK-style mnemonic
            if( i > 0 && (i+2) < nLen )
            {
                sal_Unicode c = aStr.GetChar(i+1);
                if( aStr.GetChar( i-1 ) == '(' &&
                    aStr.GetChar( i+2 ) == ')' &&
                    c >= MNEMONIC_RANGE_2_START && c <= MNEMONIC_RANGE_2_END )
                {
                    aStr.Erase( i-1, 4 );
                    nLen -= 4;
                    i--;
                    continue;
                }
            }

            // remove standard mnemonics
            aStr.Erase( i, 1 );
            nLen--;
        }
        else
            i++;
    }

    return aStr;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.21.248); FILE MERGED 2008/04/01 13:01:47 thb 1.21.248.2: #i85898# Stripping all external header guards 2008/03/28 15:45:02 rt 1.21.248.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: mnemonic.cxx,v $
 * $Revision: 1.22 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#include <string.h>
#include <vcl/svapp.hxx>
#include <vcl/settings.hxx>
#include <vcl/mnemonic.hxx>

#include <vcl/unohelp.hxx>
#include <com/sun/star/i18n/XCharacterClassification.hpp>

using namespace ::com::sun::star;

// =======================================================================

MnemonicGenerator::MnemonicGenerator()
{
    memset( maMnemonics, 1, sizeof( maMnemonics ) );
}

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

USHORT MnemonicGenerator::ImplGetMnemonicIndex( sal_Unicode c )
{
    static USHORT const aImplMnemonicRangeTab[MNEMONIC_RANGES*2] =
    {
        MNEMONIC_RANGE_1_START, MNEMONIC_RANGE_1_END,
        MNEMONIC_RANGE_2_START, MNEMONIC_RANGE_2_END,
        MNEMONIC_RANGE_3_START, MNEMONIC_RANGE_3_END,
        MNEMONIC_RANGE_4_START, MNEMONIC_RANGE_4_END
    };

    USHORT nMnemonicIndex = 0;
    for ( USHORT i = 0; i < MNEMONIC_RANGES; i++ )
    {
        if ( (c >= aImplMnemonicRangeTab[i*2]) &&
             (c <= aImplMnemonicRangeTab[i*2+1]) )
            return nMnemonicIndex+c-aImplMnemonicRangeTab[i*2];

        nMnemonicIndex += aImplMnemonicRangeTab[i*2+1]-aImplMnemonicRangeTab[i*2];
    }

    return MNEMONIC_INDEX_NOTFOUND;
}

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

sal_Unicode MnemonicGenerator::ImplFindMnemonic( const XubString& rKey )
{
    xub_StrLen nIndex = 0;
    while ( (nIndex = rKey.Search( MNEMONIC_CHAR, nIndex )) != STRING_NOTFOUND )
    {
        sal_Unicode cMnemonic = rKey.GetChar( nIndex+1 );
        if ( cMnemonic != MNEMONIC_CHAR )
            return cMnemonic;
        nIndex += 2;
    }

    return 0;
}

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

void MnemonicGenerator::RegisterMnemonic( const XubString& rKey )
{
    const ::com::sun::star::lang::Locale& rLocale = Application::GetSettings().GetUILocale();
    uno::Reference < i18n::XCharacterClassification > xCharClass = GetCharClass();

    // Don't crash even when we don't have access to i18n service
    if ( !xCharClass.is() )
        return;

    XubString aKey = xCharClass->toUpper( rKey, 0, rKey.Len(), rLocale );

    // If we find a Mnemonic, set the flag. In other case count the
    // characters, because we need this to set most as possible
    // Mnemonics
    sal_Unicode cMnemonic = ImplFindMnemonic( aKey );
    if ( cMnemonic )
    {
        USHORT nMnemonicIndex = ImplGetMnemonicIndex( cMnemonic );
        if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
            maMnemonics[nMnemonicIndex] = 0;
    }
    else
    {
        xub_StrLen nIndex = 0;
        xub_StrLen nLen = aKey.Len();
        while ( nIndex < nLen )
        {
            sal_Unicode c = aKey.GetChar( nIndex );

            USHORT nMnemonicIndex = ImplGetMnemonicIndex( c );
            if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
            {
                if ( maMnemonics[nMnemonicIndex] && (maMnemonics[nMnemonicIndex] < 0xFF) )
                    maMnemonics[nMnemonicIndex]++;
            }

            nIndex++;
        }
    }
}

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

BOOL MnemonicGenerator::CreateMnemonic( XubString& rKey )
{
    if ( !rKey.Len() || ImplFindMnemonic( rKey ) )
        return FALSE;

    const ::com::sun::star::lang::Locale& rLocale = Application::GetSettings().GetUILocale();
    uno::Reference < i18n::XCharacterClassification > xCharClass = GetCharClass();

    // Don't crash even when we don't have access to i18n service
    if ( !xCharClass.is() )
        return FALSE;

    XubString aKey = xCharClass->toUpper( rKey, 0, rKey.Len(), rLocale );

    BOOL bChanged = FALSE;
    xub_StrLen nLen = aKey.Len();

    BOOL bCJK = FALSE;
    switch( Application::GetSettings().GetUILanguage() )
    {
        case LANGUAGE_JAPANESE:
        case LANGUAGE_CHINESE_TRADITIONAL:
        case LANGUAGE_CHINESE_SIMPLIFIED:
        case LANGUAGE_CHINESE_HONGKONG:
        case LANGUAGE_CHINESE_SINGAPORE:
        case LANGUAGE_CHINESE_MACAU:
        case LANGUAGE_KOREAN:
        case LANGUAGE_KOREAN_JOHAB:
            bCJK = TRUE;
            break;
        default:
            break;
    }
    // #107889# in CJK versions ALL strings (even those that contain latin characters)
    // will get mnemonics in the form: xyz (M)
    // thus steps 1) and 2) are skipped for CJK locales

    // #110720#, avoid CJK-style mnemonics for latin-only strings that do not contain useful mnemonic chars
    if( bCJK )
    {
        BOOL bLatinOnly = TRUE;
        BOOL bMnemonicIndexFound = FALSE;
        sal_Unicode     c;
        xub_StrLen      nIndex;

        for( nIndex=0; nIndex < nLen; nIndex++ )
        {
            c = aKey.GetChar( nIndex );
            if ( ((c >= 0x3000) && (c <= 0xD7FF)) ||    // cjk
                 ((c >= 0xFF61) && (c <= 0xFFDC)) )     // halfwidth forms
            {
                bLatinOnly = FALSE;
                break;
            }
            if( ImplGetMnemonicIndex( c ) != MNEMONIC_INDEX_NOTFOUND )
                bMnemonicIndexFound = TRUE;
        }
        if( bLatinOnly && !bMnemonicIndexFound )
            return FALSE;
    }

    int             nCJK = 0;
    USHORT          nMnemonicIndex;
    sal_Unicode     c;
    xub_StrLen      nIndex = 0;
    if( !bCJK )
    {
        // 1) first try the first character of a word
        do
        {
            c = aKey.GetChar( nIndex );

            if ( nCJK != 2 )
            {
                if ( ((c >= 0x3000) && (c <= 0xD7FF)) ||    // cjk
                    ((c >= 0xFF61) && (c <= 0xFFDC)) )     // halfwidth forms
                    nCJK = 1;
                else if ( ((c >= 0x0030) && (c <= 0x0039)) || // digits
                        ((c >= 0x0041) && (c <= 0x005A)) || // latin capitals
                        ((c >= 0x0061) && (c <= 0x007A)) || // latin small
                        ((c >= 0x0370) && (c <= 0x037F)) || // greek numeral signs
                        ((c >= 0x0400) && (c <= 0x04FF)) )  // cyrillic
                    nCJK = 2;
            }

            nMnemonicIndex = ImplGetMnemonicIndex( c );
            if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
            {
                if ( maMnemonics[nMnemonicIndex] )
                {
                    maMnemonics[nMnemonicIndex] = 0;
                    rKey.Insert( MNEMONIC_CHAR, nIndex );
                    bChanged = TRUE;
                    break;
                }
            }

            // Search for next word
            do
            {
                nIndex++;
                c = aKey.GetChar( nIndex );
                if ( c == ' ' )
                    break;
            }
            while ( nIndex < nLen );
            nIndex++;
        }
        while ( nIndex < nLen );

        // 2) search for a unique/uncommon character
        if ( !bChanged )
        {
            USHORT      nBestCount = 0xFFFF;
            USHORT      nBestMnemonicIndex = 0;
            xub_StrLen  nBestIndex = 0;
            nIndex = 0;
            do
            {
                c = aKey.GetChar( nIndex );
                nMnemonicIndex = ImplGetMnemonicIndex( c );
                if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
                {
                    if ( maMnemonics[nMnemonicIndex] )
                    {
                        if ( maMnemonics[nMnemonicIndex] < nBestCount )
                        {
                            nBestCount = maMnemonics[nMnemonicIndex];
                            nBestIndex = nIndex;
                            nBestMnemonicIndex = nMnemonicIndex;
                            if ( nBestCount == 2 )
                                break;
                        }
                    }
                }

                nIndex++;
            }
            while ( nIndex < nLen );

            if ( nBestCount != 0xFFFF )
            {
                maMnemonics[nBestMnemonicIndex] = 0;
                rKey.Insert( MNEMONIC_CHAR, nBestIndex );
                bChanged = TRUE;
            }
        }
    }
    else
        nCJK = 1;

    // 3) Add English Mnemonic for CJK Text
    if ( !bChanged && (nCJK == 1) && rKey.Len() )
    {
        // Append Ascii Mnemonic
        for ( c = MNEMONIC_RANGE_2_START; c <= MNEMONIC_RANGE_2_END; c++ )
        {
            nMnemonicIndex = ImplGetMnemonicIndex( c );
            if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
            {
                if ( maMnemonics[nMnemonicIndex] )
                {
                    maMnemonics[nMnemonicIndex] = 0;
                    UniString aStr( '(' );
                    aStr += MNEMONIC_CHAR;
                    aStr += c;
                    aStr += ')';
                    nIndex = rKey.Len();
                    if( nIndex >= 2 )
                    {
                        static sal_Unicode cGreaterGreater[] = { 0xFF1E, 0xFF1E };
                        if ( rKey.EqualsAscii( ">>", nIndex-2, 2 ) ||
                            rKey.Equals( cGreaterGreater, nIndex-2, 2 ) )
                            nIndex -= 2;
                    }
                    if( nIndex >= 3 )
                    {
                        static sal_Unicode cDotDotDot[] = { 0xFF0E, 0xFF0E, 0xFF0E };
                        if ( rKey.EqualsAscii( "...", nIndex-3, 3 ) ||
                            rKey.Equals( cDotDotDot, nIndex-3, 3 ) )
                            nIndex -= 3;
                    }
                    if( nIndex >= 1)
                    {
                        sal_Unicode cLastChar = rKey.GetChar( nIndex-1 );
                        if ( (cLastChar == ':') || (cLastChar == 0xFF1A) ||
                            (cLastChar == '.') || (cLastChar == 0xFF0E) ||
                            (cLastChar == '?') || (cLastChar == 0xFF1F) ||
                            (cLastChar == ' ') )
                            nIndex--;
                    }
                    rKey.Insert( aStr, nIndex );
                    bChanged = TRUE;
                    break;
                }
            }
        }
    }

    if( ! bChanged )
    {
        /*
         *  #97809# if all else fails use the first character of a word
         *  anyway and live with duplicate mnemonics
         */
        nIndex = 0;
        do
        {
            c = aKey.GetChar( nIndex );

            nMnemonicIndex = ImplGetMnemonicIndex( c );
            if ( nMnemonicIndex != MNEMONIC_INDEX_NOTFOUND )
            {
                maMnemonics[nMnemonicIndex] = 0;
                rKey.Insert( MNEMONIC_CHAR, nIndex );
                bChanged = TRUE;
                break;
            }

            // Search for next word
            do
            {
                nIndex++;
                c = aKey.GetChar( nIndex );
                if ( c == ' ' )
                    break;
            }
            while ( nIndex < nLen );
            nIndex++;
        }
        while ( nIndex < nLen );
    }

    return bChanged;
}

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

uno::Reference< i18n::XCharacterClassification > MnemonicGenerator::GetCharClass()
{
    if ( !mxCharClass.is() )
        mxCharClass = vcl::unohelper::CreateCharacterClassification();
    return mxCharClass;
}

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

String MnemonicGenerator::EraseAllMnemonicChars( const String& rStr )
{
    String      aStr = rStr;
    xub_StrLen  nLen = aStr.Len();
    xub_StrLen  i    = 0;

    while ( i < nLen )
    {
        if ( aStr.GetChar( i ) == '~' )
        {
            // check for CJK-style mnemonic
            if( i > 0 && (i+2) < nLen )
            {
                sal_Unicode c = aStr.GetChar(i+1);
                if( aStr.GetChar( i-1 ) == '(' &&
                    aStr.GetChar( i+2 ) == ')' &&
                    c >= MNEMONIC_RANGE_2_START && c <= MNEMONIC_RANGE_2_END )
                {
                    aStr.Erase( i-1, 4 );
                    nLen -= 4;
                    i--;
                    continue;
                }
            }

            // remove standard mnemonics
            aStr.Erase( i, 1 );
            nLen--;
        }
        else
            i++;
    }

    return aStr;
}
<|endoftext|>


<commit_before>
#include <imgui.cpp>
<commit_msg>Include all imgui files<commit_after>
#include <imgui.cpp>
#include <imgui_draw.cpp>
#include <imgui_demo.cpp>
<|endoftext|>


<commit_before><commit_msg>init members in correct order<commit_after><|endoftext|>