<commit_before>#include <iostream>
#include <map>
#include <utility>
#include <vector>
#include <cmath>

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

#include <ntd/memory.hpp>

#include <texture_manager.hpp>

int main() {
    SDL_Init(SDL_INIT_EVERYTHING);

    auto window = ntd::make_smart<SDL_Window>(
        SDL_CreateWindow,
        SDL_DestroyWindow,
        "sdl-gamepad-conf",
        SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED,
        600,
        600,
        0
    );

    bool running = true;

    auto renderer = SDL_CreateRenderer(window.get(), -1, SDL_RENDERER_ACCELERATED);

    auto manager = texture_manager{renderer};
    std::map<std::string, int> configs;

    auto buttons = std::vector<std::string> {
        "A", "B", "X", "Y", "LB", "RB", "START", "SELECT", "LS", "RS"
    };

    auto hats = std::vector<std::string> {
        "DPADUP", "DPADDOWN", "DPADLEFT", "DPADRIGHT"
    };

    auto axis = std::vector<std::string>{
        "LS_X", "LS_Y", "RS_X", "RS_Y", "LT", "RT"
    };

    for(auto b : buttons) {
        auto str = std::string{"assets/gamepad_"} + b + ".png";

        manager.add(b, str);
    }

    for(auto h : hats) {
        auto str = std::string{"assets/gamepad_"} + h + ".png";

        manager.add(h, str);
    }

    for(auto a : axis) {
        auto str = std::string{"assets/gamepad_"} + a + ".png";

        manager.add(a, str);
    }

    manager.add("NOPE", "assets/gamepad_NOPE.png");

    SDL_Event event;

    int index = 0;
    bool buttons_done = false;
    bool hats_done = false;
    bool joy_moved = false;
    bool hats_are_buttons = false;
    int last_axis = -1;

    auto ptr = manager.get(buttons[index]);

    if(!SDL_WasInit(SDL_INIT_JOYSTICK)) {
        SDL_InitSubSystem(SDL_INIT_JOYSTICK);
    }

    auto joynum = SDL_NumJoysticks();

    if(joynum > 0) {
        SDL_JoystickOpen(0);
        SDL_JoystickEventState(SDL_ENABLE);

        auto name = SDL_JoystickNameForIndex(0);

        std::cout << "Gamepad detected: " << name << std::endl;

        SDL_SetWindowTitle(window.get(), name);
    }

    while(running) {
        joynum = SDL_NumJoysticks();

        while(SDL_PollEvent(&event)) {
            if(event.type == SDL_QUIT) {
                running = false;
            }

            if(joynum > 0) {
                if(event.type == SDL_JOYBUTTONDOWN && !buttons_done) {
                    auto button_id = event.jbutton.button;

                    configs.insert(std::make_pair(buttons[index], button_id));

                    index++;

                    if(index == buttons.size()) {
                        buttons_done = true;
                        index = 0;

                        ptr = manager.get(hats[index]);
                    } else {
                        ptr = manager.get(buttons[index]);
                    }
                } else if(event.type == SDL_JOYHATMOTION && event.jhat.value > 0 && !hats_done) {
                    auto hat_id = event.jhat.hat;

                    configs.insert(std::make_pair(hats[index], hat_id));

                    index++;

                    if(index == hats.size()) {
                        hats_done = true;
                        index = 0;

                        ptr = manager.get(axis[index]);
                    } else {
                        ptr = manager.get(hats[index]);
                    }
                } else if(buttons_done && !hats_done && event.type == SDL_JOYBUTTONDOWN) {
                    // hat is button
                    hats_are_buttons = true;

                    auto button_id = event.jbutton.button;

                    configs.insert(std::make_pair(hats[index], button_id));

                    index++;

                    if(index == hats.size()) {
                        hats_done = true;
                        index = 0;

                        ptr = manager.get(axis[index]);
                    } else {
                        ptr = manager.get(hats[index]);
                    }
                }

                auto tval = event.jaxis.value < 0 ? event.jaxis.value * -1 : event.jaxis.value;

                std::cout << "hats done: " << hats_done << " moved? " <<  joy_moved << " motion event? " << (event.type == SDL_JOYAXISMOTION) << " last axis? " << last_axis << " " << int{event.jaxis.axis} << " val " << (tval < 1000) << std::endl;

                if(hats_done && joy_moved && event.type == SDL_JOYAXISMOTION && last_axis == event.jaxis.axis && tval < 1000) {
                    joy_moved = false;
                }

                if(hats_done && !joy_moved && event.type == SDL_JOYAXISMOTION && tval > 32000) {
                    auto axis_id = event.jaxis.axis;

                    configs.insert(std::make_pair(axis[index], axis_id));

                    joy_moved = true;
                    last_axis = int{axis_id};

                    index++;

                    if(index == axis.size()) {
                        running = false;
                    } else {
                        ptr = manager.get(axis[index]);
                    }
                }
            }
        }

        if(joynum == 0) {
            ptr = manager.get("NOPE");
        }

        SDL_RenderClear(renderer);
        SDL_RenderCopy(renderer, ptr, 0, 0);
        SDL_RenderPresent(renderer);
    }

    std::cout << "Hats are buttons? " << hats_are_buttons << std::endl;

    for(auto &c : configs) {
        std::cout << c.first << ": " << c.second << std::endl;
    }

    if(joynum > 0 && SDL_JoystickGetAttached(0)) {
        SDL_JoystickClose(0);
    }

    SDL_DestroyRenderer(renderer);

    SDL_Quit();

    return 0;
}
<commit_msg>fix not working trigger stuff<commit_after>#include <iostream>
#include <map>
#include <utility>
#include <vector>
#include <cmath>

#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

#include <ntd/memory.hpp>

#include <texture_manager.hpp>

int main() {
    SDL_Init(SDL_INIT_EVERYTHING);

    auto window = ntd::make_smart<SDL_Window>(
        SDL_CreateWindow,
        SDL_DestroyWindow,
        "sdl-gamepad-conf",
        SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED,
        600,
        600,
        SDL_WINDOW_OPENGL
    );

    bool running = true;

    auto renderer = SDL_CreateRenderer(window.get(), -1, SDL_RENDERER_ACCELERATED);

    auto manager = texture_manager{renderer};
    std::map<std::string, int> configs;

    auto buttons = std::vector<std::string> {
        "A", "B", "X", "Y", "LB", "RB", "START", "SELECT", "LS", "RS"
    };

    auto hats = std::vector<std::string> {
        "DPADUP", "DPADDOWN", "DPADLEFT", "DPADRIGHT"
    };

    auto axis = std::vector<std::string>{
        "LS_X", "LS_Y", "RS_X", "RS_Y"
    };

    auto triggers = std::vector<std::string>{
        "LT", "RT"
    };

    for(auto b : buttons) {
        auto str = std::string{"assets/gamepad_"} + b + ".png";

        manager.add(b, str);
    }

    for(auto h : hats) {
        auto str = std::string{"assets/gamepad_"} + h + ".png";

        manager.add(h, str);
    }

    for(auto a : axis) {
        auto str = std::string{"assets/gamepad_"} + a + ".png";

        manager.add(a, str);
    }

    for(auto t : triggers) {
        auto str = std::string{"assets/gamepad_"} + t + ".png";

        manager.add(t, str);
    }

    manager.add("NOPE", "assets/gamepad_NOPE.png");

    SDL_Event event;

    int index = 0;

    bool buttons_done = false;
    bool hats_done = false;
    bool axis_done = false;

    bool joy_moved = false;
    bool hats_are_buttons = false;
    int last_axis = -1;

    auto ptr = manager.get(buttons[index]);

    auto joynum = SDL_NumJoysticks();

    if(joynum > 0) {
        SDL_JoystickOpen(0);
        SDL_JoystickEventState(SDL_ENABLE);

        auto name = SDL_JoystickNameForIndex(0);

        std::cout << "Gamepad detected: " << name << std::endl;

        SDL_SetWindowTitle(window.get(), name);
    }

    while(running) {
        joynum = SDL_NumJoysticks();

        while(SDL_PollEvent(&event)) {
            if(event.type == SDL_QUIT) {
                running = false;
            }

            if(joynum > 0) {
                if(event.type == SDL_JOYBUTTONDOWN && !buttons_done) {
                    auto button_id = event.jbutton.button;

                    configs.insert(std::make_pair(buttons[index], button_id));

                    index++;

                    if(index == buttons.size()) {
                        buttons_done = true;
                        index = 0;

                        ptr = manager.get(hats[index]);
                    } else {
                        ptr = manager.get(buttons[index]);
                    }
                } else if(event.type == SDL_JOYHATMOTION && event.jhat.value > 0 && !hats_done) {
                    auto hat_id = event.jhat.hat;

                    configs.insert(std::make_pair(hats[index], hat_id));

                    index++;

                    if(index == hats.size()) {
                        hats_done = true;
                        index = 0;

                        ptr = manager.get(axis[index]);
                    } else {
                        ptr = manager.get(hats[index]);
                    }
                } else if(buttons_done && !hats_done && event.type == SDL_JOYBUTTONDOWN) {
                    // hat is button
                    hats_are_buttons = true;

                    auto button_id = event.jbutton.button;

                    configs.insert(std::make_pair(hats[index], button_id));

                    index++;

                    if(index == hats.size()) {
                        hats_done = true;
                        index = 0;

                        ptr = manager.get(axis[index]);
                    } else {
                        ptr = manager.get(hats[index]);
                    }
                }

                if(hats_done && !axis_done) {
                    auto value = event.jaxis.value < 0 ? event.jaxis.value * -1 : event.jaxis.value;

                    if(joy_moved && event.type == SDL_JOYAXISMOTION && last_axis == event.jaxis.axis && value < 1000) {
                        joy_moved = false;
                    }

                    if(!joy_moved && event.type == SDL_JOYAXISMOTION && value > 28000) {
                        auto axis_id = event.jaxis.axis;

                        configs.insert(std::make_pair(axis[index], axis_id));

                        joy_moved = true;
                        last_axis = int{axis_id};

                        index++;

                        if(index == axis.size()) {
                            axis_done = true;
                            index = 0;
                            joy_moved = false;
                            last_axis = -1;

                            ptr = manager.get(triggers[index]);
                        } else {
                            ptr = manager.get(axis[index]);
                        }
                    }
                }

                if(axis_done) {
                    if(joy_moved && event.type == SDL_JOYAXISMOTION && last_axis == event.jaxis.axis && event.jaxis.value < -30000) {
                        joy_moved = false;
                    }

                    if(event.type == SDL_JOYAXISMOTION && event.jaxis.value > 30000) {
                        auto trigger_id = event.jaxis.axis;

                        configs.insert(std::make_pair(triggers[index], trigger_id));

                        joy_moved = true;
                        last_axis = int{trigger_id};

                        index++;

                        if(index == triggers.size()) {
                            running = false;
                        } else {
                            ptr = manager.get(triggers[index]);
                        }
                    }
                }
            }
        }

        if(joynum == 0) {
            ptr = manager.get("NOPE");
        }

        SDL_RenderClear(renderer);
        SDL_RenderCopy(renderer, ptr, 0, 0);
        SDL_RenderPresent(renderer);
    }

    std::cout << "Hats are buttons? " << hats_are_buttons << std::endl;

    for(auto &c : configs) {
        std::cout << c.first << ": " << c.second << std::endl;
    }

    if(joynum > 0 && SDL_JoystickGetAttached(0)) {
        SDL_JoystickClose(0);
    }

    SDL_DestroyRenderer(renderer);

    SDL_Quit();

    return 0;
}
<|endoftext|>


<commit_before>/**
 * Project
 * #    #     #     ######   ######
 * #   #     # #    #     #  #     #
 * #  #     #   #   #     #  #     #
 * ###     #     #  ######   ######
 * #  #    #######  #   #    #   #
 * #   #   #     #  #    #   #    #
 * #    #  #     #  #     #  #     #
 *
 * Copyright (c) 2014, Project KARR
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 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 HOLDER 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 <stdio.h>
#include <stdlib.h>

#include <GL/glut.h>
#include <vg/openvg.h>

#include <string>
#include <sstream>

#include "ArduinoDataPacket.h"
#include "Display.h"
#include "DisplayManager.h"
#include "GLUtil.h"
#include "CelicaDisplay.h"
#include "SimpleTextDisplay.h"
#include "SerialConnection.h"
#include "TestInput.h"
#include "Knight_Industries.C"

using namespace KARR;
using namespace std;

static const int w = 1024;
static const int h = 600;
static SerialConnection sArduinoConnection;

void handleKeyboard(unsigned char key, int x, int y) {
    if (key == 27)
	exit(0);
}

void handleDisplay() {
    int now;
    static bool timeinit = false;
    static int fpsdraw = -1;
    static int fps = 0;
    static int lastfps = 0;
    static ArduinoDataPacket dataPacket;

    { /* Read data from Arduino */
	if (sArduinoConnection.isOpened()) {
	    memset(&dataPacket, '\0', sizeof(ArduinoDataPacket));
	    if (sArduinoConnection.read((void *)&dataPacket, sizeof(ArduinoDataPacket))) {

		// Update data
	    }
	}
    }

#if 0
    /* Get interval from last redraw */
    now = glutGet(GLUT_ELAPSED_TIME);

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f );
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    vgClear(0,0,w,h);

    /* Draw scene */
    const Display *currentDisplay = DisplayManager::instance().getCurrent();
    if (currentDisplay)
	const_cast<Display *>(currentDisplay)->draw(/*interval*/);
    else
    {
	vgSeti(VG_MATRIX_MODE, VG_MATRIX_IMAGE_USER_TO_SURFACE);
	vgLoadIdentity();
	vgScale(1, -1); // Flip the picture
	vgTranslate(w / 2 - knight_industries.width / 2, -433); // Move to to the center
	vgDrawImage(knightIndustries);
    }

    if (fpsdraw > -1) {
	/* Draw fps */
	GLfloat overcolor[4] = {1, 1, 1, 1};
	glColor4fv(overcolor);
	stringstream ss;
	ss << "FPS: " << fpsdraw;
	GLUtil::drawString(10, 10, ss.str());
    }

    /* Swap */
    glutSwapBuffers();

    /* Count frames per second */
    ++fps;

    if (timeinit) {
	if (now - lastfps > 1000) {
	    lastfps = now;
	    fpsdraw = fps;
	    fps = 0;
	}
    } else {
	lastfps = now;
	timeinit = true;
    }
#endif
}

void cleanup() {
}

int initScreen() {
    bgfx::sdlSetWindow(sdlWindow);
#if 0
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_STENCIL | GLUT_MULTISAMPLE);

    glutInitWindowPosition(0,0);
    glutInitWindowSize(w,h);
    glutCreateWindow("KARR");

    glutDisplayFunc(handleDisplay);
    glutIdleFunc(glutPostRedisplay );
    glutKeyboardFunc(handleKeyboard);
#endif
    atexit(cleanup);

    return 0;
}

void registerDisplays() {
    DisplayManager &dm = DisplayManager::instance();
    dm.registerDisplay(new SimpleTextDisplay());
    dm.registerDisplay(new Celica205Display());
}

void initCommunication() {
    sArduinoConnection.open("/dev/ttyAMA0");
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);

    initScreen();

    initCommunication();

    registerDisplays();

    TestInput::run();

    glutMainLoop();
    return 0;
}
<commit_msg>Replace GLUT with SDL and add bgfx.<commit_after>/**
 * Project
 * #    #     #     ######   ######
 * #   #     # #    #     #  #     #
 * #  #     #   #   #     #  #     #
 * ###     #     #  ######   ######
 * #  #    #######  #   #    #   #
 * #   #   #     #  #    #   #    #
 * #    #  #     #  #     #  #     #
 *
 * Copyright (c) 2014, Project KARR
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 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 HOLDER 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 <stdio.h>
#include <stdlib.h>

#include <GL/glut.h>
#include <vg/openvg.h>

#include <SDL2/SDL.h>
#include <SDL2/SDL_syswm.h>

#include <bgfx.h>
#include <bgfxplatform.h>

#include <string>
#include <sstream>

#include "ArduinoDataPacket.h"
#include "Display.h"
#include "DisplayManager.h"
#include "GLUtil.h"
#include "CelicaDisplay.h"
#include "SimpleTextDisplay.h"
#include "SerialConnection.h"
#include "TestInput.h"
#include "Knight_Industries.C"

using namespace KARR;
using namespace std;

static const int w = 1024;
static const int h = 600;
static SerialConnection sArduinoConnection;

void handleKeyboard(unsigned char key, int x, int y) {
    if (key == 27)
	exit(0);
}

void handleDisplay() {
    int now;
    static bool timeinit = false;
    static int fpsdraw = -1;
    static int fps = 0;
    static int lastfps = 0;
    static ArduinoDataPacket dataPacket;

    { /* Read data from Arduino */
	if (sArduinoConnection.isOpened()) {
	    memset(&dataPacket, '\0', sizeof(ArduinoDataPacket));
	    if (sArduinoConnection.read((void *)&dataPacket, sizeof(ArduinoDataPacket))) {

		// Update data
	    }
	}
    }

    // Set view 0 default viewport.
    bgfx::setViewRect(0, 0, 0, w, h);
    // This dummy draw call is here to make sure that view 0 is cleared
    // if no other draw calls are submitted to view 0.
    bgfx::submit(0);
    // Use debug font to print information about this example.
    bgfx::dbgTextClear();
    bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/00-helloworld");
    bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Initialization and debug text.");
    // Advance to next frame. Rendering thread will be kicked to
    // process submitted rendering primitives.
	bgfx::frame();
#if 0
    /* Get interval from last redraw */
    now = glutGet(GLUT_ELAPSED_TIME);

    glClearColor(0.0f, 0.0f, 0.0f, 1.0f );
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    vgClear(0,0,w,h);

    /* Draw scene */
    const Display *currentDisplay = DisplayManager::instance().getCurrent();
    if (currentDisplay)
	const_cast<Display *>(currentDisplay)->draw(/*interval*/);
    else
    {
	vgSeti(VG_MATRIX_MODE, VG_MATRIX_IMAGE_USER_TO_SURFACE);
	vgLoadIdentity();
	vgScale(1, -1); // Flip the picture
	vgTranslate(w / 2 - knight_industries.width / 2, -433); // Move to to the center
	vgDrawImage(knightIndustries);
    }

    if (fpsdraw > -1) {
	/* Draw fps */
	GLfloat overcolor[4] = {1, 1, 1, 1};
	glColor4fv(overcolor);
	stringstream ss;
	ss << "FPS: " << fpsdraw;
	GLUtil::drawString(10, 10, ss.str());
    }

    /* Swap */
    glutSwapBuffers();

    /* Count frames per second */
    ++fps;

    if (timeinit) {
	if (now - lastfps > 1000) {
	    lastfps = now;
	    fpsdraw = fps;
	    fps = 0;
	}
    } else {
	lastfps = now;
	timeinit = true;
    }
#endif
}

void cleanup() {
    // Shutdown bgfx.
    bgfx::shutdown();
}

int initScreen() {
    SDL_InitSubSystem(SDL_INIT_VIDEO);

    auto sdlWindow = SDL_CreateWindow("karr"
	    , SDL_WINDOWPOS_UNDEFINED
	    , SDL_WINDOWPOS_UNDEFINED
	    , w
	    , h
	    , SDL_WINDOW_SHOWN
	    );

    bgfx::sdlSetWindow(sdlWindow);
#if 0
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_STENCIL | GLUT_MULTISAMPLE);
    glutInitWindowPosition(0,0);
    glutInitWindowSize(w,h);
    glutCreateWindow("KARR");

    glutDisplayFunc(handleDisplay);
    glutIdleFunc(glutPostRedisplay );
    glutKeyboardFunc(handleKeyboard);
#endif
    atexit(cleanup);

    bgfx::init();
    bgfx::reset(w, h, BGFX_RESET_VSYNC);

    // Set view 0 clear state.
    bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH,
	    0x303030ff, 1.0f, 0);
    return 0;
}

void registerDisplays() {
    DisplayManager &dm = DisplayManager::instance();
    dm.registerDisplay(new SimpleTextDisplay());
    dm.registerDisplay(new Celica205Display());
}

void initCommunication() {
    sArduinoConnection.open("/dev/ttyAMA0");
}

int main(int argc, char** argv) {
    SDL_Init(0);

    initScreen();

    initCommunication();

    registerDisplays();

    TestInput::run();

    do {

	SDL_Event event;
	if (SDL_PollEvent(&event)) {
	    // Do something with event
	}
	handleDisplay();
    } while (1);
    glutMainLoop();
    return 0;
}
<|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.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;
}
<commit_msg>bumping the version numbers in /trunk, now that 4.4 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.55";

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>#include <cstdlib>
#include "mseq.hpp"
#include "state.hpp"
#include "automata.hpp"

typedef
    Automata<>

    ::create_state<0>::type
    ::create_state<1, true>::type

    ::set_start_state<0>::type

    ::create_edge<0, 1, 'a'>::type
    ::create_edge<1, 1, 'a'>::type
    ::create_edge<1, 0, ','>::type

    automata;

typedef
    automata::get_state<1>::type
    state1;

template <typename T>
void print_type() {
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}

int main() {

    //if (automata::match("aa,a")::value) {
    //    std::cout << "matched" << std::endl;
    //}

    print_type<automata>();
    print_type<automata::get_edges_for<1>::type>();
    //print_type<state1>();

    return 0;
}
<commit_msg>Update examples<commit_after>#include <cstdlib>
#include "mseq.hpp"
#include "state.hpp"
#include "automata.hpp"
#include "mstring.hpp"

typedef
    Automata<>

    ::create_state<0>::type
    ::create_state<1, true>::type

    ::set_start_state<0>::type

    ::create_edge<0, 1, 'a'>::type
    ::create_edge<1, 1, 'a'>::type
    ::create_edge<1, 0, ','>::type

    automata;

typedef
    automata::get_state<1>::type
    state1;

template <typename T>
void print_type() {
    std::cout << __PRETTY_FUNCTION__ << std::endl;
}

int main() {

    //if (automata::match("aa,a")::value) {
    //    std::cout << "matched" << std::endl;
    //}

    //print_type<automata>();
    //print_type<automata::get_edges_for<1>::type>();
    //print_type<state1>();

    //print_type<automata::get_next_state<'b'>::type>();

    //automata::match<salut, 0>::value;
    if (automata::match<mstring("aaaaaa,a")>::value) {
        std::cout << "matched" << std::endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
//
// Arion
//
// Extract metadata and create beautiful thumbnails of your images.
//
// ------------
//   main.cpp
// ------------
//
// Copyright (c) 2015 Paul Filitchkin, Snapwire
//
// 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 the organization 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 HOLDER 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.
//
//------------------------------------------------------------------------------

// Local
#include "models/operation.hpp"
#include "models/resize.hpp"
#include "models/read_meta.hpp"
#include "utils/utils.hpp"
#include "arion.hpp"

// Boost
#include <boost/exception/info.hpp>
#include <boost/exception/error_info.hpp>
#include <boost/exception/all.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include <boost/lexical_cast.hpp>

// Stdlib
#include <iostream>
#include <string>

using namespace boost::program_options;
using namespace std;

#define ARION_VERSION "0.2.0-beta1"

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void showHelp(options_description& desc)
{
  cerr << desc << endl;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
  try
  {
    positional_options_description p;
    p.add("input", 1);

    string description = "Arion v";
    description += ARION_VERSION;
    description += "\n\n Arguments";

    options_description desc(description);

    desc.add_options()
        ("help", "Produce this help message")
        ("version", "Print version")
        ("input", value< string >(), "The input operations to execute in JSON");

    variables_map vm;

    store(command_line_parser(argc, argv).options(desc).positional(p).run(), vm);

    notify(vm);

    string inputJson;

    if (vm.count("help"))
    {
      showHelp(desc);
      return 1;
    }

    if (vm.count("version"))
    {
      cout << "{\"version\":\"" << ARION_VERSION << "\"}" << endl;
      return 0;
    }

    if (vm.count("input"))
    {
      inputJson = vm["input"].as<string>();
    }
    else
    {
      cout << "You must provide the input operations to execute" << endl << endl;
      showHelp(desc);
      return 1;
    }

    Arion arion;

    if (!arion.setup(inputJson))
    {
      cout << arion.getJson();
      exit(-1);
    }

    bool result = arion.run();

    cout << arion.getJson();

    if (result)
    {
      exit(0);
    }
    else
    {
      exit(-1);
    }
  }
  catch (std::exception& e)
  {
    Utils::exitWithError(e.what());
  }

  return 0;
}
<commit_msg>bump version<commit_after>//------------------------------------------------------------------------------
//
// Arion
//
// Extract metadata and create beautiful thumbnails of your images.
//
// ------------
//   main.cpp
// ------------
//
// Copyright (c) 2015 Paul Filitchkin, Snapwire
//
// 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 the organization 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 HOLDER 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.
//
//------------------------------------------------------------------------------

// Local
#include "models/operation.hpp"
#include "models/resize.hpp"
#include "models/read_meta.hpp"
#include "utils/utils.hpp"
#include "arion.hpp"

// Boost
#include <boost/exception/info.hpp>
#include <boost/exception/error_info.hpp>
#include <boost/exception/all.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include <boost/lexical_cast.hpp>

// Stdlib
#include <iostream>
#include <string>

using namespace boost::program_options;
using namespace std;

#define ARION_VERSION "0.2.0-beta2"

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void showHelp(options_description& desc)
{
  cerr << desc << endl;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
  try
  {
    positional_options_description p;
    p.add("input", 1);

    string description = "Arion v";
    description += ARION_VERSION;
    description += "\n\n Arguments";

    options_description desc(description);

    desc.add_options()
        ("help", "Produce this help message")
        ("version", "Print version")
        ("input", value< string >(), "The input operations to execute in JSON");

    variables_map vm;

    store(command_line_parser(argc, argv).options(desc).positional(p).run(), vm);

    notify(vm);

    string inputJson;

    if (vm.count("help"))
    {
      showHelp(desc);
      return 1;
    }

    if (vm.count("version"))
    {
      cout << "{\"version\":\"" << ARION_VERSION << "\"}" << endl;
      return 0;
    }

    if (vm.count("input"))
    {
      inputJson = vm["input"].as<string>();
    }
    else
    {
      cout << "You must provide the input operations to execute" << endl << endl;
      showHelp(desc);
      return 1;
    }

    Arion arion;

    if (!arion.setup(inputJson))
    {
      cout << arion.getJson();
      exit(-1);
    }

    bool result = arion.run();

    cout << arion.getJson();

    if (result)
    {
      exit(0);
    }
    else
    {
      exit(-1);
    }
  }
  catch (std::exception& e)
  {
    Utils::exitWithError(e.what());
  }

  return 0;
}
<|endoftext|>


<commit_before>/*
    гаммирование - в нашем случае сложение по модулю 2 (xor)
*/
#include <QCoreApplication>
#include <QString>
#include <iostream>
#include <fstream>
#include <QDebug>
#include <unistd.h>
#include <algorithm>
#include <qalgorithms.h>
#include <string>
#include <stdio.h>
#include <sys/stat.h>

#define SUCCESS 0
#define FAILURE 1

using namespace std;
static char *path_key;
static char *path_text;
static char *path_encr;

static const QString get_keys(ifstream &file);
static const QString get_text(ifstream &file);
static const QString get_encr_text(const QString key,
                                   const QString clear_text);
static void clear_space(QString &text);

static int menu(int argc, char **argv);
static QString get_encr(ifstream &file);

int main(int argc, char *argv[]){
    cout << "\tNice to meet you! Let\'s start!" << endl;

    path_key = (char*)calloc(MAX_INPUT, sizeof(char*));
    path_text = (char*)calloc(MAX_INPUT, sizeof(char*));

    // Get path to files
    if( menu(argc, argv) != 0 )
        return -FAILURE;

    ifstream key_file(path_key);
    if( !key_file.is_open()){
        fprintf(stderr, "Can't open file with"
                        " options: %s\r\n", strerror(errno));
        return -FAILURE;
    }

    ifstream plain_file(path_text);
    if( !plain_file.is_open()){
        fprintf(stderr, "Can't open file with"
                        " options: %s\r\n", strerror(errno));
        return -FAILURE;
    }

    const QString key_str = get_keys(key_file);
    const QString plain_str = get_text(plain_file);
    bool flag;
    printf("%x | %x\n", key_str.at(0), plain_str.at(0));

    printf("%x | %s\n", key_str.toStdWString().at(0) ^ plain_str.toStdWString().at(0),
           key_str.toStdWString().at(0) ^ plain_str.toStdWString().at(0));
    //printf("%x | %s\n", key_str.toUInt( ^ plain_str.at(0),
      //                  key_str.at(0) ^ plain_str.at(0));

    return SUCCESS;
}

/**
 * @brief menu - Parse input arguments on keys and path to file;
 * @param argc - Count of input arguments;
 * @param argv - Input arguments;
 * @return SUCCESS - If all arguments is normal;
 *         FAILURE - If was error;
 */
static int menu(int argc, char **argv){
    string help = "\tYou must to use:\n"
                  "-k\t- file which contains key;\n"
                  "-t\t- file which contains plain text;\n"
                  "-h\t- this help view;\n";
    if( ( argc != 5 ) ){
        if( !strcmp(argv[1], "-h") ){
            cout << help << endl;
            return -FAILURE;
        }
        cout << "\tYou doing something wrong!" << endl;
        cout << help << endl;
        return -FAILURE;
    }

    int opt;
    while( (opt = getopt(argc, argv, "k:t:h:")) != -1 ){
        switch(opt){
        case 'k':
            cout << "\tYour key file will be: ";
            strcpy(path_key, optarg);
            cout << path_key << endl;
            break;
        case 't':
            cout << "\tYour encrypted file will be: ";
            strcpy(path_text, optarg);
            cout << path_text << endl;
            break;
        case 'h':
            cout << help << endl;
            return -FAILURE;
        default:
            cout << "\tYou wroooong! Why?" << endl;
            cout << help << endl;
            return -FAILURE;
        }
    }

    return SUCCESS;
}

/**
 * @brief get_key - return key words or phrase for encryption, length of alphabet
 * @param file    - file which contains key words
 * @return s_key_words - if all was successfully, string of key phrase;
 *         NULL        - if was error;
 */
static const QString get_keys(ifstream &file){
    struct stat info_file;
    stat(path_key, &info_file);  // get size of file

    if( info_file.st_size <= 0 ){
        printf("Why your %s is empty? (^o^)\r\n", path_key);
        return NULL;
    }

    char *key_words = (char*)calloc(info_file.st_size, sizeof(char*));
    if( key_words == NULL ){
        printf("Couldn't allocate memory for key words. Sorry (X_X)\r\n");
        return NULL;
    }

    file.read(key_words, info_file.st_size);
    if( !file ) {
        printf("Couldn't read file with keys. Sorry (*-*)\r\n");
        return NULL;
    }

    QString s_key_words(key_words);
    clear_space(s_key_words);

    free(key_words);

    return s_key_words;
}

/**
 * @brief get_text - return string of text for encryption
 * @param file     - file which contains not encrypted text
 * @return s_text - if all was successfully, string of not encrypted text for encryption;
 *         NULL        - if was error;
 */
static const QString get_text(ifstream &file){
    struct stat info_file;
    stat(path_text, &info_file);

    if( info_file.st_size <= 0 ){   // Check size of file
        printf("Why your %s is empty? (^o^)\r\n", path_text);
        return NULL;
    }

    char *text = (char*) calloc(info_file.st_size, sizeof(char*));
    if( text == NULL ){     // If we can't allocate memory
        printf("Couldn't allocate memory for plaintext. Sorry (X_X)\r\n");
        return NULL;
    }

    file.seekg(0, ios_base::beg);           // Set cursor to start of file
    file.read(text, info_file.st_size);
    if( !file ){
        printf("Couldn't read file with plaintext. Sorry (*-*)\r\n");
        return NULL;
    }

    QString s_text(text);
    clear_space(s_text);

    free(text);
    return s_text;
}

/**
 * @brief get_encr_text - Encrypts the plaintext;
 * @param colm_alph     - column of alphabet (actually, it is just row of alphabet);
 * @param key           - Key for encryption;
 * @param clear_text    -
 * @return encr_text    - if all was successfully, string of encrypted text;
 *         NULL         - if was error;
 */
static const QString get_encr_text(const QString key, const QString clear_text){
    QString encr_text;

    for( auto iter_text = clear_text.begin(); iter_text != clear_text.end();
        iter_text++ ){
        //encr_text.push_back();
    }

/*
    int incr_alph, incr_key, incr_text;
    int pos = 0;
    QString::const_iterator iter_key = key.begin();
    for( QString::const_iterator iter_txt = clear_text.begin(); iter_txt != clear_text.end();
                                       iter_txt++, iter_key++, pos++ ) {
        if( iter_key == key.end() )
            iter_key = key.begin();

        incr_alph = colm_alph.indexOf(*iter_txt);
        if( incr_alph < 0 ){
            encr_text.append(*iter_txt);
            iter_key--;
            continue;
        }

kek:
        incr_key = colm_alph.indexOf(*iter_key);
        if( incr_key < 0 ){
            iter_key++;
            if( iter_key == key.end() )
                iter_key = key.begin();
            goto kek;
        }

        incr_text = incr_alph + incr_key;

        if( incr_text >= alph_length )
            incr_text = abs(incr_text - alph_length);

        encr_text.append(colm_alph.at(incr_text));
    }
*/
    return encr_text;
}

static void clear_space(QString &text){
   text = text.toLower();
   int pos = 0;
   while( text.contains(' ') || text.contains('\n') ) {
       pos = text.indexOf(' ');
       if( pos != -1 )
           text.remove(pos, 1);
       pos = text.indexOf('\n');
       if( pos != -1 )
           text.remove(pos, 1);
   }
}
<commit_msg>Encryption with XOR<commit_after>/*
    гаммирование - в нашем случае сложение по модулю 2 (xor)
*/
#include <QCoreApplication>
#include <QString>
#include <iostream>
#include <fstream>
#include <QDebug>
#include <unistd.h>
#include <algorithm>
#include <qalgorithms.h>
#include <string>
#include <stdio.h>
#include <sys/stat.h>

#define SUCCESS 0
#define FAILURE 1

using namespace std;
static char *path_key;
static char *path_text;
static char *path_encr;

/*************** PROTOTYPES ****************/
static const QString get_keys(ifstream &file);
static const QString get_text(ifstream &file);
static const QString get_encr_text(const QString key,
                                   const QString clear_text);
static void clear_space(QString &text);
static int menu(int argc, char **argv);
/******************************************/

int main(int argc, char *argv[]){
    cout << "\tNice to meet you! Let\'s start!" << endl;

    path_key = (char*)calloc(MAX_INPUT, sizeof(char*));
    path_text = (char*)calloc(MAX_INPUT, sizeof(char*));
    path_encr = (char*)calloc(MAX_INPUT, sizeof(char*));

    // Get path to files
    if( menu(argc, argv) != 0 )
        return -FAILURE;

    ifstream key_file(path_key);
    if( !key_file.is_open() ){
        fprintf(stderr, "Can't open file with"
                        " options: %s\r\n", strerror(errno));
        return -FAILURE;
    }

    ifstream plain_file(path_text);
    if( !plain_file.is_open() ){
        fprintf(stderr, "Can't open file with"
                        " options: %s\r\n", strerror(errno));
        return -FAILURE;
    }

    const QString key_str = get_keys(key_file);
    const QString plain_str = get_text(plain_file);
    const QString encr_str = get_encr_text(key_str, plain_str);

    cout << "Your key:\t\t" << key_str.toStdString() << endl;
    cout << "Your plain text:\t" << plain_str.toStdString() << endl;
    cout << "Your encr text:\t\t" << encr_str.toStdString() << endl;

    if( path_encr[0] == NULL )
        strcpy(path_encr, "encr.txt");
    ofstream encr_file(path_encr, ios_base::out | ios_base::trunc);
    if( !encr_file.is_open() ){
        fprintf(stderr, "Can't open file with"
                        " options: %s\r\n", strerror(errno));
        key_file.close();
        plain_file.close();

        return -FAILURE;

    }

    encr_file.write(encr_str.toUtf8(), encr_str.toUtf8().length());

    key_file.close();
    plain_file.close();
    encr_file.close();

    free(path_key);
    free(path_text);
    free(path_encr);

    return SUCCESS;
}

/**
 * @brief menu - Parse input arguments on keys and path to file;
 * @param argc - Count of input arguments;
 * @param argv - Input arguments;
 * @return SUCCESS - If all arguments is normal;
 *         FAILURE - If was error;
 */
static int menu(int argc, char **argv){
    string help = "\tYou must to use:\n"
                  "-k\t- file which contains key;\n"
                  "-t\t- file which contains plain text;\n"
                  "-e\t- file where will be contains encrypted text;\n"
                  "-h\t- this help view;\n";
    if( ( argc < 5 ) || ( argc > 7 ) ){
        cout << "\tYou doing something wrong!" << endl;
        cout << help << endl;
        return -FAILURE;
    }

    int opt;
    while( (opt = getopt(argc, argv, "k:t:e:h:")) != -1 ){
        switch(opt){
        case 'k':
            cout << "\tYour key file will be: ";
            strcpy(path_key, optarg);
            cout << path_key << endl;
            break;
        case 't':
            cout << "\tYour plaintext file will be: ";
            strcpy(path_text, optarg);
            cout << path_text << endl;
            break;
        case 'e':
            cout << "\tYour encrypted file will be: ";
            strcpy(path_encr, optarg);
            cout << path_encr << endl;
            break;
        case 'h':
            cout << help << endl;
            return -FAILURE;
        default:
            cout << "\tYou wroooong! Why?" << endl;
            cout << help << endl;
            return -FAILURE;
        }
    }

    return SUCCESS;
}

/**
 * @brief get_key - return key words or phrase for encryption, length of alphabet
 * @param file    - file which contains key words
 * @return s_key_words - if all was successfully, string of key phrase;
 *         NULL        - if was error;
 */
static const QString get_keys(ifstream &file){
    struct stat info_file;
    stat(path_key, &info_file);  // get size of file

    if( info_file.st_size <= 0 ){
        printf("Why your %s is empty? (^o^)\r\n", path_key);
        return NULL;
    }

    char *key_words = (char*)calloc(info_file.st_size, sizeof(char*));
    if( key_words == NULL ){
        printf("Couldn't allocate memory for key words. Sorry (X_X)\r\n");
        return NULL;
    }

    file.read(key_words, info_file.st_size);
    if( !file ) {
        printf("Couldn't read file with keys. Sorry (*-*)\r\n");
        return NULL;
    }

    QString s_key_words(key_words);
    clear_space(s_key_words);

    free(key_words);

    return s_key_words;
}

/**
 * @brief get_text - return string of text for encryption
 * @param file     - file which contains not encrypted text
 * @return s_text - if all was successfully, string of not encrypted text for encryption;
 *         NULL        - if was error;
 */
static const QString get_text(ifstream &file){
    struct stat info_file;
    stat(path_text, &info_file);

    if( info_file.st_size <= 0 ){   // Check size of file
        printf("Why your %s is empty? (^o^)\r\n", path_text);
        return NULL;
    }

    char *text = (char*) calloc(info_file.st_size, sizeof(char*));
    if( text == NULL ){     // If we can't allocate memory
        printf("Couldn't allocate memory for plaintext. Sorry (X_X)\r\n");
        return NULL;
    }

    file.seekg(0, ios_base::beg);           // Set cursor to start of file
    file.read(text, info_file.st_size);
    if( !file ){
        printf("Couldn't read file with plaintext. Sorry (*-*)\r\n");
        return NULL;
    }

    QString s_text(text);
    clear_space(s_text);

    free(text);
    return s_text;
}

/**
 * @brief get_encr_text - Encrypts the plaintext;
 * @param colm_alph     - column of alphabet (actually, it is just row of alphabet);
 * @param key           - Key for encryption;
 * @param clear_text    -
 * @return encr_text    - if all was successfully, string of encrypted text;
 *         NULL         - if was error;
 */
static const QString get_encr_text(const QString key, const QString clear_text){
    QString encr_text;
    uint16_t hex_key;
    uint16_t hex_pln;
    uint16_t hex_enc;

    for( auto iter_text = clear_text.begin(), iter_key = key.begin();
            iter_text != clear_text.end();
                iter_text++, iter_key++ ){
        if( iter_key == key.end())
            iter_key = key.begin();
        hex_key = iter_key->unicode();
        hex_pln = iter_text->unicode();
        hex_enc = hex_key ^ hex_pln;

        encr_text.push_back(hex_enc);
    }

/*
    int incr_alph, incr_key, incr_text;
    int pos = 0;
    QString::const_iterator iter_key = key.begin();
    for( QString::const_iterator iter_txt = clear_text.begin(); iter_txt != clear_text.end();
                                       iter_txt++, iter_key++, pos++ ) {
        if( iter_key == key.end() )
            iter_key = key.begin();

        incr_alph = colm_alph.indexOf(*iter_txt);
        if( incr_alph < 0 ){
            encr_text.append(*iter_txt);
            iter_key--;
            continue;
        }

kek:
        incr_key = colm_alph.indexOf(*iter_key);
        if( incr_key < 0 ){
            iter_key++;
            if( iter_key == key.end() )
                iter_key = key.begin();
            goto kek;
        }

        incr_text = incr_alph + incr_key;

        if( incr_text >= alph_length )
            incr_text = abs(incr_text - alph_length);

        encr_text.append(colm_alph.at(incr_text));
    }
*/
    return encr_text;
}

static void clear_space(QString &text){
   text = text.toLower();
   int pos = 0;
   while( text.contains(' ') || text.contains('\n') ) {
       pos = text.indexOf(' ');
       if( pos != -1 )
           text.remove(pos, 1);
       pos = text.indexOf('\n');
       if( pos != -1 )
           text.remove(pos, 1);
   }
}
<|endoftext|>


<commit_before>/*
 * Deck.cpp
 *
 *  Created on: 11.01.2017
 *      Author: Stefan
 */

#include <memory>
#include <random>
#include "Deck.h"
#include "Card.h"
#include "GlobalDeclarations.h"

void Deck::AddSets(std::size_t N)
{
	for(std::size_t i = 0; i < N; ++i)
	{
		AddCompleteSet();
	}
}

Deck::pCard Deck::Draw()
{
	// Random generator, copied from http://stackoverflow.com/questions/5008804/generating-random-integer-from-a-range
	std::mt19937 rng(_rd());    // random-number engine used (Mersenne-Twister in this case)
	std::uniform_int_distribution<int> uniformDist(0, Base::NumCards()-1); // guaranteed unbiased
	auto random_integer = uniformDist(rng);
	return Base::RemoveCard(random_integer);
}

void Deck::PrintNumCards() const
{
	std::cout << "Cards in Deck = " << Base::NumCards() << std::endl;
}

void Deck::AddCompleteSet()
{
	for( const auto & suit : SUIT)
	{
		for(const auto & face : FACE)
		{
			AddCard(pCard(new Card(face.first, suit)));
		}
	}
}

<commit_msg>Fix random drawing of cards<commit_after>/*
 * Deck.cpp
 *
 *  Created on: 11.01.2017
 *      Author: Stefan
 */

#include <memory>
#include <random>
#include "Deck.h"
#include "Card.h"
#include "GlobalDeclarations.h"
#include <chrono>

void Deck::AddSets(std::size_t N)
{
	for(std::size_t i = 0; i < N; ++i)
	{
		AddCompleteSet();
	}
}

Deck::pCard Deck::Draw()
{
	// Use the time for a new seed each time a card is darwn
	unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
	std::default_random_engine rng(seed);
	std::uniform_int_distribution<int> uniformDist(0, Base::NumCards()-1);
	auto random_integer = uniformDist(rng);
	return Base::RemoveCard(random_integer);
}

void Deck::PrintNumCards() const
{
	std::cout << "Cards in Deck = " << Base::NumCards() << std::endl;
}

void Deck::AddCompleteSet()
{
	for( const auto & suit : SUIT)
	{
		for(const auto & face : FACE)
		{
			AddCard(pCard(new Card(face.first, suit)));
		}
	}
}

<|endoftext|>


<commit_before>// LICENSE/*{{{*/
/*
  sxc - Simple Xmpp Client
  Copyright (C) 2008 Dennis Felsing, Andreas Waidler

  Permission to use, copy, modify, and/or distribute this software for any
  purpose with or without fee is hereby granted, provided that the above
  copyright notice and this permission notice appear in all copies.

  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
/*}}}*/

// INCLUDE/*{{{*/

#include <string>
#include <iostream>
#include <signal.h>

#include <gloox/jid.h>

#include <libsxc/Option/Parser.hxx>
#include <libsxc/Option/Option.hxx>
#include <libsxc/Option/OptionPort.hxx>
#include <libsxc/Exception/Exception.hxx>
#include <libsxc/Exception/Type.hxx>
#include <libsxc/getHostName.hxx>

#include <libsxc/Signal/Waiter.hxx>
#include <libsxc/Signal/stopOn.hxx>

#include <Control/Control.hxx>

#ifdef HAVE_CONFIG_H
# include <config.hxx>
#endif

#include <libsxc/Logger.hxx>

/*}}}*/

using libsxc::Error;

/**
 * @mainpage sxc Documentation
 *
 * @section contents Contents
 * @ref desc_sec
 *
 * @section desc_sec Description
 * sxc (pronounced "sexy) is for jabber what ii (irc it / irc improved) is for
 * IRC: A minimalistic file-based jabber client which runs in the background
 * and can be controlled with basic command line tools to read from / write
 * into the files/FIFOs sxc creates.
 */

/**
 * @brief The starting point of sxc.
 *
 * Parse the parameters the program was started with and then initialize the
 * @ref Control::Control.
 */
int main(int argc, char *argv[])/*{{{*/
{
  libsxc::Option::Parser parser;
  libsxc::Option::Option<bool> defHelp(
    &parser, 'h', "help", "Show help and exit");
  libsxc::Option::Option<bool> defVersion(
    &parser, 'V', "version", "Show version and exit");
  libsxc::Option::OptionPort port(
    &parser, 'p', "port", "port", "0 - 65535, -1 for default");
  libsxc::Option::Option<std::string> name(
    &parser, ' ', "iqname", "name",
    std::string("Name to announce (default: ") + PACKAGE + ")", PACKAGE);
  libsxc::Option::Option<std::string> version(
    &parser, ' ', "iqversion", "version",
    std::string("Version to announce (default: ") + VERSION + ")", VERSION);

  const std::string defaultResource =
    std::string(PACKAGE) + "@" + libsxc::getHostName();
  libsxc::Option::Option<gloox::JID> jid(
    &parser, ' ', "", "jid",
    "user@domain[/resource] (resource default: " + defaultResource + ")");

  try {
    parser.parse(argv);
  } catch (libsxc::Exception::OptionException &e) {
    if (libsxc::Exception::ShowUsage == e.getType()) {
      std::cerr << PACKAGE << " " << VERSION << " (C) " << COPYRIGHT
            << std::endl;
    } else if (libsxc::Exception::ShowVersion == e.getType()) {
      std::cerr << VERSION << std::endl;
      return libsxc::Exception::NoError;
    } else {
      LOG<Error>(e.getDescription());
    }

    std::vector<std::string> usage = parser.getUsage();
    for(
      std::vector<std::string>::iterator it = usage.begin();
      usage.end() != it;
      ++it) {
      std::cerr << *it << std::endl;
    }

    if (e.getType() < 0) // No error. (ShowUsage, ShowVersion)
      return libsxc::Exception::NoError;
    return e.getType();
  } catch (libsxc::Exception::Exception &e) {
    LOG<Error>(e.getDescription());
    return e.getType();
  }

  gloox::JID jidJid = jid.getValue();
  if ("" == jidJid.resource())
    jidJid.setResource(defaultResource);

  Control::Control *control;
  try {
    control = new Control::Control(
      jidJid,
      port.getValue(),
      name.getValue(),
      version.getValue());
  } catch (libsxc::Exception::Exception &e) {
    LOG<Error>(e.getDescription());
    // Don't delete control, as it failed to initialize.
    return e.getType();
  }

  // Has to be created before running any thread.
  libsxc::Signal::Waiter waiter;

  libsxc::Signal::stopOn(waiter, SIGINT);
  libsxc::Signal::stopOn(waiter, SIGTERM);

  control->run(); // Starts threads.

  waiter.run(); // blocking

  delete control;
  return 0;
}/*}}}*/

// Use no tabs at all; two spaces indentation; max. eighty chars per line.
// vim: et ts=2 sw=2 sts=2 tw=80 fdm=marker
<commit_msg>Use new parse function<commit_after>// LICENSE/*{{{*/
/*
  sxc - Simple Xmpp Client
  Copyright (C) 2008 Dennis Felsing, Andreas Waidler

  Permission to use, copy, modify, and/or distribute this software for any
  purpose with or without fee is hereby granted, provided that the above
  copyright notice and this permission notice appear in all copies.

  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
/*}}}*/

// INCLUDE/*{{{*/

#include <string>
#include <iostream>
#include <signal.h>

#include <gloox/jid.h>

#include <libsxc/Option/Parser.hxx>
#include <libsxc/Option/parse.hxx>
#include <libsxc/Option/Option.hxx>
#include <libsxc/Option/OptionPort.hxx>
#include <libsxc/Exception/Exception.hxx>
#include <libsxc/Exception/Type.hxx>
#include <libsxc/getHostName.hxx>

#include <libsxc/Signal/Waiter.hxx>
#include <libsxc/Signal/stopOn.hxx>

#include <Control/Control.hxx>

#ifdef HAVE_CONFIG_H
# include <config.hxx>
#endif

#include <libsxc/Logger.hxx>

/*}}}*/

using libsxc::Error;

/**
 * @mainpage sxc Documentation
 *
 * @section contents Contents
 * @ref desc_sec
 *
 * @section desc_sec Description
 * sxc (pronounced "sexy) is for jabber what ii (irc it / irc improved) is for
 * IRC: A minimalistic file-based jabber client which runs in the background
 * and can be controlled with basic command line tools to read from / write
 * into the files/FIFOs sxc creates.
 */

/**
 * @brief The starting point of sxc.
 *
 * Parse the parameters the program was started with and then initialize the
 * @ref Control::Control.
 */
int main(int argc, char *argv[])/*{{{*/
{
  libsxc::Option::Parser parser;
  parser.setHelp(PACKAGE " " VERSION " (C) " COPYRIGHT);
  parser.setVersion(VERSION);
  libsxc::Option::Option<bool> defHelp(
    &parser, 'h', "help", "Show help and exit");
  libsxc::Option::Option<bool> defVersion(
    &parser, 'V', "version", "Show version and exit");
  libsxc::Option::OptionPort port(
    &parser, 'p', "port", "port", "0 - 65535, -1 for default");
  libsxc::Option::Option<std::string> name(
    &parser, ' ', "iqname", "name",
    std::string("Name to announce (default: ") + PACKAGE + ")", PACKAGE);
  libsxc::Option::Option<std::string> version(
    &parser, ' ', "iqversion", "version",
    std::string("Version to announce (default: ") + VERSION + ")", VERSION);

  const std::string defaultResource =
    std::string(PACKAGE) + "@" + libsxc::getHostName();
  libsxc::Option::Option<gloox::JID> jid(
    &parser, ' ', "", "jid",
    "user@domain[/resource] (resource default: " + defaultResource + ")");

  libsxc::Option::parse(parser, argv);
  // FIXME: Handle exceptions.

  gloox::JID jidJid = jid.getValue();
  if ("" == jidJid.resource())
    jidJid.setResource(defaultResource);

  Control::Control *control;
  try {
    control = new Control::Control(
      jidJid,
      port.getValue(),
      name.getValue(),
      version.getValue());
  } catch (libsxc::Exception::Exception &e) {
    LOG<Error>(e.getDescription());
    // Don't delete control, as it failed to initialize.
    return e.getType();
  }

  // Has to be created before running any thread.
  libsxc::Signal::Waiter waiter;

  libsxc::Signal::stopOn(waiter, SIGINT);
  libsxc::Signal::stopOn(waiter, SIGTERM);

  control->run(); // Starts threads.

  waiter.run(); // blocking

  delete control;
  return 0;
}/*}}}*/

// Use no tabs at all; two spaces indentation; max. eighty chars per line.
// vim: et ts=2 sw=2 sts=2 tw=80 fdm=marker
<|endoftext|>


<commit_before>
// (c) COPYRIGHT URI/MIT 1994-1996
// Please read the full copyright statement in the file COPYRIGH.
//
// Authors:
//      jhrg,jimg       James Gallagher (jgallagher@gso.uri.edu)

// Implementation for the CE Clause class.

// $Log: Error.cc,v $
// Revision 1.2  1996/06/01 00:03:38  jimg
// Added.
//

#ifdef __GNUG__
#pragma implementation
#endif

static char rcsid[]={"$Id: Error.cc,v 1.2 1996/06/01 00:03:38 jimg Exp $"};

#include <assert.h>

#include "Error.h"

Error::Error()
    : _error_code(undefined_error), _error_message(""),
      _program_type(undefined_prog_type), _program(0)
{
}

Error::Error(ErrorCode ec, String msg)
    : _error_code(ec), _error_message(msg),
      _program_type(undefined_prog_type), _program(0)
{
}

Error::Error(ErrorCode ec, String msg, ProgramType pt, char *pgm)
    : _error_code(ec), _error_message(msg),
      _program_type(pt), _program(0)
{
    _program = new char[strlen(pgm) + 1];
    strcpy(_program, pgm);
}

Error::Error(const Error &copy_from)
    : _error_code(copy_from._error_code),
      _error_message(copy_from._error_message),
      _program_type(copy_from._program_type), _program(0)
{
    _program = new char[strlen(copy_from._program) + 1];
    strcpy(_program, copy_from._program);
}

Error::~Error()
{
    delete _program;
}

Error &
Error::operator=(const Error &rhs)
{
    if (&rhs == this)		// are they identical?
	return *this;
    else {
	_error_code = rhs._error_code;
	_error_message = rhs._error_message;
	_program_type = rhs._program_type;

	_program = new char[strlen(rhs._program) + 1];
	strcpy(_program, rhs._program);

	return *this;
    }
}

// To be a valid, an Error object must either be: 1) empty, 2) contain a
// message and a program or 3) contain only a message. Since the program is
// optional, there is no need to test for it here.
//
// NB: This mfunc does not test for malformed messages or programs - ones
// where the code is defined but not the `data'.

bool
Error::OK()
{
    bool empty = ((_error_code == undefined_error)
		  && (_error_message == "")
		  && (_program_type == undefined_prog_type)
		  && (_program == 0));

    bool message = ((_error_code != undefined_error)
		    && (_error_message != ""));

    // bool program = ((_program_type != undefined_prog_type)
    //                 && (_program != 0))

    return empty || message;
}

bool
Error::parse(FILE *fp)
{
    if (!fp) {
	cerr << "Error::parse: Null input stream" << endl;
	return false;
    }

    Errorrestart(fp);

    parser_arg arg(this);

    bool status = Errorparse(&arg) == 0;

    fclose(fp);

    // need to check the arg status because the parser may have recovered
    // from an error (and thus returned true).
    return status && arg.status() && OK();
}

void
Error::print(ostream &os = cout)
{
    if (!OK()) {
	cerr << "Bad Error object" << endl;
	return;
    }

    os << "Error {" << endl;

    if (_error_code != undefined_error) {
	os << "    " << "code = " << _error_code << ";" << endl;
	os << "    " << "message = " << _error_message << ";" << endl;

	if (_program_type != undefined_prog_type) {
	    os << "    " << "program_type = " << _program_type << ";" << endl;
	    os << "    " << "program = " << _program << ";" << endl;
	}
    }

    os << "};" << endl;
}

ErrorCode
Error::error_code(ErrorCode ec = undefined_error)
{
    if (ec == undefined_error)
	return _error_code;
    else {
	_error_code = ec;
	return _error_code;
    }
}

String
Error::error_message(String msg = "")
{
    if (msg == "")
	return String(_error_message);
    else {
	_error_message = msg;
	return String (_error_message);
    }
}

// Check the DISPLAY environment variable, if defined, use X11. If not use
// stderr.
void
Error::display_message()
{
#if TCLTK
    if (getenv("DISPLAY"))
	tk_display_message(_error_message);
    else
#else
	cerr << _error_message << endl;
#endif
}

ProgramType
Error::program_type(ProgramType pt = undefined_prog_type)
{
    if (pt == undefined_prog_type)
	return _program_type;
    else {
	_program_type = pt;
	return _program_type;
    }
}

char *
Error::program(char *pgm = 0)
{
    if (pgm == 0)
	return _program;
    else {
	_program = new char[strlen(pgm) + 1];
	strcpy(_program, pgm);
	return _program;
    }
}

String
Error::correct_error()
{
    if (OK())
	display_message();

    return String("");
}
<commit_msg>Added declarations for Errorparse() and Errorrestart().<commit_after>
// (c) COPYRIGHT URI/MIT 1994-1996
// Please read the full copyright statement in the file COPYRIGH.
//
// Authors:
//      jhrg,jimg       James Gallagher (jgallagher@gso.uri.edu)

// Implementation for the CE Clause class.

// $Log: Error.cc,v $
// Revision 1.3  1996/06/03 06:26:51  jimg
// Added declarations for Errorparse() and Errorrestart().
//
// Revision 1.2  1996/06/01 00:03:38  jimg
// Added.
//

#ifdef __GNUG__
#pragma implementation
#endif

static char rcsid[]={"$Id: Error.cc,v 1.3 1996/06/03 06:26:51 jimg Exp $"};

#include <assert.h>

#include "Error.h"
#include "parser.h"

void Errorrestart(FILE *yyin);
int Errorparse(parser_arg *arg); // defined in dds.tab.c

Error::Error()
    : _error_code(undefined_error), _error_message(""),
      _program_type(undefined_prog_type), _program(0)
{
}

Error::Error(ErrorCode ec, String msg)
    : _error_code(ec), _error_message(msg),
      _program_type(undefined_prog_type), _program(0)
{
}

Error::Error(ErrorCode ec, String msg, ProgramType pt, char *pgm)
    : _error_code(ec), _error_message(msg),
      _program_type(pt), _program(0)
{
    _program = new char[strlen(pgm) + 1];
    strcpy(_program, pgm);
}

Error::Error(const Error &copy_from)
    : _error_code(copy_from._error_code),
      _error_message(copy_from._error_message),
      _program_type(copy_from._program_type), _program(0)
{
    _program = new char[strlen(copy_from._program) + 1];
    strcpy(_program, copy_from._program);
}

Error::~Error()
{
    delete _program;
}

Error &
Error::operator=(const Error &rhs)
{
    if (&rhs == this)		// are they identical?
	return *this;
    else {
	_error_code = rhs._error_code;
	_error_message = rhs._error_message;
	_program_type = rhs._program_type;

	_program = new char[strlen(rhs._program) + 1];
	strcpy(_program, rhs._program);

	return *this;
    }
}

// To be a valid, an Error object must either be: 1) empty, 2) contain a
// message and a program or 3) contain only a message. Since the program is
// optional, there is no need to test for it here.
//
// NB: This mfunc does not test for malformed messages or programs - ones
// where the code is defined but not the `data'.

bool
Error::OK()
{
    bool empty = ((_error_code == undefined_error)
		  && (_error_message == "")
		  && (_program_type == undefined_prog_type)
		  && (_program == 0));

    bool message = ((_error_code != undefined_error)
		    && (_error_message != ""));

    // bool program = ((_program_type != undefined_prog_type)
    //                 && (_program != 0))

    return empty || message;
}

bool
Error::parse(FILE *fp)
{
    if (!fp) {
	cerr << "Error::parse: Null input stream" << endl;
	return false;
    }

    Errorrestart(fp);

    parser_arg arg(this);

    bool status = Errorparse(&arg) == 0;

    fclose(fp);

    // need to check the arg status because the parser may have recovered
    // from an error (and thus returned true).
    return status && arg.status() && OK();
}

void
Error::print(ostream &os = cout)
{
    if (!OK()) {
	cerr << "Bad Error object" << endl;
	return;
    }

    os << "Error {" << endl;

    if (_error_code != undefined_error) {
	os << "    " << "code = " << _error_code << ";" << endl;
	os << "    " << "message = " << _error_message << ";" << endl;

	if (_program_type != undefined_prog_type) {
	    os << "    " << "program_type = " << _program_type << ";" << endl;
	    os << "    " << "program = " << _program << ";" << endl;
	}
    }

    os << "};" << endl;
}

ErrorCode
Error::error_code(ErrorCode ec = undefined_error)
{
    if (ec == undefined_error)
	return _error_code;
    else {
	_error_code = ec;
	return _error_code;
    }
}

String
Error::error_message(String msg = "")
{
    if (msg == "")
	return String(_error_message);
    else {
	_error_message = msg;
	return String (_error_message);
    }
}

// Check the DISPLAY environment variable, if defined, use X11. If not use
// stderr.
void
Error::display_message()
{
#if TCLTK
    if (getenv("DISPLAY"))
	tk_display_message(_error_message);
    else
#else
	cerr << _error_message << endl;
#endif
}

ProgramType
Error::program_type(ProgramType pt = undefined_prog_type)
{
    if (pt == undefined_prog_type)
	return _program_type;
    else {
	_program_type = pt;
	return _program_type;
    }
}

char *
Error::program(char *pgm = 0)
{
    if (pgm == 0)
	return _program;
    else {
	_program = new char[strlen(pgm) + 1];
	strcpy(_program, pgm);
	return _program;
    }
}

String
Error::correct_error()
{
    if (OK())
	display_message();

    return String("");
}
<|endoftext|>


<commit_before>#include "Game.hpp"

Game::Game(options o) : players(o.players), this_player_go(o.this_player_go) {
  // Generate board and start playing
  rapidjson::Document d = get_config_from_file(o.board_config);
  string board_name(d["board_name"].GetString());
  int width = d["board_width"].GetInt();
  int height = d["board_height"].GetInt();
  rapidjson::Value& mods(d["modifiers"]);
  rapidjson::Value& scores(d["scores"]);
  this->b = new Board(board_name, width, height, mods, scores);

  // Get other details (for later implementation)
  if (d.HasMember("tiles") &&
      d["tiles"].HasMember("each") &&
      d["tiles"].HasMember("total")) {
    this->tiles_each = d["tiles"]["each"].GetInt();
    this->tiles_left = d["tiles"]["total"].GetInt();
  } else {
    this->tiles_each = 7;
    this->tiles_left = 100;
  }

  // Get the wordlist and put it in memory
  this->wordlist = new unordered_set<string >();
  this->get_wordlist(o.language_file);
  if (this->wordlist->empty()) {
    print_error("Wordlist could not be loaded. File used:\t" + o.language_file);
  }

  cout << "Words available:\t" << this->words_available << endl;
  cout << "Players:\t\t" << this->players << endl;
  cout << "Your Go:\t\t" << this->this_player_go << endl;
  cout << endl;

  assert(o.players > 0 && o.this_player_go > 0 && o.this_player_go <= o.players);

  int go = 0;
  while (!this->is_end()) {
    int player_turn = go % o.players;
    if (player_turn == o.this_player_go - 1) {
      this->b->print_board();
      cout << "Your go!" << endl;
      this->player_go();
    } else {
      this->b->print_board();
      cout << "Opponent's go:\tPlayer" << (player_turn + 1) << endl;
      this->opponent_go();
    }
    go++;
  }
  this->b->print_board();
  cout << "This is the final board!" << endl;
}

rapidjson::Document get_config_from_file(string& config) {
  ifstream config_file(config);

  // get length of file:
  config_file.seekg (0, config_file.end);
  int length = config_file.tellg();
  config_file.seekg (0, config_file.beg);
  char* config_file_raw = new char[length];

  config_file.read(config_file_raw, length);

  rapidjson::Document d;
  d.Parse(config_file_raw);

  return d;
}

bool Game::is_end(void) {
  return this->tiles_left == 0;
}

void Game::opponent_go(void) {
  while (true) {
    string input;

    // For putting on the Board
    string word;
    int x, y;
    Direction d;

    while (true) {
      string word_regex("[A-Za-z]{0,");
      word_regex.append(to_string(this->tiles_each));
      word_regex.append("}");
      regex validator(word_regex);

      // Get the word
      cout << "Please enter the word (if you type more than 1 word, the second will be ignored):\t";
      cin >> input;

      if (input.compare("") == 0) {
        cout << "The opponent passed!" << endl;
        return;
      }

      if (regex_match(input, validator) && valid_word_for_game(input)) {
        word = input;
        break;
      }

      cout << "The word you entered was invalid. Please try again." << endl;
    }

    while (true) {
      regex y_("^[A-Za-z]$");

      // Get the position
      cout << "Please enter the position on the board (e.g. 1 A):\t";
      cin >> input;
      try {
        x = stoi(input);
        if (x <= 0 || x > this->b->get_width()) {
          throw invalid_argument("X not in range");
        }
        x -= 1; // Convert from user to program
      } catch (invalid_argument e) {
        cout << "The value " << input << " is not in the range {1,"
             << this->b->get_width() << "}."<< endl;
        continue;
      }

      cin >> input;
      cout << input << endl;
      if (!regex_match(input, y_)) {
        continue;
      }
      y = (int) toupper(input[0]) - 'A';

      if (this->b->valid_position(x, y)) {
        break;
      }
    }

    while (true) {
      // Get the word
      cout << "Please enter the direction (NORTH|EAST|SOUTH|WEST):\t";
      cin >> input;
      cin.clear();
      cin.ignore(INT_MAX, '\n');

      for (auto& c : input) {
        c = toupper(c);
      }

      if (input.compare("NORTH") == 0) {
        d = NORTH; break;
      } else if (input.compare("EAST") == 0) {
        d = EAST; break;
      } else if (input.compare("SOUTH") == 0) {
        d = SOUTH; break;
      } else if (input.compare("WEST") == 0) {
        d = WEST; break;
      }

      cout << "Incorrect direction. Please try again!" << endl;
    }

    if (can_put_word_on_board(word, x, y, d)) {
      this->b->set_word(word, x, y, d);
      break;
    }

    cout << "Incorrect parameters specified. Please try again!" << endl;
  }
}

void Game::player_go(void) {
  while (true) {
    string input_; // Dummy variable
    vector<char > input;

    // For putting on the Board
    int tiles_available = 0;
    // string word;
    // int x, y;
    // Direction d;

    // Get the number of tiles
    while (true) {
      cout << "How many tiles do you have left? (Between 0 and "
           << to_string(this->tiles_each) << ")\t";
      cin >> input_;
      try {
        tiles_available = stoi(input_);
        if (tiles_available > 0 && tiles_available <= this->tiles_each) {
          break;
        }
      } catch (invalid_argument e) {
        continue;
      }
    }

    // Get the tiles
    cout << "Please enter the tiles you have left, separated by a space:\t";
    char c;
    for (int i = 0; i < tiles_available; i++) {
      cin >> c;
      input.push_back(toupper(c));
    }
    cin.clear();
    cin.ignore(INT_MAX, '\n');
    break;
  }
}

// Checks the string against the dictionary
bool Game::valid_word_for_game(string& input) {
  // Make input UPPERCASE
  for (char& c : input) { c = toupper(c); }

  // Checks for whitespace and non-alphas
  regex e("^[A-Z]*$");
  if (!regex_match(input, e)) { return false; }

  // Checks for word in dictionary
  auto it = this->wordlist->find(input);
  return it == this->wordlist->end();
}

// Assumes that string input is a valid word.
bool Game::can_put_word_on_board(string& word, int& w, int& h, Direction& d) {
  return true;
}

void Game::get_wordlist(string& filename) {
  ifstream file(filename);
  string word;
  regex e("^[A-Za-z]*$");

  while (!file.eof()) {
    getline(file, word);

    // Remove \r and \n from word
    int index, last_r, last_n;
    last_r = word.find_last_of('\r');
    if (last_r < 0) { last_r = INT_MAX; }
    last_n = word.find_last_of('\n');
    if (last_n < 0) { last_n = INT_MAX; }

    index = (last_r < last_n) ? last_r : last_n;
    if ((size_t) index > word.size()) { index = word.size(); }

    word = word.substr(0, index);

    if (regex_match(word, e)) {
      this->wordlist->insert(word);
    }
  }

  this->words_available = this->wordlist->size();
}
<commit_msg>Tidy up<commit_after>#include "Game.hpp"

Game::Game(options o) : players(o.players), this_player_go(o.this_player_go) {
  // Generate board and start playing
  rapidjson::Document d = get_config_from_file(o.board_config);
  string board_name(d["board_name"].GetString());
  int width = d["board_width"].GetInt();
  int height = d["board_height"].GetInt();
  rapidjson::Value& mods(d["modifiers"]);
  rapidjson::Value& scores(d["scores"]);
  this->b = new Board(board_name, width, height, mods, scores);

  // Get other details (for later implementation)
  if (d.HasMember("tiles") &&
      d["tiles"].HasMember("each") &&
      d["tiles"].HasMember("total")) {
    this->tiles_each = d["tiles"]["each"].GetInt();
    this->tiles_left = d["tiles"]["total"].GetInt();
  } else {
    this->tiles_each = 7;
    this->tiles_left = 100;
  }

  // Get the wordlist and put it in memory
  this->wordlist = new unordered_set<string >();
  this->get_wordlist(o.language_file);
  if (this->wordlist->empty()) {
    print_error("Wordlist could not be loaded. File used:\t" + o.language_file);
  }

  cout << "Words available:\t" << this->words_available << endl;
  cout << "Players:\t\t" << this->players << endl;
  cout << "Your Go:\t\t" << this->this_player_go << endl;
  cout << endl;

  assert(o.players > 0 && o.this_player_go > 0 && o.this_player_go <= o.players);

  int go = 0;
  while (!this->is_end()) {
    int player_turn = go % o.players;
    if (player_turn == o.this_player_go - 1) {
      this->b->print_board();
      cout << "Your go!" << endl;
      this->player_go();
    } else {
      this->b->print_board();
      cout << "Opponent's go:\tPlayer" << (player_turn + 1) << endl;
      this->opponent_go();
    }
    go++;
  }
  this->b->print_board();
  cout << "This is the final board!" << endl;
}

rapidjson::Document get_config_from_file(string& config) {
  ifstream config_file(config);

  // get length of file:
  config_file.seekg (0, config_file.end);
  int length = config_file.tellg();
  config_file.seekg (0, config_file.beg);
  char* config_file_raw = new char[length];

  config_file.read(config_file_raw, length);

  rapidjson::Document d;
  d.Parse(config_file_raw);

  return d;
}

bool Game::is_end(void) {
  return this->tiles_left == 0;
}

void Game::opponent_go(void) {
  while (true) {
    string input;

    // For putting on the Board
    string word;
    int x, y;
    Direction d;

    while (true) {
      string word_regex("[A-Za-z]{0,");
      word_regex.append(to_string(this->tiles_each));
      word_regex.append("}");
      regex validator(word_regex);

      // Get the word
      cout << "Please enter the word (if you type more than 1 word, the second will be ignored):\t";
      cin >> input;

      if (input.compare("") == 0) {
        cout << "The opponent passed!" << endl;
        return;
      }

      if (regex_match(input, validator) && valid_word_for_game(input)) {
        word = input;
        break;
      }

      cout << "The word you entered was invalid. Please try again." << endl;
    }

    while (true) {
      regex y_("^[A-Za-z]$");

      // Get the position
      cout << "Please enter the position on the board (e.g. 1 A):\t";
      cin >> input;
      try {
        x = stoi(input);
        if (x <= 0 || x > this->b->get_width()) {
          throw invalid_argument("X not in range");
        }
        x -= 1; // Convert from user to program
      } catch (invalid_argument e) {
        cout << "The value " << input << " is not in the range {1,"
             << this->b->get_width() << "}."<< endl;
        continue;
      }

      cin >> input;
      cout << input << endl;
      if (!regex_match(input, y_)) {
        continue;
      }
      y = (int) toupper(input[0]) - 'A';

      if (this->b->valid_position(x, y)) {
        break;
      }
    }

    while (true) {
      // Get the word
      cout << "Please enter the direction ( NORTH | EAST | SOUTH | WEST ):\t";
      cin >> input;
      for (auto& c : input) { c = toupper(c); }

      if (input.compare("NORTH") == 0) {
        d = NORTH; break;
      } else if (input.compare("EAST") == 0) {
        d = EAST; break;
      } else if (input.compare("SOUTH") == 0) {
        d = SOUTH; break;
      } else if (input.compare("WEST") == 0) {
        d = WEST; break;
      }

      cout << "Incorrect direction. Please try again!" << endl;
    }

    if (can_put_word_on_board(word, x, y, d)) {
      this->b->set_word(word, x, y, d);
      break;
    }

    cout << "Incorrect parameters specified. Please try again!" << endl;
  }
}

void Game::player_go(void) {
  while (true) {
    string input_; // Dummy variable
    vector<char > input;

    // For putting on the Board
    int tiles_available = 0;
    // string word;
    // int x, y;
    // Direction d;

    // Get the number of tiles
    while (true) {
      cout << "How many tiles do you have left? (Between 0 and "
           << to_string(this->tiles_each) << ")\t";
      cin >> input_;
      try {
        tiles_available = stoi(input_);
        if (tiles_available > 0 && tiles_available <= this->tiles_each) {
          break;
        }
      } catch (invalid_argument e) {
        continue;
      }
    }

    // Get the tiles
    cout << "Please enter the tiles you have left, separated by a space:\t";
    char c;
    for (int i = 0; i < tiles_available; i++) {
      cin >> c;
      input.push_back(toupper(c));
    }
    cin.clear();
    cin.ignore(INT_MAX, '\n');
    break;
  }
}

// Checks the string against the dictionary
bool Game::valid_word_for_game(string& input) {
  // Make input UPPERCASE
  for (char& c : input) { c = toupper(c); }

  // Checks for whitespace and non-alphas
  regex e("^[A-Z]*$");
  if (!regex_match(input, e)) { return false; }

  // Checks for word in dictionary
  auto it = this->wordlist->find(input);
  return it == this->wordlist->end();
}

// Assumes that string input is a valid word.
bool Game::can_put_word_on_board(string& word, int& w, int& h, Direction& d) {
  return true;
}

void Game::get_wordlist(string& filename) {
  ifstream file(filename);
  string word;
  regex e("^[A-Za-z]*$");

  while (!file.eof()) {
    getline(file, word);

    // Remove \r and \n from word
    int index, last_r, last_n;
    last_r = word.find_last_of('\r');
    if (last_r < 0) { last_r = INT_MAX; }
    last_n = word.find_last_of('\n');
    if (last_n < 0) { last_n = INT_MAX; }

    index = (last_r < last_n) ? last_r : last_n;
    if ((size_t) index > word.size()) { index = word.size(); }

    word = word.substr(0, index);

    if (regex_match(word, e)) {
      this->wordlist->insert(word);
    }
  }

  this->words_available = this->wordlist->size();
}
<|endoftext|>