<commit_before>#include <stdio.h>
#include <string>
#include <vector>
#include <random>
#include <array>
#include <math.h>
#include <sstream>
#include <iostream>
#include <thread>
#include <SDL.h>
#include <glm/glm.hpp>

static const char* const VERSION = "1.0.0\0";

#define FRAME_RES 512
std::string fractString("AABAB");
glm::vec3 FrameBuffer[FRAME_RES][FRAME_RES];
SDL_Window* m_Window = nullptr;
SDL_Surface* m_Surface = nullptr;

using namespace glm;

inline std::uint32_t ConvertPixel(const glm::vec3& pixel)
{
    int rs = m_Surface->format->Rshift;
    int gs = m_Surface->format->Gshift;
    int bs = m_Surface->format->Bshift;

    std::uint8_t r, g, b;
    if (pixel.r > 1.f)
        r = 255;

    else if (pixel.r <= 0.f)
        r = 0;
    else
        r = pixel.r * 255;

    if (pixel.g > 1.f)
        g = 255;

    else if (pixel.g <= 0.f)
        g = 0;
    else
        g = pixel.g * 255;

    if (pixel.b > 1.f)
        b = 255;

    else if (pixel.b <= 0.f)
        b = 0;
    else
        b = pixel.b * 255;

    return (b << bs) | (g << gs) | (r << rs);
}

void SwapBuffers(const vec3 frameBuf[FRAME_RES][FRAME_RES])
{
    for (int y = 0; y < FRAME_RES; y++)
    {
        Uint32 *row = (Uint32*)((Uint8*)m_Surface->pixels + y * m_Surface->pitch);
        for (int x = 0; x < FRAME_RES; x++)
            row[x] = ConvertPixel(frameBuf[y][x]);
    }
    SDL_UpdateWindowSurface(m_Window);
}

void waitForUserExit()
{
    SDL_Event e;
    bool wantExit = false;
    while (!wantExit)
    {
        SDL_PollEvent(&e);

        if (e.type == SDL_QUIT)
        {
            wantExit = true;
            exit(0);
        }
    }
}

float r(int n, const vec2& chosenPoint)
{

    float a = chosenPoint.x;
    float b = chosenPoint.y;

    int Sn = n % fractString.size();
    auto x = fractString[Sn];
    return x == 'A' ? a : b;
}

template <typename T = float>
auto clamp(T x, T a, T b) -> T
{
    return x > a ? a : x < b ? b : x;
}

#define ITERATIONS 750
std::array<float, ITERATIONS> precomtuteIterations(const vec2& cPoint)
{
    std::array<float, ITERATIONS> result;
    result[0] = 0.5f;

    for (int i = 1; i < ITERATIONS; i++)
    {
        result[i] = r(i - 1, cPoint) * result[i - 1] * (1 - result[i - 1]);
    }

    return result;
}

float computeLyapunovExponent(const std::array<float, ITERATIONS>& iterations, const vec2& cPoint)
{
    float result = 0.f;
    auto iter = iterations;
    float ri[ITERATIONS];
    auto point = cPoint;
    for (auto i = 1; i < ITERATIONS; i++)
    {
        ri[i] = abs(r(i, point));
    }

    float oneMinus2iterations[ITERATIONS];
    for (auto i = 1; i < ITERATIONS; i++)
    {
        oneMinus2iterations[i] = abs((1 - (2 * iter[i])));
    }

    for (int i = 1; i < ITERATIONS; i++)
    {
        result += logf(ri[i] * oneMinus2iterations[i]);
    }

    return (result / (float)ITERATIONS);
}

void renderFractalPixel(int x, int y)
{
    float a = (float)x / (float)(FRAME_RES);
    a = 2.f + a * 2.f;

    float b = (float)y / (float)(FRAME_RES);
    b = 2.f + b * 2.f;

    auto point = vec2(a, b);
    auto iterations = precomtuteIterations(point);
    auto lyapunovExp = computeLyapunovExponent(iterations, point);
    if (lyapunovExp < 0)
    {
        FrameBuffer[x][y] = vec3(abs(lyapunovExp), abs(lyapunovExp), 0);
    }
    else if (lyapunovExp == 0.f)
    {
        FrameBuffer[x][y] = vec3(1, 1, 0);
    }
    else
    {
        FrameBuffer[x][y] = vec3(0, lyapunovExp * 0.5, lyapunovExp);
    }
}

void renderFractalRegion(int xFrom, int xTo)
{
    for (auto x = xFrom; x < xTo; x++)
    {
        for (auto y = 0; y < FRAME_RES; y++)
        {
            renderFractalPixel(x, y);
        }
    }
    return;
}

std::vector<std::thread> threads;
void DoFractalThreaded()
{
    unsigned int numThreads = std::thread::hardware_concurrency();
    int delta = FRAME_RES / numThreads;
    for (int i = 0; i < numThreads; i++)
    {
        auto fun = std::bind(&renderFractalRegion, delta * i, delta * i + delta);
        threads.emplace_back(fun);
    }
}

typedef  std::chrono::time_point<std::chrono::high_resolution_clock> TimePoint;
template <typename T = std::chrono::seconds>
inline long long timePast(const TimePoint& start, const TimePoint& end)
{
    return std::chrono::duration_cast<T>(end - start).count();
}

#undef main
int main(int argc, char* argv[])
{
    std::cout << "Lyapunov Fractal Renderer. Version: " << VERSION << std::endl;

    if (SDL_Init(SDL_INIT_EVERYTHING != 0))
    {
        std::cout << "SDL_init failed: " << SDL_GetError() << std::endl;
        return false;
    }

    m_Window = SDL_CreateWindow("LyapunovFract", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
        FRAME_RES, FRAME_RES, SDL_WINDOW_OPENGL);

    if (!m_Window)
    {
        std::cout << "SDL_CreateWindow failed: " << SDL_GetError() << std::endl;
        return false;
    }

    m_Surface = SDL_GetWindowSurface(m_Window);

    if (!m_Surface)
    {
        std::cout << "SDL_GetWindowSurface failed: " << SDL_GetError() << std::endl;
        return false;
    }
    SwapBuffers(FrameBuffer);
    auto begin = std::chrono::high_resolution_clock::now();

    DoFractalThreaded();

    for (auto&& th : threads)
    {
        th.join();
    }
    auto end = std::chrono::high_resolution_clock::now();
    auto timeSec = timePast(begin, end);
    auto timeMili = timePast<std::chrono::milliseconds>(begin, end);

    std::stringstream ss;
    ss << "LyapunovFract: " << timeSec << " sec and " << timeMili - (timeSec * 1000) << " milisec";

    SDL_SetWindowTitle(m_Window, ss.str().c_str());
    SwapBuffers(FrameBuffer);
    waitForUserExit();
    return 0;
}
<commit_msg>removed some things that actaulyl made it slower<commit_after>#include <stdio.h>
#include <string>
#include <vector>
#include <random>
#include <array>
#include <math.h>
#include <sstream>
#include <iostream>
#include <thread>
#include <SDL.h>
#include <glm/glm.hpp>

static const char* const VERSION = "1.0.0\0";

#define FRAME_RES 512
#define ITERATIONS 750
std::string fractString("AABAB");
glm::vec3 FrameBuffer[FRAME_RES][FRAME_RES];
SDL_Window* m_Window = nullptr;
SDL_Surface* m_Surface = nullptr;

using namespace glm;

inline std::uint32_t ConvertPixel(const glm::vec3& pixel)
{
    int rs = m_Surface->format->Rshift;
    int gs = m_Surface->format->Gshift;
    int bs = m_Surface->format->Bshift;

    std::uint8_t r, g, b;
    if (pixel.r > 1.f)
        r = 255;

    else if (pixel.r <= 0.f)
        r = 0;
    else
        r = pixel.r * 255;

    if (pixel.g > 1.f)
        g = 255;

    else if (pixel.g <= 0.f)
        g = 0;
    else
        g = pixel.g * 255;

    if (pixel.b > 1.f)
        b = 255;

    else if (pixel.b <= 0.f)
        b = 0;
    else
        b = pixel.b * 255;

    return (b << bs) | (g << gs) | (r << rs);
}

void SwapBuffers(const vec3 frameBuf[FRAME_RES][FRAME_RES])
{
    for (int y = 0; y < FRAME_RES; y++)
    {
        Uint32 *row = (Uint32*)((Uint8*)m_Surface->pixels + y * m_Surface->pitch);
        for (int x = 0; x < FRAME_RES; x++)
            row[x] = ConvertPixel(frameBuf[y][x]);
    }
    SDL_UpdateWindowSurface(m_Window);
}

void waitForUserExit()
{
    SDL_Event e;
    bool wantExit = false;
    while (!wantExit)
    {
        SDL_PollEvent(&e);

        if (e.type == SDL_QUIT)
        {
            wantExit = true;
            exit(0);
        }
    }
}

float r(int n, const vec2& chosenPoint)
{

    float a = chosenPoint.x;
    float b = chosenPoint.y;

    int Sn = n % fractString.size();
    auto x = fractString[Sn];
    return x == 'A' ? a : b;
}

template <typename T = float>
auto clamp(T x, T a, T b) -> T
{
    return x > a ? a : x < b ? b : x;
}

std::array<float, ITERATIONS> precomtuteIterations(const vec2& cPoint)
{
    std::array<float, ITERATIONS> result;
    result[0] = 0.5f;

    for (int i = 1; i < ITERATIONS; i++)
    {
        result[i] = r(i - 1, cPoint) * result[i - 1] * (1 - result[i - 1]);
    }

    return result;
}

float computeLyapunovExponent(const std::array<float, ITERATIONS>& iterations, const vec2& cPoint)
{
    float result = 0.f;
    auto iter = iterations;
    float ri[ITERATIONS];
    auto point = cPoint;
    for (auto i = 1; i < ITERATIONS; i++)
    {
        ri[i] = abs(r(i, point));
    }

    float oneMinus2iterations[ITERATIONS];
    for (auto i = 1; i < ITERATIONS; i++)
    {
        oneMinus2iterations[i] = abs((1 - (2 * iter[i])));
    }

    for (int i = 1; i < ITERATIONS; i++)
    {
        result += logf(ri[i] * oneMinus2iterations[i]);
    }

    return (result / (float)ITERATIONS);
}

void renderFractalPixel(int x, int y)
{
    float a = (float)x / (float)(FRAME_RES);
    a = 2.f + a * 2.f;

    float b = (float)y / (float)(FRAME_RES);
    b = 2.f + b * 2.f;

    auto point = vec2(a, b);
    auto iterations = precomtuteIterations(point);
    auto lyapunovExp = computeLyapunovExponent(iterations, point);
    if (lyapunovExp < 0)
    {
        FrameBuffer[x][y] = vec3(abs(lyapunovExp), abs(lyapunovExp), 0);
    }
    else if (lyapunovExp == 0.f)
    {
        FrameBuffer[x][y] = vec3(1, 1, 0);
    }
    else
    {
        FrameBuffer[x][y] = vec3(0, lyapunovExp * 0.5, lyapunovExp);
    }
}

void renderFractalRegion(int xFrom, int xTo)
{
    for (auto x = xFrom; x < xTo; x++)
    {
        for (auto y = 0; y < FRAME_RES; y++)
        {
            renderFractalPixel(x, y);
        }
    }
    return;
}

std::vector<std::thread> threads;
void DoFractalThreaded()
{
    unsigned int numThreads = std::thread::hardware_concurrency();
    int delta = FRAME_RES / numThreads;
    for (int i = 0; i < numThreads; i++)
    {
        auto fun = std::bind(&renderFractalRegion, delta * i, delta * i + delta);
        threads.emplace_back(fun);
    }
}

typedef  std::chrono::time_point<std::chrono::high_resolution_clock> TimePoint;
template <typename T = std::chrono::seconds>
inline long long timePast(const TimePoint& start, const TimePoint& end)
{
    return std::chrono::duration_cast<T>(end - start).count();
}

#undef main
int main(int argc, char* argv[])
{
    std::cout << "Lyapunov Fractal Renderer. Version: " << VERSION << std::endl;

    if (SDL_Init(SDL_INIT_EVERYTHING != 0))
    {
        std::cout << "SDL_init failed: " << SDL_GetError() << std::endl;
        return false;
    }

    m_Window = SDL_CreateWindow("LyapunovFract", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
        FRAME_RES, FRAME_RES, SDL_WINDOW_OPENGL);

    if (!m_Window)
    {
        std::cout << "SDL_CreateWindow failed: " << SDL_GetError() << std::endl;
        return false;
    }

    m_Surface = SDL_GetWindowSurface(m_Window);

    if (!m_Surface)
    {
        std::cout << "SDL_GetWindowSurface failed: " << SDL_GetError() << std::endl;
        return false;
    }
    SwapBuffers(FrameBuffer);
    auto begin = std::chrono::high_resolution_clock::now();

    DoFractalThreaded();

    for (auto&& th : threads)
    {
        th.join();
    }
    auto end = std::chrono::high_resolution_clock::now();
    auto timeSec = timePast(begin, end);
    auto timeMili = timePast<std::chrono::milliseconds>(begin, end);

    std::stringstream ss;
    ss << "LyapunovFract: " << timeSec << " sec and " << timeMili - (timeSec * 1000) << " milisec";

    SDL_SetWindowTitle(m_Window, ss.str().c_str());
    SwapBuffers(FrameBuffer);
    waitForUserExit();
    return 0;
}
<|endoftext|>


<commit_before>#include "process.h"

#include <stdexcept>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>

#include "unidirectional_pipe.h"

string Process::related_binary_path(const string &argv0, const string &this_program_name, const string &desired_binary_name) {
	if (argv0.length() > this_program_name.length() &&
		argv0[argv0.length() - this_program_name.length() - 1] == '/' &&
		argv0.substr(argv0.length() - this_program_name.length(), this_program_name.length()) == this_program_name) {
		return argv0.substr(0, argv0.length() - this_program_name.length()) + desired_binary_name;
	} else {
		return desired_binary_name;
	}
}

pid_t Process::fork_and_exec(const string &binary, const char *args[]) {
	pid_t child = fork();

	if (child < 0) {
		// hit the process limit
		throw runtime_error("Couldn't fork to start binary: " + string(strerror(errno)));

	} else if (child == 0) {
		// we are the child; run the binary
		if (execv(binary.c_str(), (char * const *)args) < 0) {
			throw runtime_error("Couldn't exec " + binary + ": " + string(strerror(errno)));
		}
		throw logic_error("execv returned");

	} else {
		return child;
	}
}

pid_t Process::fork_and_exec(const string &binary, const char *args[], UnidirectionalPipe &stdin_pipe, UnidirectionalPipe &stdout_pipe) {
	pid_t child = fork();

	if (child < 0) {
		// hit the process limit
		throw runtime_error("Couldn't fork to start binary: " + string(strerror(errno)));

	} else if (child == 0) {
		// we are the child; close the ends of the pipe that we won't use (as otherwise we'd not see the pipes close when the other end is done)
		stdin_pipe.close_write();
		stdout_pipe.close_read();

		// attach our stdin
		stdin_pipe.dup_read_to(STDIN_FILENO);
		stdin_pipe.close_read();

		// attach our stdout
		stdout_pipe.dup_write_to(STDOUT_FILENO);
		stdout_pipe.close_write();

		// run the binary
		if (execv(binary.c_str(), (char * const *)args) < 0) {
			throw runtime_error("Couldn't exec " + binary + ": " + string(strerror(errno)));
		}
		throw logic_error("execv returned");

	} else {
		return child;
	}
}

void Process::fork_and_exec_pair(const string &binary1, const string &binary2, const char *args1[], const char *args2[], pid_t *child1, pid_t *child2) {
	UnidirectionalPipe pipe1;
	UnidirectionalPipe pipe2;
	*child1 = fork_and_exec(binary1, args1, pipe1, pipe2);
	*child2 = fork_and_exec(binary2, args2, pipe2, pipe1);
}

bool Process::wait_for_and_check(pid_t child) {
	int status;
	while (true) {
		if (waitpid(child, &status, 0) < 0) {
			throw runtime_error("Couldn't wait for child: " + string(strerror(errno)));
		}
		return WIFEXITED(status) && WEXITSTATUS(status) == 0;
	}
}
<commit_msg>use execvp instead of execv so ks can run from say /usr/local/bin without explicitly specifying the path<commit_after>#include "process.h"

#include <stdexcept>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>

#include "unidirectional_pipe.h"

string Process::related_binary_path(const string &argv0, const string &this_program_name, const string &desired_binary_name) {
	if (argv0.length() > this_program_name.length() &&
		argv0[argv0.length() - this_program_name.length() - 1] == '/' &&
		argv0.substr(argv0.length() - this_program_name.length(), this_program_name.length()) == this_program_name) {
		return argv0.substr(0, argv0.length() - this_program_name.length()) + desired_binary_name;
	} else {
		return desired_binary_name;
	}
}

pid_t Process::fork_and_exec(const string &binary, const char *args[]) {
	pid_t child = fork();

	if (child < 0) {
		// hit the process limit
		throw runtime_error("Couldn't fork to start binary: " + string(strerror(errno)));

	} else if (child == 0) {
		// we are the child; run the binary
		if (execvp(binary.c_str(), (char * const *)args) < 0) {
			throw runtime_error("Couldn't exec " + binary + ": " + string(strerror(errno)));
		}
		throw logic_error("execv returned");

	} else {
		return child;
	}
}

pid_t Process::fork_and_exec(const string &binary, const char *args[], UnidirectionalPipe &stdin_pipe, UnidirectionalPipe &stdout_pipe) {
	pid_t child = fork();

	if (child < 0) {
		// hit the process limit
		throw runtime_error("Couldn't fork to start binary: " + string(strerror(errno)));

	} else if (child == 0) {
		// we are the child; close the ends of the pipe that we won't use (as otherwise we'd not see the pipes close when the other end is done)
		stdin_pipe.close_write();
		stdout_pipe.close_read();

		// attach our stdin
		stdin_pipe.dup_read_to(STDIN_FILENO);
		stdin_pipe.close_read();

		// attach our stdout
		stdout_pipe.dup_write_to(STDOUT_FILENO);
		stdout_pipe.close_write();

		// run the binary
		if (execv(binary.c_str(), (char * const *)args) < 0) {
			throw runtime_error("Couldn't exec " + binary + ": " + string(strerror(errno)));
		}
		throw logic_error("execv returned");

	} else {
		return child;
	}
}

void Process::fork_and_exec_pair(const string &binary1, const string &binary2, const char *args1[], const char *args2[], pid_t *child1, pid_t *child2) {
	UnidirectionalPipe pipe1;
	UnidirectionalPipe pipe2;
	*child1 = fork_and_exec(binary1, args1, pipe1, pipe2);
	*child2 = fork_and_exec(binary2, args2, pipe2, pipe1);
}

bool Process::wait_for_and_check(pid_t child) {
	int status;
	while (true) {
		if (waitpid(child, &status, 0) < 0) {
			throw runtime_error("Couldn't wait for child: " + string(strerror(errno)));
		}
		return WIFEXITED(status) && WEXITSTATUS(status) == 0;
	}
}
<|endoftext|>


<commit_before>/*
This file is part of Groho, a simulator for inter-planetary travel and warfare.
Copyright (c) 2017, 2018 by Kaushik Ghose. Some rights reserved, see LICENSE

Entry point function for command line program
*/

#include <functional>
#include <iostream>
#include <signal.h>
#include <stdlib.h>
#include <thread>

#include "CLI11.hpp"

#ifndef NOGUI
#include "app.hpp"
#endif

#include "configuration.hpp"
#include "simulator.hpp"

#define LOGURU_IMPLEMENTATION 1
#define LOGURU_WITH_STREAMS 1
#include "loguru.hpp"

volatile sig_atomic_t keep_running = true;

void ctrl_c_pressed(int) { keep_running = false; }

void print_license()
{
    std::cout << R"(
    Groho 18.11: A simulator for inter-planetary travel and warfare
    Copyright (c) 2017, 2018 by Kaushik Ghose.
    Released under the MIT License. Some rights reserved

)";
}

struct Options {
    std::string scenario_file;
    std::string annotation_file;
    bool        non_interactive = false;
};

Options parse_arguments(int argc, char* argv[])
{
    Options opt;
    bool    show_actions_and_exit;

    CLI::App cli_options{
        "Groho: A simulator for inter-planetary travel and warfare"
    };
    cli_options.add_flag(
        "--no-gui", opt.non_interactive, "Run in non-interactive mode");
    cli_options.add_flag(
        "--actions", show_actions_and_exit, "Show action list");
    cli_options.add_option("scenariofile", opt.scenario_file, "Scenario file")
        ->check(CLI::ExistingFile);
    cli_options
        .add_option("annotationfile", opt.annotation_file, "Annotation file")
        ->check(CLI::ExistingFile);

    try {
        cli_options.parse(argc, argv);
    } catch (const CLI::ParseError& e) {
        exit(cli_options.exit(e));
    }

    if (show_actions_and_exit) {
        std::cout << sim::list_available_actions();
        exit(0);
    }

    if (opt.scenario_file == "") {
        std::cout << cli_options.help("", CLI::AppFormatMode::All);
        exit(0);
    }

    return opt;
}

// Periodically monitor scenario file and restart simulator as needed
void simulator_loop(
    sim::Simulator& simulator, Options options, unsigned int interval_ms)
{
    sim::Configuration config = sim::parse_configuration(options.scenario_file);
    simulator.restart_with(config);

    time_t last_mod_time = config.latest_modification();
    while (keep_running) {
        if (last_mod_time < config.latest_modification()) {

            LOG_S(INFO) << "Reloading scenario files";

            config = sim::parse_configuration(options.scenario_file);

            // if (new_scenario != scenario) {
            if (true) {
                LOG_S(INFO) << "Scenario file changed";
                simulator.restart_with(config);
                last_mod_time = config.latest_modification();
            }
        }

        std::this_thread::sleep_for(std::chrono::milliseconds(interval_ms));
    }
    simulator.stop();
}

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

    Options opt = parse_arguments(argc, argv);

    loguru::init(argc, argv);

    // This has to come after loguru::init
    signal(SIGINT, ctrl_c_pressed);

    sim::Simulator simulator;

    unsigned int interval_ms = 500;

    auto simulator_thread
        = std::thread(simulator_loop, std::ref(simulator), opt, interval_ms);

    int ret_val = 0;

#ifndef NOGUI
    if (!opt.non_interactive) {
        sim::GrohoApp app({ argc, argv }, simulator);
        ret_val      = app.exec();
        keep_running = false;
    }
#endif

    if (simulator_thread.joinable()) {
        simulator_thread.join();
    }

    return ret_val;
}<commit_msg>Main reconstituted<commit_after>/*
This file is part of Groho, a simulator for inter-planetary travel and warfare.
Copyright (c) 2017-2020 by Kaushik Ghose. Some rights reserved, see
LICENSE

Entry point function for command line program
*/

#include <chrono>
#include <filesystem>
#include <iostream>
#include <thread>

#include <signal.h>
#include <stdlib.h>

#include "CLI11.hpp"

#include "simulator.hpp"

#define LOGURU_IMPLEMENTATION 1
#define LOGURU_WITH_STREAMS 1
#include "loguru.hpp"

void print_license()
{
    std::cout << R"(
    Groho 20.02: A simulator for inter-planetary travel and warfare
    Copyright (c) 2017 - 2020 by Kaushik Ghose.
    Released under the MIT License. Some rights reserved.

)";
}

struct Options {
    std::string scenario_file;
    std::string output_folder;
};

Options parse_arguments(int argc, char* argv[])
{
    bool        show_actions_and_exit;
    std::string scenario_file, output_folder;

    CLI::App cli_options{ "Groho: A simulator for inter-planetary travel" };
    cli_options.add_flag(
        "--actions", show_actions_and_exit, "Show action list");
    cli_options.add_option("scenariofile", scenario_file, "Scenario file");
    cli_options.add_option("outputfolder", output_folder, "Output folder");

    try {
        cli_options.parse(argc, argv);
    } catch (const CLI::ParseError& e) {
        exit(cli_options.exit(e));
    }

    if (show_actions_and_exit) {
        std::cout << groho::Simulator::list_available_actions();
        exit(0);
    }

    if (scenario_file == "" | output_folder == "") {
        std::cout << cli_options.help("", CLI::AppFormatMode::All);
        exit(0);
    }

    return Options{ scenario_file, output_folder };
}

volatile sig_atomic_t keep_running = true;

void ctrl_c_pressed(int) { keep_running = false; }

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

    Options opt = parse_arguments(argc, argv);

    loguru::init(argc, argv);

    // This has to come after loguru::init
    signal(SIGINT, ctrl_c_pressed);

    using namespace std::chrono_literals;
    auto poll_interval_ms = 500ms;

    groho::Simulator simulator(opt.scenario_file, opt.output_folder);

    while (keep_running && simulator.ok()) {
        if (simulator.scenario_changed()) {
            simulator.restart();
        }
        std::this_thread::sleep_for(poll_interval_ms);
    }

    simulator.exit();

    return 0;
}<|endoftext|>


<commit_before>#include <iostream>

#include "topic.h"
#include "producer.h"

using namespace std;

Producer::Producer(const string& root, const string& topic) : _topic(EnvManager::getEnv(root)->getTopic(topic)), _current(-1), _env(NULL), _db(NULL) {
    Txn txn(_topic->getEnv(), NULL);
    openHead(&txn);
    txn.commit();
}

Producer::~Producer() {
    closeCurrent();
}

void Producer::stats() {

}

bool Producer::push(const Producer::BatchType& batch) {
    bool isFull = false;

    {
        Txn txn(_topic->getEnv(), _env);

        uint64_t head = _topic->getProducerHead(txn);
        for (auto item : batch) {
            MDB_val key{ sizeof(head), &++head },
                    val{ std::get<1>(item), (void*)std::get<0>(item) };

            int rc = mdb_put(txn.getTxn(), _db, &key, &val, MDB_APPEND);
            if (rc == MDB_MAP_FULL) {
                txn.abort();
                isFull = true;
                break;
            }
        }

        if (!isFull) {
            _topic->setProducerHead(txn, head);
            int rc = txn.commit();
            if (rc == MDB_MAP_FULL) {
                isFull = true;
            }
        }
    }

    if (isFull) {
        rotate();
        return push(batch);
    }

    return true;
}

void Producer::closeCurrent() {
    mdb_dbi_close(_env, _db);
    mdb_env_close(_env);
}

void Producer::openHead(Txn* txn, bool rotating) {
    uint32_t headFile = _topic->getProducerHeadFile(*txn);
    if (rotating && _current == headFile) {
        _topic->setProducerHeadFile(*txn, ++headFile, _topic->getProducerHead(*txn) + 1);
    }

    _current = headFile;

    char path[4096];
    sprintf(path, "%s/%s.%d", _topic->getEnv()->getRoot().c_str(), _topic->getName().c_str(), headFile);

    mdb_env_create(&_env);
    int rc = mdb_env_open(_env, path, MDB_NOSYNC | MDB_NOSUBDIR, 0664);
    mdb_env_set_mapsize(_env, 128 * 1024 * 1024);
    if (rc != 0) {
        mdb_env_close(_env);
        _env = NULL;
        printf("Producer open error.\n%s\n", mdb_strerror(rc));
        return;
    }

    MDB_txn *otxn;
    mdb_txn_begin(_env, NULL, 0, &otxn);
    mdb_dbi_open(otxn, NULL, MDB_CREATE, &_db);
    mdb_set_compare(otxn, _db, mdbIntCmp<uint64_t>);
    mdb_txn_commit(otxn);
}

void Producer::rotate() {
    Txn txn(_topic->getEnv(), NULL);
    closeCurrent();
    openHead(&txn, true);
    txn.commit();
}
<commit_msg>wait 500 ms on windows.<commit_after>#ifdef _WIN32
#include <windows.h>
#endif

#include <iostream>

#include "topic.h"
#include "producer.h"

using namespace std;

Producer::Producer(const string& root, const string& topic) : _topic(EnvManager::getEnv(root)->getTopic(topic)), _current(-1), _env(NULL), _db(NULL) {
    Txn txn(_topic->getEnv(), NULL);
    openHead(&txn);
    txn.commit();
}

Producer::~Producer() {
    closeCurrent();
}

void Producer::stats() {

}

bool Producer::push(const Producer::BatchType& batch) {
    bool isFull = false;

    {
        Txn txn(_topic->getEnv(), _env);

        uint64_t head = _topic->getProducerHead(txn);
        for (auto item : batch) {
            MDB_val key{ sizeof(head), &++head },
                    val{ std::get<1>(item), (void*)std::get<0>(item) };

            int rc = mdb_put(txn.getTxn(), _db, &key, &val, MDB_APPEND);
            if (rc == MDB_MAP_FULL) {
                txn.abort();
                isFull = true;
                break;
            }
        }

        if (!isFull) {
            _topic->setProducerHead(txn, head);
            int rc = txn.commit();
            if (rc == MDB_MAP_FULL) {
                isFull = true;
            }
        }
    }

    if (isFull) {
        rotate();
        return push(batch);
    }

    return true;
}

void Producer::closeCurrent() {
    mdb_dbi_close(_env, _db);
    mdb_env_close(_env);
}

void Producer::openHead(Txn* txn, bool rotating) {
    uint32_t headFile = _topic->getProducerHeadFile(*txn);
    if (rotating && _current == headFile) {
        _topic->setProducerHeadFile(*txn, ++headFile, _topic->getProducerHead(*txn) + 1);
    }

    _current = headFile;

    char path[4096];
    sprintf(path, "%s/%s.%d", _topic->getEnv()->getRoot().c_str(), _topic->getName().c_str(), headFile);

#ifdef _WIN32
    Sleep(500);
#endif
    mdb_env_create(&_env);
    int rc = mdb_env_open(_env, path, MDB_NOSYNC | MDB_NOSUBDIR, 0664);
    mdb_env_set_mapsize(_env, 128 * 1024 * 1024);
    if (rc != 0) {
        mdb_env_close(_env);
        _env = NULL;
        printf("Producer open error.\n%s\n", mdb_strerror(rc));
        return;
    }

    MDB_txn *otxn;
    mdb_txn_begin(_env, NULL, 0, &otxn);
    mdb_dbi_open(otxn, NULL, MDB_CREATE, &_db);
    mdb_set_compare(otxn, _db, mdbIntCmp<uint64_t>);
    mdb_txn_commit(otxn);
}

void Producer::rotate() {
    Txn txn(_topic->getEnv(), NULL);
    closeCurrent();
    openHead(&txn, true);
    txn.commit();
}
<|endoftext|>


<commit_before>#include <QtQuick>

#include <sailfishapp.h>
#include <QScopedPointer>
#include <QQuickView>
#include <QQmlEngine>
#include <QGuiApplication>

#include "factor.h"

int main(int argc, char *argv[])
{
    // For this example, wizard-generates single line code would be good enough,
    // but very soon it won't be enough for you anyway, so use this more detailed example from start
    QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv));
    QScopedPointer<QQuickView> view(SailfishApp::createView());

    Factorizer fact;

    runUnitTests();

//    Here's how you will add QML components whenever you start using them
//    Check https://github.com/amarchen/Wikipedia for a more full example
//    view->engine()->addImportPath(SailfishApp::pathTo("qml/components").toString());
    view->engine()->rootContext()->setContextProperty("fact", &fact);
    view->setSource(SailfishApp::pathTo("qml/main.qml"));

    view->show();

    return app->exec();
}
<commit_msg>Set some names and titles just in case they are useful to set.<commit_after>#include <QtQuick>

#include <sailfishapp.h>
#include <QScopedPointer>
#include <QQuickView>
#include <QQmlEngine>
#include <QGuiApplication>

#include "factor.h"

int main(int argc, char *argv[])
{
    // For this example, wizard-generates single line code would be good enough,
    // but very soon it won't be enough for you anyway, so use this more detailed example from start
    QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv));
    QScopedPointer<QQuickView> view(SailfishApp::createView());

    Factorizer fact;

    runUnitTests();

//    Here's how you will add QML components whenever you start using them
//    Check https://github.com/amarchen/Wikipedia for a more full example
//    view->engine()->addImportPath(SailfishApp::pathTo("qml/components").toString());
    view->engine()->rootContext()->setContextProperty("fact", &fact);
    view->setSource(SailfishApp::pathTo("qml/main.qml"));

    view->setTitle("Sailfactor");

    app->setApplicationName("harbour-sailfactor");
    app->setApplicationDisplayName("Sailfactor");

    view->show();

    return app->exec();
}
<|endoftext|>


<commit_before>
#include <llvm/IR/Function.h>
#include <llvm/IR/TypeBuilder.h>
#include <llvm/IR/IntrinsicInst.h>

#include <libdevcrypto/SHA3.h>
#include <libevm/FeeStructure.h>
#include <libevm/ExtVMFace.h>

#include "../libevmjit/Utils.h"

extern "C"
{
	#ifdef _MSC_VER
		#define EXPORT __declspec(dllexport)
	#else
		#define EXPORT
	#endif

	using namespace dev;
	using namespace dev::eth;
	using jit::i256;
	using jit::eth2llvm;

	EXPORT void ext_store(ExtVMFace* _env, i256* _index, i256* o_value)
	{
		auto index = llvm2eth(*_index);
		auto value = _env->store(index); // Interface uses native endianness
		*o_value = eth2llvm(value);
	}

	EXPORT void ext_setStore(ExtVMFace* _env, i256* _index, i256* _value)
	{
		auto index = llvm2eth(*_index);
		auto value = llvm2eth(*_value);

		if (value == 0 && _env->store(index) != 0)	// If delete
			_env->sub.refunds += c_sstoreRefundGas;	// Increase refund counter

		_env->setStore(index, value);	// Interface uses native endianness
	}

	EXPORT void ext_calldataload(ExtVMFace* _env, i256* _index, ::byte* o_value)
	{
		auto index = static_cast<size_t>(llvm2eth(*_index));
		assert(index + 31 > index); // TODO: Handle large index
		for (size_t i = index, j = 0; i <= index + 31; ++i, ++j)
			o_value[j] = i < _env->data.size() ? _env->data[i] : 0; // Keep Big Endian
		// TODO: It all can be done by adding padding to data or by using min() algorithm without branch
	}

	EXPORT void ext_balance(ExtVMFace* _env, h256* _address, i256* o_value)
	{
		auto u = _env->balance(right160(*_address));
		*o_value = eth2llvm(u);
	}

	EXPORT void ext_suicide(ExtVMFace* _env, h256 const* _address)
	{
		_env->suicide(right160(*_address));
	}

	EXPORT void ext_create(ExtVMFace* _env, i256* _endowment, i256* _initOff, i256* _initSize, h256* o_address)
	{
		auto endowment = llvm2eth(*_endowment);

		if (_env->balance(_env->myAddress) >= endowment)
		{
			_env->subBalance(endowment);
			u256 gas;   // TODO: Handle gas
			auto initOff = static_cast<size_t>(llvm2eth(*_initOff));
			auto initSize = static_cast<size_t>(llvm2eth(*_initSize));
			//auto&& initRef = bytesConstRef(_rt->getMemory().data() + initOff, initSize);
			auto initRef = bytesConstRef(); // FIXME: Handle memory
			OnOpFunc onOp {}; // TODO: Handle that thing
			h256 address(_env->create(endowment, &gas, initRef, onOp), h256::AlignRight);
			*o_address = address;
		}
		else
			*o_address = {};
	}

	EXPORT void ext_call(ExtVMFace* _env, i256* io_gas, h256* _receiveAddress, i256* _value, i256* _inOff, i256* _inSize, i256* _outOff, i256* _outSize, h256* _codeAddress, i256* o_ret)
	{
		auto&& ext = *_env;
		auto value = llvm2eth(*_value);

		auto ret = false;
		auto gas = llvm2eth(*io_gas);
		if (ext.balance(ext.myAddress) >= value)
		{
			ext.subBalance(value);
			auto receiveAddress = right160(*_receiveAddress);
			auto inOff = static_cast<size_t>(llvm2eth(*_inOff));
			auto inSize = static_cast<size_t>(llvm2eth(*_inSize));
			auto outOff = static_cast<size_t>(llvm2eth(*_outOff));
			auto outSize = static_cast<size_t>(llvm2eth(*_outSize));
			//auto&& inRef = bytesConstRef(_rt->getMemory().data() + inOff, inSize);
			//auto&& outRef = bytesConstRef(_rt->getMemory().data() + outOff, outSize);
			auto inRef = bytesConstRef(); // FIXME: Handle memory
			auto outRef = bytesConstRef(); // FIXME: Handle memory
			OnOpFunc onOp {}; // TODO: Handle that thing
			auto codeAddress = right160(*_codeAddress);
			ret = ext.call(receiveAddress, value, inRef, &gas, outRef, onOp, {}, codeAddress);
		}

		*io_gas = eth2llvm(gas);
		o_ret->a = ret ? 1 : 0;
	}

	EXPORT void ext_sha3(byte* _begin, uint64_t _size, h256* o_hash)
	{
		auto hash = sha3({_begin, _size});
		*o_hash = hash;
	}

	EXPORT unsigned char* ext_codeAt(ExtVMFace* _env, h256* _addr256)
	{
		auto addr = right160(*_addr256);
		auto& code = _env->codeAt(addr);
		return const_cast<unsigned char*>(code.data());
	}

	EXPORT void ext_codesizeAt(ExtVMFace* _env, h256* _addr256, i256* o_ret)
	{
		auto addr = right160(*_addr256);
		auto& code = _env->codeAt(addr);
		*o_ret = eth2llvm(u256(code.size()));
	}

	void ext_show_bytes(bytesConstRef _bytes)
	{
		for (auto b : _bytes)
			std::cerr << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned>(b) << " ";
		std::cerr << std::endl;
	}

	EXPORT void ext_log0(ExtVMFace* _env, i256* _memIdx, i256* _numBytes)
	{
		auto memIdx = llvm2eth(*_memIdx).convert_to<size_t>();
		auto numBytes = llvm2eth(*_numBytes).convert_to<size_t>();

		//auto dataRef = bytesConstRef(_rt->getMemory().data() + memIdx, numBytes);
		auto dataRef = bytesConstRef(); // FIXME: Handle memory
		_env->log({}, dataRef);
	}

	EXPORT void ext_log1(ExtVMFace* _env, i256* _memIdx, i256* _numBytes, i256* _topic1)
	{
		auto memIdx = static_cast<size_t>(llvm2eth(*_memIdx));
		auto numBytes = static_cast<size_t>(llvm2eth(*_numBytes));

		auto topic1 = llvm2eth(*_topic1);

		//auto dataRef = bytesConstRef(_rt->getMemory().data() + memIdx, numBytes);
		auto dataRef = bytesConstRef(); // FIXME: Handle memory
		_env->log({topic1}, dataRef);
	}

	EXPORT void ext_log2(ExtVMFace* _env, i256* _memIdx, i256* _numBytes, i256* _topic1, i256* _topic2)
	{
		auto memIdx = static_cast<size_t>(llvm2eth(*_memIdx));
		auto numBytes = static_cast<size_t>(llvm2eth(*_numBytes));

		auto topic1 = llvm2eth(*_topic1);
		auto topic2 = llvm2eth(*_topic2);

		//auto dataRef = bytesConstRef(_rt->getMemory().data() + memIdx, numBytes);
		auto dataRef = bytesConstRef(); // FIXME: Handle memory
		_env->log({ topic1, topic2 }, dataRef);
	}

	EXPORT void ext_log3(ExtVMFace* _env, i256* _memIdx, i256* _numBytes, i256* _topic1, i256* _topic2, i256* _topic3)
	{
		auto memIdx = static_cast<size_t>(llvm2eth(*_memIdx));
		auto numBytes = static_cast<size_t>(llvm2eth(*_numBytes));

		auto topic1 = llvm2eth(*_topic1);
		auto topic2 = llvm2eth(*_topic2);
		auto topic3 = llvm2eth(*_topic3);

		//auto dataRef = bytesConstRef(_rt->getMemory().data() + memIdx, numBytes);
		auto dataRef = bytesConstRef(); // FIXME: Handle memory
		_env->log({ topic1, topic2, topic3 }, dataRef);
	}

	EXPORT void ext_log4(ExtVMFace* _env, i256* _memIdx, i256* _numBytes, i256* _topic1, i256* _topic2, i256* _topic3, i256* _topic4)
	{
		auto memIdx = static_cast<size_t>(llvm2eth(*_memIdx));
		auto numBytes = static_cast<size_t>(llvm2eth(*_numBytes));

		auto topic1 = llvm2eth(*_topic1);
		auto topic2 = llvm2eth(*_topic2);
		auto topic3 = llvm2eth(*_topic3);
		auto topic4 = llvm2eth(*_topic4);

		//auto dataRef = bytesConstRef(_rt->getMemory().data() + memIdx, numBytes);
		auto dataRef = bytesConstRef(); // FIXME: Handle memory
		_env->log({ topic1, topic2, topic3, topic4 }, dataRef);
	}
}

<commit_msg>Old code removed<commit_after>
#include <libdevcrypto/SHA3.h>
#include <libevm/FeeStructure.h>
#include <libevm/ExtVMFace.h>

#include "../libevmjit/Utils.h"

extern "C"
{
	#ifdef _MSC_VER
		#define EXPORT __declspec(dllexport)
	#else
		#define EXPORT
	#endif

	using namespace dev;
	using namespace dev::eth;
	using jit::i256;
	using jit::eth2llvm;

	EXPORT void ext_store(ExtVMFace* _env, i256* _index, i256* o_value)
	{
		auto index = llvm2eth(*_index);
		auto value = _env->store(index); // Interface uses native endianness
		*o_value = eth2llvm(value);
	}

	EXPORT void ext_setStore(ExtVMFace* _env, i256* _index, i256* _value)
	{
		auto index = llvm2eth(*_index);
		auto value = llvm2eth(*_value);

		if (value == 0 && _env->store(index) != 0)	// If delete
			_env->sub.refunds += c_sstoreRefundGas;	// Increase refund counter

		_env->setStore(index, value);	// Interface uses native endianness
	}

	EXPORT void ext_calldataload(ExtVMFace* _env, i256* _index, ::byte* o_value)
	{
		auto index = static_cast<size_t>(llvm2eth(*_index));
		assert(index + 31 > index); // TODO: Handle large index
		for (size_t i = index, j = 0; i <= index + 31; ++i, ++j)
			o_value[j] = i < _env->data.size() ? _env->data[i] : 0; // Keep Big Endian
		// TODO: It all can be done by adding padding to data or by using min() algorithm without branch
	}

	EXPORT void ext_balance(ExtVMFace* _env, h256* _address, i256* o_value)
	{
		auto u = _env->balance(right160(*_address));
		*o_value = eth2llvm(u);
	}

	EXPORT void ext_suicide(ExtVMFace* _env, h256 const* _address)
	{
		_env->suicide(right160(*_address));
	}

	EXPORT void ext_create(ExtVMFace* _env, i256* _endowment, i256* _initOff, i256* _initSize, h256* o_address)
	{
		auto endowment = llvm2eth(*_endowment);

		if (_env->balance(_env->myAddress) >= endowment)
		{
			_env->subBalance(endowment);
			u256 gas;   // TODO: Handle gas
			auto initOff = static_cast<size_t>(llvm2eth(*_initOff));
			auto initSize = static_cast<size_t>(llvm2eth(*_initSize));
			//auto&& initRef = bytesConstRef(_rt->getMemory().data() + initOff, initSize);
			auto initRef = bytesConstRef(); // FIXME: Handle memory
			OnOpFunc onOp {}; // TODO: Handle that thing
			h256 address(_env->create(endowment, &gas, initRef, onOp), h256::AlignRight);
			*o_address = address;
		}
		else
			*o_address = {};
	}

	EXPORT void ext_call(ExtVMFace* _env, i256* io_gas, h256* _receiveAddress, i256* _value, i256* _inOff, i256* _inSize, i256* _outOff, i256* _outSize, h256* _codeAddress, i256* o_ret)
	{
		auto&& ext = *_env;
		auto value = llvm2eth(*_value);

		auto ret = false;
		auto gas = llvm2eth(*io_gas);
		if (ext.balance(ext.myAddress) >= value)
		{
			ext.subBalance(value);
			auto receiveAddress = right160(*_receiveAddress);
			auto inOff = static_cast<size_t>(llvm2eth(*_inOff));
			auto inSize = static_cast<size_t>(llvm2eth(*_inSize));
			auto outOff = static_cast<size_t>(llvm2eth(*_outOff));
			auto outSize = static_cast<size_t>(llvm2eth(*_outSize));
			//auto&& inRef = bytesConstRef(_rt->getMemory().data() + inOff, inSize);
			//auto&& outRef = bytesConstRef(_rt->getMemory().data() + outOff, outSize);
			auto inRef = bytesConstRef(); // FIXME: Handle memory
			auto outRef = bytesConstRef(); // FIXME: Handle memory
			OnOpFunc onOp {}; // TODO: Handle that thing
			auto codeAddress = right160(*_codeAddress);
			ret = ext.call(receiveAddress, value, inRef, &gas, outRef, onOp, {}, codeAddress);
		}

		*io_gas = eth2llvm(gas);
		o_ret->a = ret ? 1 : 0;
	}

	EXPORT void ext_sha3(byte* _begin, uint64_t _size, h256* o_hash)
	{
		auto hash = sha3({_begin, _size});
		*o_hash = hash;
	}

	EXPORT unsigned char* ext_codeAt(ExtVMFace* _env, h256* _addr256)
	{
		auto addr = right160(*_addr256);
		auto& code = _env->codeAt(addr);
		return const_cast<unsigned char*>(code.data());
	}

	EXPORT void ext_codesizeAt(ExtVMFace* _env, h256* _addr256, i256* o_ret)
	{
		auto addr = right160(*_addr256);
		auto& code = _env->codeAt(addr);
		*o_ret = eth2llvm(u256(code.size()));
	}

	EXPORT void ext_log0(ExtVMFace* _env, i256* _memIdx, i256* _numBytes)
	{
		auto memIdx = llvm2eth(*_memIdx).convert_to<size_t>();
		auto numBytes = llvm2eth(*_numBytes).convert_to<size_t>();

		//auto dataRef = bytesConstRef(_rt->getMemory().data() + memIdx, numBytes);
		auto dataRef = bytesConstRef(); // FIXME: Handle memory
		_env->log({}, dataRef);
	}

	EXPORT void ext_log1(ExtVMFace* _env, i256* _memIdx, i256* _numBytes, i256* _topic1)
	{
		auto memIdx = static_cast<size_t>(llvm2eth(*_memIdx));
		auto numBytes = static_cast<size_t>(llvm2eth(*_numBytes));

		auto topic1 = llvm2eth(*_topic1);

		//auto dataRef = bytesConstRef(_rt->getMemory().data() + memIdx, numBytes);
		auto dataRef = bytesConstRef(); // FIXME: Handle memory
		_env->log({topic1}, dataRef);
	}

	EXPORT void ext_log2(ExtVMFace* _env, i256* _memIdx, i256* _numBytes, i256* _topic1, i256* _topic2)
	{
		auto memIdx = static_cast<size_t>(llvm2eth(*_memIdx));
		auto numBytes = static_cast<size_t>(llvm2eth(*_numBytes));

		auto topic1 = llvm2eth(*_topic1);
		auto topic2 = llvm2eth(*_topic2);

		//auto dataRef = bytesConstRef(_rt->getMemory().data() + memIdx, numBytes);
		auto dataRef = bytesConstRef(); // FIXME: Handle memory
		_env->log({ topic1, topic2 }, dataRef);
	}

	EXPORT void ext_log3(ExtVMFace* _env, i256* _memIdx, i256* _numBytes, i256* _topic1, i256* _topic2, i256* _topic3)
	{
		auto memIdx = static_cast<size_t>(llvm2eth(*_memIdx));
		auto numBytes = static_cast<size_t>(llvm2eth(*_numBytes));

		auto topic1 = llvm2eth(*_topic1);
		auto topic2 = llvm2eth(*_topic2);
		auto topic3 = llvm2eth(*_topic3);

		//auto dataRef = bytesConstRef(_rt->getMemory().data() + memIdx, numBytes);
		auto dataRef = bytesConstRef(); // FIXME: Handle memory
		_env->log({ topic1, topic2, topic3 }, dataRef);
	}

	EXPORT void ext_log4(ExtVMFace* _env, i256* _memIdx, i256* _numBytes, i256* _topic1, i256* _topic2, i256* _topic3, i256* _topic4)
	{
		auto memIdx = static_cast<size_t>(llvm2eth(*_memIdx));
		auto numBytes = static_cast<size_t>(llvm2eth(*_numBytes));

		auto topic1 = llvm2eth(*_topic1);
		auto topic2 = llvm2eth(*_topic2);
		auto topic3 = llvm2eth(*_topic3);
		auto topic4 = llvm2eth(*_topic4);

		//auto dataRef = bytesConstRef(_rt->getMemory().data() + memIdx, numBytes);
		auto dataRef = bytesConstRef(); // FIXME: Handle memory
		_env->log({ topic1, topic2, topic3, topic4 }, dataRef);
	}
}

<|endoftext|>


<commit_before>
#include "Runtime.h"

#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IntrinsicInst.h>

#include <libevm/VM.h>

#include "Type.h"

namespace dev
{
namespace eth
{
namespace jit
{

llvm::StructType* RuntimeData::getType()
{
	static llvm::StructType* type = nullptr;
	if (!type)
	{
		llvm::Type* elems[] =
		{
			llvm::ArrayType::get(Type::Word, _size),
			Type::BytePtr,
			Type::BytePtr,
			Type::BytePtr
		};
		type = llvm::StructType::create(elems, "Runtime");
	}
	return type;
}

namespace
{
llvm::Twine getName(RuntimeData::Index _index)
{
	switch (_index)
	{
	default:						return "data";
	case RuntimeData::Gas:			return "gas";
	case RuntimeData::Address:		return "address";
	case RuntimeData::Caller:		return "caller";
	case RuntimeData::Origin:		return "origin";
	case RuntimeData::CallValue:	return "callvalue";
	case RuntimeData::CallDataSize:	return "calldatasize";
	case RuntimeData::GasPrice:		return "gasprice";
	case RuntimeData::PrevHash:		return "prevhash";
	case RuntimeData::CoinBase:		return "coinbase";
	case RuntimeData::TimeStamp:	return "timestamp";
	case RuntimeData::Number:		return "number";
	case RuntimeData::Difficulty:	return "difficulty";
	case RuntimeData::GasLimit:		return "gaslimit";
	case RuntimeData::CodeSize:		return "codesize";
	}
}
}

Runtime::Runtime(u256 _gas, ExtVMFace& _ext, jmp_buf _jmpBuf):
	m_ext(_ext)
{
	set(RuntimeData::Gas, _gas);
	set(RuntimeData::Address, fromAddress(_ext.myAddress));
	set(RuntimeData::Caller, fromAddress(_ext.caller));
	set(RuntimeData::Origin, fromAddress(_ext.origin));
	set(RuntimeData::CallValue, _ext.value);
	set(RuntimeData::CallDataSize, _ext.data.size());
	set(RuntimeData::GasPrice, _ext.gasPrice);
	set(RuntimeData::PrevHash, _ext.previousBlock.hash);
	set(RuntimeData::CoinBase, fromAddress(_ext.currentBlock.coinbaseAddress));
	set(RuntimeData::TimeStamp, _ext.currentBlock.timestamp);
	set(RuntimeData::Number, _ext.currentBlock.number);
	set(RuntimeData::Difficulty, _ext.currentBlock.difficulty);
	set(RuntimeData::GasLimit, _ext.currentBlock.gasLimit);
	set(RuntimeData::CodeSize, _ext.code.size());   // TODO: Use constant
	m_data.callData = _ext.data.data();
	m_data.code = _ext.code.data();
	m_data.jmpBuf = _jmpBuf;
}

void Runtime::set(RuntimeData::Index _index, u256 _value)
{
	m_data.elems[_index] = eth2llvm(_value);
}

u256 Runtime::getGas() const
{
	return llvm2eth(m_data.elems[RuntimeData::Gas]);
}

bytesConstRef Runtime::getReturnData() const
{
	// TODO: Handle large indexes
	auto offset = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataOffset]));
	auto size = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataSize]));

	assert(offset + size <= m_memory.size());
	// TODO: Handle invalid data access by returning empty ref
	return {m_memory.data() + offset, size};
}

RuntimeManager::RuntimeManager(llvm::IRBuilder<>& _builder): CompilerHelper(_builder)
{
	m_dataPtr = new llvm::GlobalVariable(*getModule(), Type::RuntimePtr, false, llvm::GlobalVariable::PrivateLinkage, llvm::UndefValue::get(Type::RuntimePtr), "rt");
	llvm::Type* args[] = {Type::BytePtr, m_builder.getInt32Ty()};
	m_longjmp = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::longjmp);

	// Export data
	auto mainFunc = getMainFunction();
	llvm::Value* dataPtr = &mainFunc->getArgumentList().back();
	m_builder.CreateStore(dataPtr, m_dataPtr);
}

llvm::Value* RuntimeManager::getRuntimePtr()
{
	if (auto mainFunc = getMainFunction())
		return mainFunc->arg_begin()->getNextNode();    // Runtime is the second parameter of main function
	return m_builder.CreateLoad(m_dataPtr, "rt");
}

llvm::Value* RuntimeManager::getPtr(RuntimeData::Index _index)
{
	llvm::Value* idxList[] = {m_builder.getInt32(0), m_builder.getInt32(0), m_builder.getInt32(_index)};
	return m_builder.CreateInBoundsGEP(getRuntimePtr(), idxList, getName(_index) + "Ptr");
}

llvm::Value* RuntimeManager::get(RuntimeData::Index _index)
{
	return m_builder.CreateLoad(getPtr(_index), getName(_index));
}

void RuntimeManager::set(RuntimeData::Index _index, llvm::Value* _value)
{
	m_builder.CreateStore(_value, getPtr(_index));
}

void RuntimeManager::registerReturnData(llvm::Value* _offset, llvm::Value* _size)
{
	set(RuntimeData::ReturnDataOffset, _offset);
	set(RuntimeData::ReturnDataSize, _size);
}

void RuntimeManager::raiseException(ReturnCode _returnCode)
{
	m_builder.CreateCall2(m_longjmp, getJmpBuf(), Constant::get(_returnCode));
}

llvm::Value* RuntimeManager::get(Instruction _inst)
{
	switch (_inst)
	{
	default: assert(false); return nullptr;
	case Instruction::GAS:			return get(RuntimeData::Gas);
	case Instruction::ADDRESS:		return get(RuntimeData::Address);
	case Instruction::CALLER:		return get(RuntimeData::Caller);
	case Instruction::ORIGIN:		return get(RuntimeData::Origin);
	case Instruction::CALLVALUE:	return get(RuntimeData::CallValue);
	case Instruction::CALLDATASIZE:	return get(RuntimeData::CallDataSize);
	case Instruction::GASPRICE:		return get(RuntimeData::GasPrice);
	case Instruction::PREVHASH:		return get(RuntimeData::PrevHash);
	case Instruction::COINBASE:		return get(RuntimeData::CoinBase);
	case Instruction::TIMESTAMP:	return get(RuntimeData::TimeStamp);
	case Instruction::NUMBER:		return get(RuntimeData::Number);
	case Instruction::DIFFICULTY:	return get(RuntimeData::Difficulty);
	case Instruction::GASLIMIT:		return get(RuntimeData::GasLimit);
	case Instruction::CODESIZE:		return get(RuntimeData::CodeSize);
	}
}

llvm::Value* RuntimeManager::getCallData()
{
	auto ptr = getBuilder().CreateStructGEP(getRuntimePtr(), 1, "calldataPtr");
	return getBuilder().CreateLoad(ptr, "calldata");
}

llvm::Value* RuntimeManager::getCode()
{
	auto ptr = getBuilder().CreateStructGEP(getRuntimePtr(), 2, "codePtr");
	return getBuilder().CreateLoad(ptr, "code");
}

llvm::Value* RuntimeManager::getJmpBuf()
{
	auto ptr = getBuilder().CreateStructGEP(getRuntimePtr(), 3, "jmpbufPtr");
	return getBuilder().CreateLoad(ptr, "jmpbuf");
}

llvm::Value* RuntimeManager::getGas()
{
	return get(RuntimeData::Gas);
}

void RuntimeManager::setGas(llvm::Value* _gas)
{
	llvm::Value* idxList[] = {m_builder.getInt32(0), m_builder.getInt32(0), m_builder.getInt32(RuntimeData::Gas)};
	auto ptr = m_builder.CreateInBoundsGEP(getRuntimePtr(), idxList, "gasPtr");
	m_builder.CreateStore(_gas, ptr);
}

}
}
}
<commit_msg>unused var removed<commit_after>
#include "Runtime.h"

#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IntrinsicInst.h>

#include <libevm/VM.h>

#include "Type.h"

namespace dev
{
namespace eth
{
namespace jit
{

llvm::StructType* RuntimeData::getType()
{
	static llvm::StructType* type = nullptr;
	if (!type)
	{
		llvm::Type* elems[] =
		{
			llvm::ArrayType::get(Type::Word, _size),
			Type::BytePtr,
			Type::BytePtr,
			Type::BytePtr
		};
		type = llvm::StructType::create(elems, "Runtime");
	}
	return type;
}

namespace
{
llvm::Twine getName(RuntimeData::Index _index)
{
	switch (_index)
	{
	default:						return "data";
	case RuntimeData::Gas:			return "gas";
	case RuntimeData::Address:		return "address";
	case RuntimeData::Caller:		return "caller";
	case RuntimeData::Origin:		return "origin";
	case RuntimeData::CallValue:	return "callvalue";
	case RuntimeData::CallDataSize:	return "calldatasize";
	case RuntimeData::GasPrice:		return "gasprice";
	case RuntimeData::PrevHash:		return "prevhash";
	case RuntimeData::CoinBase:		return "coinbase";
	case RuntimeData::TimeStamp:	return "timestamp";
	case RuntimeData::Number:		return "number";
	case RuntimeData::Difficulty:	return "difficulty";
	case RuntimeData::GasLimit:		return "gaslimit";
	case RuntimeData::CodeSize:		return "codesize";
	}
}
}

Runtime::Runtime(u256 _gas, ExtVMFace& _ext, jmp_buf _jmpBuf):
	m_ext(_ext)
{
	set(RuntimeData::Gas, _gas);
	set(RuntimeData::Address, fromAddress(_ext.myAddress));
	set(RuntimeData::Caller, fromAddress(_ext.caller));
	set(RuntimeData::Origin, fromAddress(_ext.origin));
	set(RuntimeData::CallValue, _ext.value);
	set(RuntimeData::CallDataSize, _ext.data.size());
	set(RuntimeData::GasPrice, _ext.gasPrice);
	set(RuntimeData::PrevHash, _ext.previousBlock.hash);
	set(RuntimeData::CoinBase, fromAddress(_ext.currentBlock.coinbaseAddress));
	set(RuntimeData::TimeStamp, _ext.currentBlock.timestamp);
	set(RuntimeData::Number, _ext.currentBlock.number);
	set(RuntimeData::Difficulty, _ext.currentBlock.difficulty);
	set(RuntimeData::GasLimit, _ext.currentBlock.gasLimit);
	set(RuntimeData::CodeSize, _ext.code.size());   // TODO: Use constant
	m_data.callData = _ext.data.data();
	m_data.code = _ext.code.data();
	m_data.jmpBuf = _jmpBuf;
}

void Runtime::set(RuntimeData::Index _index, u256 _value)
{
	m_data.elems[_index] = eth2llvm(_value);
}

u256 Runtime::getGas() const
{
	return llvm2eth(m_data.elems[RuntimeData::Gas]);
}

bytesConstRef Runtime::getReturnData() const
{
	// TODO: Handle large indexes
	auto offset = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataOffset]));
	auto size = static_cast<size_t>(llvm2eth(m_data.elems[RuntimeData::ReturnDataSize]));

	assert(offset + size <= m_memory.size());
	// TODO: Handle invalid data access by returning empty ref
	return {m_memory.data() + offset, size};
}

RuntimeManager::RuntimeManager(llvm::IRBuilder<>& _builder): CompilerHelper(_builder)
{
	m_dataPtr = new llvm::GlobalVariable(*getModule(), Type::RuntimePtr, false, llvm::GlobalVariable::PrivateLinkage, llvm::UndefValue::get(Type::RuntimePtr), "rt");
	m_longjmp = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::longjmp);

	// Export data
	auto mainFunc = getMainFunction();
	llvm::Value* dataPtr = &mainFunc->getArgumentList().back();
	m_builder.CreateStore(dataPtr, m_dataPtr);
}

llvm::Value* RuntimeManager::getRuntimePtr()
{
	if (auto mainFunc = getMainFunction())
		return mainFunc->arg_begin()->getNextNode();    // Runtime is the second parameter of main function
	return m_builder.CreateLoad(m_dataPtr, "rt");
}

llvm::Value* RuntimeManager::getPtr(RuntimeData::Index _index)
{
	llvm::Value* idxList[] = {m_builder.getInt32(0), m_builder.getInt32(0), m_builder.getInt32(_index)};
	return m_builder.CreateInBoundsGEP(getRuntimePtr(), idxList, getName(_index) + "Ptr");
}

llvm::Value* RuntimeManager::get(RuntimeData::Index _index)
{
	return m_builder.CreateLoad(getPtr(_index), getName(_index));
}

void RuntimeManager::set(RuntimeData::Index _index, llvm::Value* _value)
{
	m_builder.CreateStore(_value, getPtr(_index));
}

void RuntimeManager::registerReturnData(llvm::Value* _offset, llvm::Value* _size)
{
	set(RuntimeData::ReturnDataOffset, _offset);
	set(RuntimeData::ReturnDataSize, _size);
}

void RuntimeManager::raiseException(ReturnCode _returnCode)
{
	m_builder.CreateCall2(m_longjmp, getJmpBuf(), Constant::get(_returnCode));
}

llvm::Value* RuntimeManager::get(Instruction _inst)
{
	switch (_inst)
	{
	default: assert(false); return nullptr;
	case Instruction::GAS:			return get(RuntimeData::Gas);
	case Instruction::ADDRESS:		return get(RuntimeData::Address);
	case Instruction::CALLER:		return get(RuntimeData::Caller);
	case Instruction::ORIGIN:		return get(RuntimeData::Origin);
	case Instruction::CALLVALUE:	return get(RuntimeData::CallValue);
	case Instruction::CALLDATASIZE:	return get(RuntimeData::CallDataSize);
	case Instruction::GASPRICE:		return get(RuntimeData::GasPrice);
	case Instruction::PREVHASH:		return get(RuntimeData::PrevHash);
	case Instruction::COINBASE:		return get(RuntimeData::CoinBase);
	case Instruction::TIMESTAMP:	return get(RuntimeData::TimeStamp);
	case Instruction::NUMBER:		return get(RuntimeData::Number);
	case Instruction::DIFFICULTY:	return get(RuntimeData::Difficulty);
	case Instruction::GASLIMIT:		return get(RuntimeData::GasLimit);
	case Instruction::CODESIZE:		return get(RuntimeData::CodeSize);
	}
}

llvm::Value* RuntimeManager::getCallData()
{
	auto ptr = getBuilder().CreateStructGEP(getRuntimePtr(), 1, "calldataPtr");
	return getBuilder().CreateLoad(ptr, "calldata");
}

llvm::Value* RuntimeManager::getCode()
{
	auto ptr = getBuilder().CreateStructGEP(getRuntimePtr(), 2, "codePtr");
	return getBuilder().CreateLoad(ptr, "code");
}

llvm::Value* RuntimeManager::getJmpBuf()
{
	auto ptr = getBuilder().CreateStructGEP(getRuntimePtr(), 3, "jmpbufPtr");
	return getBuilder().CreateLoad(ptr, "jmpbuf");
}

llvm::Value* RuntimeManager::getGas()
{
	return get(RuntimeData::Gas);
}

void RuntimeManager::setGas(llvm::Value* _gas)
{
	llvm::Value* idxList[] = {m_builder.getInt32(0), m_builder.getInt32(0), m_builder.getInt32(RuntimeData::Gas)};
	auto ptr = m_builder.CreateInBoundsGEP(getRuntimePtr(), idxList, "gasPtr");
	m_builder.CreateStore(_gas, ptr);
}

}
}
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2003 Hans Karlsson <karlsson.h@home.se>
 * Copyright (C) 2003-2004 Adam Geitgey <adam@rootnode.org>
 * Copyright (c) 2005 Ryan Nickell <p0z3r@earthlink.net>
 *
 * This file is part of SuperKaramba.
 *
 *  SuperKaramba is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  SuperKaramba is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with SuperKaramba; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 ****************************************************************************/

#include "karambaapp.h"
#include "karambasessionmanaged.h"
#include "python/karamba.h"

#include "config-superkaramba.h"

#include <stdlib.h>

#include <KLocale>
#include <KConfig>
#include <KDebug>
#include <KStandardDirs>
#include <KCmdLineArgs>
#include <KAboutData>
#include <KWindowSystem>

#include <X11/extensions/Xrender.h>

static const char *description =
    I18N_NOOP("A KDE Eye-candy Application");

static const char *version = "0.53";

int main(int argc, char **argv)
{
    Display *dpy = XOpenDisplay(0); // open default display
    if (!dpy) {
        kWarning() << "Cannot connect to the X server";
        exit(1);
    }

    Colormap colormap = 0;
    Visual *visual = 0;

    if (KWindowSystem::compositingActive()) {
        int screen = DefaultScreen(dpy);
        int eventBase, errorBase;

        if (XRenderQueryExtension(dpy, &eventBase, &errorBase)) {
            int nvi;
            XVisualInfo templ;
            templ.screen  = screen;
            templ.depth   = 32;
            templ.c_class = TrueColor;
            XVisualInfo *xvi = XGetVisualInfo(dpy, VisualScreenMask |
                                              VisualDepthMask |
                                              VisualClassMask,
                                              &templ, &nvi);
            for (int i = 0; i < nvi; ++i) {
                XRenderPictFormat *format = XRenderFindVisualFormat(dpy,
                                            xvi[i].visual);
                if (format->type == PictTypeDirect && format->direct.alphaMask) {
                    visual = xvi[i].visual;
                    colormap = XCreateColormap(dpy, RootWindow(dpy, screen),
                                               visual, AllocNone);
                    break;
                }
            }
        }
    }

    KAboutData about("superkaramba", 0, ki18n("SuperKaramba"),
                     version, ki18n(description),
                     KAboutData::License_GPL,
                     ki18n("(c) 2003-2007 The SuperKaramba developers"), KLocalizedString(),
                     "http://utils.kde.org/projects/superkaramba");
    about.addAuthor(ki18n("Adam Geitgey"), KLocalizedString(), "adam@rootnode.org");
    about.addAuthor(ki18n("Hans Karlsson"), KLocalizedString(), "karlsson.h@home.se");
    about.addAuthor(ki18n("Ryan Nickell"), KLocalizedString(), "p0z3r@earthlink.net");
    about.addAuthor(ki18n("Petri Damstén"), KLocalizedString(), "petri.damsten@iki.fi");
    about.addAuthor(ki18n("Alexander Wiedenbruch"), KLocalizedString(), "mail@wiedenbruch.de");
    about.addAuthor(ki18n("Luke Kenneth Casson Leighton"), KLocalizedString(), "lkcl@lkcl.net");
    about.addCredit(ki18n("Sebastian Sauer"), ki18n("Work on Kross, tutorials and examples"), "mail@dipe.org");
    KCmdLineArgs::init(argc, argv, &about);

    KCmdLineOptions options;
    // { "+[URL]", I18N_NOOP( "Document to open" ), 0 },
// { "!nosystray", I18N_NOOP("Disable systray icon"), 0 },
#ifdef PYTHON_INCLUDE_PATH
   options.add("usefallback", ki18n("Use the original python bindings as scripting backend. Off by default."));
#endif
    options.add("+file", ki18n("A required argument 'file'"));
    KCmdLineArgs::addCmdLineOptions(options);
    KarambaApplication::addCmdLineOptions();
    KarambaSessionManaged ksm;

    if (!KarambaApplication::start()) {
        fprintf(stderr, "SuperKaramba is already running!\n");
        exit(0);
    }

#ifdef PYTHON_INCLUDE_PATH
    bool noUseKross = false;
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    if (args->isSet("usefallback")) {
        noUseKross = true;
        kDebug() << "Using fallback python scripting backend!" ;
    }
#endif

    KarambaApplication app(dpy, Qt::HANDLE(visual), Qt::HANDLE(colormap));

    app.setupSysTray(&about);
    int ret = 0;

#ifdef PYTHON_INCLUDE_PATH
    if (noUseKross) {
        KarambaPython::initPython();
    }
#endif

    ret = app.exec();

#ifdef PYTHON_INCLUDE_PATH
    if (noUseKross) {
        KarambaPython::shutdownPython();
    }
#endif

    return ret;
}
<commit_msg>bumping the version numbers in /trunk, now that 4.3 has been branched<commit_after>/*
 * Copyright (C) 2003 Hans Karlsson <karlsson.h@home.se>
 * Copyright (C) 2003-2004 Adam Geitgey <adam@rootnode.org>
 * Copyright (c) 2005 Ryan Nickell <p0z3r@earthlink.net>
 *
 * This file is part of SuperKaramba.
 *
 *  SuperKaramba is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  SuperKaramba is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with SuperKaramba; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 ****************************************************************************/

#include "karambaapp.h"
#include "karambasessionmanaged.h"
#include "python/karamba.h"

#include "config-superkaramba.h"

#include <stdlib.h>

#include <KLocale>
#include <KConfig>
#include <KDebug>
#include <KStandardDirs>
#include <KCmdLineArgs>
#include <KAboutData>
#include <KWindowSystem>

#include <X11/extensions/Xrender.h>

static const char *description =
    I18N_NOOP("A KDE Eye-candy Application");

static const char *version = "0.54";

int main(int argc, char **argv)
{
    Display *dpy = XOpenDisplay(0); // open default display
    if (!dpy) {
        kWarning() << "Cannot connect to the X server";
        exit(1);
    }

    Colormap colormap = 0;
    Visual *visual = 0;

    if (KWindowSystem::compositingActive()) {
        int screen = DefaultScreen(dpy);
        int eventBase, errorBase;

        if (XRenderQueryExtension(dpy, &eventBase, &errorBase)) {
            int nvi;
            XVisualInfo templ;
            templ.screen  = screen;
            templ.depth   = 32;
            templ.c_class = TrueColor;
            XVisualInfo *xvi = XGetVisualInfo(dpy, VisualScreenMask |
                                              VisualDepthMask |
                                              VisualClassMask,
                                              &templ, &nvi);
            for (int i = 0; i < nvi; ++i) {
                XRenderPictFormat *format = XRenderFindVisualFormat(dpy,
                                            xvi[i].visual);
                if (format->type == PictTypeDirect && format->direct.alphaMask) {
                    visual = xvi[i].visual;
                    colormap = XCreateColormap(dpy, RootWindow(dpy, screen),
                                               visual, AllocNone);
                    break;
                }
            }
        }
    }

    KAboutData about("superkaramba", 0, ki18n("SuperKaramba"),
                     version, ki18n(description),
                     KAboutData::License_GPL,
                     ki18n("(c) 2003-2007 The SuperKaramba developers"), KLocalizedString(),
                     "http://utils.kde.org/projects/superkaramba");
    about.addAuthor(ki18n("Adam Geitgey"), KLocalizedString(), "adam@rootnode.org");
    about.addAuthor(ki18n("Hans Karlsson"), KLocalizedString(), "karlsson.h@home.se");
    about.addAuthor(ki18n("Ryan Nickell"), KLocalizedString(), "p0z3r@earthlink.net");
    about.addAuthor(ki18n("Petri Damstén"), KLocalizedString(), "petri.damsten@iki.fi");
    about.addAuthor(ki18n("Alexander Wiedenbruch"), KLocalizedString(), "mail@wiedenbruch.de");
    about.addAuthor(ki18n("Luke Kenneth Casson Leighton"), KLocalizedString(), "lkcl@lkcl.net");
    about.addCredit(ki18n("Sebastian Sauer"), ki18n("Work on Kross, tutorials and examples"), "mail@dipe.org");
    KCmdLineArgs::init(argc, argv, &about);

    KCmdLineOptions options;
    // { "+[URL]", I18N_NOOP( "Document to open" ), 0 },
// { "!nosystray", I18N_NOOP("Disable systray icon"), 0 },
#ifdef PYTHON_INCLUDE_PATH
   options.add("usefallback", ki18n("Use the original python bindings as scripting backend. Off by default."));
#endif
    options.add("+file", ki18n("A required argument 'file'"));
    KCmdLineArgs::addCmdLineOptions(options);
    KarambaApplication::addCmdLineOptions();
    KarambaSessionManaged ksm;

    if (!KarambaApplication::start()) {
        fprintf(stderr, "SuperKaramba is already running!\n");
        exit(0);
    }

#ifdef PYTHON_INCLUDE_PATH
    bool noUseKross = false;
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    if (args->isSet("usefallback")) {
        noUseKross = true;
        kDebug() << "Using fallback python scripting backend!" ;
    }
#endif

    KarambaApplication app(dpy, Qt::HANDLE(visual), Qt::HANDLE(colormap));

    app.setupSysTray(&about);
    int ret = 0;

#ifdef PYTHON_INCLUDE_PATH
    if (noUseKross) {
        KarambaPython::initPython();
    }
#endif

    ret = app.exec();

#ifdef PYTHON_INCLUDE_PATH
    if (noUseKross) {
        KarambaPython::shutdownPython();
    }
#endif

    return ret;
}
<|endoftext|>


<commit_before>/*
This file is part of qNotesManager.

qNotesManager is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

qNotesManager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with qNotesManager. If not, see <http://www.gnu.org/licenses/>.
*/

#include <QApplication>
#include <QTextCodec>
#include <QFileInfo>
#include <QtGlobal>

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

#include "mainwindow.h"
#include "application.h"
#include "appinfo.h"

using namespace qNotesManager;

#if QT_VERSION >= 0x050000
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg);
#else
void myMessageOutput(QtMsgType type, const char *msg);
#endif

bool errorOutput;

int main(int argc, char** argv) {
	QString helpScreenText = QString().append("Usage: \n").append(VER_PRODUCTNAME_STR).append(
			" [-v] [-h] [options] [file]\n"
			"-v, --version				Print version and exit.\n"
			"-h, --help				Print this screen\n"
			"Options:\n"
			"-s, --silent			Do not send data to stderr\n"
			"-fo FILE, --file-output FILE		Send debug output to file FILE\n\n"
			"file					File to open\n");
	errorOutput = true;

	QApplication app(argc, argv);
	app.setQuitOnLastWindowClosed(false);
	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));

	QStringList arguments = QCoreApplication::arguments();

	if (arguments.count() > 1) {
		arguments.removeAt(0);

		if (arguments.count() == 1) {
			QString arg = arguments.at(0);
			if (arg == "-v" || arg == "--version") {
				fprintf(stdout, "%s version: %s\n", VER_PRODUCTNAME_STR, V_SVERSION_STR);
				return 0;
			} else if (arg == "-h" || arg == "--help") {
				fprintf(stdout, qPrintable(helpScreenText));
				return 0;
			}
			if (arguments.contains("-no") || arguments.contains("--no-output")) {
				errorOutput = false;
			}
		}
	}
#if QT_VERSION >= 0x050000
	qInstallMessageHandler(myMessageOutput);
#else
	qInstallMsgHandler(myMessageOutput);
#endif

	MainWindow w;
	QObject::connect(&app, SIGNAL(aboutToQuit()), &w, SLOT(sl_QApplication_AboutToQuit()));

	if (Application::I()->Settings.GetShowWindowOnStart()) {
		w.show();
	}

	if (Application::I()->Settings.GetOpenLastDocumentOnStart() &&
		!Application::I()->Settings.GetLastDocumentName().isEmpty() &&
		QFileInfo(Application::I()->Settings.GetLastDocumentName()).exists()) {
		w.OpenDocument(Application::I()->Settings.GetLastDocumentName());
	}

	return app.exec();
}

#if QT_VERSION >= 0x050000
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
	QByteArray localMsg = msg.toLocal8Bit();
	switch (type) {
	case QtDebugMsg:
#ifdef DEBUG
		fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
#endif
		break;
	case QtWarningMsg:
		fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
		break;
	case QtCriticalMsg:
		fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
		break;
	case QtFatalMsg:
		fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
		abort();
	}
}
#else
void myMessageOutput(QtMsgType type, const char *msg) {
	if (!errorOutput) {
		if (type == QtFatalMsg) {
			abort();
		}
		return;
	}
	switch (type) {
	case QtDebugMsg:
#ifdef DEBUG
		fprintf(stderr, "Debug: %s\n", msg);
#endif
		break;
	case QtWarningMsg:
		fprintf(stderr, "Warning: %s\n", msg);
		break;
	case QtCriticalMsg:
		fprintf(stderr, "Critical: %s\n", msg);
		break;
	case QtFatalMsg:
		fprintf(stderr, "Fatal: %s\n", msg);
		abort();
	}
}
#endif
<commit_msg>deprecated setCodecForCStrings removed<commit_after>/*
This file is part of qNotesManager.

qNotesManager is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

qNotesManager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with qNotesManager. If not, see <http://www.gnu.org/licenses/>.
*/

#include <QApplication>
#include <QTextCodec>
#include <QFileInfo>
#include <QtGlobal>

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

#include "mainwindow.h"
#include "application.h"
#include "appinfo.h"

using namespace qNotesManager;

#if QT_VERSION >= 0x050000
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg);
#else
void myMessageOutput(QtMsgType type, const char *msg);
#endif

bool errorOutput;

int main(int argc, char** argv) {
	QString helpScreenText = QString().append("Usage: \n").append(VER_PRODUCTNAME_STR).append(
			" [-v] [-h] [options] [file]\n"
			"-v, --version				Print version and exit.\n"
			"-h, --help				Print this screen\n"
			"Options:\n"
			"-s, --silent			Do not send data to stderr\n"
			"-fo FILE, --file-output FILE		Send debug output to file FILE\n\n"
			"file					File to open\n");
	errorOutput = true;

	QApplication app(argc, argv);
	app.setQuitOnLastWindowClosed(false);
	QStringList arguments = QCoreApplication::arguments();

	if (arguments.count() > 1) {
		arguments.removeAt(0);

		if (arguments.count() == 1) {
			QString arg = arguments.at(0);
			if (arg == "-v" || arg == "--version") {
				fprintf(stdout, "%s version: %s\n", VER_PRODUCTNAME_STR, V_SVERSION_STR);
				return 0;
			} else if (arg == "-h" || arg == "--help") {
				fprintf(stdout, qPrintable(helpScreenText));
				return 0;
			}
			if (arguments.contains("-no") || arguments.contains("--no-output")) {
				errorOutput = false;
			}
		}
	}
#if QT_VERSION >= 0x050000
	qInstallMessageHandler(myMessageOutput);
#else
	qInstallMsgHandler(myMessageOutput);
#endif

	MainWindow w;
	QObject::connect(&app, SIGNAL(aboutToQuit()), &w, SLOT(sl_QApplication_AboutToQuit()));

	if (Application::I()->Settings.GetShowWindowOnStart()) {
		w.show();
	}

	if (Application::I()->Settings.GetOpenLastDocumentOnStart() &&
		!Application::I()->Settings.GetLastDocumentName().isEmpty() &&
		QFileInfo(Application::I()->Settings.GetLastDocumentName()).exists()) {
		w.OpenDocument(Application::I()->Settings.GetLastDocumentName());
	}

	return app.exec();
}

#if QT_VERSION >= 0x050000
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
	QByteArray localMsg = msg.toLocal8Bit();
	switch (type) {
	case QtDebugMsg:
#ifdef DEBUG
		fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
#endif
		break;
	case QtWarningMsg:
		fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
		break;
	case QtCriticalMsg:
		fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
		break;
	case QtFatalMsg:
		fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
		abort();
	}
}
#else
void myMessageOutput(QtMsgType type, const char *msg) {
	if (!errorOutput) {
		if (type == QtFatalMsg) {
			abort();
		}
		return;
	}
	switch (type) {
	case QtDebugMsg:
#ifdef DEBUG
		fprintf(stderr, "Debug: %s\n", msg);
#endif
		break;
	case QtWarningMsg:
		fprintf(stderr, "Warning: %s\n", msg);
		break;
	case QtCriticalMsg:
		fprintf(stderr, "Critical: %s\n", msg);
		break;
	case QtFatalMsg:
		fprintf(stderr, "Fatal: %s\n", msg);
		abort();
	}
}
#endif
<|endoftext|>