<commit_before>#include <stdexcept>
#include <limits>
#include <algorithm>
#include <array>
#include <iomanip>
#include <curl/curl.h>
#include <memory>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <system_error>
#include <openssl/md5.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>

const std::string listing("http://nwn.efupw.com/rootdir/index.dat");
const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/");

const std::string file_checksum(const std::string &path);

size_t writefunction(const char *ptr, size_t size, size_t nmemb, void *userdata)
{
    std::string *s = static_cast<std::string *>(userdata);
    s->append(ptr, size * nmemb);
    return size * nmemb;
}

class CurlEasyException : public std::runtime_error
{
    public:
        CurlEasyException(const std::string &msg):
            std::runtime_error(msg) {}

        CurlEasyException(CURLcode c):
            std::runtime_error(curl_easy_strerror(c)) {}
};

class CurlEasy
{
    public:
        CurlEasy(const std::string &url):
            m_pcurl(std::make_shared<CURL *>(curl_easy_init()))
        {
            if (!*m_pcurl)
            {
                throw CurlEasyException("curl handle not properly initialized.");
            }

            if (url.empty())
            {
                throw CurlEasyException("Empty URL.");
            }

            CURLcode c = curl_easy_setopt(*m_pcurl, CURLOPT_URL, url.c_str());
            if (c != CURLE_OK)
            {
                throw CurlEasyException(c);
            }
        }

        ~CurlEasy()
        {
            if (*m_pcurl)
            {
                curl_easy_cleanup(*m_pcurl);
            }
        }

        void perform()
        {
            CURLcode c = curl_easy_perform(*m_pcurl);
            if (c != CURLE_OK)
            {
                throw CurlEasyException(c);
            }
        }

        void write_to(const std::string &dest)
        {
            CURLcode c = curl_easy_setopt(*m_pcurl,
                    CURLOPT_WRITEFUNCTION, &writefunction);

            if (c != CURLE_OK)
            {
                throw CurlEasyException(c);
            }

            c = curl_easy_setopt(*m_pcurl,
                    CURLOPT_WRITEDATA, &dest);

            if (c != CURLE_OK)
            {
                throw CurlEasyException(c);
            }
        }

    private:
        std::shared_ptr<CURL *> m_pcurl;
};

std::vector<std::string> &split(const std::string &s, char delim,
        std::vector<std::string> &elems)
{
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim))
    {
        elems.push_back(item);
    }
    return elems;
}

std::vector<std::string> split(const std::string &s, char delim)
{
    std::vector<std::string> elems;
    return split(s, delim, elems);
}

class Target
{
    public:
        enum class Status {
            Nonexistent,
            Outdated,
            Current
        };
        explicit Target(const std::string &name, const std::string &checksum):
            m_name(name.find_first_of('/') == std::string::npos ? name :
                    name, name.find_first_of('/') + 1, name.size() - 1),
            m_checksum(checksum)
            {}
        std::string name() const { return m_name; }
        const std::string checksum() const { return m_checksum; }

        void fetch()
        {
            std::cout << "Statting target " << name() << "...";
            std::string path;
            std::fstream fs(name(), std::ios_base::in);
            if (!fs.good())
            {
                fs.close();
                std::cout << " doesn't exist, creating new." << std::endl;
                auto elems = split(name(), '/');
                for (size_t i = 0, k = elems.size(); i < k; ++i)
                {
                    const std::string &s(elems[i]);
                    if (s.size() && s != ".")
                    {
                        path.append((i > 0 ? "/" : "") + s);
                        // i indicates a directory.
                        if (i < k - 1)
                        {
                            auto status = mkdir(path.c_str(), S_IRWXU);
                            if (status == -1)
                            {
                                std::error_code err(errno, std::generic_category());
                                if (err != std::errc::file_exists)
                                {
                                    std::cout << "error making dir: "
                                        << path << ": "
                                        << err.message() << std::endl;
                                }
                            }
                        }
                    }
                }
                fs.open(path, std::ios_base::out);
                if (!fs.good())
                {
                    fs.close();
                    std::cout << "Failed to create file: " << path << std::endl;
                }
                else
                {
                    fs.close();
                    do_fetch();
                    return;
                }
            }
            if (fs.good())
            {
                fs.close();
                if (status() == Status::Current)
                {
                    std::cout << " already up to date." << std::endl;
                }
                else
                {
                    std::cout << " outdated, downloading new." << std::endl;
                    do_fetch();
                }
            }
        }
        Status status()
        {
            std::ifstream is(name());
            if (!is.good())
            {
                return Status::Nonexistent;
            }
            is.close();
            auto calcsum(file_checksum(name()));
            if (calcsum == checksum())
            {
                return Status::Current;
            }
            else
            {
                return Status::Outdated;
            }
        }

    private:
        void do_fetch()
        {
            std::string s;
            std::string url(patch_dir + name());
            CurlEasy curl(CurlEasy::Builder(url)
                .with_writeto(s)
                .build());
            /*
            std::shared_ptr<CURL *> phandle =
                std::make_shared<CURL *>(curl_easy_init());
            curl_easy_setopt(*phandle, CURLOPT_URL, url.c_str());
            curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction);
            curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &s);
            //curl_easy_setopt(*phandle, CURLOPT_NOPROGRESS, 0);
            curl_easy_perform(*phandle);
            curl_easy_cleanup(*phandle);
            phandle.reset();
            */
            std::ofstream ofs(name());
            if (ofs.good())
            {
                ofs << s;
                ofs.close();
                std::cout << "Finished downloading " << name() << std::endl;
            }
            else
            {
                std::cout << "Couldn't write to " << name() << std::endl;
            }
        }

        std::string m_name;
        std::string m_checksum;
};

std::ostream& operator<<(std::ostream &os, const Target &t)
{
    return os << "name: " << t.name() << ", checksum: " << t.checksum();
}

class CurlGlobalInit
{
    public:
        CurlGlobalInit()
        {
            curl_global_init(CURL_GLOBAL_ALL);
        }

        ~CurlGlobalInit()
        {
            curl_global_cleanup();
        }
};

const std::string file_checksum(const std::string &path)
{
#ifdef md_md5
    auto md = EVP_md5();
    const int md_len = MD5_DIGEST_LENGTH;
#else
    auto md = EVP_sha1();
    const int md_len = SHA_DIGEST_LENGTH;
#endif
    std::array<unsigned char, md_len> result;
    EVP_MD_CTX *mdctx = nullptr;
    std::ifstream is(path, std::ifstream::binary);
    if (!is.good())
    {
        std::cout << "Couldn't open file " << path
           << " for checksumming." << std::endl;
        return std::string();
    }

    const int length = 8192;
    std::array<unsigned char, length> buffer;
    auto buf = reinterpret_cast<char *>(buffer.data());
    mdctx = EVP_MD_CTX_create();
    int status = EVP_DigestInit_ex(mdctx, md, nullptr);
    while (status && is)
    {
        is.read(buf, length);
        status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount());
    }
    status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr);
    EVP_MD_CTX_destroy(mdctx);
    std::stringstream calcsum;
    calcsum << std::setfill('0');

    for (unsigned char c : result)
    {
        calcsum << std::hex << std::setw(2)
            << static_cast<unsigned int>(c);
    }
    /*
    std::for_each(std::begin(result), std::end(result),
            [&calcsum](unsigned char c)
            {
            calcsum << std::hex << std::setw(2)
            << static_cast<unsigned int>(c);
            });
            */

    return calcsum.str();
}

namespace Options
{
    bool checksum(const std::string &val)
    {
        return val == "checksum";
    }
};

bool confirm()
{
    char c;
    do
    {
        std::cin >> c;
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        c = tolower(c);
    } while (c != 'y' && c != 'n');
    return c == 'y';
}

class EfuLauncher
{
    public:
        explicit EfuLauncher(const std::string path, const std::string update_check):
            m_path(path), m_update_check(update_check), m_has_update(false)
    {}

        bool has_update()
        {
            std::string fetch;
            auto phandle(std::make_shared<CURL*>(curl_easy_init()));
            curl_easy_setopt(*phandle, CURLOPT_URL, m_update_check.c_str());
            curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction);
            curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &fetch);
            curl_easy_perform(*phandle);
            curl_easy_cleanup(*phandle);

            std::vector<std::string> lines(split(fetch, '\n'));
            fetch.clear();
            for (auto beg = std::begin(lines), end = std::end(lines);
                    beg != end; ++beg)
            {
                auto keyvals(split(*beg, '='));
                if (keyvals.size() != 2)
                {
                    std::cerr << "Malformed option: " + *beg +
                        ", aborting launcher update check." << std::endl;
                    return m_has_update = false;
                }
                if (Options::checksum(keyvals[0]))
                {
                    const std::string checksum_test(keyvals[1]);
                    m_has_update = checksum_test != file_checksum(path());
                }
            }
            return m_has_update;
        }

    private:
        const std::string path() const { return m_path; }

        const std::string m_path;
        const std::string m_update_check;
        bool m_has_update;
};

int main(int argc, char *argv[])
{
    CurlGlobalInit curl_global;

    EfuLauncher l(argv[0],
            "https://raw.github.com/commonquail/efulauncher/"\
            "updatecheck/versioncheck");
    if (l.has_update())
    {
        std::cout << "A new version of the launcher is available."\
            " Would you like to download it (y/n)?" << std::endl;
        bool download(confirm());
        if (!download)
        {
            std::cout << "It is strongly recommended to always use"\
                " the latest launcher. Would you like to download it (y/n)?"
                << std::endl;
            download = confirm();
        }
        if (download)
        {
            // Download.
            std::cout << "Downloading new launcher..." << std::endl;
            std::cout << "Done." << std::endl;
        }
    }

    std::string fetch;
            CurlEasy curl(CurlEasy::Builder(listing)
                .with_writeto(fetch)
                .build());
            curl.perform();

            /*
    auto phandle(std::make_shared<CURL *>(curl_easy_init()));
    curl_easy_setopt(*phandle, CURLOPT_URL, listing.c_str());
    curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction);
    curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &fetch);
    curl_easy_perform(*phandle);
    curl_easy_cleanup(*phandle);
    phandle.reset();
    */

    auto lines(split(fetch, '\n'));
    std::vector<Target> new_targets, old_targets;
    for (auto beg = std::begin(lines), end = std::end(lines);
            beg != end; ++beg)
    {
        auto data(split(*beg, '@'));
        Target t(data[0], data[data.size() - 1]);
        auto status = t.status();
        if (status == Target::Status::Nonexistent)
        {
            new_targets.push_back(std::move(t));
        }
        else if (status == Target::Status::Outdated)
        {
            old_targets.push_back(std::move(t));
        }
    }
    if (new_targets.size())
    {
        std::cout << "New targets: " << new_targets.size() << std::endl;
        for (auto &t : new_targets)
        {
            std::cout << "- " << t.name() << std::endl;
        }
    }
    else
    {
        std::cout << "No new targets." << std::endl;
    }

    if (old_targets.size())
    {
        std::cout << "Outdated targets: " << old_targets.size() << std::endl;
        for (auto &t : old_targets)
        {
            std::cout << "- " << t.name() << std::endl;
        }
    }
    else
    {
        std::cout << "No targets out of date." << std::endl;
    }

#ifndef DEBUG
    for (auto &t : new_targets)
    {
        t.fetch();
    }
    for (auto &t : old_targets)
    {
        t.fetch();
    }
#endif

    return 0;
}
<commit_msg>Use the new curl wrapper.<commit_after>#include <stdexcept>
#include <limits>
#include <algorithm>
#include <array>
#include <iomanip>
#include <curl/curl.h>
#include <memory>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <system_error>
#include <openssl/md5.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>

const std::string listing("http://nwn.efupw.com/rootdir/index.dat");
const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/");

const std::string file_checksum(const std::string &path);

size_t writefunction(const char *ptr, size_t size, size_t nmemb, void *userdata)
{
    std::string *s = static_cast<std::string *>(userdata);
    s->append(ptr, size * nmemb);
    return size * nmemb;
}

class CurlEasyException : public std::runtime_error
{
    public:
        CurlEasyException(const std::string &msg):
            std::runtime_error(msg) {}

        CurlEasyException(CURLcode c):
            std::runtime_error(curl_easy_strerror(c)) {}
};

class CurlEasy
{
    public:
        CurlEasy(const std::string &url):
            m_pcurl(std::make_shared<CURL *>(curl_easy_init()))
        {
            if (!*m_pcurl)
            {
                throw CurlEasyException("curl handle not properly initialized.");
            }

            if (url.empty())
            {
                throw CurlEasyException("Empty URL.");
            }

            CURLcode c = curl_easy_setopt(*m_pcurl, CURLOPT_URL, url.c_str());
            if (c != CURLE_OK)
            {
                throw CurlEasyException(c);
            }
        }

        ~CurlEasy()
        {
            if (*m_pcurl)
            {
                curl_easy_cleanup(*m_pcurl);
            }
        }

        void perform()
        {
            CURLcode c = curl_easy_perform(*m_pcurl);
            if (c != CURLE_OK)
            {
                throw CurlEasyException(c);
            }
        }

        void write_to(const std::string &dest)
        {
            CURLcode c = curl_easy_setopt(*m_pcurl,
                    CURLOPT_WRITEFUNCTION, &writefunction);

            if (c != CURLE_OK)
            {
                throw CurlEasyException(c);
            }

            c = curl_easy_setopt(*m_pcurl,
                    CURLOPT_WRITEDATA, &dest);

            if (c != CURLE_OK)
            {
                throw CurlEasyException(c);
            }
        }

    private:
        std::shared_ptr<CURL *> m_pcurl;
};

std::vector<std::string> &split(const std::string &s, char delim,
        std::vector<std::string> &elems)
{
    std::stringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim))
    {
        elems.push_back(item);
    }
    return elems;
}

std::vector<std::string> split(const std::string &s, char delim)
{
    std::vector<std::string> elems;
    return split(s, delim, elems);
}

class Target
{
    public:
        enum class Status {
            Nonexistent,
            Outdated,
            Current
        };
        explicit Target(const std::string &name, const std::string &checksum):
            m_name(name.find_first_of('/') == std::string::npos ? name :
                    name, name.find_first_of('/') + 1, name.size() - 1),
            m_checksum(checksum)
            {}
        std::string name() const { return m_name; }
        const std::string checksum() const { return m_checksum; }

        void fetch()
        {
            std::cout << "Statting target " << name() << "...";
            std::string path;
            std::fstream fs(name(), std::ios_base::in);
            if (!fs.good())
            {
                fs.close();
                std::cout << " doesn't exist, creating new." << std::endl;
                auto elems = split(name(), '/');
                for (size_t i = 0, k = elems.size(); i < k; ++i)
                {
                    const std::string &s(elems[i]);
                    if (s.size() && s != ".")
                    {
                        path.append((i > 0 ? "/" : "") + s);
                        // i indicates a directory.
                        if (i < k - 1)
                        {
                            auto status = mkdir(path.c_str(), S_IRWXU);
                            if (status == -1)
                            {
                                std::error_code err(errno, std::generic_category());
                                if (err != std::errc::file_exists)
                                {
                                    std::cout << "error making dir: "
                                        << path << ": "
                                        << err.message() << std::endl;
                                }
                            }
                        }
                    }
                }
                fs.open(path, std::ios_base::out);
                if (!fs.good())
                {
                    fs.close();
                    std::cout << "Failed to create file: " << path << std::endl;
                }
                else
                {
                    fs.close();
                    do_fetch();
                    return;
                }
            }
            if (fs.good())
            {
                fs.close();
                if (status() == Status::Current)
                {
                    std::cout << " already up to date." << std::endl;
                }
                else
                {
                    std::cout << " outdated, downloading new." << std::endl;
                    do_fetch();
                }
            }
        }
        Status status()
        {
            std::ifstream is(name());
            if (!is.good())
            {
                return Status::Nonexistent;
            }
            is.close();
            auto calcsum(file_checksum(name()));
            if (calcsum == checksum())
            {
                return Status::Current;
            }
            else
            {
                return Status::Outdated;
            }
        }

    private:
        void do_fetch()
        {
            std::string s;
            std::string url(patch_dir + name());
            CurlEasy curl(url);
            curl.write_to(s);
            curl.perform();
            std::ofstream ofs(name());

            if (ofs.good())
            {
                ofs << s;
                ofs.close();
                std::cout << "Finished downloading " << name() << std::endl;
            }
            else
            {
                std::cout << "Couldn't write to " << name() << std::endl;
            }
        }

        std::string m_name;
        std::string m_checksum;
};

std::ostream& operator<<(std::ostream &os, const Target &t)
{
    return os << "name: " << t.name() << ", checksum: " << t.checksum();
}

class CurlGlobalInit
{
    public:
        CurlGlobalInit()
        {
            curl_global_init(CURL_GLOBAL_ALL);
        }

        ~CurlGlobalInit()
        {
            curl_global_cleanup();
        }
};

const std::string file_checksum(const std::string &path)
{
#ifdef md_md5
    auto md = EVP_md5();
    const int md_len = MD5_DIGEST_LENGTH;
#else
    auto md = EVP_sha1();
    const int md_len = SHA_DIGEST_LENGTH;
#endif
    std::array<unsigned char, md_len> result;
    EVP_MD_CTX *mdctx = nullptr;
    std::ifstream is(path, std::ifstream::binary);
    if (!is.good())
    {
        std::cout << "Couldn't open file " << path
           << " for checksumming." << std::endl;
        return std::string();
    }

    const int length = 8192;
    std::array<unsigned char, length> buffer;
    auto buf = reinterpret_cast<char *>(buffer.data());
    mdctx = EVP_MD_CTX_create();
    int status = EVP_DigestInit_ex(mdctx, md, nullptr);
    while (status && is)
    {
        is.read(buf, length);
        status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount());
    }
    status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr);
    EVP_MD_CTX_destroy(mdctx);
    std::stringstream calcsum;
    calcsum << std::setfill('0');

    for (unsigned char c : result)
    {
        calcsum << std::hex << std::setw(2)
            << static_cast<unsigned int>(c);
    }
    /*
    std::for_each(std::begin(result), std::end(result),
            [&calcsum](unsigned char c)
            {
            calcsum << std::hex << std::setw(2)
            << static_cast<unsigned int>(c);
            });
            */

    return calcsum.str();
}

namespace Options
{
    bool checksum(const std::string &val)
    {
        return val == "checksum";
    }
};

bool confirm()
{
    char c;
    do
    {
        std::cin >> c;
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        c = tolower(c);
    } while (c != 'y' && c != 'n');
    return c == 'y';
}

class EfuLauncher
{
    public:
        explicit EfuLauncher(const std::string path, const std::string update_check):
            m_path(path), m_update_check(update_check), m_has_update(false)
    {}

        bool has_update()
        {
            std::string fetch;
            CurlEasy curl(m_update_check.c_str());
            curl.write_to(fetch);
            curl.perform();

            std::vector<std::string> lines(split(fetch, '\n'));
            fetch.clear();
            for (auto beg = std::begin(lines), end = std::end(lines);
                    beg != end; ++beg)
            {
                auto keyvals(split(*beg, '='));
                if (keyvals.size() != 2)
                {
                    std::cerr << "Malformed option: " + *beg +
                        ", aborting launcher update check." << std::endl;
                    return m_has_update = false;
                }
                if (Options::checksum(keyvals[0]))
                {
                    const std::string checksum_test(keyvals[1]);
                    m_has_update = checksum_test != file_checksum(path());
                }
            }
            return m_has_update;
        }

    private:
        const std::string path() const { return m_path; }

        const std::string m_path;
        const std::string m_update_check;
        bool m_has_update;
};

int main(int argc, char *argv[])
{
    CurlGlobalInit curl_global;

    EfuLauncher l(argv[0],
            "https://raw.github.com/commonquail/efulauncher/"\
            "updatecheck/versioncheck");
    if (l.has_update())
    {
        std::cout << "A new version of the launcher is available."\
            " Would you like to download it (y/n)?" << std::endl;
        bool download(confirm());
        if (!download)
        {
            std::cout << "It is strongly recommended to always use"\
                " the latest launcher. Would you like to download it (y/n)?"
                << std::endl;
            download = confirm();
        }
        if (download)
        {
            // Download.
            std::cout << "Downloading new launcher..." << std::endl;
            std::cout << "Done." << std::endl;
        }
    }

    std::string fetch;
    CurlEasy curl(listing);
    curl.write_to(fetch);
    curl.perform();

    auto lines(split(fetch, '\n'));
    std::vector<Target> new_targets, old_targets;
    for (auto beg = std::begin(lines), end = std::end(lines);
            beg != end; ++beg)
    {
        auto data(split(*beg, '@'));
        Target t(data[0], data[data.size() - 1]);
        auto status = t.status();
        if (status == Target::Status::Nonexistent)
        {
            new_targets.push_back(std::move(t));
        }
        else if (status == Target::Status::Outdated)
        {
            old_targets.push_back(std::move(t));
        }
    }
    if (new_targets.size())
    {
        std::cout << "New targets: " << new_targets.size() << std::endl;
        for (auto &t : new_targets)
        {
            std::cout << "- " << t.name() << std::endl;
        }
    }
    else
    {
        std::cout << "No new targets." << std::endl;
    }

    if (old_targets.size())
    {
        std::cout << "Outdated targets: " << old_targets.size() << std::endl;
        for (auto &t : old_targets)
        {
            std::cout << "- " << t.name() << std::endl;
        }
    }
    else
    {
        std::cout << "No targets out of date." << std::endl;
    }

#ifndef DEBUG
    for (auto &t : new_targets)
    {
        t.fetch();
    }
    for (auto &t : old_targets)
    {
        t.fetch();
    }
#endif

    return 0;
}
<|endoftext|>


<commit_before><commit_msg>Do not use deprecated comphelper::string::getToken<commit_after><|endoftext|>


<commit_before>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2016 LiteIDE Team. All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
** Lesser General Public License for more details.
**
** In addition, as a special exception,  that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: quickopenwidget.cpp
// Creator: visualfc <visualfc@gmail.com>

#include "quickopenwidget.h"
#include "liteapi/liteids.h"
#include <QVBoxLayout>
#include <QComboBox>
#include <QTreeView>
#include <QFocusEvent>
#include <QHeaderView>
#include <QDebug>

//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) &&  defined(_DEBUG)
     #define _CRTDBG_MAP_ALLOC
     #include <stdlib.h>
     #include <crtdbg.h>
     #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
     #define new DEBUG_NEW
#endif
//lite_memory_check_end

QuickOpenWidget::QuickOpenWidget(LiteApi::IApplication *app, QWidget *parent) :
    QWidget(parent,Qt::Popup),// Qt::ToolTip | Qt::WindowStaysOnTopHint)
    m_liteApp(app)
{
    //this->setFocusPolicy(Qt::NoFocus);
    m_edit = new Utils::FilterLineEdit(300);
    m_view = new QTreeView;
    m_view->setHeaderHidden(true);
    m_view->setTextElideMode(Qt::ElideLeft);
#if QT_VERSION >= 0x050000
    m_view->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
#else
    m_view->header()->setResizeMode(QHeaderView::ResizeToContents);
#endif
    m_view->setEditTriggers(QAbstractItemView::NoEditTriggers);

    m_wrap = true;

    QVBoxLayout *layout = new QVBoxLayout;
    layout->setMargin(0);
    layout->setSpacing(0);
    layout->addWidget(m_edit);
    layout->addWidget(m_view);

    this->setMinimumWidth(600);

    this->setLayout(layout);

    connect(m_edit,SIGNAL(filterChanged(QString)),this,SIGNAL(filterChanged(QString)));

    m_edit->installEventFilter(this);
}

void QuickOpenWidget::setModel(QAbstractItemModel *model)
{
    m_view->setModel(model);
}

QLineEdit *QuickOpenWidget::editor()
{
    return m_edit;
}

QTreeView *QuickOpenWidget::view()
{
    return m_view;
}

void QuickOpenWidget::hideEvent(QHideEvent *e)
{
    emit hideWidget();
    QWidget::hideEvent(e);
}

void QuickOpenWidget::showView(QPoint *pos)
{
    if (pos == 0) {
        QToolBar *toolBar =  m_liteApp->actionManager()->loadToolBar(ID_TOOLBAR_STD);
        QRect rc = toolBar->frameGeometry();
        QPoint pt = rc.topRight();
        pt.rx() += 4;
        pt.ry() += 2;
        this->move(m_liteApp->mainWindow()->mapToGlobal(pt));
    } else {
        this->move(pos->x(),pos->y());
    }
    m_edit->setFocus();
    this->show();
}

bool QuickOpenWidget::eventFilter(QObject *o, QEvent *e)
{
    if (e->type() == QEvent::KeyPress) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(e);
        QAbstractItemModel *model = m_view->model();

        if (!model) {
            return false;
        }

        int row = m_view->currentIndex().row();

        const int key = ke->key();
        switch (key) {
        case Qt::Key_Up: {
            row--;
            if (row < 0) {
                if (m_wrap) {
                    row = model->rowCount()-1;
                }
            }
            QModelIndex index = model->index(row,0);
            m_view->setCurrentIndex(index);
            emit indexChanage(index);
            return true;
        }
        case Qt::Key_Down: {
            row++;
            if (row >= model->rowCount()) {
                if (m_wrap) {
                    row = 0;
                }
            }
            QModelIndex index = model->index(row,0);
            m_view->setCurrentIndex(index);
            emit indexChanage(index);
            return true;
        }
        }
    } else if (e->type() == QEvent::FocusOut) {
        if (QWidget::focusWidget() == m_view ) {
            m_edit->setFocus();
        }
        return true;
    }
    return QWidget::eventFilter(o,e);
}
<commit_msg>quickopen: fix pos for editor manager<commit_after>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2016 LiteIDE Team. All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
** Lesser General Public License for more details.
**
** In addition, as a special exception,  that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: quickopenwidget.cpp
// Creator: visualfc <visualfc@gmail.com>

#include "quickopenwidget.h"
#include "liteapi/liteids.h"
#include <QVBoxLayout>
#include <QComboBox>
#include <QTreeView>
#include <QFocusEvent>
#include <QHeaderView>
#include <QDebug>

//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) &&  defined(_DEBUG)
     #define _CRTDBG_MAP_ALLOC
     #include <stdlib.h>
     #include <crtdbg.h>
     #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
     #define new DEBUG_NEW
#endif
//lite_memory_check_end

QuickOpenWidget::QuickOpenWidget(LiteApi::IApplication *app, QWidget *parent) :
    QWidget(parent,Qt::Popup),// Qt::ToolTip | Qt::WindowStaysOnTopHint)
    m_liteApp(app)
{
    //this->setFocusPolicy(Qt::NoFocus);
    m_edit = new Utils::FilterLineEdit(300);
    m_view = new QTreeView;
    m_view->setHeaderHidden(true);
    m_view->setTextElideMode(Qt::ElideLeft);
#if QT_VERSION >= 0x050000
    m_view->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
#else
    m_view->header()->setResizeMode(QHeaderView::ResizeToContents);
#endif
    m_view->setEditTriggers(QAbstractItemView::NoEditTriggers);

    m_wrap = true;

    QVBoxLayout *layout = new QVBoxLayout;
    layout->setMargin(0);
    layout->setSpacing(0);
    layout->addWidget(m_edit);
    layout->addWidget(m_view);

    this->setMinimumWidth(600);

    this->setLayout(layout);

    connect(m_edit,SIGNAL(filterChanged(QString)),this,SIGNAL(filterChanged(QString)));

    m_edit->installEventFilter(this);
}

void QuickOpenWidget::setModel(QAbstractItemModel *model)
{
    m_view->setModel(model);
}

QLineEdit *QuickOpenWidget::editor()
{
    return m_edit;
}

QTreeView *QuickOpenWidget::view()
{
    return m_view;
}

void QuickOpenWidget::hideEvent(QHideEvent *e)
{
    emit hideWidget();
    QWidget::hideEvent(e);
}

void QuickOpenWidget::showView(QPoint *pos)
{
    if (pos == 0) {
        QPoint pt(0,0);
        this->move(m_liteApp->editorManager()->widget()->mapToGlobal(pt));
    } else {
        this->move(pos->x(),pos->y());
    }
    m_edit->setFocus();
    this->show();
}

bool QuickOpenWidget::eventFilter(QObject *o, QEvent *e)
{
    if (e->type() == QEvent::KeyPress) {
        QKeyEvent *ke = static_cast<QKeyEvent *>(e);
        QAbstractItemModel *model = m_view->model();

        if (!model) {
            return false;
        }

        int row = m_view->currentIndex().row();

        const int key = ke->key();
        switch (key) {
        case Qt::Key_Up: {
            row--;
            if (row < 0) {
                if (m_wrap) {
                    row = model->rowCount()-1;
                }
            }
            QModelIndex index = model->index(row,0);
            m_view->setCurrentIndex(index);
            emit indexChanage(index);
            return true;
        }
        case Qt::Key_Down: {
            row++;
            if (row >= model->rowCount()) {
                if (m_wrap) {
                    row = 0;
                }
            }
            QModelIndex index = model->index(row,0);
            m_view->setCurrentIndex(index);
            emit indexChanage(index);
            return true;
        }
        }
    } else if (e->type() == QEvent::FocusOut) {
        if (QWidget::focusWidget() == m_view ) {
            m_edit->setFocus();
        }
        return true;
    }
    return QWidget::eventFilter(o,e);
}
<|endoftext|>


<commit_before>#include <oglShaders.h>
#include <oglDisplay.h>

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <assert.h>

#include <memory.h>
#include <str_utils.h>
#include <string.h>

#include <OGL/OGLGpuBuffer.h>
#include <RenderBackend.h>

static GLuint _currentShaderProgram = 0;

#pragma warning(disable:4996)

void _print_shader_info_log(GLuint idx) {
	int max_length = 2048;
	int actual_length = 0;
	char shader_log[2048];
	glGetShaderInfoLog(idx, max_length, &actual_length, shader_log);
	printf("shader info log for GL index %u:\n%s\n", idx, shader_log);
}

void _print_programme_info_log(GLuint programme) {
	int max_length = 2048;
	int actual_length = 0;
	char program_log[2048];
	glGetProgramInfoLog(programme, max_length, &actual_length, program_log);
	printf("program info log for GL index %u:\n%s", programme, program_log);
}

void useShaderProgram(GLuint id) {
	//WARNING: switching shaders takes a BOATLOAD of time. it is best to switch as little as possible.
	//may even want to render all elements with the same shader before moving onto next element...
	if (_currentShaderProgram == id) return;
	_currentShaderProgram = id;
	glUseProgram(id);
//	printf("shader %d\n", id);
}

static char* read_from_disk(const char* path) {
	FILE* f = fopen(path, "r");
	if (f == NULL) {
		assert(f);
		return NULL;
	}

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

	char *str = (char*)malloc(size + 1);
	size_t bytes_read = fread(str, 1, size, f);
	int error = ferror(f);
	fclose(f);

	if (error != 0) {
		printf("File error: %d\n", error);
		free(str);
		str = NULL;
		return str;
	}

	size = bytes_read;
	char* realloc_ptr = (char*)realloc(str, size+1);
	assert(realloc_ptr != NULL);
	str = realloc_ptr;
	str[size] = 0;

	return str;
}

static GLuint compile_shader(const char* str, GLuint shader_type) {
	GLuint f_shader = glCreateShader(shader_type);
	glShaderSource(f_shader, 1, &str, NULL);
	glCompileShader(f_shader);

	// check for compile errors
	int params = -1;
	glGetShaderiv(f_shader, GL_COMPILE_STATUS, &params);
	if (GL_TRUE != params) {
		fprintf(stderr, "ERROR: GL shader index %i did not compile\n", f_shader);
		_print_shader_info_log(f_shader);
		glDeleteShader(f_shader);
		return 0;
	}

	return f_shader;
}

void HgOglShader::setup_shader(HgOglShader* shader) {
	shader_source* source = shader->m_shaderSource.get();

	GLuint vert_id = 0;
	GLuint frag_id = 0;
	GLuint geom_id = 0;

	if (!source->vert_source.empty()) vert_id = compile_shader(source->vert_source.c_str(), GL_VERTEX_SHADER);
	if (!source->frag_source.empty()) frag_id = compile_shader(source->frag_source.c_str(), GL_FRAGMENT_SHADER);
	if (!source->geom_source.empty()) geom_id = compile_shader(source->geom_source.c_str(), GL_GEOMETRY_SHADER);

	source->vert_source = source->frag_source = source->geom_source = "";

	if ((vert_id == 0) && (frag_id == 0) && (geom_id == 0)) return;

	GLuint shader_program = shader->program_id;
	if (shader_program==0) shader_program = glCreateProgram();

	if (vert_id>0) glAttachShader(shader_program, vert_id);
	if (frag_id>0) glAttachShader(shader_program, frag_id);
	if (geom_id>0) glAttachShader(shader_program, geom_id);
	glLinkProgram(shader_program);

	if (vert_id > 0) {
		glDetachShader(shader_program, vert_id);
		glDeleteShader(vert_id);
	}
	if (frag_id > 0) {
		glDetachShader(shader_program, frag_id);
		glDeleteShader(frag_id);
	}
	if (geom_id > 0) {
		glDetachShader(shader_program, geom_id);
		glDeleteShader(geom_id);
	}

	// check if link was successful
	GLint params = -1;
	glGetProgramiv(shader_program, GL_LINK_STATUS, &params);
	if (GL_TRUE != params) {
		fprintf(stderr,
			"ERROR: could not link shader programme GL index %u\n",
			shader_program);
		_print_programme_info_log(shader_program);
		return;
	}
	shader->program_id = shader_program;
	shader->m_loadState = LoadState::READY;

	GLint size; // size of the variable
	GLenum type; // type of the variable (float, vec3 or mat4, etc)

	GLchar name[64]; // variable name in GLSL
	GLsizei length; // name length

	//create list of uniforms
	GLint uniform_count = 0;
	glGetProgramiv(shader_program, GL_ACTIVE_UNIFORMS, &uniform_count);

	memset(shader->m_uniformLocations, -1, sizeof(*shader->m_uniformLocations)*U_UNIFORM_COUNT);

	for (GLuint i = 0; i < uniform_count; i++)
	{
		glGetActiveUniform(shader_program, i, 64, &length, &size, &type, name);
		//printf("Uniform #%d Type: %u Name: %s\n", i, type, name);
		for (int j = 0; j < U_UNIFORM_COUNT; j++) {
			if (strcmp(name, UniformString[j]) == 0) {
				shader->m_uniformLocations[j] = glGetUniformLocation(shader_program, name);
				break;
			}
			if (j == (U_UNIFORM_COUNT - 1)) fprintf(stderr, "HgShaders: Unknown uniform \"%s\"\n", name);
		}
	}
}

std::unique_ptr<HgShader> HgOglShader::Create(const char* vert, const char* frag) {
	std::unique_ptr<HgOglShader> s = std::make_unique<HgOglShader>();

	auto source = std::make_unique<shader_source>();
	source->vert_file_path = str_copy(vert);
	source->frag_file_path = str_copy(frag);
	s->setProgramCode(source);

	return s;
}

HgOglShader::HgOglShader()
	:program_id(0), m_loadState(LoadState::NOT_LOADED)
{
	memset(m_uniformLocations, -1, sizeof(m_uniformLocations));
}

HgOglShader::~HgOglShader() {
	destroy();
}

void HgOglShader::load() {
	if (!m_shaderSource->vert_file_path.empty()) m_shaderSource->vert_source = read_from_disk(m_shaderSource->vert_file_path.c_str());
	if (!m_shaderSource->frag_file_path.empty()) m_shaderSource->frag_source = read_from_disk(m_shaderSource->frag_file_path.c_str());
	if (!m_shaderSource->geom_file_path.empty()) m_shaderSource->geom_source = read_from_disk(m_shaderSource->geom_file_path.c_str());

	m_loadState = LoadState::SOURCE_LOADED;
}

void HgOglShader::destroy() {
	if (program_id > 0) glDeleteProgram(program_id);
	program_id = 0;
}

void HgOglShader::enable() {
	if (m_loadState == LoadState::NOT_LOADED) return;

	if (program_id == 0 || m_loadState == LoadState::SOURCE_LOADED) setup_shader(this);
	if (program_id>0) useShaderProgram(program_id);
}

void HgOglShader::setLocalUniforms(const quaternion* rotation, const point* position, float scale, const point* origin, const RenderData* rd, const HgCamera* camera) {
	GLuint old_program = _currentShaderProgram;

	if (old_program == program_id) {
		sendLocalUniformsToGPU(rotation, position, scale, origin, rd, camera);
		return;
	}

	//Log warning about being slow and change to this program
	fprintf(stderr, "Warning (%s): Temporary shader context change.\n", __FUNCTION__);
	enable();

	sendLocalUniformsToGPU(rotation, position, scale, origin, rd, camera);

	useShaderProgram(old_program); //change back to previous program
}

void HgOglShader::uploadMatrices(const HgMath::mat4f& modelView, const HgMath::mat4f& projection, const HgMath::mat4f& view) {
	using namespace HgMath;
	constexpr const int matrixCount = 3;

	float mm[16 * matrixCount];

	if (m_uniformLocations[U_MATRICES] <= -1) return;

	modelView.store(mm);
	projection.store(mm + 16);
	view.store(mm + 32);
	glUniformMatrix4fv(m_uniformLocations[U_MATRICES], matrixCount, GL_FALSE, mm);
}

void HgOglShader::sendLocalUniformsToGPU(const quaternion* rotation, const point* position, float scale, const point* origin, const RenderData* rd, const HgCamera* camera) {
	OGLRenderData* oglrd = (OGLRenderData*)rd;

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, oglrd->textureID[HgTexture::DIFFUSE]);
	if ((m_uniformLocations[U_DIFFUSE_TEXTURE] > -1) && (oglrd->textureID[HgTexture::DIFFUSE] > 0)) {
		//		glBindTexture(GL_TEXTURE_2D, oglrd->textureID[HgTexture::DIFFUSE]);
		glUniform1i(m_uniformLocations[U_DIFFUSE_TEXTURE], 0);
	}

	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, oglrd->textureID[HgTexture::SPECULAR]);
	if ((m_uniformLocations[U_SPECULAR_TEXTURE] > -1) && (oglrd->textureID[HgTexture::SPECULAR] > 0)) {
		//		glBindTexture(GL_TEXTURE_2D, oglrd->textureID[HgTexture::SPECULAR]);
		glUniform1i(m_uniformLocations[U_SPECULAR_TEXTURE], 1);
	}

	glActiveTexture(GL_TEXTURE2);
	glBindTexture(GL_TEXTURE_2D, oglrd->textureID[HgTexture::NORMAL]);
	if ((m_uniformLocations[U_NORMAL_TEXTURE] > -1) && (oglrd->textureID[HgTexture::NORMAL] > 0)) {
		//		glBindTexture(GL_TEXTURE_2D, oglrd->textureID[HgTexture::SPECULAR]);
		glUniform1i(m_uniformLocations[U_NORMAL_TEXTURE], 2);
	}

	glActiveTexture(GL_TEXTURE3);
	if ((m_uniformLocations[U_BUFFER_OBJECT1] > -1) && (oglrd->gpuBuffer != nullptr)) {
		OGLHgGPUBuffer* api = (OGLHgGPUBuffer*)oglrd->gpuBuffer->apiImpl();
		if (oglrd->gpuBuffer->NeedsUpdate()) {
			//api->OGLHgGPUBuffer::SendToGPU(oglrd->gpuBuffer.get()); //no vtable lookup
			api->OGLHgGPUBuffer::SendToGPU(oglrd->gpuBuffer); //no vtable lookup
		}
		api->OGLHgGPUBuffer::Bind(); //no vtable lookup
		glUniform1i(m_uniformLocations[U_BUFFER_OBJECT1], 3);
	}
}<commit_msg>remove if<commit_after>#include <oglShaders.h>
#include <oglDisplay.h>

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <assert.h>

#include <memory.h>
#include <str_utils.h>
#include <string.h>

#include <OGL/OGLGpuBuffer.h>
#include <RenderBackend.h>

static GLuint _currentShaderProgram = 0;

#pragma warning(disable:4996)

void _print_shader_info_log(GLuint idx) {
	int max_length = 2048;
	int actual_length = 0;
	char shader_log[2048];
	glGetShaderInfoLog(idx, max_length, &actual_length, shader_log);
	printf("shader info log for GL index %u:\n%s\n", idx, shader_log);
}

void _print_programme_info_log(GLuint programme) {
	int max_length = 2048;
	int actual_length = 0;
	char program_log[2048];
	glGetProgramInfoLog(programme, max_length, &actual_length, program_log);
	printf("program info log for GL index %u:\n%s", programme, program_log);
}

void useShaderProgram(GLuint id) {
	//WARNING: switching shaders takes a BOATLOAD of time. it is best to switch as little as possible.
	//may even want to render all elements with the same shader before moving onto next element...
	if (_currentShaderProgram == id) return;
	_currentShaderProgram = id;
	glUseProgram(id);
//	printf("shader %d\n", id);
}

static char* read_from_disk(const char* path) {
	FILE* f = fopen(path, "r");
	if (f == NULL) {
		assert(f);
		return NULL;
	}

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

	char *str = (char*)malloc(size + 1);
	size_t bytes_read = fread(str, 1, size, f);
	int error = ferror(f);
	fclose(f);

	if (error != 0) {
		printf("File error: %d\n", error);
		free(str);
		str = NULL;
		return str;
	}

	size = bytes_read;
	char* realloc_ptr = (char*)realloc(str, size+1);
	assert(realloc_ptr != NULL);
	str = realloc_ptr;
	str[size] = 0;

	return str;
}

static GLuint compile_shader(const char* str, GLuint shader_type) {
	GLuint f_shader = glCreateShader(shader_type);
	glShaderSource(f_shader, 1, &str, NULL);
	glCompileShader(f_shader);

	// check for compile errors
	int params = -1;
	glGetShaderiv(f_shader, GL_COMPILE_STATUS, &params);
	if (GL_TRUE != params) {
		fprintf(stderr, "ERROR: GL shader index %i did not compile\n", f_shader);
		_print_shader_info_log(f_shader);
		glDeleteShader(f_shader);
		return 0;
	}

	return f_shader;
}

void HgOglShader::setup_shader(HgOglShader* shader) {
	shader_source* source = shader->m_shaderSource.get();

	GLuint vert_id = 0;
	GLuint frag_id = 0;
	GLuint geom_id = 0;

	if (!source->vert_source.empty()) vert_id = compile_shader(source->vert_source.c_str(), GL_VERTEX_SHADER);
	if (!source->frag_source.empty()) frag_id = compile_shader(source->frag_source.c_str(), GL_FRAGMENT_SHADER);
	if (!source->geom_source.empty()) geom_id = compile_shader(source->geom_source.c_str(), GL_GEOMETRY_SHADER);

	source->vert_source = source->frag_source = source->geom_source = "";

	if ((vert_id == 0) && (frag_id == 0) && (geom_id == 0)) return;

	GLuint shader_program = shader->program_id;
	if (shader_program==0) shader_program = glCreateProgram();

	if (vert_id>0) glAttachShader(shader_program, vert_id);
	if (frag_id>0) glAttachShader(shader_program, frag_id);
	if (geom_id>0) glAttachShader(shader_program, geom_id);
	glLinkProgram(shader_program);

	if (vert_id > 0) {
		glDetachShader(shader_program, vert_id);
		glDeleteShader(vert_id);
	}
	if (frag_id > 0) {
		glDetachShader(shader_program, frag_id);
		glDeleteShader(frag_id);
	}
	if (geom_id > 0) {
		glDetachShader(shader_program, geom_id);
		glDeleteShader(geom_id);
	}

	// check if link was successful
	GLint params = -1;
	glGetProgramiv(shader_program, GL_LINK_STATUS, &params);
	if (GL_TRUE != params) {
		fprintf(stderr,
			"ERROR: could not link shader programme GL index %u\n",
			shader_program);
		_print_programme_info_log(shader_program);
		return;
	}
	shader->program_id = shader_program;
	shader->m_loadState = LoadState::READY;

	GLint size; // size of the variable
	GLenum type; // type of the variable (float, vec3 or mat4, etc)

	GLchar name[64]; // variable name in GLSL
	GLsizei length; // name length

	//create list of uniforms
	GLint uniform_count = 0;
	glGetProgramiv(shader_program, GL_ACTIVE_UNIFORMS, &uniform_count);

	memset(shader->m_uniformLocations, -1, sizeof(*shader->m_uniformLocations)*U_UNIFORM_COUNT);

	for (GLuint i = 0; i < uniform_count; i++)
	{
		glGetActiveUniform(shader_program, i, 64, &length, &size, &type, name);
		//printf("Uniform #%d Type: %u Name: %s\n", i, type, name);
		for (int j = 0; j < U_UNIFORM_COUNT; j++) {
			if (strcmp(name, UniformString[j]) == 0) {
				shader->m_uniformLocations[j] = glGetUniformLocation(shader_program, name);
				break;
			}
			if (j == (U_UNIFORM_COUNT - 1)) fprintf(stderr, "HgShaders: Unknown uniform \"%s\"\n", name);
		}
	}
}

std::unique_ptr<HgShader> HgOglShader::Create(const char* vert, const char* frag) {
	std::unique_ptr<HgOglShader> s = std::make_unique<HgOglShader>();

	auto source = std::make_unique<shader_source>();
	source->vert_file_path = str_copy(vert);
	source->frag_file_path = str_copy(frag);
	s->setProgramCode(source);

	return s;
}

HgOglShader::HgOglShader()
	:program_id(0), m_loadState(LoadState::NOT_LOADED)
{
	memset(m_uniformLocations, -1, sizeof(m_uniformLocations));
}

HgOglShader::~HgOglShader() {
	destroy();
}

void HgOglShader::load() {
	if (!m_shaderSource->vert_file_path.empty()) m_shaderSource->vert_source = read_from_disk(m_shaderSource->vert_file_path.c_str());
	if (!m_shaderSource->frag_file_path.empty()) m_shaderSource->frag_source = read_from_disk(m_shaderSource->frag_file_path.c_str());
	if (!m_shaderSource->geom_file_path.empty()) m_shaderSource->geom_source = read_from_disk(m_shaderSource->geom_file_path.c_str());

	m_loadState = LoadState::SOURCE_LOADED;
}

void HgOglShader::destroy() {
	if (program_id > 0) glDeleteProgram(program_id);
	program_id = 0;
}

void HgOglShader::enable() {
	if (m_loadState == LoadState::NOT_LOADED) return;

	if (program_id == 0 || m_loadState == LoadState::SOURCE_LOADED) setup_shader(this);
	if (program_id>0) useShaderProgram(program_id);
}

void HgOglShader::setLocalUniforms(const quaternion* rotation, const point* position, float scale, const point* origin, const RenderData* rd, const HgCamera* camera) {
	GLuint old_program = _currentShaderProgram;

	if (old_program == program_id) {
		sendLocalUniformsToGPU(rotation, position, scale, origin, rd, camera);
		return;
	}

	//Log warning about being slow and change to this program
	fprintf(stderr, "Warning (%s): Temporary shader context change.\n", __FUNCTION__);
	enable();

	sendLocalUniformsToGPU(rotation, position, scale, origin, rd, camera);

	useShaderProgram(old_program); //change back to previous program
}

void HgOglShader::uploadMatrices(const HgMath::mat4f& modelView, const HgMath::mat4f& projection, const HgMath::mat4f& view) {
	using namespace HgMath;
	constexpr const int matrixCount = 3;

	float mm[16 * matrixCount];

	//if (m_uniformLocations[U_MATRICES] <= -1) return; //everything needs matrices. don't bother checking

	modelView.store(mm);
	projection.store(mm + 16);
	view.store(mm + 32);
	glUniformMatrix4fv(m_uniformLocations[U_MATRICES], matrixCount, GL_FALSE, mm);
}

void HgOglShader::sendLocalUniformsToGPU(const quaternion* rotation, const point* position, float scale, const point* origin, const RenderData* rd, const HgCamera* camera) {
	OGLRenderData* oglrd = (OGLRenderData*)rd;

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, oglrd->textureID[HgTexture::DIFFUSE]);
	if ((m_uniformLocations[U_DIFFUSE_TEXTURE] > -1) && (oglrd->textureID[HgTexture::DIFFUSE] > 0)) {
		//		glBindTexture(GL_TEXTURE_2D, oglrd->textureID[HgTexture::DIFFUSE]);
		glUniform1i(m_uniformLocations[U_DIFFUSE_TEXTURE], 0);
	}

	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, oglrd->textureID[HgTexture::SPECULAR]);
	if ((m_uniformLocations[U_SPECULAR_TEXTURE] > -1) && (oglrd->textureID[HgTexture::SPECULAR] > 0)) {
		//		glBindTexture(GL_TEXTURE_2D, oglrd->textureID[HgTexture::SPECULAR]);
		glUniform1i(m_uniformLocations[U_SPECULAR_TEXTURE], 1);
	}

	glActiveTexture(GL_TEXTURE2);
	glBindTexture(GL_TEXTURE_2D, oglrd->textureID[HgTexture::NORMAL]);
	if ((m_uniformLocations[U_NORMAL_TEXTURE] > -1) && (oglrd->textureID[HgTexture::NORMAL] > 0)) {
		//		glBindTexture(GL_TEXTURE_2D, oglrd->textureID[HgTexture::SPECULAR]);
		glUniform1i(m_uniformLocations[U_NORMAL_TEXTURE], 2);
	}

	glActiveTexture(GL_TEXTURE3);
	if ((m_uniformLocations[U_BUFFER_OBJECT1] > -1) && (oglrd->gpuBuffer != nullptr)) {
		OGLHgGPUBuffer* api = (OGLHgGPUBuffer*)oglrd->gpuBuffer->apiImpl();
		if (oglrd->gpuBuffer->NeedsUpdate()) {
			//api->OGLHgGPUBuffer::SendToGPU(oglrd->gpuBuffer.get()); //no vtable lookup
			api->OGLHgGPUBuffer::SendToGPU(oglrd->gpuBuffer); //no vtable lookup
		}
		api->OGLHgGPUBuffer::Bind(); //no vtable lookup
		glUniform1i(m_uniformLocations[U_BUFFER_OBJECT1], 3);
	}
}<|endoftext|>


<commit_before>// expect-success
/*
 * Copyright 2014 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define IN_FRUIT_CPP_FILE

#include <fruit/impl/data_structures/semistatic_graph.h>
#include <fruit/impl/data_structures/semistatic_graph.templates.h>

#include <vector>

using namespace std;
using namespace fruit::impl;

using Graph = SemistaticGraph<int, const char*>;
using node_iterator = Graph::node_iterator;
using edge_iterator = Graph::edge_iterator;

vector<size_t> no_neighbors = {};

struct SimpleNode {
  size_t id;
  const char* value;
  const vector<size_t>* neighbors;
  bool is_terminal;

  size_t getId() { return id; }
  const char* getValue() { return value; }
  bool isTerminal() { return is_terminal; }
  vector<size_t>::const_iterator getEdgesBegin() { return neighbors->begin(); }
  vector<size_t>::const_iterator getEdgesEnd() { return neighbors->end(); }
};

void test_empty() {
  vector<SimpleNode> values{};
  Graph graph(values.begin(), values.end());
  assert(graph.find(0) == graph.end());
  assert(graph.find(2) == graph.end());
  assert(graph.find(5) == graph.end());
}

void test_1_node_no_edges() {
  vector<SimpleNode> values{{2, "foo", &no_neighbors, false}};
  Graph graph(values.begin(), values.end());
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == false);
  assert(graph.find(5) == graph.end());
}

void test_1_node_no_edges_terminal() {
  vector<SimpleNode> values{{2, "foo", &no_neighbors, true}};
  Graph graph(values.begin(), values.end());
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == true);
  assert(graph.find(5) == graph.end());
}

void test_1_node_self_edge() {
  vector<size_t> neighbors = {2};
  vector<SimpleNode> values{{2, "foo", &neighbors, false}};
  Graph graph(values.begin(), values.end());
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == false);
  edge_iterator itr = graph.at(2).neighborsBegin();
  (void)itr;
  assert(itr.getNodeIterator(graph).getNode() == string("foo"));
  assert(itr.getNodeIterator(graph).isTerminal() == false);
  assert(graph.find(5) == graph.end());
}

void test_2_nodes_one_edge() {
  vector<size_t> neighbors = {2};
  vector<SimpleNode> values{{2, "foo", &no_neighbors, false}, {3, "bar", &neighbors, false}};
  Graph graph(values.begin(), values.end());
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == false);
  assert(graph.at(3).getNode() == string("bar"));
  assert(graph.at(3).isTerminal() == false);
  edge_iterator itr = graph.at(3).neighborsBegin();
  (void)itr;
  assert(itr.getNodeIterator(graph).getNode() == string("foo"));
  assert(itr.getNodeIterator(graph).isTerminal() == false);
  assert(graph.find(5) == graph.end());
}

void test_3_nodes_two_edges() {
  vector<size_t> neighbors = {2, 4};
  vector<SimpleNode> values{{2, "foo", &no_neighbors, false}, {3, "bar", &neighbors, false}, {4, "baz", &no_neighbors, true}};
  Graph graph(values.begin(), values.end());
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == false);
  assert(graph.at(3).getNode() == string("bar"));
  assert(graph.at(3).isTerminal() == false);
  edge_iterator itr = graph.at(3).neighborsBegin();
  assert(itr.getNodeIterator(graph).getNode() == string("foo"));
  assert(itr.getNodeIterator(graph).isTerminal() == false);
  ++itr;
  assert(itr.getNodeIterator(graph).getNode() == string("baz"));
  assert(itr.getNodeIterator(graph).isTerminal() == true);
  assert(graph.at(4).getNode() == string("baz"));
  assert(graph.at(4).isTerminal() == true);
  assert(graph.find(5) == graph.end());
}

void test_add_node() {
  vector<SimpleNode> old_values{{2, "foo", &no_neighbors, false}, {4, "baz", &no_neighbors, true}};
  Graph old_graph(old_values.begin(), old_values.end());
  vector<size_t> neighbors = {2, 4};
  vector<SimpleNode> new_values{{3, "bar", &neighbors, false}};
  Graph graph(old_graph, new_values.begin(), new_values.end());
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == false);
  assert(graph.at(3).getNode() == string("bar"));
  assert(graph.at(3).isTerminal() == false);
  edge_iterator itr = graph.at(3).neighborsBegin();
  assert(itr.getNodeIterator(graph).getNode() == string("foo"));
  assert(itr.getNodeIterator(graph).isTerminal() == false);
  ++itr;
  assert(itr.getNodeIterator(graph).getNode() == string("baz"));
  assert(itr.getNodeIterator(graph).isTerminal() == true);
  assert(graph.at(4).getNode() == string("baz"));
  assert(graph.at(4).isTerminal() == true);
  assert(graph.find(5) == graph.end());
}

void test_set_terminal() {
  vector<size_t> neighbors = {2, 4};
  vector<SimpleNode> values{{2, "foo", &no_neighbors, false}, {3, "bar", &neighbors, false}, {4, "baz", &no_neighbors, true}};
  Graph graph(values.begin(), values.end());
  graph.changeNodeToTerminal(3);
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == false);
  assert(graph.at(3).getNode() == string("bar"));
  assert(graph.at(3).isTerminal() == true);
  assert(graph.at(4).getNode() == string("baz"));
  assert(graph.at(4).isTerminal() == true);
  assert(graph.find(5) == graph.end());
}

void test_move_constructor() {
  vector<size_t> neighbors = {2};
  vector<SimpleNode> values{{2, "foo", &no_neighbors, false}, {3, "bar", &neighbors, false}};
  Graph graph1(values.begin(), values.end());
  Graph graph = std::move(graph1);
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == false);
  assert(graph.at(3).getNode() == string("bar"));
  assert(graph.at(3).isTerminal() == false);
  edge_iterator itr = graph.at(3).neighborsBegin();
  (void)itr;
  assert(itr.getNodeIterator(graph).getNode() == string("foo"));
  assert(itr.getNodeIterator(graph).isTerminal() == false);
  assert(graph.find(5) == graph.end());
}

void test_move_assignment() {
  vector<size_t> neighbors = {2};
  vector<SimpleNode> values{{2, "foo", &no_neighbors, false}, {3, "bar", &neighbors, false}};
  Graph graph1(values.begin(), values.end());
  Graph graph;
  graph = std::move(graph1);
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == false);
  assert(graph.at(3).getNode() == string("bar"));
  assert(graph.at(3).isTerminal() == false);
  edge_iterator itr = graph.at(3).neighborsBegin();
  (void)itr;
  assert(itr.getNodeIterator(graph).getNode() == string("foo"));
  assert(itr.getNodeIterator(graph).isTerminal() == false);
  assert(graph.find(5) == graph.end());
}

int main() {

  test_empty();
  test_1_node_no_edges();
  test_1_node_no_edges_terminal();
  test_1_node_self_edge();
  test_2_nodes_one_edge();
  test_3_nodes_two_edges();
  test_add_node();
  test_set_terminal();
  test_move_constructor();
  test_move_assignment();

  return 0;
}
<commit_msg>Increase unit test coverage for SemistaticGraph, now also testing const methods and const_node_iterator.<commit_after>// expect-success
/*
 * Copyright 2014 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#define IN_FRUIT_CPP_FILE

#include <fruit/impl/data_structures/semistatic_graph.h>
#include <fruit/impl/data_structures/semistatic_graph.templates.h>

#include <vector>

using namespace std;
using namespace fruit::impl;

using Graph = SemistaticGraph<int, const char*>;
using node_iterator = Graph::node_iterator;
using edge_iterator = Graph::edge_iterator;

vector<size_t> no_neighbors = {};

struct SimpleNode {
  size_t id;
  const char* value;
  const vector<size_t>* neighbors;
  bool is_terminal;

  size_t getId() { return id; }
  const char* getValue() { return value; }
  bool isTerminal() { return is_terminal; }
  vector<size_t>::const_iterator getEdgesBegin() { return neighbors->begin(); }
  vector<size_t>::const_iterator getEdgesEnd() { return neighbors->end(); }
};

void test_empty() {
  vector<SimpleNode> values{};
  Graph graph(values.begin(), values.end());
  assert(graph.find(0) == graph.end());
  assert(graph.find(2) == graph.end());
  assert(graph.find(5) == graph.end());
  const Graph& cgraph = graph;
  assert(cgraph.find(0) == cgraph.end());
  assert(cgraph.find(2) == cgraph.end());
  assert(cgraph.find(5) == cgraph.end());
}

void test_1_node_no_edges() {
  vector<SimpleNode> values{{2, "foo", &no_neighbors, false}};

  Graph graph(values.begin(), values.end());
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == false);
  assert(graph.find(5) == graph.end());
  const Graph& cgraph = graph;
  assert(cgraph.find(0) == cgraph.end());
  assert(!(cgraph.find(2) == cgraph.end()));
  assert(cgraph.find(2).getNode() == string("foo"));
  assert(cgraph.find(2).isTerminal() == false);
  assert(cgraph.find(5) == cgraph.end());
}

void test_1_node_no_edges_terminal() {
  vector<SimpleNode> values{{2, "foo", &no_neighbors, true}};
  Graph graph(values.begin(), values.end());
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == true);
  assert(graph.find(5) == graph.end());
  const Graph& cgraph = graph;
  assert(cgraph.find(0) == cgraph.end());
  assert(!(cgraph.find(2) == cgraph.end()));
  assert(cgraph.find(2).getNode() == string("foo"));
  assert(cgraph.find(2).isTerminal() == true);
  assert(cgraph.find(5) == cgraph.end());
}

void test_1_node_self_edge() {
  vector<size_t> neighbors = {2};
  vector<SimpleNode> values{{2, "foo", &neighbors, false}};
  Graph graph(values.begin(), values.end());
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == false);
  edge_iterator itr = graph.at(2).neighborsBegin();
  (void)itr;
  assert(itr.getNodeIterator(graph).getNode() == string("foo"));
  assert(itr.getNodeIterator(graph).isTerminal() == false);
  assert(graph.find(5) == graph.end());
  const Graph& cgraph = graph;
  assert(cgraph.find(0) == cgraph.end());
  assert(!(cgraph.find(2) == cgraph.end()));
  assert(cgraph.find(2).getNode() == string("foo"));
  assert(cgraph.find(2).isTerminal() == false);
}

void test_2_nodes_one_edge() {
  vector<size_t> neighbors = {2};
  vector<SimpleNode> values{{2, "foo", &no_neighbors, false}, {3, "bar", &neighbors, false}};
  Graph graph(values.begin(), values.end());
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == false);
  assert(graph.at(3).getNode() == string("bar"));
  assert(graph.at(3).isTerminal() == false);
  edge_iterator itr = graph.at(3).neighborsBegin();
  (void)itr;
  assert(itr.getNodeIterator(graph).getNode() == string("foo"));
  assert(itr.getNodeIterator(graph).isTerminal() == false);
  assert(graph.find(5) == graph.end());
  const Graph& cgraph = graph;
  assert(cgraph.find(0) == cgraph.end());
  assert(!(cgraph.find(2) == cgraph.end()));
  assert(cgraph.find(2).getNode() == string("foo"));
  assert(cgraph.find(2).isTerminal() == false);
  assert(cgraph.find(3).getNode() == string("bar"));
  assert(cgraph.find(3).isTerminal() == false);
}

void test_3_nodes_two_edges() {
  vector<size_t> neighbors = {2, 4};
  vector<SimpleNode> values{{2, "foo", &no_neighbors, false}, {3, "bar", &neighbors, false}, {4, "baz", &no_neighbors, true}};
  Graph graph(values.begin(), values.end());
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == false);
  assert(graph.at(3).getNode() == string("bar"));
  assert(graph.at(3).isTerminal() == false);
  edge_iterator itr = graph.at(3).neighborsBegin();
  assert(itr.getNodeIterator(graph).getNode() == string("foo"));
  assert(itr.getNodeIterator(graph).isTerminal() == false);
  ++itr;
  assert(itr.getNodeIterator(graph).getNode() == string("baz"));
  assert(itr.getNodeIterator(graph).isTerminal() == true);
  assert(graph.at(4).getNode() == string("baz"));
  assert(graph.at(4).isTerminal() == true);
  assert(graph.find(5) == graph.end());
  const Graph& cgraph = graph;
  assert(cgraph.find(0) == cgraph.end());
  assert(!(cgraph.find(2) == cgraph.end()));
  assert(cgraph.find(2).getNode() == string("foo"));
  assert(cgraph.find(2).isTerminal() == false);
  assert(cgraph.find(3).getNode() == string("bar"));
  assert(cgraph.find(3).isTerminal() == false);
  assert(cgraph.find(4).getNode() == string("baz"));
  assert(cgraph.find(4).isTerminal() == true);
  assert(cgraph.find(5) == cgraph.end());
}

void test_add_node() {
  vector<SimpleNode> old_values{{2, "foo", &no_neighbors, false}, {4, "baz", &no_neighbors, true}};
  Graph old_graph(old_values.begin(), old_values.end());
  vector<size_t> neighbors = {2, 4};
  vector<SimpleNode> new_values{{3, "bar", &neighbors, false}};
  Graph graph(old_graph, new_values.begin(), new_values.end());
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == false);
  assert(graph.at(3).getNode() == string("bar"));
  assert(graph.at(3).isTerminal() == false);
  edge_iterator itr = graph.at(3).neighborsBegin();
  assert(itr.getNodeIterator(graph).getNode() == string("foo"));
  assert(itr.getNodeIterator(graph).isTerminal() == false);
  ++itr;
  assert(itr.getNodeIterator(graph).getNode() == string("baz"));
  assert(itr.getNodeIterator(graph).isTerminal() == true);
  assert(graph.at(4).getNode() == string("baz"));
  assert(graph.at(4).isTerminal() == true);
  assert(graph.find(5) == graph.end());
  const Graph& cgraph = graph;
  assert(cgraph.find(0) == cgraph.end());
  assert(!(cgraph.find(2) == cgraph.end()));
  assert(cgraph.find(2).getNode() == string("foo"));
  assert(cgraph.find(2).isTerminal() == false);
  assert(cgraph.find(3).getNode() == string("bar"));
  assert(cgraph.find(3).isTerminal() == false);
  assert(cgraph.find(4).getNode() == string("baz"));
  assert(cgraph.find(4).isTerminal() == true);
  assert(cgraph.find(5) == cgraph.end());
}

void test_set_terminal() {
  vector<size_t> neighbors = {2, 4};
  vector<SimpleNode> values{{2, "foo", &no_neighbors, false}, {3, "bar", &neighbors, false}, {4, "baz", &no_neighbors, true}};
  Graph graph(values.begin(), values.end());
  graph.changeNodeToTerminal(3);
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == false);
  assert(graph.at(3).getNode() == string("bar"));
  assert(graph.at(3).isTerminal() == true);
  assert(graph.at(4).getNode() == string("baz"));
  assert(graph.at(4).isTerminal() == true);
  assert(graph.find(5) == graph.end());
  const Graph& cgraph = graph;
  assert(cgraph.find(0) == cgraph.end());
  assert(!(cgraph.find(2) == cgraph.end()));
  assert(cgraph.find(2).getNode() == string("foo"));
  assert(cgraph.find(3).getNode() == string("bar"));
  assert(cgraph.find(4).getNode() == string("baz"));
  assert(cgraph.find(5) == cgraph.end());
}

void test_move_constructor() {
  vector<size_t> neighbors = {2};
  vector<SimpleNode> values{{2, "foo", &no_neighbors, false}, {3, "bar", &neighbors, false}};
  Graph graph1(values.begin(), values.end());
  Graph graph = std::move(graph1);
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == false);
  assert(graph.at(3).getNode() == string("bar"));
  assert(graph.at(3).isTerminal() == false);
  edge_iterator itr = graph.at(3).neighborsBegin();
  (void)itr;
  assert(itr.getNodeIterator(graph).getNode() == string("foo"));
  assert(itr.getNodeIterator(graph).isTerminal() == false);
  assert(graph.find(5) == graph.end());
}

void test_move_assignment() {
  vector<size_t> neighbors = {2};
  vector<SimpleNode> values{{2, "foo", &no_neighbors, false}, {3, "bar", &neighbors, false}};
  Graph graph1(values.begin(), values.end());
  Graph graph;
  graph = std::move(graph1);
  assert(graph.find(0) == graph.end());
  assert(!(graph.find(2) == graph.end()));
  assert(graph.at(2).getNode() == string("foo"));
  assert(graph.at(2).isTerminal() == false);
  assert(graph.at(3).getNode() == string("bar"));
  assert(graph.at(3).isTerminal() == false);
  edge_iterator itr = graph.at(3).neighborsBegin();
  (void)itr;
  assert(itr.getNodeIterator(graph).getNode() == string("foo"));
  assert(itr.getNodeIterator(graph).isTerminal() == false);
  assert(graph.find(5) == graph.end());
}

int main() {

  test_empty();
  test_1_node_no_edges();
  test_1_node_no_edges_terminal();
  test_1_node_self_edge();
  test_2_nodes_one_edge();
  test_3_nodes_two_edges();
  test_add_node();
  test_set_terminal();
  test_move_constructor();
  test_move_assignment();

  return 0;
}
<|endoftext|>


<commit_before>#include <Scene/Member/cModeSelect.h>
#include <CameraManager/cCameraManager.h>
#include "Resource\TextureManager.h"
#include"cinder\gl\gl.h"
#include <Utility/cInput.h>
#include "cinder\Easing.h"
#include "Particle\cParticleManager.h"
#include <Sound/Wav.h>
#include"Resource\cSoundManager.h"
#include <Scene/Member/Tutorial.h>
#include <Network.hpp>
#include <Scene/Member/cMatching.h>
#include <Scene/Member/cGameMain.h>
#include <Scene/cSceneManager.h>
#include <Game/cGameManager.h>
#include <Scene/Member/cTitle.h>
#include"Resource\cImageManager.h"
#include <Network.hpp>
#include <Resource/cJsonManager.h>
#include <Network/cMatchingMemberManager.h>
using namespace ci;
using namespace ci::app;

using namespace Node;

using namespace Node::Action;

using namespace Network;
using namespace Network::Packet::Event;
using namespace Network::Packet::Request;
using namespace Network::Packet::Response;
namespace Scene
{
namespace Member
{
cModeSelect::cModeSelect( )
{

}
cModeSelect::~cModeSelect( )
{

}
void cModeSelect::setup()
{
	auto bgm = Sound::Wav(cinder::app::getAssetDirectories().front().string() + "/BGM/modeselect.wav");
	introloopBGM.create(bgm.data(), bgm.size(), 22.130F, 78.594F);
	introloopBGM.gain(0.15F);
	introloopBGM.play();
	CAMERA->refPosition = ci::vec3(0,0,-0.001);
	ENV->setMouseControl(false);
	CAMERA->setCameraAngle(ci::vec2(M_PI/18.f, M_PI / 18.f));
	CAMERA->setup();
	createTextureNames();

	for (float i = 0; i < 4; i++) {
		mSelectCards.push_back(std::make_shared<ModeSelect::cSelectCard>(i*2.f*M_PI / 4.f, iconnames[i], ci::vec3(0, 0.5, 3), ci::vec3(2.5, 0.5, 4.75),i));
	}
	root = Node::node::create();
	root->set_content_size(app::getWindowSize());
	root->set_schedule_update();
	root->set_scale(vec2(1, -1));
	root->set_position(root->get_content_size() * vec2(-0.5F, 0.5F));

	auto fader = root->add_child(Node::Renderer::rect::create(app::getWindowSize()));
	fader->set_color(ColorA(0, 0, 0, 1));
	fader->set_anchor_point(vec2(0, 0));
	fader->run_action(sequence::create( fade_out::create(1.0F), call_func::create([this]
	{
		this->isfading = false;
		//ci::app::console() << "ӂ	" << std::endl;
	})));
	//this->isfading = false;
}
void cModeSelect::shutDown()
{
	mSelectCards.clear();
	iconnames.clear();
	introloopBGM.stop();
}
void cModeSelect::update(float t)
{
	for (auto& it : mSelectCards) {
		it->update(t);
	}
	updateBackGround(t);
	updateButtonAlfa(t);
	updateArrow(t);
	introloopBGM.update(t);
	selectIcon();
	if (ENV->pushKey(ci::app::KeyEvent::KEY_RETURN)|| ENV->isPadPush(ENV->BUTTON_2)) {
		desideScene();
	}
	root->entry_update(t);

	if (watching == false)
	{
		if (ENV->pushKey(ci::app::KeyEvent::KEY_a))
		{
			watching = true;
			Network::cUDPClientManager::getInstance()->open();
			cUDPClientManager::getInstance()->connect(Resource::JSON["server.json"]["ip"].asString());
		}
	}

	else
	{
		Network::cUDPClientManager::getInstance()->update(t);
		if (cUDPClientManager::getInstance()->isConnected() == false)return;

		if (fase == WatchFase::NONE)
		{
			cUDPClientManager::getInstance()->send(new cReqInRoomWatching(100));
			fase = WatchFase::BEIGN;
		}

		else if (fase == WatchFase::BEIGN)
		{
			auto m = Network::cUDPClientManager::getInstance()->getUDPManager();

			while (auto resInRoom = m->ResInRoom.get())
			{
				if (resInRoom->mFlag = false)
				{
					cUDPClientManager::getInstance()->send(new cReqInRoom(100));
					continue;
				}
				cUDPClientManager::getInstance()->send(new cReqWantTeamIn(0));
				fase == WatchFase::WAIT;
			}
		}

		else if (fase == WatchFase::WAIT)
		{
			auto m = Network::cUDPClientManager::getInstance()->getUDPManager();
			while (auto resWantTeamIn = m->ResWantTeamIn.get())
			{
				if (resWantTeamIn->mFlag == 1)
				Network::cMatchingMemberManager::getInstance()->mPlayerTeamNum = resWantTeamIn->mTeamNum;;
			}
			int count = 0;
			while (auto eveTeamMember = m->EveTeamMember.get())
			{
				cMatchingMemberManager::getInstance()->addPlayerDatas(
					eveTeamMember->mNameStr, eveTeamMember->mTeamNum, eveTeamMember->mPlayerID, cNetworkHandle("", 0));
			}
			while (auto resCheckBeginGame = m->ResCheckBeginGame.get())
			{
				cMatchingMemberManager::getInstance()->mPlayerID = resCheckBeginGame->mPlayerID;
				cSceneManager::getInstance()->shift<Scene::Member::cGameMain>();
				continue;
			}
		}

	}

}
void cModeSelect::draw()
{
	mDrawFunc.drawTextureCube(ci::vec3(0), ci::vec3(16, 9, 20), ci::vec3(M_PI/12.f, 0, mBackGroundRotateZ), "modeselect/selectsky.png", ci::ColorA(1, 1, 1));

	for (auto& it : mSelectCards) {
		it->draw();
	}
	drawButton();

	mDrawFunc.drawTextureRect3D(ci::vec3(-0.85-aroowtranceY/2.f, -0.7+aroowtranceY,-0.3), ci::vec3(0.8, 0.16,0),ci::vec3(0,0,M_PI- M_PI / 12.f) , "modeselect/redright.png", ci::ColorA(1, 1, 1, arrowAlfa));
	mDrawFunc.drawTextureRect3D(ci::vec3(1.55+aroowtranceY/2.f, -0.7 + aroowtranceY, -0.3), ci::vec3(-0.8, 0.12, 0), ci::vec3(0, 0, M_PI + M_PI / 4.25f),  "modeselect/redright.png", ci::ColorA(1, 1, 1, arrowAlfa));
	//mDrawFunc.drawTextureRect3D(ci::vec3(-400, -175 + aroowtranceY), ci::vec3(250, 50), M_PI - M_PI / 9.f, "redright.png", ci::ColorA(1, 1, 1, arrowAlfa));
}
void cModeSelect::draw2D()
{
	/*mDrawFunc.drawTextureRect2D(ci::vec2(400,-175+aroowtranceY), ci::vec2(-250, 50), M_PI+M_PI/9.f, "redright.png", ci::ColorA(1, 1, 1,arrowAlfa));
	mDrawFunc.drawTextureRect2D(ci::vec2(-400, -175+aroowtranceY), ci::vec2(250, 50), M_PI - M_PI / 9.f, "redright.png", ci::ColorA(1, 1,1, arrowAlfa));*/
	mDrawFunc.drawTextureRect2D(ci::vec2(550,-320), ci::vec2(-590,449)*0.52f, M_PI, "title/logo.png", ci::ColorA(1, 1, 1, 1));
	root->entry_render(mat4());
}
void cModeSelect::resize()
{

}

void cModeSelect::createTextureNames()
{
	iconnames.push_back("modeselect/online.png");
	iconnames.push_back("modeselect/tutorial.png");
	iconnames.push_back("modeselect/gotitle.png");
	iconnames.push_back("modeselect/training.png");

}

void cModeSelect::changeScene()
{

	switch (MSelectScene)
	{
	case 0:
		shiftOnlineBattle();
		return;
	case 1:
		shiftTutorial();
		return;
	case 2:
		shiftTitle();
		return;
	case 3:
		shiftLocalBattle();
		return;
	default:
		break;
	}
}

void cModeSelect::selectIcon()
{
	if (isfading)return;

	if (ENV->pushKey(ci::app::KeyEvent::KEY_LEFT)||ENV->getPadAxisPushMinus(0)) {
		Resource::cSoundManager::getInstance()->findSe("ModeSelect/cursor.wav").setGain(0.4f);
		Resource::cSoundManager::getInstance()->findSe("ModeSelect/cursor.wav").play();
		for (auto& it : mSelectCards) {
			it->setEasing(true);
		}
		MSelectScene++;
		if (MSelectScene == 4)MSelectScene = 0;
		return;
	}
	if (ENV->pushKey(ci::app::KeyEvent::KEY_RIGHT) || ENV->getPadAxisPushPlus(0)) {
		Resource::cSoundManager::getInstance()->findSe("ModeSelect/cursor.wav").setGain(0.4f);
		Resource::cSoundManager::getInstance()->findSe("ModeSelect/cursor.wav").play();
		for (auto& it : mSelectCards) {
			it->setEasing(false);
		}
		MSelectScene--;
		if (MSelectScene < 0)MSelectScene = 3;
		return;
	}
}

void cModeSelect::shiftOnlineBattle()
{
	//introloopBGM.stop();
	cSceneManager::getInstance()->shift<Scene::Member::cMatching>();
}

void cModeSelect::shiftTitle()
{
	//introloopBGM.stop();
	cSceneManager::getInstance()->shift<Scene::Member::cTitle>();
}

void cModeSelect::shiftLocalBattle()
{
	//introloopBGM.stop();
	Network::cUDPClientManager::getInstance()->open();
	Network::cUDPServerManager::getInstance()->open();
	Network::cUDPClientManager::getInstance()->connectOfflineServer();
	Game::cGameManager::getInstance()->setTime(0.0F);
	cSceneManager::getInstance()->shift<Scene::Member::cGameMain>();
}

void cModeSelect::shiftTutorial()
{
	//introloopBGM.stop();
	Network::cUDPClientManager::getInstance()->open();
	Network::cUDPServerManager::getInstance()->open();
	Network::cUDPClientManager::getInstance()->connectOfflineServer();
	Game::cGameManager::getInstance()->setTime(0.0F);
	cSceneManager::getInstance()->shift<Scene::Member::cTutorial>();
}

void cModeSelect::desideScene()
{
	if (isfading)return;
	for (auto& it : mSelectCards) {
		if (it->getIsEasing())return;//C[WO͖
	}
	Resource::cSoundManager::getInstance()->findSe("ModeSelect/return.wav").setGain(0.8f);
	Resource::cSoundManager::getInstance()->findSe("ModeSelect/return.wav").play();
	introloopBGM.fadeout(0.9f,0.0f);
	isfading = true;
	auto fader = root->add_child(Node::Renderer::rect::create(app::getWindowSize()));
	fader->set_color(ColorA(0, 0, 0, 0));
	fader->set_anchor_point(vec2(0, 0));
	fader->run_action(sequence::create( fade_in::create(1.0F), call_func::create([this]
	{
		this->changeScene();
	})));
}

void cModeSelect::updateBackGround(float t)
{
	mBackGroundRotateZ += 0.02f*t;
}

void cModeSelect::drawButton()
{
	ci::vec3 pos = ci::vec3(-0.5, -0.4, -1.78);
	mDrawFunc.drawTextureRect3D(pos, ci::vec3(0.2, 0.2, 0), ci::vec3(0, M_PI, 0), "modeselect/buttonb.png", ci::ColorA(1, 1, 1, 1));
	mDrawFunc.drawTextureRect3D(pos+ci::vec3(0,0,-0.01), ci::vec3(0.2, 0.2, 0)*buttonscale, ci::vec3(0, M_PI, 0), "modeselect/ring.png", ci::ColorA(1, 1, 0, buttonalfa));

}

void cModeSelect::updateButtonAlfa(float t)
{
	float speed = 2.18f;
	buttonAlfaT += speed*t;
	bool isend = false;
	if (buttonAlfaT >= 1.0f) {
		buttonAlfaT = 1.0f;
		isend = true;
	}
	buttonalfa = EaseCubicIn(buttonAlfaT, 0.4f, 0.8f);
	buttonscale = EaseCubicIn(buttonAlfaT, 0.8f, 1.2f);
	if (isend) {
		buttonAlfaT = 0.0f;
	}

}

void cModeSelect::updateArrow(float t)
{
	float speed = 1.09f;
	arrowT += speed*t;
	bool isend = false;
	if (arrowT >= 1.0f) {
		arrowT = 1.0f;
		isend = true;
	}
	aroowtranceY = EaseReturn(arrowT, 0, 0.05f);//PT
	arrowAlfa = EaseReturn(arrowT, 0.5f, 0.5f);
	if (isend) {
		arrowT = 0.0f;
	}
}

float cModeSelect::EaseReturn(const float t, const float s, const float e)
{
	return s + -4.f*e*(t - 0.5f)*(t - 0.5f) + e;
}

}
}
<commit_msg>modeSelectに感染者移行処理追加<commit_after>#include <Scene/Member/cModeSelect.h>
#include <CameraManager/cCameraManager.h>
#include "Resource\TextureManager.h"
#include"cinder\gl\gl.h"
#include <Utility/cInput.h>
#include "cinder\Easing.h"
#include "Particle\cParticleManager.h"
#include <Sound/Wav.h>
#include"Resource\cSoundManager.h"
#include <Scene/Member/Tutorial.h>
#include <Network.hpp>
#include <Scene/Member/cMatching.h>
#include <Scene/Member/cGameMain.h>
#include <Scene/cSceneManager.h>
#include <Game/cGameManager.h>
#include <Scene/Member/cTitle.h>
#include"Resource\cImageManager.h"
#include <Network.hpp>
#include <Resource/cJsonManager.h>
#include <Network/cMatchingMemberManager.h>
using namespace ci;
using namespace ci::app;

using namespace Node;

using namespace Node::Action;

using namespace Network;
using namespace Network::Packet::Event;
using namespace Network::Packet::Request;
using namespace Network::Packet::Response;
namespace Scene
{
namespace Member
{
cModeSelect::cModeSelect( )
{

}
cModeSelect::~cModeSelect( )
{

}
void cModeSelect::setup()
{
	auto bgm = Sound::Wav(cinder::app::getAssetDirectories().front().string() + "/BGM/modeselect.wav");
	introloopBGM.create(bgm.data(), bgm.size(), 22.130F, 78.594F);
	introloopBGM.gain(0.15F);
	introloopBGM.play();
	CAMERA->refPosition = ci::vec3(0,0,-0.001);
	ENV->setMouseControl(false);
	CAMERA->setCameraAngle(ci::vec2(M_PI/18.f, M_PI / 18.f));
	CAMERA->setup();
	createTextureNames();

	for (float i = 0; i < 4; i++) {
		mSelectCards.push_back(std::make_shared<ModeSelect::cSelectCard>(i*2.f*M_PI / 4.f, iconnames[i], ci::vec3(0, 0.5, 3), ci::vec3(2.5, 0.5, 4.75),i));
	}
	root = Node::node::create();
	root->set_content_size(app::getWindowSize());
	root->set_schedule_update();
	root->set_scale(vec2(1, -1));
	root->set_position(root->get_content_size() * vec2(-0.5F, 0.5F));

	auto fader = root->add_child(Node::Renderer::rect::create(app::getWindowSize()));
	fader->set_color(ColorA(0, 0, 0, 1));
	fader->set_anchor_point(vec2(0, 0));
	fader->run_action(sequence::create( fade_out::create(1.0F), call_func::create([this]
	{
		this->isfading = false;
		//ci::app::console() << "ӂ	" << std::endl;
	})));
	//this->isfading = false;
}
void cModeSelect::shutDown()
{
	mSelectCards.clear();
	iconnames.clear();
	introloopBGM.stop();
}
void cModeSelect::update(float t)
{
	if (watching == false)
	{
	for (auto& it : mSelectCards) {
		it->update(t);
	}
	updateBackGround(t);
	updateButtonAlfa(t);
	updateArrow(t);
	introloopBGM.update(t);
	selectIcon();
	if (ENV->pushKey(ci::app::KeyEvent::KEY_RETURN)|| ENV->isPadPush(ENV->BUTTON_2)) {
		desideScene();
	}
	root->entry_update(t);
		if (ENV->pushKey(ci::app::KeyEvent::KEY_a))
		{
			watching = true;
			Network::cUDPClientManager::getInstance()->open();
			cUDPClientManager::getInstance()->connect(Resource::JSON["server.json"]["ip"].asString());
			fase = WatchFase::NONE;
		}
	}

	else
	{
		Network::cUDPClientManager::getInstance()->update(t);
		if (cUDPClientManager::getInstance()->isConnected() == false)return;

		if (fase == WatchFase::NONE)
		{
			cUDPClientManager::getInstance()->send(new cReqInRoomWatching(100));
			fase = WatchFase::BEIGN;
		}

		else if (fase == WatchFase::BEIGN)
		{
			auto m = Network::cUDPClientManager::getInstance()->getUDPManager();

			while (auto resInRoom = m->ResInRoom.get())
			{
				if (resInRoom->mFlag = false)
				{
					cUDPClientManager::getInstance()->send(new cReqInRoom(100));
					continue;
				}
				cUDPClientManager::getInstance()->send(new cReqWantTeamIn(0));
				fase = WatchFase::WAIT;
			}
		}

		else if (fase == WatchFase::WAIT)
		{
			auto m = Network::cUDPClientManager::getInstance()->getUDPManager();
			while (auto resWantTeamIn = m->ResWantTeamIn.get())
			{
				if (resWantTeamIn->mFlag == 1)
				Network::cMatchingMemberManager::getInstance()->mPlayerTeamNum = resWantTeamIn->mTeamNum;;
			}
			while (auto eveTeamMember = m->EveTeamMember.get())
			{
				cMatchingMemberManager::getInstance()->addPlayerDatas(
					eveTeamMember->mNameStr, eveTeamMember->mTeamNum, eveTeamMember->mPlayerID, cNetworkHandle("", 0));
			}
			while (auto resCheckBeginGame = m->ResCheckBeginGame.get())
			{
				cMatchingMemberManager::getInstance()->mPlayerID = resCheckBeginGame->mPlayerID;
				cSceneManager::getInstance()->shift<Scene::Member::cGameMain>();
				continue;
			}
		}

	}

}
void cModeSelect::draw()
{
	mDrawFunc.drawTextureCube(ci::vec3(0), ci::vec3(16, 9, 20), ci::vec3(M_PI/12.f, 0, mBackGroundRotateZ), "modeselect/selectsky.png", ci::ColorA(1, 1, 1));

	for (auto& it : mSelectCards) {
		it->draw();
	}
	drawButton();

	mDrawFunc.drawTextureRect3D(ci::vec3(-0.85-aroowtranceY/2.f, -0.7+aroowtranceY,-0.3), ci::vec3(0.8, 0.16,0),ci::vec3(0,0,M_PI- M_PI / 12.f) , "modeselect/redright.png", ci::ColorA(1, 1, 1, arrowAlfa));
	mDrawFunc.drawTextureRect3D(ci::vec3(1.55+aroowtranceY/2.f, -0.7 + aroowtranceY, -0.3), ci::vec3(-0.8, 0.12, 0), ci::vec3(0, 0, M_PI + M_PI / 4.25f),  "modeselect/redright.png", ci::ColorA(1, 1, 1, arrowAlfa));
	//mDrawFunc.drawTextureRect3D(ci::vec3(-400, -175 + aroowtranceY), ci::vec3(250, 50), M_PI - M_PI / 9.f, "redright.png", ci::ColorA(1, 1, 1, arrowAlfa));
}
void cModeSelect::draw2D()
{
	/*mDrawFunc.drawTextureRect2D(ci::vec2(400,-175+aroowtranceY), ci::vec2(-250, 50), M_PI+M_PI/9.f, "redright.png", ci::ColorA(1, 1, 1,arrowAlfa));
	mDrawFunc.drawTextureRect2D(ci::vec2(-400, -175+aroowtranceY), ci::vec2(250, 50), M_PI - M_PI / 9.f, "redright.png", ci::ColorA(1, 1,1, arrowAlfa));*/
	mDrawFunc.drawTextureRect2D(ci::vec2(550,-320), ci::vec2(-590,449)*0.52f, M_PI, "title/logo.png", ci::ColorA(1, 1, 1, 1));
	root->entry_render(mat4());
}
void cModeSelect::resize()
{

}

void cModeSelect::createTextureNames()
{
	iconnames.push_back("modeselect/online.png");
	iconnames.push_back("modeselect/tutorial.png");
	iconnames.push_back("modeselect/gotitle.png");
	iconnames.push_back("modeselect/training.png");

}

void cModeSelect::changeScene()
{

	switch (MSelectScene)
	{
	case 0:
		shiftOnlineBattle();
		return;
	case 1:
		shiftTutorial();
		return;
	case 2:
		shiftTitle();
		return;
	case 3:
		shiftLocalBattle();
		return;
	default:
		break;
	}
}

void cModeSelect::selectIcon()
{
	if (isfading)return;

	if (ENV->pushKey(ci::app::KeyEvent::KEY_LEFT)||ENV->getPadAxisPushMinus(0)) {
		Resource::cSoundManager::getInstance()->findSe("ModeSelect/cursor.wav").setGain(0.4f);
		Resource::cSoundManager::getInstance()->findSe("ModeSelect/cursor.wav").play();
		for (auto& it : mSelectCards) {
			it->setEasing(true);
		}
		MSelectScene++;
		if (MSelectScene == 4)MSelectScene = 0;
		return;
	}
	if (ENV->pushKey(ci::app::KeyEvent::KEY_RIGHT) || ENV->getPadAxisPushPlus(0)) {
		Resource::cSoundManager::getInstance()->findSe("ModeSelect/cursor.wav").setGain(0.4f);
		Resource::cSoundManager::getInstance()->findSe("ModeSelect/cursor.wav").play();
		for (auto& it : mSelectCards) {
			it->setEasing(false);
		}
		MSelectScene--;
		if (MSelectScene < 0)MSelectScene = 3;
		return;
	}
}

void cModeSelect::shiftOnlineBattle()
{
	//introloopBGM.stop();
	cSceneManager::getInstance()->shift<Scene::Member::cMatching>();
}

void cModeSelect::shiftTitle()
{
	//introloopBGM.stop();
	cSceneManager::getInstance()->shift<Scene::Member::cTitle>();
}

void cModeSelect::shiftLocalBattle()
{
	//introloopBGM.stop();
	Network::cUDPClientManager::getInstance()->open();
	Network::cUDPServerManager::getInstance()->open();
	Network::cUDPClientManager::getInstance()->connectOfflineServer();
	Game::cGameManager::getInstance()->setTime(0.0F);
	cSceneManager::getInstance()->shift<Scene::Member::cGameMain>();
}

void cModeSelect::shiftTutorial()
{
	//introloopBGM.stop();
	Network::cUDPClientManager::getInstance()->open();
	Network::cUDPServerManager::getInstance()->open();
	Network::cUDPClientManager::getInstance()->connectOfflineServer();
	Game::cGameManager::getInstance()->setTime(0.0F);
	cSceneManager::getInstance()->shift<Scene::Member::cTutorial>();
}

void cModeSelect::desideScene()
{
	if (isfading)return;
	for (auto& it : mSelectCards) {
		if (it->getIsEasing())return;//C[WO͖
	}
	Resource::cSoundManager::getInstance()->findSe("ModeSelect/return.wav").setGain(0.8f);
	Resource::cSoundManager::getInstance()->findSe("ModeSelect/return.wav").play();
	introloopBGM.fadeout(0.9f,0.0f);
	isfading = true;
	auto fader = root->add_child(Node::Renderer::rect::create(app::getWindowSize()));
	fader->set_color(ColorA(0, 0, 0, 0));
	fader->set_anchor_point(vec2(0, 0));
	fader->run_action(sequence::create( fade_in::create(1.0F), call_func::create([this]
	{
		this->changeScene();
	})));
}

void cModeSelect::updateBackGround(float t)
{
	mBackGroundRotateZ += 0.02f*t;
}

void cModeSelect::drawButton()
{
	ci::vec3 pos = ci::vec3(-0.5, -0.4, -1.78);
	mDrawFunc.drawTextureRect3D(pos, ci::vec3(0.2, 0.2, 0), ci::vec3(0, M_PI, 0), "modeselect/buttonb.png", ci::ColorA(1, 1, 1, 1));
	mDrawFunc.drawTextureRect3D(pos+ci::vec3(0,0,-0.01), ci::vec3(0.2, 0.2, 0)*buttonscale, ci::vec3(0, M_PI, 0), "modeselect/ring.png", ci::ColorA(1, 1, 0, buttonalfa));

}

void cModeSelect::updateButtonAlfa(float t)
{
	float speed = 2.18f;
	buttonAlfaT += speed*t;
	bool isend = false;
	if (buttonAlfaT >= 1.0f) {
		buttonAlfaT = 1.0f;
		isend = true;
	}
	buttonalfa = EaseCubicIn(buttonAlfaT, 0.4f, 0.8f);
	buttonscale = EaseCubicIn(buttonAlfaT, 0.8f, 1.2f);
	if (isend) {
		buttonAlfaT = 0.0f;
	}

}

void cModeSelect::updateArrow(float t)
{
	float speed = 1.09f;
	arrowT += speed*t;
	bool isend = false;
	if (arrowT >= 1.0f) {
		arrowT = 1.0f;
		isend = true;
	}
	aroowtranceY = EaseReturn(arrowT, 0, 0.05f);//PT
	arrowAlfa = EaseReturn(arrowT, 0.5f, 0.5f);
	if (isend) {
		arrowT = 0.0f;
	}
}

float cModeSelect::EaseReturn(const float t, const float s, const float e)
{
	return s + -4.f*e*(t - 0.5f)*(t - 0.5f) + e;
}

}
}
<|endoftext|>


<commit_before>// http://doc.qt.io/qt-5/qtwebview-minibrowser-example.html
#include <getopt.h>
#include <unistd.h>
#include <iostream>

#include <QtCore/QString>
#include "QtCore/QSocketNotifier"
#include <QGuiApplication>
#include <QtQuick/QQuickView>
#include <QtWebView/QtWebView>
#include <QtQml/QQmlContext>
#include <QtDebug>

#include "moc_Interpreter.cpp"
#include "moc_KioskContext.cpp"

#define VERSION "0.0.1"

int version() {
  std::cout << "kiosk " << VERSION;
#if DEBUG
  std::cout << " -- debug version";
#endif
  std::cout << std::endl;
  std::cout << "Copyright (C) 2017 Jean-Daniel Michaud." << std::endl;
  std::cout << "License MIT: MIT License <https://opensource.org/licenses/MIT>." << std::endl;
  std::cout << "This is free software: you are free to change and redistribute it." << std::endl;
  std::cout << "There is NO WARRANTY, to the extent permitted by law." << std::endl;
  std::cout << std::endl;
  std::cout << "Written by Jean-Daniel Michaud" << std::endl;
  return 0;
}

int help() {
  std::cout << "Usage: ggrep [OPTION]... [URL]" << std::endl;
  return 0;
}

int do_version, do_help, url_specified;
struct option longopts[] = {
   { "version", no_argument,       & do_version,    1   },
   { "help",    no_argument,       & do_help,       1   },
   { 0, 0, 0, 0 }
};

void manage_options(int argc, char **argv, QString &url) {
  // If no url is provided, the value is ""
  int c;
  while ((c = getopt_long(argc, argv, "vh", longopts, NULL)) != -1) {
    switch (c) {
    case 0: /* getopt_long() set a variable, just keep going */
      break;
    case 'h':
      help();
      exit(0);
    case 'v':
      version();
      exit(0);
    case 1:
      break;
    case ':':   /* missing option argument */
      std::cerr << "option '" << argv[optind - 1]
                << "' requires an argument" << std::endl;
      break;
    case '?':   /* invalid option */
      std::cerr << "option `" << argv[optind - 1]
                << "' is invalid: ignored" << std::endl;
      break;
    default:
      std::cerr << "error parsing options" << std::endl;
      break;
    }
  }
  // Treat non option argument (url)
  url = argv[optind];
  // Just ignore all subsequent arguments
}

int main(int argc, char *argv[])
{
  // Retrieve parameters
  QString url = "";
  manage_options(argc, argv, url);
  if (url == "") {
    url = "about:blank";
  }

  // Create context
  KioskContext context;
  context.setUrl(url);

  // Create interpreter
  Interpreter interpreter;
  URLCommand urlCommand(context);
  interpreter.register_("url", &urlCommand);

  // Create Application
  QGuiApplication app(argc, argv);
  QtWebView::initialize();
  QGuiApplication::setApplicationDisplayName(
    QCoreApplication::translate("main", "Kiosk"));

  // Create View
  QQuickView view;
  view.rootContext()->setContextProperty("context", &context);
  view.setSource(QUrl("qrc:/main.qml"));
  view.show();

  // Connect to stdin event
  QSocketNotifier sn(STDIN_FILENO, QSocketNotifier::Read);
  sn.setEnabled(true);
  Interpreter::connect(&sn, SIGNAL(activated(int)), &interpreter, SLOT(readCommand()));

  return app.exec();
}

#include "main.moc"
<commit_msg>Do not read from stdin by default.<commit_after>// http://doc.qt.io/qt-5/qtwebview-minibrowser-example.html
#include <unistd.h>
#include <fcntl.h>

#include <getopt.h>
#include <unistd.h>
#include <iostream>

#include <QtCore/QString>
#include "QtCore/QSocketNotifier"
#include <QGuiApplication>
#include <QtQuick/QQuickView>
#include <QtWebView/QtWebView>
#include <QtQml/QQmlContext>
#include <QtDebug>

#include "moc_Interpreter.cpp"
#include "moc_KioskContext.cpp"

#define VERSION "0.0.1"

int version() {
  std::cout << "kiosk " << VERSION;
#if DEBUG
  std::cout << " -- debug version";
#endif
  std::cout << std::endl;
  std::cout << "Copyright (C) 2017 Jean-Daniel Michaud." << std::endl;
  std::cout << "License MIT: MIT License <https://opensource.org/licenses/MIT>." << std::endl;
  std::cout << "This is free software: you are free to change and redistribute it." << std::endl;
  std::cout << "There is NO WARRANTY, to the extent permitted by law." << std::endl;
  std::cout << std::endl;
  std::cout << "Written by Jean-Daniel Michaud" << std::endl;
  return 0;
}

int help() {
  std::cout << "Usage: kiosk [OPTION]... [URL]" << std::endl;
  std::cout << "  -v    return the version" << std::endl;
  std::cout << "  -h    display this help" << std::endl;
  std::cout << "  -c    read commands from the standard input" << std::endl;
  return 0;
}

int do_version, do_help, read_stdin;
struct option longopts[] = {
   { "version", no_argument,       & do_version,    1   },
   { "help",    no_argument,       & do_help,       1   },
   { "cli",     no_argument,       & read_stdin,    0   },
   { 0, 0, 0, 0 }
};

void manage_options(int argc, char **argv, QString &url) {
  // If no url is provided, the value is ""
  int c;
  while ((c = getopt_long(argc, argv, "vhc", longopts, NULL)) != -1) {
    switch (c) {
    case 0: /* getopt_long() set a variable, just keep going */
      break;
    case 'h':
      help();
      exit(0);
    case 'v':
      version();
      exit(0);
    case 'c':
      read_stdin = 1;
      std::cout << "read_stdin:" << read_stdin << std::endl;
      break;
    case 1:
      break;
    case ':':   /* missing option argument */
      std::cerr << "option '" << argv[optind - 1]
                << "' requires an argument" << std::endl;
      break;
    case '?':   /* invalid option */
      std::cerr << "option `" << argv[optind - 1]
                << "' is invalid: ignored" << std::endl;
      break;
    default:
      std::cerr << "error parsing options" << std::endl;
      break;
    }
  }
  // Treat non option argument (url)
  url = argv[optind];
  // Just ignore all subsequent arguments
}

int main(int argc, char *argv[])
{
  // Retrieve parameters
  QString url = "";
  manage_options(argc, argv, url);
  if (url == "") {
    url = "about:blank";
  }

  // Create context
  KioskContext context;
  context.setUrl(url);

  // Create interpreter
  Interpreter interpreter;
  URLCommand urlCommand(context);
  interpreter.register_("url", &urlCommand);

  // Create Application
  QGuiApplication app(argc, argv);
  QtWebView::initialize();
  QGuiApplication::setApplicationDisplayName(
    QCoreApplication::translate("main", "Kiosk"));

  // Create View
  QQuickView view;
  view.rootContext()->setContextProperty("context", &context);
  view.setSource(QUrl("qrc:/main.qml"));
  view.show();

  // If stdin is open, connect to stdin event
  QSocketNotifier sn(STDIN_FILENO, QSocketNotifier::Read);
  if (read_stdin) {
    std::cout << "reading standard input" << std::endl;
    sn.setEnabled(true);
    Interpreter::connect(&sn, SIGNAL(activated(int)), &interpreter, SLOT(readCommand()));
  }

  return app.exec();
}

#include "main.moc"
<|endoftext|>