<commit_before>#include <cstdlib>

#include <fstream>
#include <memory>

#include <boost/program_options.hpp>

#include "UI/ui_factory.hpp"
#include "player_factory.hpp"
#include "exception.hpp"
#include "logger.hpp"

#include "state/main_menu_state.hpp"
#include "state/game_state.hpp"
#include "state/state_manager.hpp"

namespace po = boost::program_options;
namespace logging = boost::log;

struct game_opts_t {
    std::string ui_type;
};

static int init(int argc, char **argv, game_opts_t *game_opts);
static void init_logging(const std::string &logfile);

int main(int argc, char **argv)
{
    game_opts_t game_opts;

    if (init(argc, argv, &game_opts) < 0) {
        return EXIT_FAILURE;
    }

    boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;
    BOOST_LOG_SEV(lg, logging::trivial::info) << "Creating "
        << game_opts.ui_type << " UI";

    Quoridor::StateManager stm;
    Quoridor::UI::UIFactory uif;

    stm.create_ui(uif, game_opts.ui_type);
    std::shared_ptr<Quoridor::IState> menu_state(new Quoridor::MainMenuState(stm.ui()));
    stm.change_state(std::shared_ptr<Quoridor::IState>(menu_state));

    stm.draw();
    while (stm.is_running()) {
        stm.handle_events();
        stm.update();
        stm.draw();
    }

    return EXIT_SUCCESS;
}

static int init(int argc, char **argv, game_opts_t *game_opts)
{
    std::string logfile;

    po::options_description options("Options");
    options.add_options()
    (
        "ui,i",
        po::value<std::string>(&game_opts->ui_type)->default_value("ncurses"),
        "user interface"
    )
    (
         "log,l",
        po::value<std::string>(&logfile)->default_value("quoridor.log"),
        "logging file"
    )
    (
         "help,h",
         "show help message"
    );
    po::variables_map vm;

    try {
        po::store(po::parse_command_line(argc, argv, options), vm);
    }
    catch (po::error &e) {
        std::cerr << e.what() << std::endl;
        return -1;
    }

    po::notify(vm);

    if (vm.count("help")) {
        std::cout << options << std::endl;
        return -1;
    }

    init_logging(logfile);

    return 0;
}

static void init_logging(const std::string &logfile)
{
    boost::log::add_file_log(
        boost::log::keywords::file_name = logfile,
        boost::log::keywords::open_mode = std::ios_base::app,
        boost::log::keywords::auto_flush = true,
        boost::log::keywords::format = (
            boost::log::expressions::stream
                << boost::log::expressions::format_date_time<
                    boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M:%S")
                << " [" << boost::log::trivial::severity << "] "
                << boost::log::expressions::smessage
        )
    );
    boost::log::add_console_log(
        std::clog,
        boost::log::keywords::format = (
            boost::log::expressions::stream
                << boost::log::expressions::format_named_scope("Scope", boost::log::keywords::format = "%n")
                << ": [" << boost::log::trivial::severity << "] "
                << boost::log::expressions::smessage
        )
    );

    boost::log::add_common_attributes();
    boost::log::core::get()->add_global_attribute("Scope",
            boost::log::attributes::named_scope());
}
<commit_msg>Remove named scope from console logger<commit_after>#include <cstdlib>

#include <fstream>
#include <memory>

#include <boost/program_options.hpp>

#include "UI/ui_factory.hpp"
#include "player_factory.hpp"
#include "exception.hpp"
#include "logger.hpp"

#include "state/main_menu_state.hpp"
#include "state/game_state.hpp"
#include "state/state_manager.hpp"

namespace po = boost::program_options;
namespace logging = boost::log;

struct game_opts_t {
    std::string ui_type;
};

static int init(int argc, char **argv, game_opts_t *game_opts);
static void init_logging(const std::string &logfile);

int main(int argc, char **argv)
{
    game_opts_t game_opts;

    if (init(argc, argv, &game_opts) < 0) {
        return EXIT_FAILURE;
    }

    boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;
    BOOST_LOG_SEV(lg, logging::trivial::info) << "Creating "
        << game_opts.ui_type << " UI";

    Quoridor::StateManager stm;
    Quoridor::UI::UIFactory uif;

    stm.create_ui(uif, game_opts.ui_type);
    std::shared_ptr<Quoridor::IState> menu_state(new Quoridor::MainMenuState(stm.ui()));
    stm.change_state(std::shared_ptr<Quoridor::IState>(menu_state));

    stm.draw();
    while (stm.is_running()) {
        stm.handle_events();
        stm.update();
        stm.draw();
    }

    return EXIT_SUCCESS;
}

static int init(int argc, char **argv, game_opts_t *game_opts)
{
    std::string logfile;

    po::options_description options("Options");
    options.add_options()
    (
        "ui,i",
        po::value<std::string>(&game_opts->ui_type)->default_value("ncurses"),
        "user interface"
    )
    (
         "log,l",
        po::value<std::string>(&logfile)->default_value("quoridor.log"),
        "logging file"
    )
    (
         "help,h",
         "show help message"
    );
    po::variables_map vm;

    try {
        po::store(po::parse_command_line(argc, argv, options), vm);
    }
    catch (po::error &e) {
        std::cerr << e.what() << std::endl;
        return -1;
    }

    po::notify(vm);

    if (vm.count("help")) {
        std::cout << options << std::endl;
        return -1;
    }

    init_logging(logfile);

    return 0;
}

static void init_logging(const std::string &logfile)
{
    boost::log::add_file_log(
        boost::log::keywords::file_name = logfile,
        boost::log::keywords::open_mode = std::ios_base::app,
        boost::log::keywords::auto_flush = true,
        boost::log::keywords::format = (
            boost::log::expressions::stream
                << boost::log::expressions::format_date_time<
                    boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M:%S")
                << " [" << boost::log::trivial::severity << "] "
                << boost::log::expressions::smessage
        )
    );
    boost::log::add_console_log(
        std::clog,
        boost::log::keywords::format = (
            boost::log::expressions::stream
                << "[" << boost::log::trivial::severity << "] "
                << boost::log::expressions::smessage
        )
    );

    boost::log::add_common_attributes();
    boost::log::core::get()->add_global_attribute("Scope",
            boost::log::attributes::named_scope());
}
<|endoftext|>


<commit_before>#include "ui/mainwindow.h"
#include <QApplication>
#include <QStyleFactory>

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  a.setStyle(QStyleFactory::create("Fusion"));

  QPalette dark;
  dark.setColor(QPalette::Window, QColor(53, 53, 53));
  dark.setColor(QPalette::WindowText, Qt::white);
  dark.setColor(QPalette::Base, QColor(25, 25, 25));
  dark.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
  dark.setColor(QPalette::ToolTipBase, Qt::white);
  dark.setColor(QPalette::ToolTipText, Qt::white);
  dark.setColor(QPalette::Text, Qt::white);
  dark.setColor(QPalette::Button, QColor(53, 53, 53));
  dark.setColor(QPalette::ButtonText, Qt::white);
  dark.setColor(QPalette::BrightText, Qt::red);
  dark.setColor(QPalette::Link, QColor(42, 130, 218));
  dark.setColor(QPalette::Highlight, QColor(254,165,0));
  dark.setColor(QPalette::HighlightedText, Qt::black);
  a.setPalette(dark);

  Main_window w;
  w.show();

  return a.exec();
}
<commit_msg>Set locale<commit_after>#include "ui/mainwindow.h"
#include <QApplication>
#include <QLocale>
#include <QStyleFactory>

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  a.setStyle(QStyleFactory::create("Fusion"));

  QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));

  QPalette dark;
  dark.setColor(QPalette::Window, QColor(53, 53, 53));
  dark.setColor(QPalette::WindowText, Qt::white);
  dark.setColor(QPalette::Base, QColor(25, 25, 25));
  dark.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
  dark.setColor(QPalette::ToolTipBase, Qt::white);
  dark.setColor(QPalette::ToolTipText, Qt::white);
  dark.setColor(QPalette::Text, Qt::white);
  dark.setColor(QPalette::Button, QColor(53, 53, 53));
  dark.setColor(QPalette::ButtonText, Qt::white);
  dark.setColor(QPalette::BrightText, Qt::red);
  dark.setColor(QPalette::Link, QColor(42, 130, 218));
  dark.setColor(QPalette::Highlight, QColor(51,231,247));
  dark.setColor(QPalette::HighlightedText, Qt::black);
  a.setPalette(dark);

  Main_window w;
  w.show();

  return a.exec();
}
<|endoftext|>


<commit_before><commit_msg>Fix declaration<commit_after><|endoftext|>


<commit_before>// MAIN SOURCE

#include <iostream>
#include <fstream>

#include "checker.h"
#include "include/configuration.h"

#include "gflags/gflags.h"

namespace sqlcheck {

Configuration state;

}  // namespace sqlcheck

DEFINE_bool(c, false, "Display warnings in color mode");
DEFINE_bool(v, false, "Display verbose warnings");
DEFINE_uint64(r, sqlcheck::RISK_LEVEL_ALL,
              "Set of anti-patterns to check \n"
              "1 (all anti-patterns, default) \n"
              "2 (only medium and high risk anti-patterns) \n"
              "3 (only high risk anti-patterns) \n");
DEFINE_string(f, "", "SQL file name"); // standard input

void ConfigureChecker(sqlcheck::Configuration &state) {

  // Default Values
  state.risk_level = sqlcheck::RISK_LEVEL_ALL;
  state.file_name = "";
  state.testing_mode = false;
  state.verbose = false;
  state.color_mode = false;

  // Configure checker
  state.color_mode = FLAGS_c;
  state.verbose = FLAGS_v;
  state.file_name = FLAGS_f;
  state.risk_level = (sqlcheck::RiskLevel) FLAGS_r;

  // Run validators
  std::cout << "+-------------------------------------------------+\n"
            << "|                   SQLCHECK                      |\n"
            << "+-------------------------------------------------+\n";

  ValidateRiskLevel(state);
  ValidateFileName(state);
  std::cout << "-------------------------------------------------\n";

}

int main(int argc, char **argv) {

  try {

    // Parse the input arguments from the user
    gflags::SetUsageMessage("");
    gflags::SetVersionString("1.2");

    gflags::ParseCommandLineFlags(&argc, &argv, true);

    // Customize the checker configuration
    ConfigureChecker(sqlcheck::state);

    // Invoke the checker
    sqlcheck::Check(sqlcheck::state);

  }
  // Catching at the top level ensures that
  // destructors are always called
  catch (std::exception& exc) {
    std::cerr << exc.what() << std::endl;
    gflags::ShutDownCommandLineFlags();
    exit(EXIT_FAILURE);
  }

  gflags::ShutDownCommandLineFlags();
  return (EXIT_SUCCESS);
}
<commit_msg>Updated help message<commit_after>// MAIN SOURCE

#include <iostream>
#include <fstream>

#include "checker.h"
#include "include/configuration.h"

#include "gflags/gflags.h"

namespace sqlcheck {

Configuration state;

}  // namespace sqlcheck

DEFINE_bool(c, false, "Display warnings in color mode");
DEFINE_bool(color_mode, false, "Display warnings in color mode");
DEFINE_bool(v, false, "Display verbose warnings");
DEFINE_bool(verbose, false, "Display verbose warnings");
DEFINE_bool(h, false, "Print help message");
DEFINE_uint64(r, sqlcheck::RISK_LEVEL_ALL,
              "Set of anti-patterns to check \n"
              "1 (all anti-patterns, default) \n"
              "2 (only medium and high risk anti-patterns) \n"
              "3 (only high risk anti-patterns) \n");
DEFINE_uint64(risk_level, sqlcheck::RISK_LEVEL_ALL,
              "Set of anti-patterns to check \n"
              "1 (all anti-patterns, default) \n"
              "2 (only medium and high risk anti-patterns) \n"
              "3 (only high risk anti-patterns) \n");
DEFINE_string(f, "", "SQL file name"); // standard input
DEFINE_string(file_name, "", "SQL file name"); // standard input

void ConfigureChecker(sqlcheck::Configuration &state) {

  // Default Values
  state.risk_level = sqlcheck::RISK_LEVEL_ALL;
  state.file_name = "";
  state.testing_mode = false;
  state.verbose = false;
  state.color_mode = false;

  // Configure checker
  state.color_mode = FLAGS_c || FLAGS_color_mode;
  state.verbose = FLAGS_v || FLAGS_verbose;
  if(FLAGS_f.empty() == false){
    state.file_name = FLAGS_f;
  }
  if(FLAGS_file_name.empty() == false){
    state.file_name = FLAGS_file_name;
  }
  if(FLAGS_r != 0){
    state.risk_level = (sqlcheck::RiskLevel) FLAGS_r;
  }
  if(FLAGS_risk_level != 0){
    state.risk_level = (sqlcheck::RiskLevel) FLAGS_risk_level;
  }

  // Run validators
  std::cout << "+-------------------------------------------------+\n"
            << "|                   SQLCHECK                      |\n"
            << "+-------------------------------------------------+\n";

  ValidateRiskLevel(state);
  ValidateFileName(state);
  std::cout << "-------------------------------------------------\n";

}

void Usage() {
  std::cout <<
      "Command line options : sqlcheck <options>\n"
      "   -f -file_name          :  SQL file name\n"
      "   -r -risk_level         :  Set of anti-patterns to check\n"
      "                           :  1 (all anti-patterns, default) \n"
      "                           :  2 (only medium and high risk anti-patterns) \n"
      "                           :  3 (only high risk anti-patterns) \n"
      "   -c -color_mode         :  Display warnings in color mode \n"
      "   -v -verbose            :  Display verbose warnings \n"
      "   -h -help               :  Print help message \n";
  exit(EXIT_SUCCESS);
}

int main(int argc, char **argv) {

  try {

    // Parse the input arguments from the user
    gflags::SetUsageMessage("");
    gflags::SetVersionString("1.2");

    gflags::ParseCommandLineFlags(&argc, &argv, true);

    // Print help message
    if(FLAGS_h == true){
      FLAGS_h = false;
      Usage();

      gflags::ShutDownCommandLineFlags();
      return (EXIT_SUCCESS);
    }

    // Customize the checker configuration
    ConfigureChecker(sqlcheck::state);

    // Invoke the checker
    sqlcheck::Check(sqlcheck::state);

  }
  // Catching at the top level ensures that
  // destructors are always called
  catch (std::exception& exc) {
    std::cerr << exc.what() << std::endl;
    gflags::ShutDownCommandLineFlags();
    exit(EXIT_FAILURE);
  }

  gflags::ShutDownCommandLineFlags();
  return (EXIT_SUCCESS);
}
<|endoftext|>


<commit_before>#include <QtGui/QGuiApplication>
#include <QQmlContext>
#include <QStateMachine>
#include <QDebug>
#include <QListView>
#include <QApplication>
#include <memory>
#include "./window.h"
#include "./scene.h"
#include "./nodes.h"
#include "./input/invoke_manager.h"
#include "./input/signal_manager.h"
#include "./input/scxml_importer.h"
#include "./mouse_shape_controller.h"
#include "./labeller_context.h"

int main(int argc, char **argv)
{
  qputenv("QT_MESSAGE_PATTERN",
          QString("%{time [yyyy'-'MM'-'dd' 'hh':'mm':'ss]} - %{threadid} "
                  "%{if-category}%{category}: %{endif}%{message}").toUtf8());
  if (qgetenv("QT_LOGGING_CONF").size() == 0)
    qputenv("QT_LOGGING_CONF", "../config/logging.ini");

  // QApplication application(argc, argv);
  QGuiApplication application(argc, argv);

  auto invokeManager = std::shared_ptr<InvokeManager>(new InvokeManager());
  auto nodes = std::make_shared<Nodes>();
  auto labeller = std::make_shared<Forces::Labeller>();
  auto scene = std::make_shared<Scene>(invokeManager, nodes, labeller);

  /*
  QListView *view = new QListView;

  view->setWindowTitle("View onto a string list model");

  LabellerContext labellerContext(labeller);
  view->setModel(&labellerContext);
view->show();
*/
  Window window(scene);
  // QQuickView window;
  window.rootContext()->setContextProperty("window", &window);
  window.rootContext()->setContextProperty("nodes", nodes.get());
  LabellerContext labellerContext(labeller);
  window.rootContext()->setContextProperty("labeller", &labellerContext);
  window.setSource(QUrl("qrc:ui.qml"));

  MouseShapeController mouseShapeController(window);

  auto signalManager = std::shared_ptr<SignalManager>(new SignalManager());
  ScxmlImporter importer(QUrl::fromLocalFile("config/states.xml"),
                         invokeManager, signalManager);

  invokeManager->addHandler(&window);
  invokeManager->addHandler("mouseShape", &mouseShapeController);
  signalManager->addSender("KeyboardEventSender", &window);

  auto stateMachine = importer.import();

  // just for printCurrentState slot for debugging
  window.stateMachine = stateMachine;

  stateMachine->start();

  window.show();

  return application.exec();
}
<commit_msg>Remove debugging code.<commit_after>#include <QtGui/QGuiApplication>
#include <QQmlContext>
#include <QStateMachine>
#include <QDebug>
#include <memory>
#include "./window.h"
#include "./scene.h"
#include "./nodes.h"
#include "./input/invoke_manager.h"
#include "./input/signal_manager.h"
#include "./input/scxml_importer.h"
#include "./mouse_shape_controller.h"
#include "./labeller_context.h"

int main(int argc, char **argv)
{
  qputenv("QT_MESSAGE_PATTERN",
          QString("%{time [yyyy'-'MM'-'dd' 'hh':'mm':'ss]} - %{threadid} "
                  "%{if-category}%{category}: %{endif}%{message}").toUtf8());
  if (qgetenv("QT_LOGGING_CONF").size() == 0)
    qputenv("QT_LOGGING_CONF", "../config/logging.ini");

  QGuiApplication application(argc, argv);

  auto invokeManager = std::shared_ptr<InvokeManager>(new InvokeManager());
  auto nodes = std::make_shared<Nodes>();
  auto labeller = std::make_shared<Forces::Labeller>();
  auto scene = std::make_shared<Scene>(invokeManager, nodes, labeller);

  Window window(scene);
  window.rootContext()->setContextProperty("window", &window);
  window.rootContext()->setContextProperty("nodes", nodes.get());
  LabellerContext labellerContext(labeller);
  window.rootContext()->setContextProperty("labeller", &labellerContext);
  window.setSource(QUrl("qrc:ui.qml"));

  MouseShapeController mouseShapeController(window);

  auto signalManager = std::shared_ptr<SignalManager>(new SignalManager());
  ScxmlImporter importer(QUrl::fromLocalFile("config/states.xml"),
                         invokeManager, signalManager);

  invokeManager->addHandler(&window);
  invokeManager->addHandler("mouseShape", &mouseShapeController);
  signalManager->addSender("KeyboardEventSender", &window);

  auto stateMachine = importer.import();

  // just for printCurrentState slot for debugging
  window.stateMachine = stateMachine;

  stateMachine->start();

  window.show();

  return application.exec();
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <string>

#ifdef __APPLE__
#include <OpenGL/glu.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#else
#include "GL/glu.h"
#include "SDL2/SDL.h"
#include "SD2/SDL_opengl.h"
#endif

namespace evil {

static const char* lastError = "";

const char *GetError() {
		return lastError;
}

void SetError(const char *error) {
		lastError = error;
}

void SetError( const unsigned char* error) {
		lastError = (const char*)error;
}

void error(const char *fmt, ... )
{
		char buffer[512];
		va_list args;
		va_start(args, fmt);
		vsnprintf(buffer, sizeof(buffer), fmt, args);
		va_end(args);

		fprintf(stderr, "%s\n", buffer);
}

static SDL_Window *window = nullptr;
static SDL_GLContext context = nullptr;

static bool initGL()
{
		glMatrixMode( GL_PROJECTION );
		glLoadIdentity();

		GLenum error = glGetError();

		if( error != GL_NO_ERROR ) {
				SetError( gluErrorString(error));
				return false;
		}

		glMatrixMode( GL_MODELVIEW );
		glLoadIdentity();

		error = glGetError();
		if( error != GL_NO_ERROR ) {
				SetError( gluErrorString(error));
				return false;
		}

		glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );

		error = glGetError();
		if( error != GL_NO_ERROR ) {
				SetError( gluErrorString(error));
				return false;
		}
		return true;
}

static bool init()
{
		if( SDL_Init(SDL_INIT_EVERYTHING ) < 0 ) {
				error("SDL init failed: %s", SDL_GetError());
				return false;
		}

		SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 2);
		SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1);

		window = SDL_CreateWindow( "Evil", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
															 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN );

		if( !window ) {
				error( "Couldn't create Window: %s", SDL_GetError());
				return false;
		}

		context = SDL_GL_CreateContext( window );
		if( !context ) {
				error("Couldnt' create GL context: %s", SDL_GetError());
				return false;
		}

		if( SDL_GL_SetSwapInterval(1) < 0 ) {
				error("Couldn't set VSYNC: %s", SDL_GetError());
				return false;
		}

		if( !initGL()) {
				error("Couldn't initialize OpenGL: %s", GetError());
				return false;
		}
		return true;
}

static void render() {
		glClear(GL_COLOR_BUFFER_BIT);
}

static void close() {
		if( context ) {
				SDL_GL_DeleteContext( context );
				context = nullptr;
		}
		if( window ) {
				SDL_DestroyWindow( window );
				window = nullptr;
		}
		SDL_Quit();
}

}
using namespace std;
using namespace evil;

int main(int argc, char** argv)
{
		if( !init() ) {
				return 1;
		}

		SDL_StartTextInput();

		bool running = true;

		while(running) {
				SDL_Event e;
				while( SDL_PollEvent(&e) ) {
						switch( e.type ) {
						case SDL_QUIT:
								running = false;
								break;
						case SDL_TEXTINPUT:
								// do stuff
								break;
						}
				}
				render();
				SDL_GL_SwapWindow( window );
		}

		SDL_StopTextInput();

		close();

		return 0;
}

<commit_msg>stuff<commit_after>#include <cstdio>
#include <string>

#ifdef __APPLE__
#include <OpenGL/glu.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#else
#include "GL/glu.h"
#include "SDL2/SDL.h"
#include "SDL2/SDL_opengl.h"
#endif

namespace evil {

static const char* lastError = "";

const char *GetError() {
		return lastError;
}

void SetError(const char *error) {
		lastError = error;
}

void SetError( const unsigned char* error) {
		lastError = (const char*)error;
}

void error(const char *fmt, ... )
{
		char buffer[512];
		va_list args;
		va_start(args, fmt);
		vsnprintf(buffer, sizeof(buffer), fmt, args);
		va_end(args);

		fprintf(stderr, "%s\n", buffer);
}

static SDL_Window *window = nullptr;
static SDL_GLContext context = nullptr;

static bool initGL()
{
		glMatrixMode( GL_PROJECTION );
		glLoadIdentity();

		GLenum error = glGetError();

		if( error != GL_NO_ERROR ) {
				SetError( gluErrorString(error));
				return false;
		}

		glMatrixMode( GL_MODELVIEW );
		glLoadIdentity();

		error = glGetError();
		if( error != GL_NO_ERROR ) {
				SetError( gluErrorString(error));
				return false;
		}

		glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );

		error = glGetError();
		if( error != GL_NO_ERROR ) {
				SetError( gluErrorString(error));
				return false;
		}
		return true;
}

static bool init()
{
		if( SDL_Init(SDL_INIT_EVERYTHING ) < 0 ) {
				error("SDL init failed: %s", SDL_GetError());
				return false;
		}

		SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 2);
		SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1);

		window = SDL_CreateWindow( "Evil", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
															 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN );

		if( !window ) {
				error( "Couldn't create Window: %s", SDL_GetError());
				return false;
		}

		context = SDL_GL_CreateContext( window );
		if( !context ) {
				error("Couldnt' create GL context: %s", SDL_GetError());
				return false;
		}

		if( SDL_GL_SetSwapInterval(1) < 0 ) {
				error("Couldn't set VSYNC: %s", SDL_GetError());
				return false;
		}

		if( !initGL()) {
				error("Couldn't initialize OpenGL: %s", GetError());
				return false;
		}
		return true;
}

static void render() {
		glClear(GL_COLOR_BUFFER_BIT);
}

static void close() {
		if( context ) {
				SDL_GL_DeleteContext( context );
				context = nullptr;
		}
		if( window ) {
				SDL_DestroyWindow( window );
				window = nullptr;
		}
		SDL_Quit();
}

}
using namespace std;
using namespace evil;

int main(int argc, char** argv)
{
		if( !init() ) {
				return 1;
		}

		SDL_StartTextInput();

		bool running = true;

		while(running) {
				SDL_Event e;
				while( SDL_PollEvent(&e) ) {
						switch( e.type ) {
						case SDL_QUIT:
								running = false;
								break;
						case SDL_TEXTINPUT:
								// do stuff
								break;
						}
				}
				render();
				SDL_GL_SwapWindow( window );
		}

		SDL_StopTextInput();

		close();

		return 0;
}

<|endoftext|>


<commit_before>/*
 * Worldvisions Weaver Software:
 *   Copyright (C) 1997-2003 Net Integration Technologies, Inc.
 *
 * WvDial configuration utility.  Generates a basic wvdial.conf file.
 */
#include "wvmodemscan.h"
#include "wvfile.h"
#include "wvconf.h"
#include <ctype.h>

void check_ppp_options()
{
    WvFile file("/etc/ppp/options", O_RDONLY);
    char *line;

    while ((line = file.getline(0)) != NULL)
    {
	line = trim_string(line);

	// comments and blank lines are ignored
	if (line[0] == '#'  ||  !line[0])
	    continue;

	// IP addresses are allowed
	if (strchr(line, '.') || strchr(line, ':'))
	    continue;

	// but baud rates and tty names are not!
	// a 'connect' line is usually bad too.
	if (isdigit(line[0])
	    || !strncmp(line, "/dev", 4)
	    || !strncmp(line, "tty",  3)
	    || !strncmp(line, "cua",  3)
	    || !strncmp(line, "connect", 7))
	{
	    wvcon->print("\n*** WARNING!  Line \"%s\"\n"
		"   in /etc/ppp/options may conflict with wvdial!\n\n", line);
	}
    }
}

int main(int argc, char **argv)
{
#if DEBUG
    free(malloc(1));    // for electric fence
#endif

    if (argc != 2 || argv[1][0]=='-')
    {
	wvcon->print("Usage: %s <configfile-name>\n"
		"\t(create/update a wvdial.conf file automatically)\n",
		argv[0]);
	return 1;
    }

    wvcon->print("Scanning your serial ports for a modem.\n\n");

    WvModemScanList l;
    while (!l.isdone())
	l.execute();

    if (l.count() < 1)
    {
	wvcon->print("\n\n"
	  "Sorry, no modem was detected!  "
	    "Is it in use by another program?\n"
	  "Did you configure it properly with setserial?\n\n"

	  "Please read the FAQ at http://open.nit.ca/wvdial/\n\n"

	  "If you still have problems, send mail to "
	    "wvdial-list@lists.nit.ca.\n");
	return 1;
    }

    WvModemScanList::Iter i(l);

    i.rewind(); i.next();
    WvModemScan &m = *i;
    WvString fn = m.filename(), init = m.initstr();

    wvcon->print("\nFound %s on %s",
        m.is_isdn() ? "an ISDN TA" :
        strncmp("/dev/ttyACM",fn,11) ? "a modem" : "an USB modem", (const char *)fn);
    if (m.use_modem_link) {
        wvcon->print(", using link /dev/modem in config.\n");
        fn = "/dev/modem";
    } else {
        wvcon->print(".\n");
    }
    WvConf cfg(argv[1],0660); // Create it read/write owner and group only
    static char s[]="Dialer Defaults";
    cfg.set(s, "Modem", fn);
    cfg.setint(s, "Baud", m.maxbaud());
    cfg.set(s, "Init1", m.is_isdn() ? "AT&F" : "ATZ");
    cfg.set(s, "Init2", init);
    cfg.set(s, "ISDN",  m.use_default_asyncmap() ? "1" : "0");
    cfg.set(s, "Modem Name",  m.modem_name ? (const char *)m.modem_name : "");
    cfg.set(s, "Modem Type",  m.is_isdn() ? "ISDN Terminal Adapter" :
            strncmp("/dev/ttyACM",fn,11) ? "Analog Modem" : "USB Modem");

    if (m.modem_name)
        wvcon->print("Config for %s written to %s.\n", (const char *)m.modem_name, argv[1]);
    else
        wvcon->print("Modem configuration written to %s.\n", argv[1]);

    // insert some entries to let people know what they need to edit
    if (!cfg.get(s, "Phone"))
	cfg.set(s, "; Phone", "<Target Phone Number>");
    if (!cfg.get(s, "Username"))
	cfg.set(s, "; Username", "<Your Login Name>");
    if (!cfg.get(s, "Password"))
	cfg.set(s, "; Password", "<Your Password>");

    check_ppp_options();

    return 0;
}
<commit_msg>Removed the mixing of WvConfEmu and WvConf in WvDial.<commit_after>/*
 * Worldvisions Weaver Software:
 *   Copyright (C) 1997-2003 Net Integration Technologies, Inc.
 *
 * WvDial configuration utility.  Generates a basic wvdial.conf file.
 */
#include "uniconfroot.h"
#include "wvconfemu.h"
#include "wvfile.h"
#include "wvmodemscan.h"
#include "wvstrutils.h"
#include <ctype.h>

void check_ppp_options()
{
    WvFile file("/etc/ppp/options", O_RDONLY);
    char *line;

    while ((line = file.getline(0)) != NULL)
    {
	line = trim_string(line);

	// comments and blank lines are ignored
	if (line[0] == '#'  ||  !line[0])
	    continue;

	// IP addresses are allowed
	if (strchr(line, '.') || strchr(line, ':'))
	    continue;

	// but baud rates and tty names are not!
	// a 'connect' line is usually bad too.
	if (isdigit(line[0])
	    || !strncmp(line, "/dev", 4)
	    || !strncmp(line, "tty",  3)
	    || !strncmp(line, "cua",  3)
	    || !strncmp(line, "connect", 7))
	{
	    wvcon->print("\n*** WARNING!  Line \"%s\"\n"
		"   in /etc/ppp/options may conflict with wvdial!\n\n", line);
	}
    }
}

int main(int argc, char **argv)
{
#if DEBUG
    free(malloc(1));    // for electric fence
#endif

    if (argc != 2 || argv[1][0]=='-')
    {
	wvcon->print("Usage: %s <configfile-name>\n"
		"\t(create/update a wvdial.conf file automatically)\n",
		argv[0]);
	return 1;
    }

    wvcon->print("Scanning your serial ports for a modem.\n\n");

    WvModemScanList l;
    while (!l.isdone())
	l.execute();

    if (l.count() < 1)
    {
	wvcon->print("\n\n"
	  "Sorry, no modem was detected!  "
	    "Is it in use by another program?\n"
	  "Did you configure it properly with setserial?\n\n"

	  "Please read the FAQ at http://open.nit.ca/wvdial/\n\n"

	  "If you still have problems, send mail to "
	    "wvdial-list@lists.nit.ca.\n");
	return 1;
    }

    WvModemScanList::Iter i(l);

    i.rewind(); i.next();
    WvModemScan &m = *i;
    WvString fn = m.filename(), init = m.initstr();

    wvcon->print("\nFound %s on %s",
        m.is_isdn() ? "an ISDN TA" :
        strncmp("/dev/ttyACM",fn,11) ? "a modem" : "an USB modem", (const char *)fn);
    if (m.use_modem_link) {
        wvcon->print(", using link /dev/modem in config.\n");
        fn = "/dev/modem";
    } else {
        wvcon->print(".\n");
    }
    UniConfRoot uni(WvString("ini:%s", argv[1]), 0660);
    WvConfEmu cfg(uni); // Create it read/write owner and group only
    static char s[]="Dialer Defaults";
    cfg.set(s, "Modem", fn);
    cfg.setint(s, "Baud", m.maxbaud());
    cfg.set(s, "Init1", m.is_isdn() ? "AT&F" : "ATZ");
    cfg.set(s, "Init2", init);
    cfg.set(s, "ISDN",  m.use_default_asyncmap() ? "1" : "0");
    cfg.set(s, "Modem Name",  m.modem_name ? (const char *)m.modem_name : "");
    cfg.set(s, "Modem Type",  m.is_isdn() ? "ISDN Terminal Adapter" :
            strncmp("/dev/ttyACM",fn,11) ? "Analog Modem" : "USB Modem");

    if (m.modem_name)
        wvcon->print("Config for %s written to %s.\n", (const char *)m.modem_name, argv[1]);
    else
        wvcon->print("Modem configuration written to %s.\n", argv[1]);

    // insert some entries to let people know what they need to edit
    if (!cfg.get(s, "Phone"))
	cfg.set(s, "; Phone", "<Target Phone Number>");
    if (!cfg.get(s, "Username"))
	cfg.set(s, "; Username", "<Your Login Name>");
    if (!cfg.get(s, "Password"))
	cfg.set(s, "; Password", "<Your Password>");

    check_ppp_options();

    return 0;
}
<|endoftext|>


<commit_before>//
//  DIYSeqEngine.cpp
//  AudioKit
//
//  Created by Jeff Cooper on 1/25/19.
//  Copyright © 2019 AudioKit. All rights reserved.
//

#include <stdio.h>
#pragma once
#import "AKSoundpipeKernel.hpp"

#define NOTEON 0x90
#define NOTEOFF 0x80
#define INITVALUE -1.0
#define MIDINOTECOUNT 128

struct MIDIEvent {
    uint8_t status;
    uint8_t data1;
    uint8_t data2;
    double beat;
    double duration;
};

struct MIDINote {
    struct MIDIEvent noteOn;
    struct MIDIEvent noteOff;
};

enum {
    startPointAddress = 0,
};

class AKDIYSeqEngineDSPKernel : public AKSoundpipeKernel, public AKOutputBuffered {
public:
    // MARK: Member Functions

    AKDIYSeqEngineDSPKernel() {}

    void init(int channelCount, double sampleRate) override {
        printf("deboog: inited diyseqengine\n");
        AKSoundpipeKernel::init(channelCount, sampleRate);
    }

    void setTargetAU(AudioUnit target) {
        targetAU = target;
    }

    void start() {
        resetPlaybackVariables();
        started = true;
        isPlaying = true;
    }

//    void playFrom(double beat) {
//        int position = beat;
//    }

    void stop() {
        printf("deboog: stopped diyseqengine\n");
        started = false;
        isPlaying = false;
    }

    void reset() {
        printf("deboog: resetted diyseqengine\n");
        resetted = true;
        startPointRamper.reset();
    }

    void destroy() {
        AKSoundpipeKernel::destroy();
    }

    void setStartPoint(float value) {
        startPoint = value;
    }

    void setParameter(AUParameterAddress address, AUValue value) {
        switch (address) {
            case startPointAddress:
                startPointRamper.setUIValue(clamp(value, 0.0f, 10.0f));
                break;
        }
    }

    AUValue getParameter(AUParameterAddress address) {
        switch (address) {
            case startPointAddress:
                return startPointRamper.getUIValue();

            default: return 0.0f;
        }
    }

    void startRamp(AUParameterAddress address, AUValue value, AUAudioFrameCount duration) override {
        switch (address) {
            case startPointAddress:
                startPointRamper.startRamp(clamp(value, 0.0f, 10.0f), duration);
                break;
        }
    }

    void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {

        if (isPlaying) {
            if (positionInSamples >= lengthInSamples()){
                if (loopEnabled) {
                    positionInSamples = 0;
                } else {
                    printf("deboog: seq finished %i \n", lengthInSamples());
                    stop();
                    return;
                }
            }
            UInt64 currentStartSample = positionModulo();
            UInt64 currentEndSample = currentStartSample + frameCount;
            for (int i = 0; i < eventCount; i++) {
                int triggerTime = beatToSamples(events[i].beat);
                if ((currentStartSample <= triggerTime && triggerTime < currentEndSample)
                    && stopAfterCurrentNotes == false) {
                    int offset = (int)(triggerTime - currentStartSample);
                    sendMidiData(events[i].status, events[i].data1, events[i].data2,
                                 offset, events[i].beat);
                    //printf("deboog event %i will fire at %i offset %i \n", i, triggerTime, offset);
                }

                //            if (((startSample <= triggerTime && triggerTime <= endSample)) && *stopAfterCurrentNotes == false)
                //            {
                //                int time = triggerTime - startSample + offset;
                //                if (self->_eventCallback != NULL) {
                //                    self->_eventCallback(events[i].status, events[i].data1, events[i].data2);
                //                }

                //            }
            }
            positionInSamples += frameCount;
        }
        framesCounted += frameCount;
    }

    int addMIDIEvent(uint8_t status, uint8_t data1, uint8_t data2, double beat) {
        events[eventCount].status = status;
        events[eventCount].data1 = data1;
        events[eventCount].data2 = data2;
        events[eventCount].beat = beat;

        eventCount += 1;
        return eventCount;
    }

private:
    void sendMidiData(UInt8 status, UInt8 data1, UInt8 data2, double offset, double time) {
//        printf("deboog: sending: %i %i at %f\n", status, data1, time);
        if (midiPort == 0 || midiEndpoint == 0) {
            MusicDeviceMIDIEvent(targetAU, status, data1, data2, offset);
        } else {
            MIDIPacketList packetList;
            packetList.numPackets = 1;
            MIDIPacket* firstPacket = &packetList.packet[0];
            firstPacket->length = 3;
            firstPacket->data[0] = status;
            firstPacket->data[1] = data1;
            firstPacket->data[2] = data2;
            firstPacket->timeStamp = offset;
            MIDISend(midiPort, midiEndpoint, &packetList);
        }
    }

    int lengthInSamples() {
        return beatToSamples(lengthInBeats);
    }

    void resetPlaybackVariables() {
        positionInSamples = 0;
    }

    int beatToSamples(double beat) {
        return (int)(beat / bpm * 60 * sampleRate);
    }

    int positionModulo() {
        return positionInSamples % lengthInSamples();
    }

    bool validTriggerTime(double beat){
        return true;
    }

private:

    float startPoint = 0;
    AudioUnit targetAU;
    UInt64 framesCounted = 0;
    UInt64 positionInSamples = 0;

public:
    bool started = false;
    bool resetted = false;
    ParameterRamper startPointRamper = 1;

    bool isPlaying = false;
    MIDIPortRef midiPort;
    MIDIEndpointRef midiEndpoint;
    AKCCallback loopCallback = nullptr;
    MIDIEvent events[512];
    int eventCount = 0;
    double lengthInBeats = 4.0;
    double bpm = 120.0;
    bool stopAfterCurrentNotes = false;
    bool loopEnabled = true;
};
<commit_msg>remove aksoundpipekernel<commit_after>//
//  DIYSeqEngine.cpp
//  AudioKit
//
//  Created by Jeff Cooper on 1/25/19.
//  Copyright © 2019 AudioKit. All rights reserved.
//

#include <stdio.h>
#pragma once

#define NOTEON 0x90
#define NOTEOFF 0x80
#define INITVALUE -1.0
#define MIDINOTECOUNT 128

struct MIDIEvent {
    uint8_t status;
    uint8_t data1;
    uint8_t data2;
    double beat;
    double duration;
};

struct MIDINote {
    struct MIDIEvent noteOn;
    struct MIDIEvent noteOff;
};

enum {
    startPointAddress = 0,
};

class AKDIYSeqEngineDSPKernel : public AKDSPKernel, public AKOutputBuffered {
public:
    // MARK: Member Functions

    AKDIYSeqEngineDSPKernel() {}

    void init(int channelCount, double sampleRate) override {
        printf("deboog: inited diyseqengine\n");
    }

    void setTargetAU(AudioUnit target) {
        targetAU = target;
    }

    void start() {
        resetPlaybackVariables();
        started = true;
        isPlaying = true;
    }

//    void playFrom(double beat) {
//        int position = beat;
//    }

    void stop() {
        printf("deboog: stopped diyseqengine\n");
        started = false;
        isPlaying = false;
    }

    void reset() {
        printf("deboog: resetted diyseqengine\n");
        resetted = true;
        startPointRamper.reset();
    }

    void destroy() {

    }

    void setStartPoint(float value) {
        startPoint = value;
    }

    void setParameter(AUParameterAddress address, AUValue value) {
        switch (address) {
            case startPointAddress:
                startPointRamper.setUIValue(clamp(value, 0.0f, 10.0f));
                break;
        }
    }

    AUValue getParameter(AUParameterAddress address) {
        switch (address) {
            case startPointAddress:
                return startPointRamper.getUIValue();

            default: return 0.0f;
        }
    }

    void startRamp(AUParameterAddress address, AUValue value, AUAudioFrameCount duration) override {
        switch (address) {
            case startPointAddress:
                startPointRamper.startRamp(clamp(value, 0.0f, 10.0f), duration);
                break;
        }
    }

    void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {

        if (isPlaying) {
            if (positionInSamples >= lengthInSamples()){
                if (loopEnabled) {
                    positionInSamples = 0;
                } else {
                    printf("deboog: seq finished %i \n", lengthInSamples());
                    stop();
                    return;
                }
            }
            UInt64 currentStartSample = positionModulo();
            UInt64 currentEndSample = currentStartSample + frameCount;
            for (int i = 0; i < eventCount; i++) {
                int triggerTime = beatToSamples(events[i].beat);
                if ((currentStartSample <= triggerTime && triggerTime < currentEndSample)
                    && stopAfterCurrentNotes == false) {
                    int offset = (int)(triggerTime - currentStartSample);
                    sendMidiData(events[i].status, events[i].data1, events[i].data2,
                                 offset, events[i].beat);
                    //printf("deboog event %i will fire at %i offset %i \n", i, triggerTime, offset);
                }

                //            if (((startSample <= triggerTime && triggerTime <= endSample)) && *stopAfterCurrentNotes == false)
                //            {
                //                int time = triggerTime - startSample + offset;
                //                if (self->_eventCallback != NULL) {
                //                    self->_eventCallback(events[i].status, events[i].data1, events[i].data2);
                //                }

                //            }
            }
            positionInSamples += frameCount;
        }
        framesCounted += frameCount;
    }

    int addMIDIEvent(uint8_t status, uint8_t data1, uint8_t data2, double beat) {
        events[eventCount].status = status;
        events[eventCount].data1 = data1;
        events[eventCount].data2 = data2;
        events[eventCount].beat = beat;

        eventCount += 1;
        return eventCount;
    }

private:
    void sendMidiData(UInt8 status, UInt8 data1, UInt8 data2, double offset, double time) {
//        printf("deboog: sending: %i %i at %f\n", status, data1, time);
        if (midiPort == 0 || midiEndpoint == 0) {
            MusicDeviceMIDIEvent(targetAU, status, data1, data2, offset);
        } else {
            MIDIPacketList packetList;
            packetList.numPackets = 1;
            MIDIPacket* firstPacket = &packetList.packet[0];
            firstPacket->length = 3;
            firstPacket->data[0] = status;
            firstPacket->data[1] = data1;
            firstPacket->data[2] = data2;
            firstPacket->timeStamp = offset;
            MIDISend(midiPort, midiEndpoint, &packetList);
        }
    }

    int lengthInSamples() {
        return beatToSamples(lengthInBeats);
    }

    void resetPlaybackVariables() {
        positionInSamples = 0;
    }

    int beatToSamples(double beat) {
        return (int)(beat / bpm * 60 * sampleRate);
    }

    int positionModulo() {
        return positionInSamples % lengthInSamples();
    }

    bool validTriggerTime(double beat){
        return true;
    }

private:

    float startPoint = 0;
    AudioUnit targetAU;
    UInt64 framesCounted = 0;
    UInt64 positionInSamples = 0;

public:
    bool started = false;
    bool resetted = false;
    ParameterRamper startPointRamper = 1;

    bool isPlaying = false;
    MIDIPortRef midiPort;
    MIDIEndpointRef midiEndpoint;
    AKCCallback loopCallback = nullptr;
    MIDIEvent events[512];
    int eventCount = 0;
    double lengthInBeats = 4.0;
    double bpm = 120.0;
    bool stopAfterCurrentNotes = false;
    bool loopEnabled = true;
};
<|endoftext|>


<commit_before><commit_msg>coverity#735764 Unchecked dynamic_cast<commit_after><|endoftext|>


<commit_before>#include <EXTERN.h> // from the Perl distribution
#include <perl.h> // from the Perl distribution

#ifdef WIN32
// Perl win32 specific includes, found in perl\\lib\\CORE\\win32.h
// Defines the windows specific convenience RunPerl() function,
// which is not available on other operating systems.
#include <win32.h>
#include <wchar.h>
#endif

#include <cstdio>
#include <cstdlib>

#ifdef WIN32
int main(int argc, char **argv, char **env)
{
	SetCurrentDirectory("libexec");

	// If the Slic3r is installed in a localized directory (containing non-iso
	// characters), spaces or semicolons, use short file names.
	char    exe_path[MAX_PATH] = {0};
	char    script_path[MAX_PATH];
	char    gui_flag[6] = {"--gui"};
#ifdef FORCE_GUI
	char**  command_line = (char**)malloc(sizeof(char*) * ((++ argc) + 2));
#else
	char**  command_line = (char**)malloc(sizeof(char*) * ((++ argc) + 1));
#endif
	{
		// Unicode path. This will not be used directly, but to test, whether
		// there are any non-ISO characters, in which case the path is converted to a
		// short path (using 8.3 directory names).

		wchar_t exe_path_w[MAX_PATH] = {0};
		char    drive[_MAX_DRIVE];
		char    dir[_MAX_DIR];
		char    fname[_MAX_FNAME];
		char    ext[_MAX_EXT];
		bool    needs_short_paths = false;
		int     len;
		int     i;
		GetModuleFileNameA(NULL, exe_path, MAX_PATH-1);
		GetModuleFileNameW(NULL, exe_path_w, MAX_PATH-1);
		len = strlen(exe_path);

		if (len != wcslen(exe_path_w)) {
			needs_short_paths = true;
		} else {
			for (i = 0; i < len; ++ i)
				if ((wchar_t)exe_path[i] != exe_path_w[i] || exe_path[i] == ' ' ||
						exe_path[i] == ';') {
					needs_short_paths = true;
					break;
				}
		}
		if (needs_short_paths) {
			wchar_t exe_path_short[MAX_PATH] = {0};
			GetShortPathNameW(exe_path_w, exe_path_short, MAX_PATH);
			len = wcslen(exe_path_short);
			for (i = 0; i <= len; ++ i)
				exe_path[i] = (char)exe_path_short[i];
		}
		_splitpath(exe_path, drive, dir, fname, ext);
		_makepath(script_path, drive, dir, NULL, NULL);
		if (needs_short_paths)
			printf("Slic3r installed in a loclized path. Using an 8.3 path: \"%s\"\n",
					script_path);
		SetDllDirectoryA(script_path);
		strcat(dir, "libexec\\");
		_makepath(script_path, drive, dir, "slic3r", "pl");
		command_line[0] = exe_path;
		command_line[1] = script_path;
		memcpy(command_line + 2, argv + 1, sizeof(char*) * (argc - 2));
#ifdef FORCE_GUI
		command_line[argc] = gui_flag;
		command_line[argc+1] = NULL;
#else
		command_line[argc] = NULL;
#endif
		// Unset the PERL5LIB and PERLLIB environment variables.
		SetEnvironmentVariable("PERL5LIB", NULL);
		SetEnvironmentVariable("PERLLIB", NULL);
#if 0
		printf("Arguments: \r\n");
		for (size_t i = 0; i < argc + 1; ++ i)
			printf(" %d: %s\r\n", i, command_line[i]);
#endif
	}
#ifdef FORCE_GUI
	RunPerl(argc+1, command_line, NULL);
#else
	RunPerl(argc, command_line, NULL);
#endif
	free(command_line);
}
#else

int main(int argc, char **argv, char **env)
{
    PerlInterpreter *my_perl = perl_alloc();
    if (my_perl == NULL) {
        fprintf(stderr, "Cannot start perl interpreter. Exiting.\n");
        return -1;
    }
    perl_construct(my_perl);

#ifdef FORCE_GUI
    char* command_line[] = { "slic3r", "slic3r.pl", "--gui" };
#else
    char* command_line[] = { "slic3r", "slic3r.pl" };
#endif
    perl_parse(my_perl, NULL, 3, command_line, (char **)NULL);
    perl_run(my_perl);
    perl_destruct(my_perl);
    perl_free(my_perl);
}
#endif
<commit_msg>Revert "Append libexec to the slic3r.pl path"<commit_after>#include <EXTERN.h> // from the Perl distribution
#include <perl.h> // from the Perl distribution

#ifdef WIN32
// Perl win32 specific includes, found in perl\\lib\\CORE\\win32.h
// Defines the windows specific convenience RunPerl() function,
// which is not available on other operating systems.
#include <win32.h>
#include <wchar.h>
#endif

#include <cstdio>
#include <cstdlib>

#ifdef WIN32
int main(int argc, char **argv, char **env)
{
	SetCurrentDirectory("libexec");

	// If the Slic3r is installed in a localized directory (containing non-iso
	// characters), spaces or semicolons, use short file names.
	char    exe_path[MAX_PATH] = {0};
	char    script_path[MAX_PATH];
	char    gui_flag[6] = {"--gui"};
#ifdef FORCE_GUI
	char**  command_line = (char**)malloc(sizeof(char*) * ((++ argc) + 2));
#else
	char**  command_line = (char**)malloc(sizeof(char*) * ((++ argc) + 1));
#endif
	{
		// Unicode path. This will not be used directly, but to test, whether
		// there are any non-ISO characters, in which case the path is converted to a
		// short path (using 8.3 directory names).

		wchar_t exe_path_w[MAX_PATH] = {0};
		char    drive[_MAX_DRIVE];
		char    dir[_MAX_DIR];
		char    fname[_MAX_FNAME];
		char    ext[_MAX_EXT];
		bool    needs_short_paths = false;
		int     len;
		int     i;
		GetModuleFileNameA(NULL, exe_path, MAX_PATH-1);
		GetModuleFileNameW(NULL, exe_path_w, MAX_PATH-1);
		len = strlen(exe_path);

		if (len != wcslen(exe_path_w)) {
			needs_short_paths = true;
		} else {
			for (i = 0; i < len; ++ i)
				if ((wchar_t)exe_path[i] != exe_path_w[i] || exe_path[i] == ' ' ||
						exe_path[i] == ';') {
					needs_short_paths = true;
					break;
				}
		}
		if (needs_short_paths) {
			wchar_t exe_path_short[MAX_PATH] = {0};
			GetShortPathNameW(exe_path_w, exe_path_short, MAX_PATH);
			len = wcslen(exe_path_short);
			for (i = 0; i <= len; ++ i)
				exe_path[i] = (char)exe_path_short[i];
		}
		_splitpath(exe_path, drive, dir, fname, ext);
		_makepath(script_path, drive, dir, NULL, NULL);
		if (needs_short_paths)
			printf("Slic3r installed in a loclized path. Using an 8.3 path: \"%s\"\n",
					script_path);
		SetDllDirectoryA(script_path);
		_makepath(script_path, drive, dir, "slic3r", "pl");
		command_line[0] = exe_path;
		command_line[1] = script_path;
		memcpy(command_line + 2, argv + 1, sizeof(char*) * (argc - 2));
#ifdef FORCE_GUI
		command_line[argc] = gui_flag;
		command_line[argc+1] = NULL;
#else
		command_line[argc] = NULL;
#endif
		// Unset the PERL5LIB and PERLLIB environment variables.
		SetEnvironmentVariable("PERL5LIB", NULL);
		SetEnvironmentVariable("PERLLIB", NULL);
#if 0
		printf("Arguments: \r\n");
		for (size_t i = 0; i < argc + 1; ++ i)
			printf(" %d: %s\r\n", i, command_line[i]);
#endif
	}
#ifdef FORCE_GUI
	RunPerl(argc+1, command_line, NULL);
#else
	RunPerl(argc, command_line, NULL);
#endif
	free(command_line);
}
#else

int main(int argc, char **argv, char **env)
{
    PerlInterpreter *my_perl = perl_alloc();
    if (my_perl == NULL) {
        fprintf(stderr, "Cannot start perl interpreter. Exiting.\n");
        return -1;
    }
    perl_construct(my_perl);

#ifdef FORCE_GUI
    char* command_line[] = { "slic3r", "slic3r.pl", "--gui" };
#else
    char* command_line[] = { "slic3r", "slic3r.pl" };
#endif
    perl_parse(my_perl, NULL, 3, command_line, (char **)NULL);
    perl_run(my_perl);
    perl_destruct(my_perl);
    perl_free(my_perl);
}
#endif
<|endoftext|>


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

#pragma hdrstop

#include "fuarea.hxx"

#include <svx/svxids.hrc>
#ifndef _SVX_TAB_AREA_HXX //autogen
#include <svx/tabarea.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif

#include "drawdoc.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#include "app.hrc"
#include <svx/svxdlg.hxx> //CHINA001
#include <svx/dialogs.hrc> //CHINA001

namespace sd {
TYPEINIT1( FuArea, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuArea::FuArea( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}

FunctionReference FuArea::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
    FunctionReference xFunc( new FuArea( pViewSh, pWin, pView, pDoc, rReq ) );
    xFunc->DoExecute(rReq);
    return xFunc;
}

void FuArea::DoExecute( SfxRequest& rReq )
{
    const SfxItemSet* pArgs = rReq.GetArgs();

    if( !pArgs )
    {
        // erst einmal alle eingabeparameter fuer den dialog retten
        SfxItemSet aInputAttr( pDoc->GetPool() );
        pView->GetAttributes( aInputAttr );

        const XFillStyleItem    &rIFillStyleItem    = (const XFillStyleItem &) aInputAttr.Get (XATTR_FILLSTYLE);
        const XFillColorItem    &rIFillColorItem    = (const XFillColorItem &) aInputAttr.Get (XATTR_FILLCOLOR);
        const XFillGradientItem &rIFillGradientItem = (const XFillGradientItem &) aInputAttr.Get (XATTR_FILLGRADIENT);
        const XFillHatchItem    &rIFillHatchItem    = (const XFillHatchItem &) aInputAttr.Get (XATTR_FILLHATCH);
        const XFillBitmapItem   &rIXFillBitmapItem  = (const XFillBitmapItem &) aInputAttr.Get (XATTR_FILLBITMAP);

        SfxItemSet* pNewAttr = new SfxItemSet( pDoc->GetPool() );
        pView->GetAttributes( *pNewAttr );

        //CHINA001 SvxAreaTabDialog* pDlg = new SvxAreaTabDialog( NULL, pNewAttr, pDoc, pView );
        SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
        DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001
        AbstractSvxAreaTabDialog * pDlg = pFact->CreateSvxAreaTabDialog( NULL,
                                                                        pNewAttr,
                                                                        pDoc,
                                                                        ResId(RID_SVXDLG_AREA),
                                                                        pView);
        DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
        if ( pDlg->Execute() == RET_OK )
        {
            pView->SetAttributes (*(pDlg->GetOutputItemSet ()));
        }

        // Attribute wurden geaendert, Listboxes in Objectbars muessen aktualisiert werden
        static USHORT SidArray[] = {
                        SID_ATTR_FILL_STYLE,
                        SID_ATTR_FILL_COLOR,
                        SID_ATTR_FILL_GRADIENT,
                        SID_ATTR_FILL_HATCH,
                        SID_ATTR_FILL_BITMAP,
                        0 };

        pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );

        delete pDlg;
        delete pNewAttr;
    }

    rReq.Ignore ();

}

void FuArea::Activate()
{
}

void FuArea::Deactivate()
{
}

} // end of namespace sd
<commit_msg>INTEGRATION: CWS pchfix02 (1.6.214); FILE MERGED 2006/09/01 17:37:04 kaib 1.6.214.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fuarea.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 18:46:34 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include "fuarea.hxx"

#include <svx/svxids.hrc>
#ifndef _SVX_TAB_AREA_HXX //autogen
#include <svx/tabarea.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif

#include "drawdoc.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#include "app.hrc"
#include <svx/svxdlg.hxx> //CHINA001
#include <svx/dialogs.hrc> //CHINA001

namespace sd {
TYPEINIT1( FuArea, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuArea::FuArea( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}

FunctionReference FuArea::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
    FunctionReference xFunc( new FuArea( pViewSh, pWin, pView, pDoc, rReq ) );
    xFunc->DoExecute(rReq);
    return xFunc;
}

void FuArea::DoExecute( SfxRequest& rReq )
{
    const SfxItemSet* pArgs = rReq.GetArgs();

    if( !pArgs )
    {
        // erst einmal alle eingabeparameter fuer den dialog retten
        SfxItemSet aInputAttr( pDoc->GetPool() );
        pView->GetAttributes( aInputAttr );

        const XFillStyleItem    &rIFillStyleItem    = (const XFillStyleItem &) aInputAttr.Get (XATTR_FILLSTYLE);
        const XFillColorItem    &rIFillColorItem    = (const XFillColorItem &) aInputAttr.Get (XATTR_FILLCOLOR);
        const XFillGradientItem &rIFillGradientItem = (const XFillGradientItem &) aInputAttr.Get (XATTR_FILLGRADIENT);
        const XFillHatchItem    &rIFillHatchItem    = (const XFillHatchItem &) aInputAttr.Get (XATTR_FILLHATCH);
        const XFillBitmapItem   &rIXFillBitmapItem  = (const XFillBitmapItem &) aInputAttr.Get (XATTR_FILLBITMAP);

        SfxItemSet* pNewAttr = new SfxItemSet( pDoc->GetPool() );
        pView->GetAttributes( *pNewAttr );

        //CHINA001 SvxAreaTabDialog* pDlg = new SvxAreaTabDialog( NULL, pNewAttr, pDoc, pView );
        SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
        DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001
        AbstractSvxAreaTabDialog * pDlg = pFact->CreateSvxAreaTabDialog( NULL,
                                                                        pNewAttr,
                                                                        pDoc,
                                                                        ResId(RID_SVXDLG_AREA),
                                                                        pView);
        DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
        if ( pDlg->Execute() == RET_OK )
        {
            pView->SetAttributes (*(pDlg->GetOutputItemSet ()));
        }

        // Attribute wurden geaendert, Listboxes in Objectbars muessen aktualisiert werden
        static USHORT SidArray[] = {
                        SID_ATTR_FILL_STYLE,
                        SID_ATTR_FILL_COLOR,
                        SID_ATTR_FILL_GRADIENT,
                        SID_ATTR_FILL_HATCH,
                        SID_ATTR_FILL_BITMAP,
                        0 };

        pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );

        delete pDlg;
        delete pNewAttr;
    }

    rReq.Ignore ();

}

void FuArea::Activate()
{
}

void FuArea::Deactivate()
{
}

} // end of namespace sd
<|endoftext|>


<commit_before>#include <stdexcept>
#include <limits>
#include <algorithm>
#include <array>
#include <memory>
#include <iomanip>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
//#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <system_error>

#include <openssl/md5.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
/*
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
*/

#ifndef EFU_CURLEASY_H
#include "curleasy.h"
#endif

#if defined(_WIN32) && !defined(EFU_WINERRORSTRING_H)
#include "win_error_string.hpp"
#endif

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

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

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

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

void make_dir(const std::string &path)
{
#ifdef _WIN32
    unsigned file_start = path.find_last_of("/\\");
    if (!CreateDirectory(path.substr(0, file_start).c_str(), nullptr))
    {
        WinErrorString wes;
        if (wes.code() != ERROR_ALREADY_EXISTS)
        {
            throw std::ios_base::failure("sdf" + wes.str());
        }
    }
#else
    auto elems = split(path, '/');
    std::string descend;
    for (size_t i = 0, k = elems.size() - 1; i < k; ++i)
    {
        const std::string &s(elems[i]);
        if (s.size() && s != ".")
        {
            descend.append((i > 0 ? "/" : "") + s);
            auto status = mkdir(descend.c_str(), S_IRWXU);
            if (status == -1)
            {
                std::error_code err(errno, std::generic_category());
                if (err != std::errc::file_exists)
                {
                    std::cout << "error making dir: "
                        << descend << ": "
                        << err.message() << std::endl;
                }
            }
        }
    }
#endif
}

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

        void fetch()
        {
            std::cout << "Statting target " << name() << "...";
            std::fstream fs(name(), std::ios_base::in);
            if (!fs.good())
            {
                fs.close();
                std::cout << " doesn't exist, creating new." << std::endl;
                make_dir(name());
                fs.open(name(), std::ios_base::out);
                if (!fs.good())
                {
                    fs.close();
                    std::cout << "Failed to create file: " << name() << std::endl;
                }
                else
                {
                    fs.close();
                    do_fetch();
                    return;
                }
            }
            if (fs.good())
            {
                fs.close();
                if (status() == Status::Current)
                {
                    std::cout << " already up to date." << std::endl;
                }
                else
                {
                    std::cout << " outdated, downloading new." << std::endl;
                    do_fetch();
                }
            }
        }
        Status status()
        {
            std::ifstream is(name());
            if (!is.good())
            {
                return Status::Nonexistent;
            }
            is.close();

            auto calcsum(file_checksum(name()));
            if (calcsum == checksum())
            {
                return Status::Current;
            }
            else
            {
                return Status::Outdated;
            }
        }

    private:
        void do_fetch()
        {
            std::ofstream ofs(name(), std::ios::binary);
            if (ofs.good())
            {
                std::string s;
                std::string url(patch_dir + name());
                CurlEasy curl(url);
                curl.write_to(s);
                curl.progressbar(true);
                curl.perform();

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

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

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

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

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

#ifdef CPP11_FOR_EACH
    for (const unsigned char c : result)
#else
    std::for_each(std::begin(result), std::end(result),
            [&calcsum](const unsigned char c)
#endif
    {
        calcsum << std::hex << std::setw(2)
            << static_cast<unsigned int>(c);
    }
#ifndef CPP11_FOR_EACH
    );
#endif

    return calcsum.str();
}

namespace Options
{
    bool version(const std::string &val)
    {
        return val == "version";
    }
    bool update_path(const std::string &val)
    {
        return val == "update path";
    }
};

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

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

        bool has_update()
        {
            if (m_has_update)
            {
                return m_has_update;
            }

            std::string fetch;
            CurlEasy curl(m_update_check.c_str());
            curl.write_to(fetch);
            //TODO
            try
            {
                curl.perform();
            }
            catch (CurlEasyException &e)
            {
                std::cout << e.what() << std::endl;
            }

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

            }
            return m_has_update;
        }

        bool get_update()
        {
            if (!m_has_update || m_update_path.empty())
            {
                return m_has_update = false;
            }
            return !(m_has_update = false);
        }

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

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

            if (old_targets.size())
            {
                std::cout << "Outdated targets: " << old_targets.size() << std::endl;
#ifdef CPP11_FOR_EACH
                for (auto &t : old_targets)
#else
                std::for_each(old_targets.cbegin(), old_targets.cend(),
                    [](const Target &t)
#endif
                {
                    std::cout << "- " << t.name() << std::endl;
                }
#ifndef CPP11_FOR_EACH
                );
#endif
            }
            else
            {
                std::cout << "No targets out of date." << std::endl;
            }

#ifndef DEBUG
#ifdef CPP11_FOR_EACH
            for (auto &t : old_targets)
#else
            std::for_each(old_targets.cbegin(), old_targets.cend(),
                [](Target &t)
#endif
            {
                t.fetch();
            }
#ifndef CPP11_FOR_EACH
            );

            std::for_each(old_targets.cbegin(), old_targets.cend(),
                [](Target &t)
#else
            for (auto &t : old_targets)
#endif
            {
                t.fetch();
            }
#ifndef CPP11_FOR_EACH
            );
#endif
#endif
        }

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

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

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

    EfuLauncher l(argv[0],
            "https://raw.github.com/commonquail/efulauncher/"\
            "master/versioncheck");

    if (l.has_update())
    {
        std::cout << "A new version of the launcher is available."\
            " Would you like to download it (y/n)?" << std::endl;
        bool download(confirm());
        if (!download)
        {
            std::cout << "It is strongly recommended to always use"\
                " the latest launcher. Would you like to download it (y/n)?"
                << std::endl;
            download = confirm();
        }
        if (download)
        {
            // Download.
            std::cout << "Downloading new launcher..." << std::endl;
            if (l.get_update())
            {
                std::cout << "Done. Please extract and run the new launcher." << std::endl;
            }
            return 0;
        }
    }

    try
    {
        l.stat_targets();
    }
    catch (std::exception &e)
    {
        std::cerr << e.what() << std::endl;
    }

    return 0;
}
<commit_msg>Add a TODO I'm sick of seeing in git diff.<commit_after>#include <stdexcept>
#include <limits>
#include <algorithm>
#include <array>
#include <memory>
#include <iomanip>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
//#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <system_error>

#include <openssl/md5.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
/*
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
*/

#ifndef EFU_CURLEASY_H
#include "curleasy.h"
#endif

#if defined(_WIN32) && !defined(EFU_WINERRORSTRING_H)
#include "win_error_string.hpp"
#endif

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

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

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

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

void make_dir(const std::string &path)
{
#ifdef _WIN32
    unsigned file_start = path.find_last_of("/\\");
    if (!CreateDirectory(path.substr(0, file_start).c_str(), nullptr))
    {
        WinErrorString wes;
        if (wes.code() != ERROR_ALREADY_EXISTS)
        {
            throw std::ios_base::failure("sdf" + wes.str());
        }
    }
#else
    auto elems = split(path, '/');
    std::string descend;
    for (size_t i = 0, k = elems.size() - 1; i < k; ++i)
    {
        const std::string &s(elems[i]);
        if (s.size() && s != ".")
        {
            descend.append((i > 0 ? "/" : "") + s);
            auto status = mkdir(descend.c_str(), S_IRWXU);
            if (status == -1)
            {
                std::error_code err(errno, std::generic_category());
                if (err != std::errc::file_exists)
                {
                    std::cout << "error making dir: "
                        << descend << ": "
                        << err.message() << std::endl;
                }
            }
        }
    }
#endif
}

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

        void fetch()
        {
            std::cout << "Statting target " << name() << "...";
            std::fstream fs(name(), std::ios_base::in);
            if (!fs.good())
            {
                fs.close();
                std::cout << " doesn't exist, creating new." << std::endl;
                make_dir(name());
                fs.open(name(), std::ios_base::out);
                if (!fs.good())
                {
                    fs.close();
                    std::cout << "Failed to create file: " << name() << std::endl;
                }
                else
                {
                    fs.close();
                    do_fetch();
                    return;
                }
            }
            if (fs.good())
            {
                fs.close();
                if (status() == Status::Current)
                {
                    std::cout << " already up to date." << std::endl;
                }
                else
                {
                    std::cout << " outdated, downloading new." << std::endl;
                    do_fetch();
                }
            }
        }
        Status status()
        {
            std::ifstream is(name());
            if (!is.good())
            {
                return Status::Nonexistent;
            }
            is.close();

            auto calcsum(file_checksum(name()));
            if (calcsum == checksum())
            {
                return Status::Current;
            }
            else
            {
                return Status::Outdated;
            }
        }

    private:
        void do_fetch()
        {
            std::ofstream ofs(name(), std::ios::binary);
            if (ofs.good())
            {
                std::string s;
                std::string url(patch_dir + name());
                CurlEasy curl(url);
                curl.write_to(s);
                curl.progressbar(true);
                curl.perform();

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

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

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

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

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

#ifdef CPP11_FOR_EACH
    for (const unsigned char c : result)
#else
    std::for_each(std::begin(result), std::end(result),
            [&calcsum](const unsigned char c)
#endif
    {
        calcsum << std::hex << std::setw(2)
            << static_cast<unsigned int>(c);
    }
#ifndef CPP11_FOR_EACH
    );
#endif

    return calcsum.str();
}

namespace Options
{
    bool version(const std::string &val)
    {
        return val == "version";
    }
    bool update_path(const std::string &val)
    {
        return val == "update path";
    }
};

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

class EfuLauncher
{
    public:
    // TODO: assignment, copy operator
        explicit EfuLauncher(const std::string path,
                const std::string update_check):
            m_path(path),
            m_update_check(update_check),
            m_has_update(false)
    {}

        bool has_update()
        {
            if (m_has_update)
            {
                return m_has_update;
            }

            std::string fetch;
            CurlEasy curl(m_update_check.c_str());
            curl.write_to(fetch);
            //TODO
            try
            {
                curl.perform();
            }
            catch (CurlEasyException &e)
            {
                std::cout << e.what() << std::endl;
            }

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

            }
            return m_has_update;
        }

        bool get_update()
        {
            if (!m_has_update || m_update_path.empty())
            {
                return m_has_update = false;
            }
            return !(m_has_update = false);
        }

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

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

            if (old_targets.size())
            {
                std::cout << "Outdated targets: " << old_targets.size() << std::endl;
#ifdef CPP11_FOR_EACH
                for (auto &t : old_targets)
#else
                std::for_each(old_targets.cbegin(), old_targets.cend(),
                    [](const Target &t)
#endif
                {
                    std::cout << "- " << t.name() << std::endl;
                }
#ifndef CPP11_FOR_EACH
                );
#endif
            }
            else
            {
                std::cout << "No targets out of date." << std::endl;
            }

#ifndef DEBUG
#ifdef CPP11_FOR_EACH
            for (auto &t : old_targets)
#else
            std::for_each(old_targets.cbegin(), old_targets.cend(),
                [](Target &t)
#endif
            {
                t.fetch();
            }
#ifndef CPP11_FOR_EACH
            );

            std::for_each(old_targets.cbegin(), old_targets.cend(),
                [](Target &t)
#else
            for (auto &t : old_targets)
#endif
            {
                t.fetch();
            }
#ifndef CPP11_FOR_EACH
            );
#endif
#endif
        }

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

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

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

    EfuLauncher l(argv[0],
            "https://raw.github.com/commonquail/efulauncher/"\
            "master/versioncheck");

    if (l.has_update())
    {
        std::cout << "A new version of the launcher is available."\
            " Would you like to download it (y/n)?" << std::endl;
        bool download(confirm());
        if (!download)
        {
            std::cout << "It is strongly recommended to always use"\
                " the latest launcher. Would you like to download it (y/n)?"
                << std::endl;
            download = confirm();
        }
        if (download)
        {
            // Download.
            std::cout << "Downloading new launcher..." << std::endl;
            if (l.get_update())
            {
                std::cout << "Done. Please extract and run the new launcher." << std::endl;
            }
            return 0;
        }
    }

    try
    {
        l.stat_targets();
    }
    catch (std::exception &e)
    {
        std::cerr << e.what() << std::endl;
    }

    return 0;
}
<|endoftext|>