<commit_before>/*!
    \file launcher_console.cpp
    \brief Console launcher implementation
    \author Ivan Shynkarenka
    \date 16.07.2015
    \copyright MIT License
*/

#include "benchmark/launcher_console.h"

#include "benchmark/console.h"
#include "benchmark/reporter_console.h"
#include "benchmark/reporter_csv.h"
#include "benchmark/reporter_json.h"
#include "benchmark/version.h"

#include <iomanip>
#include <regex>

#include <OptionParser.h>

namespace CppBenchmark {

void LauncherConsole::Initialize(const int argc, char const* const* const argv)
{
    auto parser = optparse::OptionParser().version(version);

    const char* output[] = { "console", "csv", "json" };

    parser.add_option("-f", "--filter").help("Filter benchmarks by the given regexp pattern");
    parser.add_option("-l", "--list").action("store_true").help("List all avaliable benchmarks");
    parser.add_option("-o", "--output").choices(&output[0], &output[3]).set_default(output[0]).help("Output format (console, csv, json). Default: %default");
    parser.add_option("-q", "--quiet").action("store_true").help("Launch in quiet mode. No progress will be shown!");
    parser.add_option("-r", "--histograms").action("store").type("int").set_default(0).help("Create High Dynamic Range (HDR) Histogram files with a given resolution. Default: %default");

    optparse::Values options = parser.parse_args(argc, argv);

    // Check for double initialization
    if (_init)
    {
        parser.error("Console launcher double initialization!");
    }

    // Print help
    if (options.get("help"))
    {
        parser.print_help();
        exit(EXIT_SUCCESS);
    }

    // Setup console launcher parameters
    _list = options.get("list");
    _silent = options.get("silent");
    _histograms = (int32_t)options.get("histograms");
    if (options.is_set("filter"))
        _filter = options["filter"];
    if (options.is_set("output"))
        _output = options["output"];

    // Update initialization flag
    _init = true;
}

void LauncherConsole::Execute()
{
    if (_list)
    {
        // List all suitable benchmarks
        std::regex matcher(_filter);
        for (auto& benchmark : _benchmarks)
        {
            // Match benchmark name with the given pattern
            if (_filter.empty() || std::regex_match(benchmark->name(), matcher))
                std::cout << benchmark->name() << std::endl;
        }
    }
    else
    {
        // Launch all suitable benchmarks
        Launcher::Launch(_filter);
    }
}

void LauncherConsole::Report() const
{
    if (_output == "console")
    {
        ReporterConsole reporter(std::cout);
        Launcher::Report(reporter);
    }
    else if (_output == "csv")
    {
        ReporterCSV reporter(std::cout);
        Launcher::Report(reporter);
    }
    else if (_output == "json")
    {
        ReporterJSON reporter(std::cout);
        Launcher::Report(reporter);
    }

    // Report histograms
    if (_histograms > 0)
        Launcher::ReportHistograms(_histograms);
}

void LauncherConsole::onLaunching(int current, int total, const BenchmarkBase& benchmark, const Context& context, int attempt)
{
    if (_silent)
        return;

    std::cerr << Color::DARKGREY << "[" << std::setw(3) << (100 * current / total) << "%] " << Color::GREY << "Launching " << Color::LIGHTCYAN << benchmark.name() << context.description() << Color::GREY << ". Attempt " << Color::WHITE << attempt << Color::GREY << "...";
}

void LauncherConsole::onLaunched(int current, int total, const BenchmarkBase& benchmark, const Context& context, int attempt)
{
    if (_silent)
        return;

    std::cerr << Color::LIGHTGREEN << "Done!" << std::endl;
}

} // namespace CppBenchmark
<commit_msg>update<commit_after>/*!
    \file launcher_console.cpp
    \brief Console launcher implementation
    \author Ivan Shynkarenka
    \date 16.07.2015
    \copyright MIT License
*/

#include "benchmark/launcher_console.h"

#include "benchmark/console.h"
#include "benchmark/reporter_console.h"
#include "benchmark/reporter_csv.h"
#include "benchmark/reporter_json.h"
#include "benchmark/version.h"

#include <iomanip>
#include <regex>

#include <OptionParser.h>

namespace CppBenchmark {

void LauncherConsole::Initialize(const int argc, char const* const* const argv)
{
    auto parser = optparse::OptionParser().version(version);

    const char* output[] = { "console", "csv", "json" };

    parser.add_option("-f", "--filter").dest("filter").help("Filter benchmarks by the given regexp pattern");
    parser.add_option("-l", "--list").dest("list").action("store_true").help("List all avaliable benchmarks");
    parser.add_option("-o", "--output").dest("output").choices(&output[0], &output[3]).set_default(output[0]).help("Output format (console, csv, json). Default: %default");
    parser.add_option("-q", "--quiet").dest("quiet").action("store_true").help("Launch in quiet mode. No progress will be shown!");
    parser.add_option("-r", "--histograms").dest("histograms").action("store").type("int").set_default(0).help("Create High Dynamic Range (HDR) Histogram files with a given resolution. Default: %default");

    optparse::Values options = parser.parse_args(argc, argv);

    // Check for double initialization
    if (_init)
    {
        parser.error("Console launcher double initialization!");
    }

    // Print help
    if (options.get("help"))
    {
        parser.print_help();
        exit(EXIT_SUCCESS);
    }

    // Setup console launcher parameters
    _list = options.get("list");
    _quiet = options.get("quiet");
    _histograms = (int32_t)options.get("histograms");
    if (options.is_set("filter"))
        _filter = options["filter"];
    if (options.is_set("output"))
        _output = options["output"];

    // Update initialization flag
    _init = true;
}

void LauncherConsole::Execute()
{
    if (_list)
    {
        // List all suitable benchmarks
        std::regex matcher(_filter);
        for (auto& benchmark : _benchmarks)
        {
            // Match benchmark name with the given pattern
            if (_filter.empty() || std::regex_match(benchmark->name(), matcher))
                std::cout << benchmark->name() << std::endl;
        }
    }
    else
    {
        // Launch all suitable benchmarks
        Launcher::Launch(_filter);
    }
}

void LauncherConsole::Report() const
{
    if (_output == "console")
    {
        ReporterConsole reporter(std::cout);
        Launcher::Report(reporter);
    }
    else if (_output == "csv")
    {
        ReporterCSV reporter(std::cout);
        Launcher::Report(reporter);
    }
    else if (_output == "json")
    {
        ReporterJSON reporter(std::cout);
        Launcher::Report(reporter);
    }

    // Report histograms
    if (_histograms > 0)
        Launcher::ReportHistograms(_histograms);
}

void LauncherConsole::onLaunching(int current, int total, const BenchmarkBase& benchmark, const Context& context, int attempt)
{
    if (_quiet)
        return;

    std::cerr << Color::DARKGREY << "[" << std::setw(3) << (100 * current / total) << "%] " << Color::GREY << "Launching " << Color::LIGHTCYAN << benchmark.name() << context.description() << Color::GREY << ". Attempt " << Color::WHITE << attempt << Color::GREY << "...";
}

void LauncherConsole::onLaunched(int current, int total, const BenchmarkBase& benchmark, const Context& context, int attempt)
{
    if (_quiet)
        return;

    std::cerr << Color::LIGHTGREEN << "Done!" << std::endl;
}

} // namespace CppBenchmark
<|endoftext|>


<commit_before>#include <ctrcommon/app.hpp>
#include <ctrcommon/gpu.hpp>
#include <ctrcommon/input.hpp>
#include <ctrcommon/nor.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>

#include "rop.h"

#include <sys/errno.h>
#include <stdio.h>
#include <string.h>

#include <sstream>
#include <iomanip>

typedef enum {
    INSTALL_CIA,
    DELETE_CIA,
    DELETE_TITLE,
    LAUNCH_TITLE
} Mode;

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

    bool ninjhax = platformIsNinjhax();

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

    MediaType destination = SD;
    Mode mode = INSTALL_CIA;
    bool exit = false;
    bool showNetworkPrompts = true;
    u64 freeSpace = fsGetFreeSpace(destination);

    std::string batchInfo = "";
    int prevProgress = -1;
    auto onProgress = [&](u64 pos, u64 totalSize) {
        u32 progress = (u32) ((pos * 100) / totalSize);
        if(prevProgress != (int) progress) {
            prevProgress = (int) progress;

            std::stringstream details;
            details << batchInfo;
            details << "Press B to cancel.";

            uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
        }

        inputPoll();
        return !inputIsPressed(BUTTON_B);
    };

    auto onLoop = [&]() {
        if(ninjhax && inputIsPressed(BUTTON_START)) {
            exit = true;
            return true;
        }

        bool breakLoop = false;

        if(inputIsPressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fsGetFreeSpace(destination);
            if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
                breakLoop = true;
            }
        }

        if(inputIsPressed(BUTTON_R)) {
            if(mode == INSTALL_CIA) {
                mode = DELETE_CIA;
            } else if(mode == DELETE_CIA) {
                mode = DELETE_TITLE;
                breakLoop = true;
            } else if(mode == DELETE_TITLE) {
                mode = LAUNCH_TITLE;
            } else if(mode == LAUNCH_TITLE) {
                mode = INSTALL_CIA;
                breakLoop = true;
            }
        }

        if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
            while(platformIsRunning()) {
                gpuClearScreens();

                RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN, [&](std::stringstream& infoStream) {
                    if(inputIsPressed(BUTTON_A)) {
                        showNetworkPrompts = !showNetworkPrompts;
                    }

                    infoStream << "\n";
                    infoStream << "Prompts: " << (showNetworkPrompts ? "Enabled" : "Disabled") << "\n";
                    infoStream << "Press A to toggle prompts.";
                });

                if(file.fd == NULL) {
                    break;
                }

                std::stringstream confirmStream;
                confirmStream << "Install the received application?" << "\n";
                confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)";
                if(!showNetworkPrompts || uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
                    AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
                    prevProgress = -1;
                    if(showNetworkPrompts || ret != APP_SUCCESS) {
                        std::stringstream resultMsg;
                        resultMsg << "Install ";
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret);
                        }

                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                    }
                }

                fclose(file.fd);
            }
        }

        if(inputIsPressed(BUTTON_SELECT)) {
            u32 selected = 0;
            bool dirty = true;
            while(platformIsRunning()) {
                inputPoll();
                if(inputIsPressed(BUTTON_B)) {
                    break;
                }

                if(inputIsPressed(BUTTON_A)) {
                    std::stringstream stream;
                    stream << "Install the selected ROP?" << "\n";
                    stream << ropNames[selected];

                    if(uiPrompt(TOP_SCREEN, stream.str(), true)) {
                        u16 userSettingsOffset = 0;
                        bool result = norRead(0x20, &userSettingsOffset, 2) && norWrite(userSettingsOffset << 3, rops[selected], ROP_SIZE);

                        std::stringstream resultMsg;
                        resultMsg << "ROP installation ";
                        if(result) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << platformGetErrorString(platformGetError());
                        }

                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                    }

                    dirty = true;
                }

                if(inputIsPressed(BUTTON_LEFT)) {
                    if(selected == 0) {
                        selected = ROP_COUNT - 1;
                    } else {
                        selected--;
                    }

                    dirty = true;
                }

                if(inputIsPressed(BUTTON_RIGHT)) {
                    if(selected >= ROP_COUNT - 1) {
                        selected = 0;
                    } else {
                        selected++;
                    }

                    dirty = true;
                }

                if(dirty) {
                    std::stringstream stream;
                    stream << "Select a ROP to install." << "\n";
                    stream << "< " << ropNames[selected] << " >" << "\n";
                    stream << "Press A to install, B to cancel.";
                    uiDisplayMessage(TOP_SCREEN, stream.str());
                }
            }
		}

        std::stringstream stream;
        stream << "Battery: ";
        if(platformIsBatteryCharging()) {
            stream << "Charging";
        } else {
            for(u32 i = 0; i < platformGetBatteryLevel(); i++) {
                stream << "|";
            }
        }

        stream << ", WiFi: ";
        if(!platformIsWifiConnected()) {
            stream << "Disconnected";
        } else {
            for(u32 i = 0; i < platformGetWifiLevel(); i++) {
                stream << "|";
            }
        }

        stream << "\n";

        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        if(mode == INSTALL_CIA) {
            stream << "X - Install all CIAs in the current directory" << "\n";
            stream << "Y - Receive an app over the network" << "\n";
        } else if(mode == DELETE_CIA) {
            stream << "X - Delete all CIAs in the current directory" << "\n";
        }

        stream << "SELECT - Install MSET ROP";

        if(ninjhax) {
            stream << "\n" << "START - Exit to launcher";
        }

        std::string str = stream.str();
        const std::string title = "FBI v1.4.1";
        gputDrawString(title, (gpuGetViewportWidth() - gputGetStringWidth(title, 16)) / 2, (gpuGetViewportHeight() - gputGetStringHeight(title, 16) + gputGetStringHeight(str, 8)) / 2, 16, 16);
        gputDrawString(str, (gpuGetViewportWidth() - gputGetStringWidth(str, 8)) / 2, 4, 8, 8);

        return breakLoop;
    };

    while(platformIsRunning()) {
        if(mode == INSTALL_CIA || mode == DELETE_CIA) {
            uiDisplayMessage(BOTTOM_SCREEN, "Loading file list...");

            std::string fileTarget;
            uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
                if(inputIsPressed(BUTTON_X)) {
                    std::stringstream confirmMsg;
                    if(mode == INSTALL_CIA) {
                        confirmMsg << "Install ";
                    } else {
                        confirmMsg << "Delete ";
                    }

                    confirmMsg << "all CIAs in the current directory?";
                    if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                        bool failed = false;
                        std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
                        u32 currItem = 0;
                        for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
                            std::string path = (*it).path;
                            if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
                                std::string displayFileName = (*it).name;
                                if(displayFileName.length() > 40) {
                                    displayFileName.resize(40);
                                    displayFileName += "...";
                                }

                                if(mode == INSTALL_CIA) {
                                    std::stringstream batchInstallStream;
                                    batchInstallStream << displayFileName << " (" << currItem << ")" << "\n";

                                    batchInfo = batchInstallStream.str();
                                    AppResult ret = appInstallFile(destination, path, onProgress);
                                    prevProgress = -1;
                                    batchInfo = "";
                                    if(ret != APP_SUCCESS) {
                                        Error error = platformGetError();
                                        platformSetError(error);

                                        std::stringstream resultMsg;
                                        resultMsg << "Install failed!" << "\n";
                                        resultMsg << displayFileName << "\n";
                                        resultMsg << appGetResultString(ret);
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        if(error.module != MODULE_NN_AM || error.description != DESCRIPTION_ALREADY_EXISTS) {
                                            failed = true;
                                            break;
                                        }
                                    }
                                } else {
                                    std::stringstream deleteStream;
                                    deleteStream << "Deleting CIA..." << "\n";
                                    deleteStream << displayFileName << " (" << currItem << ")";

                                    uiDisplayMessage(TOP_SCREEN, deleteStream.str());
                                    if(remove(path.c_str()) != 0) {
                                        std::stringstream resultMsg;
                                        resultMsg << "Delete failed!" << "\n";
                                        resultMsg << displayFileName << "\n";
                                        resultMsg << strerror(errno);
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        failed = true;
                                        break;
                                    } else {
                                        updateList = true;
                                    }
                                }
                            }

                            currItem++;
                        }

                        if(!failed) {
                            uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
                        }

                        freeSpace = fsGetFreeSpace(destination);
                    }
                }

                return onLoop();
            }, [&](const std::string path, bool &updateList) {
                std::stringstream confirmMsg;
                if(mode == INSTALL_CIA) {
                    confirmMsg << "Install ";
                } else {
                    confirmMsg << "Delete ";
                }

                confirmMsg << "the selected CIA?";
                if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                    std::stringstream resultMsg;
                    if(mode == INSTALL_CIA) {
                        resultMsg << "Install ";
                    } else {
                        resultMsg << "Delete ";
                    }

                    if(mode == INSTALL_CIA) {
                        AppResult ret = appInstallFile(destination, path, onProgress);
                        prevProgress = -1;
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret);
                        }
                    } else {
                        uiDisplayMessage(TOP_SCREEN, "Deleting CIA...");
                        if(remove(path.c_str()) != 0) {
                            updateList = true;
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << strerror(errno);
                        }
                    }

                    uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                    freeSpace = fsGetFreeSpace(destination);
                }

                return false;
            });
        } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
            uiDisplayMessage(BOTTOM_SCREEN, "Loading title list...");

            App appTarget;
            uiSelectApp(&appTarget, destination, [&](bool &updateList) {
                return onLoop();
            }, [&](App app, bool &updateList) {
                if(mode == DELETE_TITLE) {
                    if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) {
                        updateList = true;
                        uiDisplayMessage(TOP_SCREEN, "Deleting title...");
                        AppResult ret = appDelete(app);

                        std::stringstream resultMsg;
                        resultMsg << "Delete ";
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret);
                        }

                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                        freeSpace = fsGetFreeSpace(destination);
                    }
                } else if(mode == LAUNCH_TITLE) {
                    if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
                        updateList = true;
                        uiDisplayMessage(TOP_SCREEN, "Launching title...");
                        AppResult ret = appLaunch(app);

                        if(ret != APP_SUCCESS) {
                            std::stringstream resultMsg;
                            resultMsg << "Launch failed!" << "\n";
                            resultMsg << appGetResultString(ret);
                            uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                        } else {
                            while(true) {
                            }
                        }
                    }
                }

                return false;
            });
        }

        if(exit) {
            break;
        }
    }

    platformCleanup();
    return 0;
}
<commit_msg>Add overwrite prompt when installing an already installed title.<commit_after>#include <ctrcommon/app.hpp>
#include <ctrcommon/gpu.hpp>
#include <ctrcommon/input.hpp>
#include <ctrcommon/nor.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>

#include "rop.h"

#include <sys/errno.h>
#include <stdio.h>
#include <string.h>

#include <sstream>
#include <iomanip>

typedef enum {
    INSTALL_CIA,
    DELETE_CIA,
    DELETE_TITLE,
    LAUNCH_TITLE
} Mode;

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

    bool ninjhax = platformIsNinjhax();

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

    MediaType destination = SD;
    Mode mode = INSTALL_CIA;
    bool exit = false;
    bool showNetworkPrompts = true;
    u64 freeSpace = fsGetFreeSpace(destination);

    std::string batchInfo = "";
    int prevProgress = -1;
    auto onProgress = [&](u64 pos, u64 totalSize) {
        u32 progress = (u32) ((pos * 100) / totalSize);
        if(prevProgress != (int) progress) {
            prevProgress = (int) progress;

            std::stringstream details;
            details << batchInfo;
            details << "Press B to cancel.";

            uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
        }

        inputPoll();
        return !inputIsPressed(BUTTON_B);
    };

    auto onLoop = [&]() {
        if(ninjhax && inputIsPressed(BUTTON_START)) {
            exit = true;
            return true;
        }

        bool breakLoop = false;

        if(inputIsPressed(BUTTON_L)) {
            if(destination == SD) {
                destination = NAND;
            } else {
                destination = SD;
            }

            freeSpace = fsGetFreeSpace(destination);
            if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
                breakLoop = true;
            }
        }

        if(inputIsPressed(BUTTON_R)) {
            if(mode == INSTALL_CIA) {
                mode = DELETE_CIA;
            } else if(mode == DELETE_CIA) {
                mode = DELETE_TITLE;
                breakLoop = true;
            } else if(mode == DELETE_TITLE) {
                mode = LAUNCH_TITLE;
            } else if(mode == LAUNCH_TITLE) {
                mode = INSTALL_CIA;
                breakLoop = true;
            }
        }

        if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
            while(platformIsRunning()) {
                gpuClearScreens();

                RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN, [&](std::stringstream& infoStream) {
                    if(inputIsPressed(BUTTON_A)) {
                        showNetworkPrompts = !showNetworkPrompts;
                    }

                    infoStream << "\n";
                    infoStream << "Prompts: " << (showNetworkPrompts ? "Enabled" : "Disabled") << "\n";
                    infoStream << "Press A to toggle prompts.";
                });

                if(file.fd == NULL) {
                    break;
                }

                std::stringstream confirmStream;
                confirmStream << "Install the received application?" << "\n";
                confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)";
                if(!showNetworkPrompts || uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
                    AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress);
                    prevProgress = -1;
                    if(showNetworkPrompts || ret != APP_SUCCESS) {
                        std::stringstream resultMsg;
                        resultMsg << "Install ";
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret);
                        }

                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                    }
                }

                fclose(file.fd);
            }
        }

        if(inputIsPressed(BUTTON_SELECT)) {
            u32 selected = 0;
            bool dirty = true;
            while(platformIsRunning()) {
                inputPoll();
                if(inputIsPressed(BUTTON_B)) {
                    break;
                }

                if(inputIsPressed(BUTTON_A)) {
                    std::stringstream stream;
                    stream << "Install the selected ROP?" << "\n";
                    stream << ropNames[selected];

                    if(uiPrompt(TOP_SCREEN, stream.str(), true)) {
                        u16 userSettingsOffset = 0;
                        bool result = norRead(0x20, &userSettingsOffset, 2) && norWrite(userSettingsOffset << 3, rops[selected], ROP_SIZE);

                        std::stringstream resultMsg;
                        resultMsg << "ROP installation ";
                        if(result) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << platformGetErrorString(platformGetError());
                        }

                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                    }

                    dirty = true;
                }

                if(inputIsPressed(BUTTON_LEFT)) {
                    if(selected == 0) {
                        selected = ROP_COUNT - 1;
                    } else {
                        selected--;
                    }

                    dirty = true;
                }

                if(inputIsPressed(BUTTON_RIGHT)) {
                    if(selected >= ROP_COUNT - 1) {
                        selected = 0;
                    } else {
                        selected++;
                    }

                    dirty = true;
                }

                if(dirty) {
                    std::stringstream stream;
                    stream << "Select a ROP to install." << "\n";
                    stream << "< " << ropNames[selected] << " >" << "\n";
                    stream << "Press A to install, B to cancel.";
                    uiDisplayMessage(TOP_SCREEN, stream.str());
                }
            }
		}

        std::stringstream stream;
        stream << "Battery: ";
        if(platformIsBatteryCharging()) {
            stream << "Charging";
        } else {
            for(u32 i = 0; i < platformGetBatteryLevel(); i++) {
                stream << "|";
            }
        }

        stream << ", WiFi: ";
        if(!platformIsWifiConnected()) {
            stream << "Disconnected";
        } else {
            for(u32 i = 0; i < platformGetWifiLevel(); i++) {
                stream << "|";
            }
        }

        stream << "\n";

        stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
        stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
        stream << "L - Switch Destination, R - Switch Mode" << "\n";
        if(mode == INSTALL_CIA) {
            stream << "X - Install all CIAs in the current directory" << "\n";
            stream << "Y - Receive an app over the network" << "\n";
        } else if(mode == DELETE_CIA) {
            stream << "X - Delete all CIAs in the current directory" << "\n";
        }

        stream << "SELECT - Install MSET ROP";

        if(ninjhax) {
            stream << "\n" << "START - Exit to launcher";
        }

        std::string str = stream.str();
        const std::string title = "FBI v1.4.2";
        gputDrawString(title, (gpuGetViewportWidth() - gputGetStringWidth(title, 16)) / 2, (gpuGetViewportHeight() - gputGetStringHeight(title, 16) + gputGetStringHeight(str, 8)) / 2, 16, 16);
        gputDrawString(str, (gpuGetViewportWidth() - gputGetStringWidth(str, 8)) / 2, 4, 8, 8);

        return breakLoop;
    };

    while(platformIsRunning()) {
        if(mode == INSTALL_CIA || mode == DELETE_CIA) {
            uiDisplayMessage(BOTTOM_SCREEN, "Loading file list...");

            std::string fileTarget;
            uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
                if(inputIsPressed(BUTTON_X)) {
                    std::stringstream confirmMsg;
                    if(mode == INSTALL_CIA) {
                        confirmMsg << "Install ";
                    } else {
                        confirmMsg << "Delete ";
                    }

                    confirmMsg << "all CIAs in the current directory?";
                    if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                        bool failed = false;
                        std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
                        u32 currItem = 0;
                        for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
                            std::string path = (*it).path;
                            if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) {
                                std::string displayFileName = (*it).name;
                                if(displayFileName.length() > 40) {
                                    displayFileName.resize(40);
                                    displayFileName += "...";
                                }

                                if(mode == INSTALL_CIA) {
                                    App app = appGetCiaInfo(path, destination);
                                    if(appIsInstalled(app)) {
                                        std::stringstream overwriteMsg;
                                        overwriteMsg << "Title already installed, overwrite?" << "\n";
                                        overwriteMsg << displayFileName;
                                        if(uiPrompt(TOP_SCREEN, overwriteMsg.str(), true)) {
                                            uiDisplayMessage(TOP_SCREEN, "Deleting title...");
                                            AppResult ret = appDelete(app);
                                            if(ret != APP_SUCCESS) {
                                                std::stringstream resultMsg;
                                                resultMsg << "Delete failed!" << "\n";
                                                resultMsg << appGetResultString(ret);
                                                uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                                                failed = true;
                                                break;
                                            }
                                        } else {
                                            continue;
                                        }
                                    }

                                    std::stringstream batchInstallStream;
                                    batchInstallStream << displayFileName << " (" << currItem << ")" << "\n";

                                    batchInfo = batchInstallStream.str();
                                    AppResult ret = appInstallFile(destination, path, onProgress);
                                    prevProgress = -1;
                                    batchInfo = "";
                                    if(ret != APP_SUCCESS) {
                                        Error error = platformGetError();
                                        platformSetError(error);

                                        std::stringstream resultMsg;
                                        resultMsg << "Install failed!" << "\n";
                                        resultMsg << displayFileName << "\n";
                                        resultMsg << appGetResultString(ret);
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        if(error.module != MODULE_NN_AM || error.description != DESCRIPTION_ALREADY_EXISTS) {
                                            failed = true;
                                            break;
                                        }
                                    }
                                } else {
                                    std::stringstream deleteStream;
                                    deleteStream << "Deleting CIA..." << "\n";
                                    deleteStream << displayFileName << " (" << currItem << ")";

                                    uiDisplayMessage(TOP_SCREEN, deleteStream.str());
                                    if(remove(path.c_str()) != 0) {
                                        std::stringstream resultMsg;
                                        resultMsg << "Delete failed!" << "\n";
                                        resultMsg << displayFileName << "\n";
                                        resultMsg << strerror(errno);
                                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                                        failed = true;
                                        break;
                                    } else {
                                        updateList = true;
                                    }
                                }
                            }

                            currItem++;
                        }

                        if(!failed) {
                            uiPrompt(TOP_SCREEN, "Install succeeded!\n", false);
                        }

                        freeSpace = fsGetFreeSpace(destination);
                    }
                }

                return onLoop();
            }, [&](const std::string path, bool &updateList) {
                std::stringstream confirmMsg;
                if(mode == INSTALL_CIA) {
                    confirmMsg << "Install ";
                } else {
                    confirmMsg << "Delete ";
                }

                confirmMsg << "the selected CIA?";
                if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
                    std::stringstream resultMsg;
                    if(mode == INSTALL_CIA) {
                        resultMsg << "Install ";
                    } else {
                        resultMsg << "Delete ";
                    }

                    if(mode == INSTALL_CIA) {
                        App app = appGetCiaInfo(path, destination);
                        if(appIsInstalled(app)) {
                            std::stringstream overwriteMsg;
                            overwriteMsg << "Title already installed, overwrite?";
                            if(uiPrompt(TOP_SCREEN, overwriteMsg.str(), true)) {
                                uiDisplayMessage(TOP_SCREEN, "Deleting title...");
                                AppResult ret = appDelete(app);
                                if(ret != APP_SUCCESS) {
                                    std::stringstream deleteResultMsg;
                                    deleteResultMsg << "Delete failed!" << "\n";
                                    deleteResultMsg << appGetResultString(ret);
                                    uiPrompt(TOP_SCREEN, deleteResultMsg.str(), false);

                                    return false;
                                }
                            } else {
                                return false;
                            }
                        }

                        AppResult ret = appInstallFile(destination, path, onProgress);
                        prevProgress = -1;
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret);
                        }
                    } else {
                        uiDisplayMessage(TOP_SCREEN, "Deleting CIA...");
                        if(remove(path.c_str()) != 0) {
                            updateList = true;
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << strerror(errno);
                        }
                    }

                    uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                    freeSpace = fsGetFreeSpace(destination);
                }

                return false;
            });
        } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
            uiDisplayMessage(BOTTOM_SCREEN, "Loading title list...");

            App appTarget;
            uiSelectApp(&appTarget, destination, [&](bool &updateList) {
                return onLoop();
            }, [&](App app, bool &updateList) {
                if(mode == DELETE_TITLE) {
                    if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) {
                        updateList = true;
                        uiDisplayMessage(TOP_SCREEN, "Deleting title...");
                        AppResult ret = appDelete(app);

                        std::stringstream resultMsg;
                        resultMsg << "Delete ";
                        if(ret == APP_SUCCESS) {
                            resultMsg << "succeeded!";
                        } else {
                            resultMsg << "failed!" << "\n";
                            resultMsg << appGetResultString(ret);
                        }

                        uiPrompt(TOP_SCREEN, resultMsg.str(), false);

                        freeSpace = fsGetFreeSpace(destination);
                    }
                } else if(mode == LAUNCH_TITLE) {
                    if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
                        updateList = true;
                        uiDisplayMessage(TOP_SCREEN, "Launching title...");
                        AppResult ret = appLaunch(app);

                        if(ret != APP_SUCCESS) {
                            std::stringstream resultMsg;
                            resultMsg << "Launch failed!" << "\n";
                            resultMsg << appGetResultString(ret);
                            uiPrompt(TOP_SCREEN, resultMsg.str(), false);
                        } else {
                            while(true) {
                            }
                        }
                    }
                }

                return false;
            });
        }

        if(exit) {
            break;
        }
    }

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


<commit_before>//===-- Mangler.cpp - Self-contained c/asm llvm name mangler --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Unified name mangler for CWriter and assembly backends.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/Mangler.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/ADT/StringExtras.h"
using namespace llvm;

static char HexDigit(int V) {
  return V < 10 ? V+'0' : V+'A'-10;
}

static std::string MangleLetter(unsigned char C) {
  return std::string("_")+HexDigit(C >> 4) + HexDigit(C & 15) + "_";
}

/// makeNameProper - We don't want identifier names non-C-identifier characters
/// in them, so mangle them as appropriate.
///
std::string Mangler::makeNameProper(const std::string &X, const char *Prefix) {
  std::string Result;

  // If X does not start with (char)1, add the prefix.
  std::string::const_iterator I = X.begin();
  if (*I != 1)
    Result = Prefix;
  else
    ++I;  // Skip over the marker.

  // Mangle the first letter specially, don't allow numbers...
  if (*I >= '0' && *I <= '9')
    Result += MangleLetter(*I++);

  for (std::string::const_iterator E = X.end(); I != E; ++I)
    if ((*I < 'a' || *I > 'z') && (*I < 'A' || *I > 'Z') &&
        (*I < '0' || *I > '9') && *I != '_' && *I != '$')
      Result += MangleLetter(*I);
    else
      Result += *I;
  return Result;
}

/// getTypeID - Return a unique ID for the specified LLVM type.
///
unsigned Mangler::getTypeID(const Type *Ty) {
  unsigned &E = TypeMap[Ty];
  if (E == 0) E = ++TypeCounter;
  return E;
}

std::string Mangler::getValueName(const Value *V) {
  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
    return getValueName(GV);

  std::string &Name = Memo[V];
  if (!Name.empty())
    return Name;       // Return the already-computed name for V.

  // Always mangle local names.
  Name = "ltmp_" + utostr(Count++) + "_" + utostr(getTypeID(V->getType()));
  return Name;
}

std::string Mangler::getValueName(const GlobalValue *GV) {
  // Check to see whether we've already named V.
  std::string &Name = Memo[GV];
  if (!Name.empty())
    return Name;       // Return the already-computed name for V.

  // Name mangling occurs as follows:
  // - If V is an intrinsic function, do not change name at all
  // - Otherwise, mangling occurs if global collides with existing name.
  if (isa<Function>(GV) && cast<Function>(GV)->getIntrinsicID()) {
    Name = GV->getName(); // Is an intrinsic function
  } else if (!MangledGlobals.count(GV)) {
    Name = makeNameProper(GV->getName(), Prefix);
  } else {
    unsigned TypeUniqueID = getTypeID(GV->getType());
    Name = "l" + utostr(TypeUniqueID) + "_" + makeNameProper(GV->getName());
  }

  return Name;
}

void Mangler::InsertName(GlobalValue *GV,
                         std::map<std::string, GlobalValue*> &Names) {
  if (!GV->hasName()) {   // We must mangle unnamed globals.
    MangledGlobals.insert(GV);
    return;
  }

  // Figure out if this is already used.
  GlobalValue *&ExistingValue = Names[GV->getName()];
  if (!ExistingValue) {
    ExistingValue = GV;
  } else {
    // If GV is external but the existing one is static, mangle the existing one
    if (GV->hasExternalLinkage() && !ExistingValue->hasExternalLinkage()) {
      MangledGlobals.insert(ExistingValue);
      ExistingValue = GV;
    } else {
      // Otherwise, mangle GV
      MangledGlobals.insert(GV);
    }
  }
}

Mangler::Mangler(Module &m, const char *prefix)
  : M(m), Prefix(prefix), TypeCounter(0), Count(0) {
  // Calculate which global values have names that will collide when we throw
  // away type information.
  std::map<std::string, GlobalValue*> Names;
  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
    InsertName(I, Names);
  for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
    InsertName(I, Names);
}
<commit_msg>remove the M instance var<commit_after>//===-- Mangler.cpp - Self-contained c/asm llvm name mangler --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Unified name mangler for CWriter and assembly backends.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/Mangler.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/ADT/StringExtras.h"
using namespace llvm;

static char HexDigit(int V) {
  return V < 10 ? V+'0' : V+'A'-10;
}

static std::string MangleLetter(unsigned char C) {
  return std::string("_")+HexDigit(C >> 4) + HexDigit(C & 15) + "_";
}

/// makeNameProper - We don't want identifier names non-C-identifier characters
/// in them, so mangle them as appropriate.
///
std::string Mangler::makeNameProper(const std::string &X, const char *Prefix) {
  std::string Result;

  // If X does not start with (char)1, add the prefix.
  std::string::const_iterator I = X.begin();
  if (*I != 1)
    Result = Prefix;
  else
    ++I;  // Skip over the marker.

  // Mangle the first letter specially, don't allow numbers...
  if (*I >= '0' && *I <= '9')
    Result += MangleLetter(*I++);

  for (std::string::const_iterator E = X.end(); I != E; ++I)
    if ((*I < 'a' || *I > 'z') && (*I < 'A' || *I > 'Z') &&
        (*I < '0' || *I > '9') && *I != '_' && *I != '$')
      Result += MangleLetter(*I);
    else
      Result += *I;
  return Result;
}

/// getTypeID - Return a unique ID for the specified LLVM type.
///
unsigned Mangler::getTypeID(const Type *Ty) {
  unsigned &E = TypeMap[Ty];
  if (E == 0) E = ++TypeCounter;
  return E;
}

std::string Mangler::getValueName(const Value *V) {
  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
    return getValueName(GV);

  std::string &Name = Memo[V];
  if (!Name.empty())
    return Name;       // Return the already-computed name for V.

  // Always mangle local names.
  Name = "ltmp_" + utostr(Count++) + "_" + utostr(getTypeID(V->getType()));
  return Name;
}

std::string Mangler::getValueName(const GlobalValue *GV) {
  // Check to see whether we've already named V.
  std::string &Name = Memo[GV];
  if (!Name.empty())
    return Name;       // Return the already-computed name for V.

  // Name mangling occurs as follows:
  // - If V is an intrinsic function, do not change name at all
  // - Otherwise, mangling occurs if global collides with existing name.
  if (isa<Function>(GV) && cast<Function>(GV)->getIntrinsicID()) {
    Name = GV->getName(); // Is an intrinsic function
  } else if (!MangledGlobals.count(GV)) {
    Name = makeNameProper(GV->getName(), Prefix);
  } else {
    unsigned TypeUniqueID = getTypeID(GV->getType());
    Name = "l" + utostr(TypeUniqueID) + "_" + makeNameProper(GV->getName());
  }

  return Name;
}

void Mangler::InsertName(GlobalValue *GV,
                         std::map<std::string, GlobalValue*> &Names) {
  if (!GV->hasName()) {   // We must mangle unnamed globals.
    MangledGlobals.insert(GV);
    return;
  }

  // Figure out if this is already used.
  GlobalValue *&ExistingValue = Names[GV->getName()];
  if (!ExistingValue) {
    ExistingValue = GV;
  } else {
    // If GV is external but the existing one is static, mangle the existing one
    if (GV->hasExternalLinkage() && !ExistingValue->hasExternalLinkage()) {
      MangledGlobals.insert(ExistingValue);
      ExistingValue = GV;
    } else {
      // Otherwise, mangle GV
      MangledGlobals.insert(GV);
    }
  }
}

Mangler::Mangler(Module &M, const char *prefix)
  : Prefix(prefix), Count(0), TypeCounter(0) {
  // Calculate which global values have names that will collide when we throw
  // away type information.
  std::map<std::string, GlobalValue*> Names;
  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
    InsertName(I, Names);
  for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
    InsertName(I, Names);
}
<|endoftext|>


<commit_before>/* Nom: main.cpp
 * Description: module sous-système de contrôle: gestion du dialogue avec l'utilisateur et interface graphique
 * Date: 08.02.2014
 * version : 1.0
 * responsable du module : Pauline Maury Laribière
 * groupe : Alexandre Devienne, Pauline Maury Laribière
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

extern "C"
{
#include "sim.h"
}

enum Mode {ERROR, FORCE, INTEGRATION, GRAPHIC, SIMULATION, MODE_UNSET};
typedef enum Mode MODE;

MODE read_mode(char string[]);

int main (int argc, char *argv[])
{
	enum Mode mode;
    mode = read_mode(argv[1]);

	if(argc!=3)
	{
		printf("syntaxe attendue : sim.x [Error|Force|Integration|Graphic|Simulation,nom_fichier]\n");
	}
	else
	{
		switch(mode)
		{
			case ERROR: sim_error(argv[2]);
			break;
			case FORCE: sim_force(argv[2]);
			break;
			case INTEGRATION: //sim_integration(argv[2]);
			break;
			case GRAPHIC: //sim_graphic(argv[2]);
			break;
			case SIMULATION: //sim_simulation(argv[2]);
			break;
			case MODE_UNSET: printf("syntaxe attendue : sim.x [Error|Force|Integration|Graphic|Simulation,nom_fichier]\n");
			return EXIT_FAILURE;
		}
	}
	return EXIT_SUCCESS;
}

MODE read_mode(char string[])
{
	MODE mode;
	if(strcmp(string, "Error" ) == 0)
    {
		mode = ERROR;
    }
    else if (strcmp(string, "Force" ) == 0)
    {
		mode = FORCE;
    }
    else if (strcmp(string, "Integration" ) == 0)
    {
		mode = INTEGRATION;
    }
    else if (strcmp(string, "Graphic" ) == 0)
    {
		mode = GRAPHIC;
    }
    else if (strcmp(string, "Simulation" ) == 0)
    {
		mode = SIMULATION;
    }
    else
    {
		mode = MODE_UNSET;
    }
    return mode;
}

<commit_msg>update main.cpp mode unset<commit_after>/* Nom: main.cpp
 * Description: module sous-système de contrôle: gestion du dialogue
				avec l'utilisateur et interface graphique
 * Date: 08.02.2014
 * version : 1.0
 * responsable du module : Pauline Maury Laribière
 * groupe : Alexandre Devienne, Pauline Maury Laribière
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

extern "C"
{
#include "sim.h"
}

enum Mode {ERROR, FORCE, INTEGRATION, GRAPHIC, SIMULATION, MODE_UNSET};
typedef enum Mode MODE;

static MODE read_mode(char string[]);

int main (int argc, char *argv[])
{
	enum Mode mode;
    mode = MODE_UNSET;

	if(argc==3)
	{
		mode = read_mode(argv[1]);
	}
	switch(mode)
	{
		case ERROR: sim_error(argv[2]);
		break;
		case FORCE: sim_force(argv[2]);
		break;
		case INTEGRATION: //sim_integration(argv[2]);
		break;
		case GRAPHIC: //sim_graphic(argv[2]);
		break;
		case SIMULATION: //sim_simulation(argv[2]);
		break;
		case MODE_UNSET: printf("Syntaxe attendue : sim.x [Error"
								"|Force|Integration|Graphic|Simulation,"
								"nom_fichier]\n");
		return EXIT_FAILURE;
	}
	return EXIT_SUCCESS;
}

static MODE read_mode(char string[])
{
	MODE mode;
	if(strcmp(string, "Error" ) == 0)
    {
		mode = ERROR;
    }
    else if (strcmp(string, "Force" ) == 0)
    {
		mode = FORCE;
    }
    else if (strcmp(string, "Integration" ) == 0)
    {
		mode = INTEGRATION;
    }
    else if (strcmp(string, "Graphic" ) == 0)
    {
		mode = GRAPHIC;
    }
    else if (strcmp(string, "Simulation" ) == 0)
    {
		mode = SIMULATION;
    }
    else
    {
		mode = MODE_UNSET;
    }
    return mode;
}

<|endoftext|>


<commit_before>/*
 *
 *                                   C R I S S C R O S S
 *                          A multi purpose cross platform library.
 *                              formerly Codename "Technetium"
 *                             project started August 14, 2006
 *
 * Copyright (c) 2006, Steven Noonan <steven@uplinklabs.net>, Rudolf Olah <omouse@gmail.com>,
 * and Miah Clayton <miah@io-in.com>. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice, this list
 *       of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this
 *       list of conditions and the following disclaimer in the documentation and/or other
 *       materials provided with the distribution.
 *     * Neither the name of Uplink Laboratories nor the names of its contributors may be
 *       used to endorse or promote products derived from this software without specific
 *       prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "universal_include.h"

#define NETWORK_DIAGNOSTIC

#include "core_filesystem.h"
#include "core_console.h"
#include "core_error.h"

#ifdef NETWORK_DIAGNOSTIC
#	include "udpsocket.h"
#endif

#ifdef CPUID_PROGRAM
#	include "core_cpuid.h"
#endif

#ifdef SORT_PROGRAM
#	include "SortClass.h"
#endif

using namespace CrissCross;
using namespace CrissCross::IO;

#ifdef NETWORK_DIAGNOSTIC
using namespace CrissCross::Network;
#endif

using namespace std;

int
RunApplication ( int argc, char **argv )
{
	int retval = 0;
	CoreConsole *console = new CoreConsole ();

#ifdef NETWORK_DIAGNOSTIC

	UDPSocket *socket_out = new UDPSocket();
	UDPSocket *socket_in = new UDPSocket();
	string input = "";
	console->WriteLine ( "Enter an IP to send diagnostic requests to." );
	while ( input.length() == 0 )
		cin >> input;

	retval = socket_out->Bind ( input.c_str(), 9931 );
	if ( retval != CC_ERR_NONE )
		abort();
	retval = socket_in->Listen ( 9931 );
	if ( retval != CC_ERR_NONE )
		abort();

	time_t LastIncomingPacket, Now;
	int InSeqID = -1, OutSeqID = 1, loss = 0, tempSeq, SeqDiff;
	unsigned int len;
	char buffer[128];
	char *buf = NULL;

	// Establish a "connection"
	printf ( "Waiting for initial reply... " );
	while ( true )
	{
#ifdef TARGET_OS_WINDOWS
		Sleep ( 300 );
#else
		usleep ( 300000 );
#endif
		memset ( buffer, 0, sizeof ( buffer ) );
		memcpy ( buffer, &InSeqID, sizeof ( int ) );

		retval = socket_out->Send ( buffer, sizeof ( buffer ) );
		retval = socket_in->Read ( &buf, &len );

		if ( retval == CrissCross::CC_ERR_NONE )
			break;
	}
	delete [] buf;

	// Calm before the storm...
	// Sleep ( 1500 );

	time ( &LastIncomingPacket ); // Initial packet does count

	printf ( "Received!\nRunning diagnostic...\n" );
	while ( true )
	{
		memset ( buffer, 0, sizeof ( buffer ) );
		memcpy ( buffer, &OutSeqID, sizeof ( int ) );
		retval = socket_out->Send ( buffer, sizeof ( buffer ) );
		retval = socket_in->Read ( &buf, &len );

		if ( buf )
			memcpy ( &tempSeq, buf, sizeof ( int ) );
		else
			tempSeq = -5;

		if ( tempSeq != -5 && tempSeq != -1 && buf )
		{
			time ( &LastIncomingPacket );
			SeqDiff = tempSeq - InSeqID;
			if ( SeqDiff == 1 )
			{
				// A difference of 1 means we just got the appropriate SeqID.
				InSeqID = tempSeq;
			} else if ( SeqDiff > 1 ) {
				// A difference of > 1 means we skipped one or more.
				if ( InSeqID != -1 )
					loss += SeqDiff - 1;
				InSeqID = tempSeq;
			} else if ( SeqDiff < 1 ) {
				// A difference of < 1 means we got one late.
				loss -= 1;
			} else {
				// What the hell?
				printf ( "SeqID %d unhandled.\n", tempSeq );
			}
			delete [] buf;
			buf = NULL;
		}
		time ( &Now );
		printf ( "In: %d Out: %d Loss: %d Last Packet: %lds  \r", InSeqID, OutSeqID, loss, Now - LastIncomingPacket );
		OutSeqID++;
#ifdef TARGET_OS_WINDOWS
		Sleep(100);
#else
		usleep ( 100 );
#endif
	}

	system ( "pause" );
#endif

#ifdef SORT_PROGRAM
    int ints[1024];
    memset ( ints, 0, sizeof ( ints ) );
    srand ( GetTickCount() );

    for ( int i = 0; i < 1024; i++ )
    {
        ints[i] = rand();
        printf ( "%d ", ints[i] );
    }
    printf ( "\n\n" );

    HeapSort<int> *sort = new HeapSort<int>();
    IntegerCompare *comparison = new IntegerCompare();

    sort->Sort ( ints, 1024, comparison );

    for ( int i = 0; i < 1024; i++ )
    {
        printf ( "%d ", ints[i] );
    }
    printf ( "\n\n" );

    delete sort;
    delete comparison;
#endif

#ifdef CPUID_PROGRAM
    CoreCPUID *cpuid = new CoreCPUID ();
    console->SetColour ( console->FG_RED | console->FG_INTENSITY );
    console->WriteLine ( "======================" );
    console->WriteLine ( "= CPU IDENTIFICATION =" );
    console->WriteLine ( "======================" );
    console->SetColour ( 0 );
    console->WriteLine ();

    cpuid->Go ();
    console->WriteLine ( "There are %d processors in the system.",
                         cpuid->GetCPUCount () );

    for ( int i = 0; i < MAX_PROCESSORS; i++ )
    {
        if ( cpuid->proc[i]->Manufacturer != NULL )
        {
            console->WriteLine ( "CPU[%d] Manufacturer: %s", i,
                                 cpuid->proc[i]->Manufacturer );
            console->WriteLine ( "CPU[%d] Name: %s", i,
                                 cpuid->proc[i]->ProcessorName );
            console->
                WriteLine ( "CPU[%d] Family: %d, Model: %d, Stepping: %d", i,
                            cpuid->proc[i]->Family, cpuid->proc[i]->Model,
                            cpuid->proc[i]->Stepping );
            if ( cpuid->proc[i]->caches.Size () > 0 )
            {
                console->WriteLine ( "CPU[%d] Caches:", i );
                for ( int j = 0; j < cpuid->proc[i]->caches.Size (); j++ )
                {
                    if ( cpuid->proc[i]->caches.ValidIndex ( j ) )
                        console->Write ( "  %s",
                                         cpuid->proc[i]->caches.
                                         GetData ( j ) );
                }
                console->WriteLine ();
            }
            console->Write ( "CPU[%d] Features: ", i );
            RedBlackTree < Feature *, char *>::nodeType * node =
                cpuid->proc[i]->features.rootNode;
            node->beenThere =
                RedBlackTree < Feature *, char *>::NODE_ITSELF_VISITED;
            while ( cpuid->proc[i]->features.ValidNode ( node ) )
            {
                if ( node->data->Enabled )
                    console->Write ( "%s ", node->id );
                cpuid->proc[i]->features.getNext ( &node );
            }
            console->WriteLine ();
            console->WriteLine ();
        }
    }
    delete cpuid;
#endif
    delete console;

    return 0;
}
<commit_msg>Setting CPUID as default app.<commit_after>/*
 *
 *                                   C R I S S C R O S S
 *                          A multi purpose cross platform library.
 *                              formerly Codename "Technetium"
 *                             project started August 14, 2006
 *
 * Copyright (c) 2006, Steven Noonan <steven@uplinklabs.net>, Rudolf Olah <omouse@gmail.com>,
 * and Miah Clayton <miah@io-in.com>. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice, this list
 *       of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this
 *       list of conditions and the following disclaimer in the documentation and/or other
 *       materials provided with the distribution.
 *     * Neither the name of Uplink Laboratories nor the names of its contributors may be
 *       used to endorse or promote products derived from this software without specific
 *       prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "universal_include.h"

#define CPUID_PROGRAM

#include "core_filesystem.h"
#include "core_console.h"
#include "core_error.h"

#ifdef NETWORK_DIAGNOSTIC
#	include "udpsocket.h"
#endif

#ifdef CPUID_PROGRAM
#	include "core_cpuid.h"
#endif

#ifdef SORT_PROGRAM
#	include "SortClass.h"
#endif

using namespace CrissCross;
using namespace CrissCross::IO;

#ifdef NETWORK_DIAGNOSTIC
using namespace CrissCross::Network;
#endif

using namespace std;

int
RunApplication ( int argc, char **argv )
{
	CoreConsole *console = new CoreConsole ();

#ifdef NETWORK_DIAGNOSTIC
	int retval = 0;

	UDPSocket *socket_out = new UDPSocket();
	UDPSocket *socket_in = new UDPSocket();
	string input = "";
	console->WriteLine ( "Enter an IP to send diagnostic requests to." );
	while ( input.length() == 0 )
		cin >> input;

	retval = socket_out->Bind ( input.c_str(), 9931 );
	if ( retval != CC_ERR_NONE )
		abort();
	retval = socket_in->Listen ( 9931 );
	if ( retval != CC_ERR_NONE )
		abort();

	time_t LastIncomingPacket, Now;
	int InSeqID = -1, OutSeqID = 1, loss = 0, tempSeq, SeqDiff;
	unsigned int len;
	char buffer[128];
	char *buf = NULL;

	// Establish a "connection"
	printf ( "Waiting for initial reply... " );
	while ( true )
	{
#ifdef TARGET_OS_WINDOWS
		Sleep ( 300 );
#else
		usleep ( 300000 );
#endif
		memset ( buffer, 0, sizeof ( buffer ) );
		memcpy ( buffer, &InSeqID, sizeof ( int ) );

		retval = socket_out->Send ( buffer, sizeof ( buffer ) );
		retval = socket_in->Read ( &buf, &len );

		if ( retval == CrissCross::CC_ERR_NONE )
			break;
	}
	delete [] buf;

	// Calm before the storm...
	// Sleep ( 1500 );

	time ( &LastIncomingPacket ); // Initial packet does count

	printf ( "Received!\nRunning diagnostic...\n" );
	while ( true )
	{
		memset ( buffer, 0, sizeof ( buffer ) );
		memcpy ( buffer, &OutSeqID, sizeof ( int ) );
		retval = socket_out->Send ( buffer, sizeof ( buffer ) );
		retval = socket_in->Read ( &buf, &len );

		if ( buf )
			memcpy ( &tempSeq, buf, sizeof ( int ) );
		else
			tempSeq = -5;

		if ( tempSeq != -5 && tempSeq != -1 && buf )
		{
			time ( &LastIncomingPacket );
			SeqDiff = tempSeq - InSeqID;
			if ( SeqDiff == 1 )
			{
				// A difference of 1 means we just got the appropriate SeqID.
				InSeqID = tempSeq;
			} else if ( SeqDiff > 1 ) {
				// A difference of > 1 means we skipped one or more.
				if ( InSeqID != -1 )
					loss += SeqDiff - 1;
				InSeqID = tempSeq;
			} else if ( SeqDiff < 1 ) {
				// A difference of < 1 means we got one late.
				loss -= 1;
			} else {
				// What the hell?
				printf ( "SeqID %d unhandled.\n", tempSeq );
			}
			delete [] buf;
			buf = NULL;
		}
		time ( &Now );
		printf ( "In: %d Out: %d Loss: %d Last Packet: %lds  \r", InSeqID, OutSeqID, loss, Now - LastIncomingPacket );
		OutSeqID++;
#ifdef TARGET_OS_WINDOWS
		Sleep(100);
#else
		usleep ( 100 );
#endif
	}

	system ( "pause" );
#endif

#ifdef SORT_PROGRAM
    int ints[1024];
    memset ( ints, 0, sizeof ( ints ) );
    srand ( GetTickCount() );

    for ( int i = 0; i < 1024; i++ )
    {
        ints[i] = rand();
        printf ( "%d ", ints[i] );
    }
    printf ( "\n\n" );

    HeapSort<int> *sort = new HeapSort<int>();
    IntegerCompare *comparison = new IntegerCompare();

    sort->Sort ( ints, 1024, comparison );

    for ( int i = 0; i < 1024; i++ )
    {
        printf ( "%d ", ints[i] );
    }
    printf ( "\n\n" );

    delete sort;
    delete comparison;
#endif

#ifdef CPUID_PROGRAM
    CoreCPUID *cpuid = new CoreCPUID ();
    console->SetColour ( console->FG_RED | console->FG_INTENSITY );
    console->WriteLine ( "======================" );
    console->WriteLine ( "= CPU IDENTIFICATION =" );
    console->WriteLine ( "======================" );
    console->SetColour ( 0 );
    console->WriteLine ();

    cpuid->Go ();
    console->WriteLine ( "There are %d processors in the system.",
                         cpuid->GetCPUCount () );

    for ( int i = 0; i < MAX_PROCESSORS; i++ )
    {
        if ( cpuid->proc[i]->Manufacturer != NULL )
        {
            console->WriteLine ( "CPU[%d] Manufacturer: %s", i,
                                 cpuid->proc[i]->Manufacturer );
            console->WriteLine ( "CPU[%d] Name: %s", i,
                                 cpuid->proc[i]->ProcessorName );
            console->
                WriteLine ( "CPU[%d] Family: %d, Model: %d, Stepping: %d", i,
                            cpuid->proc[i]->Family, cpuid->proc[i]->Model,
                            cpuid->proc[i]->Stepping );
            if ( cpuid->proc[i]->caches.Size () > 0 )
            {
                console->WriteLine ( "CPU[%d] Caches:", i );
                for ( int j = 0; j < cpuid->proc[i]->caches.Size (); j++ )
                {
                    if ( cpuid->proc[i]->caches.ValidIndex ( j ) )
                        console->Write ( "  %s",
                                         cpuid->proc[i]->caches.
                                         GetData ( j ) );
                }
                console->WriteLine ();
            }
            console->Write ( "CPU[%d] Features: ", i );
            RedBlackTree < Feature *, char *>::nodeType * node =
                cpuid->proc[i]->features.rootNode;
            node->beenThere =
                RedBlackTree < Feature *, char *>::NODE_ITSELF_VISITED;
            while ( cpuid->proc[i]->features.ValidNode ( node ) )
            {
                if ( node->data->Enabled )
                    console->Write ( "%s ", node->id );
                cpuid->proc[i]->features.getNext ( &node );
            }
            console->WriteLine ();
            console->WriteLine ();
        }
    }
    delete cpuid;
#endif
    delete console;

    return 0;
}
<|endoftext|>


<commit_before>#include <cstring>
#include <iostream>

#include "MrMangler.h"
#include "FuncDecl.h"

mangle_fn parseArgs(int argc, char** argv, FILE* &input_file)
{
    for(int i=1; i < argc; ++i) {
      if(0 == strcmp(argv[i], "--help") ||
         0 == strcmp(argv[i], "-h")) {
           std::cout << "help:" <<std::endl;
           exit(0);
      }

      if(0 == strcmp(argv[i], "--windows") ||
         0 == strcmp(argv[i], "-w")) {
           return &mangle_windows;
      }

      if(0 == strcmp(argv[i], "--Itanium") ||
         0 == strcmp(argv[i], "-i")) {
          return &mangle_itanium;
      }

      if ('-' != argv[i][0]) {
        input_file = fopen(argv[i], "r");
        if (!input_file) {
           std::cout << "Error opening input file "<< argv[i] << std::endl;
           exit(0);
        }
      }
    }

    return &mangle_itanium;
}

int main(int argc, char** argv)
{
    mangle_fn target_mangler = &mangle_itanium;
    FILE* f = nullptr;
    if (argc > 1)
        target_mangler = parseArgs(argc, argv, f);

    const FuncDecl* func_decl = ParseStdin(f);
    if (f)
      fclose(f);

    const std::string mangled_str = target_mangler(func_decl);
    std::cout << mangled_str << std::endl;

    return 0;
}
<commit_msg>Document CLI options in help<commit_after>#include <cstring>
#include <iostream>

#include "MrMangler.h"
#include "FuncDecl.h"

void printHelp()
{
  std::cout << "Usage: MrMangler [optional args] <input file>" <<std::endl;
  std::cout << std::endl;

  std::cout << "<input file>       Input file to read from, otherwise "
               "use stdin." << std::endl;
  std::cout << std::endl;

  std::cout << "Optional args:" << std::endl;
  std::cout << "  [-h|--help]      Print this message." <<
  std::endl;

  std::cout << "  [-i|--itanium]   Use itanium mangling. This is the"
               " defualt mangling scheme."<< std::endl;

  std::cout << "  [-w|--windows]   Use windows decoration." <<
  std::endl;
}

mangle_fn parseArgs(int argc, char** argv, FILE* &input_file)
{
    mangle_fn return_fn = &mangle_itanium;
    for(int i=1; i < argc; ++i) {
      if(0 == strcmp(argv[i], "--help") ||
         0 == strcmp(argv[i], "-h")) {
           printHelp();
           exit(0);
      }

      if(0 == strcmp(argv[i], "--windows") ||
         0 == strcmp(argv[i], "-w")) {
           return_fn = mangle_windows;
      }

      if(0 == strcmp(argv[i], "--Itanium") ||
         0 == strcmp(argv[i], "-i")) {
          return_fn = mangle_itanium;
      }

      if ('-' != argv[i][0]) {
        input_file = fopen(argv[i], "r");
        if (!input_file) {
           std::cout << "Error opening input file "<< argv[i] << std::endl;
           exit(0);
        }
      }
    }

    return return_fn;
}

int main(int argc, char** argv)
{
    mangle_fn target_mangler = &mangle_itanium;
    FILE* f = nullptr;
    if (argc > 1)
        target_mangler = parseArgs(argc, argv, f);

    const FuncDecl* func_decl = ParseStdin(f);
    if (f)
      fclose(f);

    const std::string mangled_str = target_mangler(func_decl);
    std::cout << mangled_str << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>#include <shiny/scoped_runtime.hpp>
//#include <shiny/plumbing/vertex_buffer.hpp>
#include <iostream>

#include <atma/intrusive_ptr.hpp>
#include <shiny/voodoo/thread.hpp>
#include <shiny/voodoo/command.hpp>
#include <shiny/plumbing/vertex_buffer.hpp>
#include <shiny/voodoo/context.hpp>

#include <fooey/widgets/window.hpp>
#include <fooey/fooey.hpp>

#include <atma/math/vector4f.hpp>
#include <atma/math/matrix4f.hpp>

int main()
{
	// setup up gui
	auto renderer = fooey::system_renderer();
	auto wnd = fooey::window("Excitement.", 480, 360);
	renderer->add_window(wnd);

	// runtime!
	auto SR = shiny::scoped_runtime_t();
	// context per window!
	auto context = shiny::create_context(shiny::defer_construction);
	//context->bind_to(wnd);

	bool running = true;

#if 0
	wnd->on_minimise += [](atma::event_flow_t& fc) {
		std::cout << "bam, minimised" << std::endl;
		fc.stop_execution();
		fc.prevent_default_behaviour();
	};

	wnd->on_minimise += [](atma::event_flow_t&) {
		std::cout << "you jelly, Qt?" << std::endl;
	};

	wnd->on_maximise += [](atma::event_flow_t&) {
		std::cout << "wow, maximised" << std::endl;
	};

	wnd->on_resize += [](uint32_t width, uint32_t height) {
		shiny::signal_resize(width, height);
	};

	wnd->on_restore += [](atma::event_flow_t&) {
		std::cout << "ooh, restored" << std::endl;
	};

#endif
	wnd->on_resize.add("shiny", [](fooey::widget_event_t const&, uint32_t width, uint32_t height) {
		std::cout << "WM_SIZE: " << width << ", " << height << std::endl;
	});

	wnd->on_close.add("shiny", [&running](fooey::widget_event_t const&) {
		std::cout << "lol, bye" << std::endl;
		running = false;
	});

	#if 0
	wnd->key_state.on_key(fooey::key_t::Ctrl + fooey::key_t::F, [&context]{
		shiny::signal_fullscreen_toggle(context);
	});
	#endif

	// game loop
	while (running)
		;
}<commit_msg>testing out new event framework<commit_after>#include <shiny/scoped_runtime.hpp>
//#include <shiny/plumbing/vertex_buffer.hpp>
#include <iostream>

#include <atma/intrusive_ptr.hpp>
#include <shiny/voodoo/thread.hpp>
#include <shiny/voodoo/command.hpp>
#include <shiny/plumbing/vertex_buffer.hpp>
#include <shiny/voodoo/context.hpp>

#include <fooey/widgets/window.hpp>
#include <fooey/fooey.hpp>

#include <atma/math/vector4f.hpp>
#include <atma/math/matrix4f.hpp>

struct dragon_event_t : fooey::event_t
{
};

int main()
{
	// setup up gui
	auto renderer = fooey::system_renderer();
	auto wnd = fooey::window("Excitement.", 480, 360);
	renderer->add_window(wnd);

	// runtime!
	auto SR = shiny::scoped_runtime_t();
	// context per window!
	auto context = shiny::create_context(shiny::defer_construction);
	//context->bind_to(wnd);

	bool running = true;

	wnd->on("close.dragons", [](dragon_event_t& e){
		std::cout << "close.dragon" << std::endl;
	});

	wnd->on("close.dragons.things", [](dragon_event_t& e){
		std::cout << "close.dragon.things" << std::endl;
	});

	wnd->fire("close.things", dragon_event_t());

#if 0
	wnd->on_minimise += [](atma::event_flow_t& fc) {
		std::cout << "bam, minimised" << std::endl;
		fc.stop_execution();
		fc.prevent_default_behaviour();
	};

	wnd->on_minimise += [](atma::event_flow_t&) {
		std::cout << "you jelly, Qt?" << std::endl;
	};

	wnd->on_maximise += [](atma::event_flow_t&) {
		std::cout << "wow, maximised" << std::endl;
	};

	wnd->on_resize += [](uint32_t width, uint32_t height) {
		shiny::signal_resize(width, height);
	};

	wnd->on_restore += [](atma::event_flow_t&) {
		std::cout << "ooh, restored" << std::endl;
	};

#endif
	wnd->on_resize.add("shiny", [](fooey::widget_event_t const&, uint32_t width, uint32_t height) {
		std::cout << "WM_SIZE: " << width << ", " << height << std::endl;
	});

	wnd->on_close.add("shiny", [&running](fooey::widget_event_t const&) {
		std::cout << "lol, bye" << std::endl;
		running = false;
	});

	#if 0
	wnd->key_state.on_key(fooey::key_t::Ctrl + fooey::key_t::F, [&context]{
		shiny::signal_fullscreen_toggle(context);
	});
	#endif

	// game loop
	while (running)
		;
}<|endoftext|>


<commit_before>#pragma once

#include "../macros.hpp"

namespace wrd
{
	namespace indep
	{
		struct BuildFeatures
		{	WRD_INHERIT(BuildFeatures)
			typedef std::string string;

			struct Date
			{
				static const string& get();
				static wint getYear();
				static wint getMonth();
				static wint getDay();
			};
			struct Time
			{
				static const string& get();
				static wint getHour();
				static wint getMinute();
				static wint getSecond();
			};
			struct Version
			{
				static const string& get();
				static const string& getValue();
				static const string& getName();
				static wint getMajor();
				static wint getMinor();
				static wint getFix();
			};
			enum PlatformType
			{
				PLATFORM_TYPE_START = 0,
				WINDOW = PLATFORM_TYPE_START,
				PLATFORM_TYPE_END,
				LINUX = PLATFORM_TYPE_END
			};
			struct Platform
			{
				static PlatformType get();
				static const string& getName();
				static const string& getVersion();
			};
			enum BuildType
			{
				BUILD_TYPE_START = 0,
				DEBUG = BUILD_TYPE_START,
				BUILD_TYPE_END,
				RELEASE = BUILD_TYPE_END
			};
			struct Building
			{
				static BuildType get();
				static const string& getName();
			};
		};
	}
}
<commit_msg>- [indep] BuildFeatures has private accessor.<commit_after>#pragma once

#include "../macros.hpp"

namespace wrd
{
	namespace indep
	{
		class BuildFeatures
		{	WRD_INHERIT(BuildFeatures)
			typedef std::string string;

		public:
			struct Date
			{
				static const string& get();
				static wint getYear();
				static wint getMonth();
				static wint getDay();
			};
			struct Time
			{
				static const string& get();
				static wint getHour();
				static wint getMinute();
				static wint getSecond();
			};
			struct Version
			{
				static const string& get();
				static const string& getValue();
				static const string& getName();
				static wint getMajor();
				static wint getMinor();
				static wint getFix();
			};
			enum PlatformType
			{
				PLATFORM_TYPE_START = 0,
				WINDOW = PLATFORM_TYPE_START,
				PLATFORM_TYPE_END,
				LINUX = PLATFORM_TYPE_END
			};
			struct Platform
			{
				static PlatformType get();
				static const string& getName();
				static const string& getVersion();
			};
			enum BuildType
			{
				BUILD_TYPE_START = 0,
				DEBUG = BUILD_TYPE_START,
				BUILD_TYPE_END,
				RELEASE = BUILD_TYPE_END
			};
			struct Building
			{
				static BuildType get();
				static const string& getName();
			};
		};
	}
}
<|endoftext|>


<commit_before><commit_msg>fix uninitialized state in rendertarget sample<commit_after><|endoftext|>