<commit_before>//
// Created by salmon on 17-10-11.
//

#include "simpla/SIMPLA_config.h"

#include <simpla/application/SPInit.h>
#include <simpla/geometry/BoxUtilities.h>
#include <simpla/geometry/Cube.h>
#include <simpla/geometry/csCartesian.h>
#include <simpla/mesh/CoRectMesh.h>
#include <simpla/mesh/EBMesh.h>
#include <simpla/mesh/RectMesh.h>
#include <simpla/predefine/engine/SimpleTimeIntegrator.h>
#include <simpla/predefine/physics/Maxwell.h>
#include <simpla/predefine/physics/PML.h>
#include <simpla/scheme/FVM.h>
#include <simpla/utilities/Logo.h>
#include <simpla/utilities/parse_command_line.h>
namespace simpla {
using SimpleMaxwell = domain::Maxwell<engine::Domain<geometry::csCartesian, scheme::FVM, mesh::CoRectMesh>>;
using SimplePML = domain::PML<engine::Domain<geometry::csCartesian, scheme::FVM, mesh::CoRectMesh>>;

}  // namespace simpla {

using namespace simpla;
using namespace simpla::engine;

int main(int argc, char **argv) {
    size_type num_of_step = 10;
    size_type checkpoint_interval = 1;
    simpla::parse_cmd_line(  //
        argc, argv, [&](std::string const &opt, std::string const &value) -> int {
            if (false) {
            } else if (opt == "n") {
                num_of_step = static_cast<size_type>(std::atoi(value.c_str()));
            } else if (opt == "checkpoint") {
                checkpoint_interval = static_cast<size_type>(std::atoi(value.c_str()));
            }
            return CONTINUE;
        });

    simpla::Initialize(argc, argv);
    auto scenario = SimpleTimeIntegrator::New();
    scenario->SetName("MultiDomain");

    scenario->GetAtlas()->SetOrigin({0, 0, 0});
    scenario->GetAtlas()->SetGridWidth({1, 1, 1});
    scenario->GetAtlas()->SetPeriodicDimensions({1, 1, 1});

    scenario->GetAtlas()->NewChart<simpla::geometry::csCartesian>();

    auto center = scenario->NewDomain<SimpleMaxwell>("Center");
    center->SetBoundary(geometry::Cube::New(box_type{{-15, -25, -20}, {15, 25, 20}}));
    center->PostInitialCondition.Connect([=](DomainBase *self, Real time_now) {
        if (auto d = dynamic_cast<SimpleMaxwell *>(self)) {
            d->B = [&](point_type const &x) {

                return point_type{std::sin(2 * PI * x[1] / 50) * std::sin(2 * PI * x[2] / 40),
                                  std::sin(2 * PI * x[0] / 30) * std::sin(2 * PI * x[2] / 40),
                                  std::sin(2 * PI * x[0] / 30) * std::sin(2 * PI * x[1] / 50)};
            };
        }
    });
    //    scenario->NewDomain<SimpleMaxwell>("boundary0")
    //        ->SetBoundary(geometry::Cube::New(box_type{{-20, -25, -20}, {-15, 25, 20}}));
    //    scenario->NewDomain<SimpleMaxwell>("boundary1")
    //        ->SetBoundary(geometry::Cube::New(box_type{{15, -25, -20}, {20, 25, 20}}));
    auto pml = scenario->NewDomain<SimplePML>("PML");
    pml->SetBoundingBox(box_type{{-20, -25, -20}, {20, 25, 20}});
    pml->SetCenterBox(center->GetBoundingBox());

    scenario->SetTimeEnd(1.0e-8);
    scenario->SetMaxStep(num_of_step);
    scenario->SetUp();

    if (auto atlas = scenario->GetAtlas()) {
        scenario->GetAtlas()->Decompose({3, 3, 3});
        auto c_box = center->GetBoundingBox();
        auto box_list = geometry::HaloBoxDecompose(
            atlas->GetIndexBox(),
            std::make_tuple(std::get<1>(atlas->GetChart()->invert_local_coordinates(std::get<0>(c_box))),
                            std::get<1>(atlas->GetChart()->invert_local_coordinates(std::get<1>(c_box)))));
        for (auto const &b : box_list) { atlas->AddPatch(b); }
    }

    scenario->ConfigureAttribute<size_type>("E", "CheckPoint", checkpoint_interval);
    scenario->ConfigureAttribute<size_type>("B", "CheckPoint", checkpoint_interval);
    //    scenario->ConfigureAttribute<size_type>("a0", "CheckPoint", 1);
    //    scenario->ConfigureAttribute<size_type>("a1", "CheckPoint", 1);
    //    scenario->ConfigureAttribute<size_type>("a2", "CheckPoint", 1);
    //    scenario->ConfigureAttribute<size_type>("s0", "CheckPoint", 1);
    //    scenario->ConfigureAttribute<size_type>("s1", "CheckPoint", 1);
    //    scenario->ConfigureAttribute<size_type>("s2", "CheckPoint", 1);
    VERBOSE << "Scenario: " << *scenario->Serialize();
    TheStart();
    scenario->Run();
    TheEnd();

    scenario->TearDown();
    simpla::Finalize();
}<commit_msg>MultiDomain success;PML fail<commit_after>//
// Created by salmon on 17-10-11.
//

#include "simpla/SIMPLA_config.h"

#include <simpla/application/SPInit.h>
#include <simpla/geometry/BoxUtilities.h>
#include <simpla/geometry/Cube.h>
#include <simpla/geometry/csCartesian.h>
#include <simpla/mesh/CoRectMesh.h>
#include <simpla/mesh/EBMesh.h>
#include <simpla/mesh/RectMesh.h>
#include <simpla/predefine/engine/SimpleTimeIntegrator.h>
#include <simpla/predefine/physics/Maxwell.h>
#include <simpla/predefine/physics/PML.h>
#include <simpla/scheme/FVM.h>
#include <simpla/utilities/Logo.h>
#include <simpla/utilities/parse_command_line.h>
namespace simpla {
using SimpleMaxwell = domain::Maxwell<engine::Domain<geometry::csCartesian, scheme::FVM, mesh::CoRectMesh>>;
using SimplePML = domain::PML<engine::Domain<geometry::csCartesian, scheme::FVM, mesh::CoRectMesh>>;

}  // namespace simpla {

using namespace simpla;
using namespace simpla::engine;

int main(int argc, char **argv) {
    size_type num_of_step = 10;
    size_type checkpoint_interval = 1;
    simpla::parse_cmd_line(  //
        argc, argv, [&](std::string const &opt, std::string const &value) -> int {
            if (false) {
            } else if (opt == "n") {
                num_of_step = static_cast<size_type>(std::atoi(value.c_str()));
            } else if (opt == "checkpoint") {
                checkpoint_interval = static_cast<size_type>(std::atoi(value.c_str()));
            }
            return CONTINUE;
        });

    simpla::Initialize(argc, argv);
    auto scenario = SimpleTimeIntegrator::New();
    scenario->SetName("MultiDomain");

    scenario->GetAtlas()->SetOrigin({0, 0, 0});
    scenario->GetAtlas()->SetGridWidth({1, 1, 1});
    scenario->GetAtlas()->SetPeriodicDimensions({1, 1, 1});

    scenario->GetAtlas()->NewChart<simpla::geometry::csCartesian>();

    auto center = scenario->NewDomain<SimpleMaxwell>("Center");
    center->SetBoundary(geometry::Cube::New(box_type{{-15, -25, -20}, {15, 25, 20}}));
    center->PostInitialCondition.Connect([=](DomainBase *self, Real time_now) {
        if (auto d = dynamic_cast<SimpleMaxwell *>(self)) {
            d->B = [&](point_type const &x) {

                return point_type{std::sin(2 * PI * x[1] / 50) * std::sin(2 * PI * x[2] / 40),
                                  std::sin(2 * PI * x[0] / 30) * std::sin(2 * PI * x[2] / 40),
                                  std::sin(2 * PI * x[0] / 30) * std::sin(2 * PI * x[1] / 50)};
            };
        }
    });
        scenario->NewDomain<SimpleMaxwell>("boundary0")
            ->SetBoundary(geometry::Cube::New(box_type{{-20, -25, -20}, {-15, 25, 20}}));
        scenario->NewDomain<SimpleMaxwell>("boundary1")
            ->SetBoundary(geometry::Cube::New(box_type{{15, -25, -20}, {20, 25, 20}}));
//    auto pml = scenario->NewDomain<SimplePML>("PML");
//    pml->SetBoundingBox(box_type{{-20, -25, -20}, {20, 25, 20}});
//    pml->SetCenterBox(center->GetBoundingBox());

    scenario->SetTimeEnd(1.0e-8);
    scenario->SetMaxStep(num_of_step);
    scenario->SetUp();

    if (auto atlas = scenario->GetAtlas()) {
        scenario->GetAtlas()->Decompose({3, 3, 3});
        auto c_box = center->GetBoundingBox();
        auto box_list = geometry::HaloBoxDecompose(
            atlas->GetIndexBox(),
            std::make_tuple(std::get<1>(atlas->GetChart()->invert_local_coordinates(std::get<0>(c_box))),
                            std::get<1>(atlas->GetChart()->invert_local_coordinates(std::get<1>(c_box)))));
        for (auto const &b : box_list) { atlas->AddPatch(b); }
    }

    scenario->ConfigureAttribute<size_type>("E", "CheckPoint", checkpoint_interval);
    scenario->ConfigureAttribute<size_type>("B", "CheckPoint", checkpoint_interval);
    //    scenario->ConfigureAttribute<size_type>("a0", "CheckPoint", 1);
    //    scenario->ConfigureAttribute<size_type>("a1", "CheckPoint", 1);
    //    scenario->ConfigureAttribute<size_type>("a2", "CheckPoint", 1);
    //    scenario->ConfigureAttribute<size_type>("s0", "CheckPoint", 1);
    //    scenario->ConfigureAttribute<size_type>("s1", "CheckPoint", 1);
    //    scenario->ConfigureAttribute<size_type>("s2", "CheckPoint", 1);
    VERBOSE << "Scenario: " << *scenario->Serialize();
    TheStart();
    scenario->Run();
    TheEnd();

    scenario->TearDown();
    simpla::Finalize();
}<|endoftext|>


<commit_before>//Author: Julian Yi
//Date Started: 14 July 2017, Friday.
//Purpose: This is a project to create a working chess engine and gui using C++.
//File: This is the main file.
#include <iostream>
#include "board.h"
#include "pawn.h"
#include "knight.h"
#include "bishop.h"
#include "coord.h"
#include "ui.h"
#include "BearLibTerminal.h"

void handleInput(board& Chessboard);

int main()
{
	// Initialize board.
	auto Chessboard = std::make_shared<board>();
	Chessboard->initializeBoard();

	for (int i = 0; i < 8; i++) {
		Chessboard->placePiece(PieceType::Pawn, {i, 1}, TeamColor::White);
	}

	Chessboard->placePiece(PieceType::Rook, {0, 0}, TeamColor::White);
	Chessboard->placePiece(PieceType::Rook, {7, 0}, TeamColor::White);
	Chessboard->placePiece(PieceType::Knight, {1, 0}, TeamColor::White);
	Chessboard->placePiece(PieceType::Knight, {6, 0}, TeamColor::White);
	Chessboard->placePiece(PieceType::Bishop, {2, 0}, TeamColor::White);
	Chessboard->placePiece(PieceType::Bishop, {5, 0}, TeamColor::White);
	Chessboard->placePiece(PieceType::Queen, {3, 0}, TeamColor::White);
	Chessboard->placePiece(PieceType::King, { 4,0 }, TeamColor::White);

	for (int i = 0; i < 8; i++) {
		Chessboard->placePiece(PieceType::Pawn, {i, 6}, TeamColor::Black);
	}
	Chessboard->placePiece(PieceType::Rook, {0, 7}, TeamColor::Black);
	Chessboard->placePiece(PieceType::Rook, {7, 7}, TeamColor::Black);
	Chessboard->placePiece(PieceType::Knight, {1, 7}, TeamColor::Black);
	Chessboard->placePiece(PieceType::Knight, {6, 7}, TeamColor::Black);
	Chessboard->placePiece(PieceType::Bishop, {2, 7}, TeamColor::Black);
	Chessboard->placePiece(PieceType::Bishop, {5, 7}, TeamColor::Black);
	Chessboard->placePiece(PieceType::Queen, {3, 7}, TeamColor::Black);
	Chessboard->placePiece(PieceType::King, { 4,7 }, TeamColor::Black);

	Chessboard->placePiece(PieceType::Pawn, { 2,3 }, TeamColor::Black);

	Chessboard->movePiece({ 1,1 }, { 1,2 }); //success
	Chessboard->movePiece({ 1,2 }, { 2,3 }); //success
	Chessboard->movePiece({ 2,3 }, { 3,3 }); //fail

	Chessboard->placePiece(PieceType::Pawn, { 3,4 }, TeamColor::Black);
	Chessboard->movePiece({ 3,4 }, { 2,3 }); //success

	Chessboard->placePiece(PieceType::Pawn, { 1,2 }, TeamColor::White);
	Chessboard->movePiece({ 2,3 }, { 1,2 });
	//Chessboard->movePiece({ 1,2 }, { 0,1 });
	//Chessboard->movePiece({ 0,1 }, { 1,0 });
	//Chessboard->movePiece({ 1,1 }, { 1,0 });

	/*
	it all works
	// Test an attack.
	// Expected Output : success, knight is destroyed
	Chessboard->movePiece({3, 4}, {1, 2});

	// Test creating a piece into the occupied coordinate (same color)
	// Expected Output : failure
	Chessboard->placePiece(PieceType::Rook, { 3,3 }, TeamColor::White);
	Chessboard->placePiece(PieceType::Pawn, { 3,3 }, TeamColor::White);

	// Test creating a piece into the occupied coordinate (different color)
	// Expected Output : failure
	Chessboard->deletePiece({ 3,3 });
	Chessboard->placePiece(PieceType::Pawn, { 3,3 }, TeamColor::White);
	Chessboard->placePiece(PieceType::Bishop, { 3,3 }, TeamColor::Black);

	// Test Moving a piece into the occupied coordinate (same color)
	// Expected Output : failure
	Chessboard->placePiece(PieceType::Pawn, { 3,2 }, TeamColor::White);
	Chessboard->movePiece({ 3,2 }, { 3,3 });
	*/

	// Test Pawn's valid moves

	// Open the terminal. Since no terminal_set() method is called,
	// the terminal will use default settings.
	terminal_open();

	// Font setup. ./font/FSEX300.ttf
	terminal_set("window: title='Chess', size='46x24'; font: ./font/FSEX300.ttf, size=32x32");

	// Palette.
	terminal_set("palette: whitepiece=#C2CCCF, blackpiece=#4D483C, whitetile=#02171F, blacktile=#000000;");

	terminal_set(
	    "input:"
	    "cursor-symbol = 0x1F,"
	    "cursor-blink-rate = 500,"
	    "precise-mouse = false,"
	    "mouse-cursor = true,"
	    "filter=[keyboard, mouse];"
	);

	// Print intro text.
	terminal_print(1, 1, "Chess Engine");
	terminal_print(4, 2, "by Julian Yi, Sean Brock, and Simon Kim");
	terminal_print(1, 4, "Press Enter to start...");
	terminal_refresh();

	// Create UI manager
	ui UIManager;
	// Register the chessboard in a board element.
	UIManager.addElement(std::make_shared<boardElement>(Chessboard), { 2, 5 });

	//roughdraft until I figure out a better way to do this
	int mouseClicks = 0;
	int xCursor = 0;
	int yCursor = 0;
	coord current = {0, 0};
	coord next = {0, 0};
	bool clicked = false;

	bool running = true;
	coord boardOffset{ 2, 5 };

	while (running) {
 		// Check for input. termnial_read() is blocking, meaning the
		// program will wait until it reads a key press.
		auto key = terminal_read();
		// Reset the terminal to blank state.
		terminal_clear();

		// Text goes on layer 3.
		terminal_layer(3);

		// Print instructions.
		//terminal_print(1, 1, "Press Enter to start...");

		// Handle key presses.
		switch (key) {
			case TK_CLOSE:
				running = false;
				break;
			case TK_ESCAPE:
				running = false;
				break;
			case TK_ENTER:
				break;
			case TK_MOUSE_MOVE:
				xCursor = terminal_state(TK_MOUSE_X);
		 		yCursor = terminal_state(TK_MOUSE_Y);
				break;
			case TK_MOUSE_LEFT:
				mouseClicks++; //amount of time something is clicked

				//if the clicked square has something then set the object clicked flag to true and set the current coordinate
				if (Chessboard->isOccupied({ (xCursor - boardOffset.x), (yCursor - boardOffset.y) }) == true && (mouseClicks == 1))
				{
					current = { (xCursor - boardOffset.x), (yCursor - boardOffset.y) };
					std::cout << "first click" << current.x << "," << current.y << std::endl;
					clicked = true;
					std::cout << mouseClicks;
				}
				//if clicked flag is false and there is nothing on the board don't do anything
				else if(Chessboard->isOccupied({ (xCursor - boardOffset.x), (yCursor - boardOffset.y) }) == false && clicked == false)
				{
					current = { -1, -1 };
					std::cout << "nothing was clicked" << std::endl;
					mouseClicks = 0;
				}
				//mouseClicks has to be higher than 1 to perform the move function. clicked flag also has to be true
				//handles move
				if(clicked == true && mouseClicks > 1)
				{
					//do something with that piece
					next = {(xCursor - boardOffset.x), (yCursor - boardOffset.y)};
					std::cout << "second click" << next.x << "," << next.y << std::endl;
					Chessboard->movePiece(current, next);
					clicked = false;
					std::cout << mouseClicks;
					mouseClicks = 0;
				}
				break;
			default:
				terminal_print(1, 2, "The key pressed has no function.");
				break;
		}

		// Draw board
		UIManager.draw();

		if((2 <= xCursor && xCursor <=9) && (5 <= yCursor && yCursor <= 12))
		{
			int select = 0x02C7;
			terminal_layer(2);
			terminal_color(color_from_name("green"));
			terminal_put(xCursor, yCursor, select);
		}

			 	//TK_MOUSE_CLICK
		//set the flag
		//flag true then call something.
		/*
		if (key == TK_MOUSE_LEFT)
		{
			int mouseClicks = terminal_state(TK_MOUSE_LEFT);
			if(mouseClicks == 1)
			{
				//select the piece
				current = {(xCursor - boardOffset.x), (yCursor - boardOffset.y)};
				std::cout << "first click" << current.x << "," << current.y << std::endl;
			}
			else if(mouseClicks == 2)
			{
				//do something with that piece
				next = {(xCursor - boardOffset.x), (yCursor - boardOffset.y)};
				std::cout << "second click" << next.x << "," << next.y << std::endl;
				Chessboard->movePiece(current, next);
			}
		}
		*/

		// Commit the buffer and draw it.
		// Move to ui manager eventually.
		terminal_refresh();

	}

	// We're done here.
	terminal_close();

	return 0;
}
<commit_msg>CRLF to LF<commit_after>//Author: Julian Yi
//Date Started: 14 July 2017, Friday.
//Purpose: This is a project to create a working chess engine and gui using C++.
//File: This is the main file.
#include <iostream>
#include "board.h"
#include "pawn.h"
#include "knight.h"
#include "bishop.h"
#include "coord.h"
#include "ui.h"
#include "BearLibTerminal.h"

void handleInput(board& Chessboard);

int main()
{
	// Initialize board.
	auto Chessboard = std::make_shared<board>();
	Chessboard->initializeBoard();

	for (int i = 0; i < 8; i++) {
		Chessboard->placePiece(PieceType::Pawn, {i, 1}, TeamColor::White);
	}

	Chessboard->placePiece(PieceType::Rook, {0, 0}, TeamColor::White);
	Chessboard->placePiece(PieceType::Rook, {7, 0}, TeamColor::White);
	Chessboard->placePiece(PieceType::Knight, {1, 0}, TeamColor::White);
	Chessboard->placePiece(PieceType::Knight, {6, 0}, TeamColor::White);
	Chessboard->placePiece(PieceType::Bishop, {2, 0}, TeamColor::White);
	Chessboard->placePiece(PieceType::Bishop, {5, 0}, TeamColor::White);
	Chessboard->placePiece(PieceType::Queen, {3, 0}, TeamColor::White);
	Chessboard->placePiece(PieceType::King, { 4,0 }, TeamColor::White);

	for (int i = 0; i < 8; i++) {
		Chessboard->placePiece(PieceType::Pawn, {i, 6}, TeamColor::Black);
	}
	Chessboard->placePiece(PieceType::Rook, {0, 7}, TeamColor::Black);
	Chessboard->placePiece(PieceType::Rook, {7, 7}, TeamColor::Black);
	Chessboard->placePiece(PieceType::Knight, {1, 7}, TeamColor::Black);
	Chessboard->placePiece(PieceType::Knight, {6, 7}, TeamColor::Black);
	Chessboard->placePiece(PieceType::Bishop, {2, 7}, TeamColor::Black);
	Chessboard->placePiece(PieceType::Bishop, {5, 7}, TeamColor::Black);
	Chessboard->placePiece(PieceType::Queen, {3, 7}, TeamColor::Black);
	Chessboard->placePiece(PieceType::King, { 4,7 }, TeamColor::Black);

	Chessboard->placePiece(PieceType::Pawn, { 2,3 }, TeamColor::Black);

	Chessboard->movePiece({ 1,1 }, { 1,2 }); //success
	Chessboard->movePiece({ 1,2 }, { 2,3 }); //success
	Chessboard->movePiece({ 2,3 }, { 3,3 }); //fail

	Chessboard->placePiece(PieceType::Pawn, { 3,4 }, TeamColor::Black);
	Chessboard->movePiece({ 3,4 }, { 2,3 }); //success

	Chessboard->placePiece(PieceType::Pawn, { 1,2 }, TeamColor::White);
	Chessboard->movePiece({ 2,3 }, { 1,2 });
	//Chessboard->movePiece({ 1,2 }, { 0,1 });
	//Chessboard->movePiece({ 0,1 }, { 1,0 });
	//Chessboard->movePiece({ 1,1 }, { 1,0 });

	/*
	it all works
	// Test an attack.
	// Expected Output : success, knight is destroyed
	Chessboard->movePiece({3, 4}, {1, 2});

	// Test creating a piece into the occupied coordinate (same color)
	// Expected Output : failure
	Chessboard->placePiece(PieceType::Rook, { 3,3 }, TeamColor::White);
	Chessboard->placePiece(PieceType::Pawn, { 3,3 }, TeamColor::White);

	// Test creating a piece into the occupied coordinate (different color)
	// Expected Output : failure
	Chessboard->deletePiece({ 3,3 });
	Chessboard->placePiece(PieceType::Pawn, { 3,3 }, TeamColor::White);
	Chessboard->placePiece(PieceType::Bishop, { 3,3 }, TeamColor::Black);

	// Test Moving a piece into the occupied coordinate (same color)
	// Expected Output : failure
	Chessboard->placePiece(PieceType::Pawn, { 3,2 }, TeamColor::White);
	Chessboard->movePiece({ 3,2 }, { 3,3 });
	*/

	// Test Pawn's valid moves

	// Open the terminal. Since no terminal_set() method is called,
	// the terminal will use default settings.
	terminal_open();

	// Font setup. ./font/FSEX300.ttf
	terminal_set("window: title='Chess', size='46x24'; font: ./font/FSEX300.ttf, size=32x32");

	// Palette.
	terminal_set("palette: whitepiece=#C2CCCF, blackpiece=#4D483C, whitetile=#02171F, blacktile=#000000;");

	terminal_set(
	    "input:"
	    "cursor-symbol = 0x1F,"
	    "cursor-blink-rate = 500,"
	    "precise-mouse = false,"
	    "mouse-cursor = true,"
	    "filter=[keyboard, mouse];"
	);

	// Print intro text.
	terminal_print(1, 1, "Chess Engine");
	terminal_print(4, 2, "by Julian Yi, Sean Brock, and Simon Kim");
	terminal_print(1, 4, "Press Enter to start...");
	terminal_refresh();

	// Create UI manager
	ui UIManager;
	// Register the chessboard in a board element.
	UIManager.addElement(std::make_shared<boardElement>(Chessboard), { 2, 5 });

	//roughdraft until I figure out a better way to do this
	int mouseClicks = 0;
	int xCursor = 0;
	int yCursor = 0;
	coord current = {0, 0};
	coord next = {0, 0};
	bool clicked = false;

	bool running = true;
	coord boardOffset{ 2, 5 };

	while (running) {
 		// Check for input. termnial_read() is blocking, meaning the
		// program will wait until it reads a key press.
		auto key = terminal_read();
		// Reset the terminal to blank state.
		terminal_clear();

		// Text goes on layer 3.
		terminal_layer(3);

		// Print instructions.
		//terminal_print(1, 1, "Press Enter to start...");

		// Handle key presses.
		switch (key) {
			case TK_CLOSE:
				running = false;
				break;
			case TK_ESCAPE:
				running = false;
				break;
			case TK_ENTER:
				break;
			case TK_MOUSE_MOVE:
				xCursor = terminal_state(TK_MOUSE_X);
		 		yCursor = terminal_state(TK_MOUSE_Y);
				break;
			case TK_MOUSE_LEFT:
				mouseClicks++; //amount of time something is clicked

				//if the clicked square has something then set the object clicked flag to true and set the current coordinate
				if (Chessboard->occupied({ (xCursor - boardOffset.x), (yCursor - boardOffset.y) }) == true && (mouseClicks == 1))
				{
					current = { (xCursor - boardOffset.x), (yCursor - boardOffset.y) };
					std::cout << "first click" << current.x << "," << current.y << std::endl;
					clicked = true;
					std::cout << mouseClicks;
				}
				//if clicked flag is false and there is nothing on the board don't do anything
				else if(Chessboard->occupied({ (xCursor - boardOffset.x), (yCursor - boardOffset.y) }) == false && clicked == false)
				{
					current = { -1, -1 };
					std::cout << "nothing was clicked" << std::endl;
					mouseClicks = 0;
				}
				//mouseClicks has to be higher than 1 to perform the move function. clicked flag also has to be true
				//handles move
				if(clicked == true && mouseClicks > 1)
				{
					//do something with that piece
					next = {(xCursor - boardOffset.x), (yCursor - boardOffset.y)};
					std::cout << "second click" << next.x << "," << next.y << std::endl;
					Chessboard->movePiece(current, next);
					clicked = false;
					std::cout << mouseClicks;
					mouseClicks = 0;
				}
				break;
			default:
				terminal_print(1, 2, "The key pressed has no function.");
				break;
		}

		// Draw board
		UIManager.draw();

		if((2 <= xCursor && xCursor <=9) && (5 <= yCursor && yCursor <= 12))
		{
			int select = 0x02C7;
			terminal_layer(2);
			terminal_color(color_from_name("green"));
			terminal_put(xCursor, yCursor, select);
		}

			 	//TK_MOUSE_CLICK
		//set the flag
		//flag true then call something.
		/*
		if (key == TK_MOUSE_LEFT)
		{
			int mouseClicks = terminal_state(TK_MOUSE_LEFT);
			if(mouseClicks == 1)
			{
				//select the piece
				current = {(xCursor - boardOffset.x), (yCursor - boardOffset.y)};
				std::cout << "first click" << current.x << "," << current.y << std::endl;
			}
			else if(mouseClicks == 2)
			{
				//do something with that piece
				next = {(xCursor - boardOffset.x), (yCursor - boardOffset.y)};
				std::cout << "second click" << next.x << "," << next.y << std::endl;
				Chessboard->movePiece(current, next);
			}
		}
		*/

		// Commit the buffer and draw it.
		// Move to ui manager eventually.
		terminal_refresh();

	}

	// We're done here.
	terminal_close();

	return 0;
}
<|endoftext|>


<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "unittest/gtest.hpp"

#include "clustering/immediate_consistency/branch/broadcaster.hpp"
#include "clustering/immediate_consistency/branch/listener.hpp"
#include "clustering/immediate_consistency/branch/replier.hpp"
#include "memcached/protocol.hpp"
#include "unittest/branch_history_manager.hpp"
#include "unittest/clustering_utils.hpp"
#include "unittest/unittest_utils.hpp"
#include "unittest/dummy_metadata_controller.hpp"

namespace unittest {

void run_with_broadcaster(
        boost::function< void(io_backender_t *,
                              simple_mailbox_cluster_t *,
                              branch_history_manager_t<memcached_protocol_t> *,
                              clone_ptr_t<watchable_t<boost::optional<boost::optional<broadcaster_business_card_t<memcached_protocol_t> > > > >,
                              scoped_ptr_t<broadcaster_t<memcached_protocol_t> > *,
                              test_store_t<memcached_protocol_t> *,
                              scoped_ptr_t<listener_t<memcached_protocol_t> > *,
                              order_source_t *)> fun) {
    order_source_t order_source;

    /* Set up a cluster so mailboxes can be created */
    simple_mailbox_cluster_t cluster;

    /* Set up branch history manager */
    in_memory_branch_history_manager_t<memcached_protocol_t> branch_history_manager;

    // io backender
    io_backender_t io_backender(file_direct_io_mode_t::buffered_desired);

    /* Set up a broadcaster and initial listener */
    test_store_t<memcached_protocol_t> initial_store(&io_backender, &order_source, static_cast<memcached_protocol_t::context_t *>(NULL));
    cond_t interruptor;

    scoped_ptr_t<broadcaster_t<memcached_protocol_t> > broadcaster(
        new broadcaster_t<memcached_protocol_t>(
            cluster.get_mailbox_manager(),
            &branch_history_manager,
            &initial_store.store,
            &get_global_perfmon_collection(),
            &order_source,
            &interruptor));

    watchable_variable_t<boost::optional<boost::optional<broadcaster_business_card_t<memcached_protocol_t> > > > broadcaster_business_card_watchable_variable(boost::optional<boost::optional<broadcaster_business_card_t<memcached_protocol_t> > >(boost::optional<broadcaster_business_card_t<memcached_protocol_t> >(broadcaster->get_business_card())));

    scoped_ptr_t<listener_t<memcached_protocol_t> > initial_listener(
        new listener_t<memcached_protocol_t>(base_path_t("."),
                                             &io_backender,
                                             cluster.get_mailbox_manager(),
                                             broadcaster_business_card_watchable_variable.get_watchable(),
                                             &branch_history_manager,
                                             broadcaster.get(),
                                             &get_global_perfmon_collection(),
                                             &interruptor,
                                             &order_source));

    fun(&io_backender,
        &cluster,
        &branch_history_manager,
        broadcaster_business_card_watchable_variable.get_watchable(),
        &broadcaster,
        &initial_store,
        &initial_listener,
        &order_source);
}

void run_in_thread_pool_with_broadcaster(
        boost::function< void(io_backender_t *,
                              simple_mailbox_cluster_t *,
                              branch_history_manager_t<memcached_protocol_t> *,
                              clone_ptr_t<watchable_t<boost::optional<boost::optional<broadcaster_business_card_t<memcached_protocol_t> > > > >,
                              scoped_ptr_t<broadcaster_t<memcached_protocol_t> > *,
                              test_store_t<memcached_protocol_t> *,
                              scoped_ptr_t<listener_t<memcached_protocol_t> > *,
                              order_source_t *)> fun)
{
    unittest::run_in_thread_pool(boost::bind(&run_with_broadcaster, fun));
}

/* `PartialBackfill` backfills only in a specific sub-region. */

void write_to_broadcaster(broadcaster_t<memcached_protocol_t> *broadcaster, const std::string& key, const std::string& value, order_token_t otok, signal_t *) {
    sarc_mutation_t set;
    set.key = store_key_t(key);
    set.data = data_buffer_t::create(value.size());
    memcpy(set.data->buf(), value.c_str(), value.size());
    set.flags = 123;
    set.exptime = 0;
    set.add_policy = add_policy_yes;
    set.replace_policy = replace_policy_yes;
    unittest::fake_fifo_enforcement_t enforce;
    memcached_protocol_t::write_t write(set, time(NULL), 12345);
    fifo_enforcer_sink_t::exit_write_t exiter(&enforce.sink, enforce.source.enter_write());
    class : public broadcaster_t<memcached_protocol_t>::write_callback_t, public cond_t {
    public:
        void on_response(peer_id_t, const memcached_protocol_t::write_response_t &) {
            /* ignore */
        }
        void on_done() {
            pulse();
        }
    } write_callback;
    cond_t non_interruptor;
    spawn_write_fake_ack_checker_t ack_checker;
    broadcaster->spawn_write(write, &exiter, otok, &write_callback, &non_interruptor, &ack_checker);
    write_callback.wait_lazily_unordered();
}

void run_partial_backfill_test(io_backender_t *io_backender,
                               simple_mailbox_cluster_t *cluster,
                               branch_history_manager_t<memcached_protocol_t> *branch_history_manager,
                               clone_ptr_t<watchable_t<boost::optional<boost::optional<broadcaster_business_card_t<memcached_protocol_t> > > > > broadcaster_metadata_view,
                               scoped_ptr_t<broadcaster_t<memcached_protocol_t> > *broadcaster,
                               test_store_t<memcached_protocol_t> *,
                               scoped_ptr_t<listener_t<memcached_protocol_t> > *initial_listener,
                               order_source_t *order_source) {
    /* Set up a replier so the broadcaster can handle operations */
    EXPECT_FALSE((*initial_listener)->get_broadcaster_lost_signal()->is_pulsed());
    replier_t<memcached_protocol_t> replier(initial_listener->get(), cluster->get_mailbox_manager(), branch_history_manager);

    watchable_variable_t<boost::optional<boost::optional<replier_business_card_t<memcached_protocol_t> > > >
        replier_business_card_variable(boost::optional<boost::optional<replier_business_card_t<memcached_protocol_t> > >(boost::optional<replier_business_card_t<memcached_protocol_t> >(replier.get_business_card())));

    /* Start sending operations to the broadcaster */
    std::map<std::string, std::string> inserter_state;
    test_inserter_t inserter(
        boost::bind(&write_to_broadcaster, broadcaster->get(), _1, _2, _3, _4),
        NULL,
        &mc_key_gen,
        order_source,
        "memcached_backfill run_partial_backfill_test inserter",
        &inserter_state);
    nap(10000);

    /* Set up a second mirror */
    test_store_t<memcached_protocol_t> store2(io_backender, order_source, static_cast<memcached_protocol_t::context_t *>(NULL));
    cond_t interruptor;
    listener_t<memcached_protocol_t> listener2(
        base_path_t("."),
        io_backender,
        cluster->get_mailbox_manager(),
        broadcaster_metadata_view,
        branch_history_manager,
        &store2.store,
        replier_business_card_variable.get_watchable(),
        generate_uuid(),
        &get_global_perfmon_collection(),
        &interruptor,
        order_source);

    EXPECT_FALSE((*initial_listener)->get_broadcaster_lost_signal()->is_pulsed());
    EXPECT_FALSE(listener2.get_broadcaster_lost_signal()->is_pulsed());

    nap(10000);

    /* Stop the inserter, then let any lingering writes finish */
    inserter.stop();
    /* Let any lingering writes finish */
    // TODO: 100 seconds?
    nap(100000);

    for (std::map<std::string, std::string>::iterator it = inserter_state.begin();
            it != inserter_state.end(); it++) {
        get_query_t get;
        get.key = store_key_t(it->first);
        memcached_protocol_t::read_t read(get, time(NULL));
        unittest::fake_fifo_enforcement_t enforce;
        fifo_enforcer_sink_t::exit_read_t exiter(&enforce.sink, enforce.source.enter_read());
        cond_t non_interruptor;
        memcached_protocol_t::read_response_t response;
        broadcaster->get()->read(read, &response, &exiter, order_source->check_in("unittest::(memcached)run_partial_backfill_test").with_read_mode(), &non_interruptor);
        get_result_t get_result = boost::get<get_result_t>(response.result);
        EXPECT_TRUE(get_result.value.get() != NULL);
        EXPECT_EQ(it->second.size(), static_cast<size_t>(get_result.value->size()));
        if (static_cast<size_t>(get_result.value->size()) == it->second.size()) {
            EXPECT_EQ(it->second, std::string(get_result.value->buf(), get_result.value->size()));
        }
    }
}

TEST(MemcachedBackfill, Backfill) {
     run_in_thread_pool_with_broadcaster(&run_partial_backfill_test);
}

}   /* namespace unittest */

<commit_msg>Put some debugfs into MemcachedBackfill.Backfill.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#include "unittest/gtest.hpp"

#include "clustering/immediate_consistency/branch/broadcaster.hpp"
#include "clustering/immediate_consistency/branch/listener.hpp"
#include "clustering/immediate_consistency/branch/replier.hpp"
#include "memcached/protocol.hpp"
#include "unittest/branch_history_manager.hpp"
#include "unittest/clustering_utils.hpp"
#include "unittest/unittest_utils.hpp"
#include "unittest/dummy_metadata_controller.hpp"

namespace unittest {

void run_with_broadcaster(
        boost::function< void(io_backender_t *,
                              simple_mailbox_cluster_t *,
                              branch_history_manager_t<memcached_protocol_t> *,
                              clone_ptr_t<watchable_t<boost::optional<boost::optional<broadcaster_business_card_t<memcached_protocol_t> > > > >,
                              scoped_ptr_t<broadcaster_t<memcached_protocol_t> > *,
                              test_store_t<memcached_protocol_t> *,
                              scoped_ptr_t<listener_t<memcached_protocol_t> > *,
                              order_source_t *)> fun) {
    order_source_t order_source;

    /* Set up a cluster so mailboxes can be created */
    simple_mailbox_cluster_t cluster;

    /* Set up branch history manager */
    in_memory_branch_history_manager_t<memcached_protocol_t> branch_history_manager;

    // io backender
    io_backender_t io_backender(file_direct_io_mode_t::buffered_desired);

    /* Set up a broadcaster and initial listener */
    test_store_t<memcached_protocol_t> initial_store(&io_backender, &order_source, static_cast<memcached_protocol_t::context_t *>(NULL));
    cond_t interruptor;

    scoped_ptr_t<broadcaster_t<memcached_protocol_t> > broadcaster(
        new broadcaster_t<memcached_protocol_t>(
            cluster.get_mailbox_manager(),
            &branch_history_manager,
            &initial_store.store,
            &get_global_perfmon_collection(),
            &order_source,
            &interruptor));

    watchable_variable_t<boost::optional<boost::optional<broadcaster_business_card_t<memcached_protocol_t> > > > broadcaster_business_card_watchable_variable(boost::optional<boost::optional<broadcaster_business_card_t<memcached_protocol_t> > >(boost::optional<broadcaster_business_card_t<memcached_protocol_t> >(broadcaster->get_business_card())));

    scoped_ptr_t<listener_t<memcached_protocol_t> > initial_listener(
        new listener_t<memcached_protocol_t>(base_path_t("."),
                                             &io_backender,
                                             cluster.get_mailbox_manager(),
                                             broadcaster_business_card_watchable_variable.get_watchable(),
                                             &branch_history_manager,
                                             broadcaster.get(),
                                             &get_global_perfmon_collection(),
                                             &interruptor,
                                             &order_source));

    fun(&io_backender,
        &cluster,
        &branch_history_manager,
        broadcaster_business_card_watchable_variable.get_watchable(),
        &broadcaster,
        &initial_store,
        &initial_listener,
        &order_source);
}

void run_in_thread_pool_with_broadcaster(
        boost::function< void(io_backender_t *,
                              simple_mailbox_cluster_t *,
                              branch_history_manager_t<memcached_protocol_t> *,
                              clone_ptr_t<watchable_t<boost::optional<boost::optional<broadcaster_business_card_t<memcached_protocol_t> > > > >,
                              scoped_ptr_t<broadcaster_t<memcached_protocol_t> > *,
                              test_store_t<memcached_protocol_t> *,
                              scoped_ptr_t<listener_t<memcached_protocol_t> > *,
                              order_source_t *)> fun)
{
    unittest::run_in_thread_pool(boost::bind(&run_with_broadcaster, fun));
}

/* `PartialBackfill` backfills only in a specific sub-region. */

void write_to_broadcaster(broadcaster_t<memcached_protocol_t> *broadcaster, const std::string& key, const std::string& value, order_token_t otok, signal_t *) {
    sarc_mutation_t set;
    set.key = store_key_t(key);
    set.data = data_buffer_t::create(value.size());
    memcpy(set.data->buf(), value.c_str(), value.size());
    set.flags = 123;
    set.exptime = 0;
    set.add_policy = add_policy_yes;
    set.replace_policy = replace_policy_yes;
    unittest::fake_fifo_enforcement_t enforce;
    memcached_protocol_t::write_t write(set, time(NULL), 12345);
    fifo_enforcer_sink_t::exit_write_t exiter(&enforce.sink, enforce.source.enter_write());
    class : public broadcaster_t<memcached_protocol_t>::write_callback_t, public cond_t {
    public:
        void on_response(peer_id_t, const memcached_protocol_t::write_response_t &) {
            /* ignore */
        }
        void on_done() {
            pulse();
        }
    } write_callback;
    cond_t non_interruptor;
    spawn_write_fake_ack_checker_t ack_checker;
    broadcaster->spawn_write(write, &exiter, otok, &write_callback, &non_interruptor, &ack_checker);
    write_callback.wait_lazily_unordered();
}

void run_partial_backfill_test(io_backender_t *io_backender,
                               simple_mailbox_cluster_t *cluster,
                               branch_history_manager_t<memcached_protocol_t> *branch_history_manager,
                               clone_ptr_t<watchable_t<boost::optional<boost::optional<broadcaster_business_card_t<memcached_protocol_t> > > > > broadcaster_metadata_view,
                               scoped_ptr_t<broadcaster_t<memcached_protocol_t> > *broadcaster,
                               test_store_t<memcached_protocol_t> *,
                               scoped_ptr_t<listener_t<memcached_protocol_t> > *initial_listener,
                               order_source_t *order_source) {
    /* Set up a replier so the broadcaster can handle operations */
    EXPECT_FALSE((*initial_listener)->get_broadcaster_lost_signal()->is_pulsed());
    replier_t<memcached_protocol_t> replier(initial_listener->get(), cluster->get_mailbox_manager(), branch_history_manager);

    watchable_variable_t<boost::optional<boost::optional<replier_business_card_t<memcached_protocol_t> > > >
        replier_business_card_variable(boost::optional<boost::optional<replier_business_card_t<memcached_protocol_t> > >(boost::optional<replier_business_card_t<memcached_protocol_t> >(replier.get_business_card())));

    debugf("start sending operations to the broadcaster\n");
    /* Start sending operations to the broadcaster */
    std::map<std::string, std::string> inserter_state;
    test_inserter_t inserter(
        boost::bind(&write_to_broadcaster, broadcaster->get(), _1, _2, _3, _4),
        NULL,
        &mc_key_gen,
        order_source,
        "memcached_backfill run_partial_backfill_test inserter",
        &inserter_state);
    debugf("<nap A>\n");
    nap(10000);

    debugf("</nap A>, set up a second mirror\n");
    /* Set up a second mirror */
    test_store_t<memcached_protocol_t> store2(io_backender, order_source, static_cast<memcached_protocol_t::context_t *>(NULL));
    cond_t interruptor;
    listener_t<memcached_protocol_t> listener2(
        base_path_t("."),
        io_backender,
        cluster->get_mailbox_manager(),
        broadcaster_metadata_view,
        branch_history_manager,
        &store2.store,
        replier_business_card_variable.get_watchable(),
        generate_uuid(),
        &get_global_perfmon_collection(),
        &interruptor,
        order_source);

    debugf("listener2 constructed\n");
    EXPECT_FALSE((*initial_listener)->get_broadcaster_lost_signal()->is_pulsed());
    EXPECT_FALSE(listener2.get_broadcaster_lost_signal()->is_pulsed());

    debugf("<nap B>\n");
    nap(10000);

    debugf("</nap B>, inserter.stop\n");
    /* Stop the inserter, then let any lingering writes finish */
    inserter.stop();
    /* Let any lingering writes finish */
    debugf("<nap C> (100 seconds)\n");
    // TODO: 100 seconds?
    nap(100000);
    debugf("</nap C>\n");

    for (std::map<std::string, std::string>::iterator it = inserter_state.begin();
            it != inserter_state.end(); it++) {
        get_query_t get;
        get.key = store_key_t(it->first);
        memcached_protocol_t::read_t read(get, time(NULL));
        unittest::fake_fifo_enforcement_t enforce;
        fifo_enforcer_sink_t::exit_read_t exiter(&enforce.sink, enforce.source.enter_read());
        cond_t non_interruptor;
        memcached_protocol_t::read_response_t response;
        broadcaster->get()->read(read, &response, &exiter, order_source->check_in("unittest::(memcached)run_partial_backfill_test").with_read_mode(), &non_interruptor);
        get_result_t get_result = boost::get<get_result_t>(response.result);
        EXPECT_TRUE(get_result.value.get() != NULL);
        EXPECT_EQ(it->second.size(), static_cast<size_t>(get_result.value->size()));
        if (static_cast<size_t>(get_result.value->size()) == it->second.size()) {
            EXPECT_EQ(it->second, std::string(get_result.value->buf(), get_result.value->size()));
        }
    }
    debugf("done for loop\n");
}

TEST(MemcachedBackfill, Backfill) {
     run_in_thread_pool_with_broadcaster(&run_partial_backfill_test);
}

}   /* namespace unittest */

<|endoftext|>


<commit_before><commit_msg>coverity#1242662 unused member<commit_after><|endoftext|>


<commit_before>#include "JNIBridge.h"
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

namespace jni
{

// __thread is not supported on android (dynamic linker) :(
template <typename T>
class TLS
{
public:
	TLS()  { pthread_key_create(&m_Key, free); }
	~TLS() { pthread_key_delete(m_Key); }
	inline operator T () const { return static_cast<T>(pthread_getspecific(m_Key)); }
	inline T operator = (const T value) { pthread_setspecific(m_Key, value); return value; }
private:
	TLS(const TLS& tls);
	TLS<T> operator = (const TLS<T>&);
private:
	pthread_key_t m_Key;
};

static JavaVM*     g_JavaVM;

jobject kNull(0);

// --------------------------------------------------------------------------------------
// Oracle JNI functions (hidden)
// http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/functions.html#wp9502
// --------------------------------------------------------------------------------------
static jint PushLocalFrame(jint capacity)
{
	JNI_CALL_RETURN(jint, true, true, env->PushLocalFrame(capacity));
}

static jobject PopLocalFrame(jobject result)
{
	JNI_CALL_RETURN(jobject, true, false, env->PopLocalFrame(result));
}

// --------------------------------------------------------------------------------------
// Initialization and error functions (hidden)
// --------------------------------------------------------------------------------------
struct Error
{
	Errno _errno;
	char  errstr[256];
};
static TLS<Error*> g_Error;

static inline Error& GetErrorInternal()
{
	Error* error = g_Error;
	if (!error)
	{
		error = static_cast<Error*>(malloc(sizeof(*error)));
		memset(error, 0, sizeof(*error));
		g_Error = error;
	}
	return *error;
}

static inline void SetError(Errno _errno, const char* errmsg)
{
	Error& error = GetErrorInternal();
	if (error._errno)
		return;

	error._errno = _errno;
	strcpy(error.errstr, errmsg);
}

static void ClearErrors()
{
	JNIEnv* env = AttachCurrentThread();
	if (env)
	{
		GetErrorInternal()._errno = kJNI_NO_ERROR;
		env->ExceptionClear();
	}
}

// --------------------------------------------------------------------------------------
// Initialization and error functions (public)
// --------------------------------------------------------------------------------------
void Initialize(JavaVM& vm)
{
	g_JavaVM = &vm;
}

Errno PeekError()
{
	return GetErrorInternal()._errno;
}

const char* GetErrorMessage()
{
	return &GetErrorInternal().errstr[0];
}

Errno CheckError()
{
	Errno _errno = PeekError();
	if (_errno)
		ClearErrors();
	return _errno;
}

jthrowable ExceptionThrown(jclass clazz)
{
	JNIEnv* env = AttachCurrentThread();
	if (!env)
		return 0;

	jthrowable t = env->ExceptionOccurred();
	if (!t)
		return 0;

	if (clazz)
	{
		env->ExceptionClear();
		if (!env->IsInstanceOf(t, clazz))
		{
			env->Throw(t); // re-throw
			return 0;
		}
	}

	ClearErrors();
	return t;
}

bool CheckForParameterError(bool valid)
{
	if (!valid)
		SetError(kJNI_INVALID_PARAMETERS, "java.lang.IllegalArgumentException: Null parameter detected");
	return !valid;
}

bool CheckForExceptionError(JNIEnv* env) // Do we need to make this safer?
{
	if (env->ExceptionCheck())
	{
		Error& error = GetErrorInternal();
		if (!error._errno)
		{
			SetError(kJNI_EXCEPTION_THROWN, "java.lang.IllegalThreadStateException: Unable to determine exception message");

			LocalFrame frame;
			jthrowable t = env->ExceptionOccurred();
			env->ExceptionClear();
			{
				jclass jobject_class = env->FindClass("java/lang/Object");
				jstring jmessage = Op<jstring>::CallMethod(t, env->GetMethodID(jobject_class, "toString", "()Ljava/lang/String;"));

				const char* message = env->GetStringUTFChars(jmessage, NULL);
				strncpy(error.errstr, message, sizeof(error.errstr));
				error.errstr[sizeof(error.errstr) - 1] = 0;

				env->ReleaseStringUTFChars(jmessage, message);
			}
			env->Throw(t); // re-throw exception
			if (!env->ExceptionOccurred())
			{
				int* p = 0; *p = 4711;
			}
		}
		return true;
	}
	return false;
}

// --------------------------------------------------------------------------------------
// Oracle JNI functions (public)
// http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/functions.html#wp9502
// --------------------------------------------------------------------------------------

JavaVM* GetJavaVM()
{
	return g_JavaVM;
}

JNIEnv* GetEnv()
{
	JavaVM* vm = g_JavaVM;
	if (!vm)
		return 0;

	JNIEnv* env(0);
	vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6);
	return env;
}

JNIEnv* AttachCurrentThread()
{
	JavaVM* vm = g_JavaVM;
	if (!vm)
		return 0;

	JNIEnv* env = GetEnv();
	if (!env)
	{
		JavaVMAttachArgs args;
		args.version = JNI_VERSION_1_6;
		args.name = NULL;
		args.group = NULL;
	#if !ANDROID
		vm->AttachCurrentThread(reinterpret_cast<void**>(&env), &args);
	#else
		vm->AttachCurrentThread(&env, &args);
	#endif
	}

	if (!env)
		SetError(kJNI_ATTACH_FAILED, "java.lang.IllegalThreadStateException: Unable to attach to VM");

	return env;
}

void DetachCurrentThread()
{
	JavaVM* vm = g_JavaVM;
	if (!vm)
		return;

	vm->DetachCurrentThread();
}

jclass FindClass(const char* name)
{
	JNI_CALL_RETURN(jclass, name, true, env->FindClass(name));
}

jint Throw(jthrowable object)
{
	JNI_CALL_RETURN(jint, object, true, env->Throw(object));
}

jint ThrowNew(jclass clazz, const char* message)
{
	JNI_CALL_RETURN(jint, clazz && message, true, env->ThrowNew(clazz, message));
}

void FatalError(const char* str)
{
	JNI_CALL(str, false, env->FatalError(str));
}

jobject NewLocalRef(jobject object)
{
	JNI_CALL_RETURN(jobject, object, true, env->NewLocalRef(object));
}

void DeleteLocalRef(jobject object)
{
	JNI_CALL(object, false, env->DeleteLocalRef(object));
}

jobject NewGlobalRef(jobject object)
{
	JNI_CALL_RETURN(jobject, object, true, env->NewGlobalRef(object));
}

void DeleteGlobalRef(jobject object)
{
	JNI_CALL(object, false, env->DeleteGlobalRef(object));
}

jobject NewWeakGlobalRef(jobject object)
{
	JNI_CALL_RETURN(jobject, object, true, env->NewWeakGlobalRef(object));
}

void DeleteWeakGlobalRef(jobject object)
{
	JNI_CALL(object, false, env->DeleteWeakGlobalRef(object));
}

jclass GetObjectClass(jobject object)
{
	JNI_CALL_RETURN(jclass, object, true, env->GetObjectClass(object));
}

jboolean IsInstanceOf(jobject object, jclass clazz)
{
	JNI_CALL_RETURN(jboolean, object && clazz, true, env->IsInstanceOf(object, clazz));
}

jboolean IsSameObject(jobject object1, jobject object2)
{
	JNI_CALL_RETURN(jboolean, object1 && object2, true, env->IsSameObject(object1, object2));
}

jmethodID GetMethodID(jclass clazz, const char* name, const char* signature)
{
	JNI_CALL_RETURN(jmethodID, clazz && name && signature, true, env->GetMethodID(clazz, name, signature));
}

jfieldID GetFieldID(jclass clazz, const char* name, const char* signature)
{
	JNI_CALL_RETURN(jfieldID, clazz && name && signature, true, env->GetFieldID(clazz, name, signature));
}

jmethodID GetStaticMethodID(jclass clazz, const char* name, const char* signature)
{
	JNI_CALL_RETURN(jmethodID, clazz && name && signature, true, env->GetStaticMethodID(clazz, name, signature));
}

jfieldID GetStaticFieldID(jclass clazz, const char* name, const char* signature)
{
	JNI_CALL_RETURN(jfieldID, clazz && name && signature, true, env->GetStaticFieldID(clazz, name, signature));
}

jobject ToReflectedMethod(jclass clazz, jmethodID methodID, bool isStatic)
{
	JNI_CALL_RETURN(jobject, clazz && methodID, true, env->ToReflectedMethod(clazz, methodID, isStatic));
}

jobject NewObject(jclass clazz, jmethodID methodID, ...)
{
	va_list args;
	va_start(args, methodID);
	JNI_CALL_DECLARE(jobject, result, clazz && methodID, true, env->NewObjectV(clazz, methodID, args));
	va_end(args);
	return result;
}

jstring NewStringUTF(const char* str)
{
	JNI_CALL_RETURN(jstring, str, true, env->NewStringUTF(str));
}

jsize GetStringUTFLength(jstring string)
{
	JNI_CALL_RETURN(jsize, string, true, env->GetStringUTFLength(string));
}

const char* GetStringUTFChars(jstring str, jboolean* isCopy)
{
	JNI_CALL_RETURN(const char*, str, true, env->GetStringUTFChars(str, isCopy));
}

void ReleaseStringUTFChars(jstring str, const char* utfchars)
{
	JNI_CALL(str && utfchars, false, env->ReleaseStringUTFChars(str, utfchars));
}

size_t GetArrayLength(jarray obj)
{
	JNI_CALL_RETURN(size_t, obj, true, env->GetArrayLength(obj));
}

jobjectArray NewObjectArray(jsize length, jclass elementClass, jobject initialElement)
{
	JNI_CALL_RETURN(jobjectArray, elementClass, true, env->NewObjectArray(length, elementClass, initialElement));
}

jobject GetObjectArrayElement(jobjectArray obj, size_t index)
{
	JNI_CALL_RETURN(jobject, obj, true, env->GetObjectArrayElement(obj, index));
}

void SetObjectArrayElement(jobjectArray obj, size_t index, jobject val)
{
	JNI_CALL(obj, true, env->SetObjectArrayElement(obj, index, val));
}

void* GetPrimitiveArrayCritical(jarray obj, jboolean *isCopy)
{
	JNI_CALL_RETURN(void*, obj, false, env->GetPrimitiveArrayCritical(obj, isCopy));
}

void ReleasePrimitiveArrayCritical(jarray obj, void *carray, jint mode)
{
	JNI_CALL(obj, false, env->ReleasePrimitiveArrayCritical(obj, carray, mode));
}

jobject NewDirectByteBuffer(void* buffer, jlong size)
{
	JNI_CALL_RETURN(jobject, buffer, true, env->NewDirectByteBuffer(buffer, size));
}

void* GetDirectBufferAddress(jobject byteBuffer)
{
	JNI_CALL_RETURN(void*, byteBuffer, true, env->GetDirectBufferAddress(byteBuffer));
}

jlong GetDirectBufferCapacity(jobject byteBuffer)
{
	JNI_CALL_RETURN(jlong, byteBuffer, true, env->GetDirectBufferCapacity(byteBuffer));
}

// --------------------------------------------------------------------------------------
// ThreadScope
// --------------------------------------------------------------------------------------
ThreadScope::ThreadScope()
{
	m_NeedDetach = !jni::GetEnv();
}

ThreadScope::~ThreadScope()
{
	if (m_NeedDetach)
		jni::DetachCurrentThread();
}

// --------------------------------------------------------------------------------------
// LocalFrame
// --------------------------------------------------------------------------------------
LocalFrame::LocalFrame(jint capacity)
{
	if (PushLocalFrame(capacity) < 0)
		FatalError("Out of memory: Unable to allocate local frame(64)");
	m_FramePushed = (PeekError() == kJNI_NO_ERROR);
}
LocalFrame::~LocalFrame()
{
	if (m_FramePushed)
		PopLocalFrame(NULL);
}

}
<commit_msg>Clear errors before pushing new frame<commit_after>#include "JNIBridge.h"
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

namespace jni
{

// __thread is not supported on android (dynamic linker) :(
template <typename T>
class TLS
{
public:
	TLS()  { pthread_key_create(&m_Key, free); }
	~TLS() { pthread_key_delete(m_Key); }
	inline operator T () const { return static_cast<T>(pthread_getspecific(m_Key)); }
	inline T operator = (const T value) { pthread_setspecific(m_Key, value); return value; }
private:
	TLS(const TLS& tls);
	TLS<T> operator = (const TLS<T>&);
private:
	pthread_key_t m_Key;
};

static JavaVM*     g_JavaVM;

jobject kNull(0);

// --------------------------------------------------------------------------------------
// Oracle JNI functions (hidden)
// http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/functions.html#wp9502
// --------------------------------------------------------------------------------------
static jint PushLocalFrame(jint capacity)
{
	JNI_CALL_RETURN(jint, true, true, env->PushLocalFrame(capacity));
}

static jobject PopLocalFrame(jobject result)
{
	JNI_CALL_RETURN(jobject, true, false, env->PopLocalFrame(result));
}

// --------------------------------------------------------------------------------------
// Initialization and error functions (hidden)
// --------------------------------------------------------------------------------------
struct Error
{
	Errno _errno;
	char  errstr[256];
};
static TLS<Error*> g_Error;

static inline Error& GetErrorInternal()
{
	Error* error = g_Error;
	if (!error)
	{
		error = static_cast<Error*>(malloc(sizeof(*error)));
		memset(error, 0, sizeof(*error));
		g_Error = error;
	}
	return *error;
}

static inline void SetError(Errno _errno, const char* errmsg)
{
	Error& error = GetErrorInternal();
	if (error._errno)
		return;

	error._errno = _errno;
	strcpy(error.errstr, errmsg);
}

static void ClearErrors()
{
	JNIEnv* env = AttachCurrentThread();
	if (env)
	{
		GetErrorInternal()._errno = kJNI_NO_ERROR;
		env->ExceptionClear();
	}
}

// --------------------------------------------------------------------------------------
// Initialization and error functions (public)
// --------------------------------------------------------------------------------------
void Initialize(JavaVM& vm)
{
	g_JavaVM = &vm;
}

Errno PeekError()
{
	return GetErrorInternal()._errno;
}

const char* GetErrorMessage()
{
	return &GetErrorInternal().errstr[0];
}

Errno CheckError()
{
	Errno _errno = PeekError();
	if (_errno)
		ClearErrors();
	return _errno;
}

jthrowable ExceptionThrown(jclass clazz)
{
	JNIEnv* env = AttachCurrentThread();
	if (!env)
		return 0;

	jthrowable t = env->ExceptionOccurred();
	if (!t)
		return 0;

	if (clazz)
	{
		env->ExceptionClear();
		if (!env->IsInstanceOf(t, clazz))
		{
			env->Throw(t); // re-throw
			return 0;
		}
	}

	ClearErrors();
	return t;
}

bool CheckForParameterError(bool valid)
{
	if (!valid)
		SetError(kJNI_INVALID_PARAMETERS, "java.lang.IllegalArgumentException: Null parameter detected");
	return !valid;
}

bool CheckForExceptionError(JNIEnv* env) // Do we need to make this safer?
{
	if (env->ExceptionCheck())
	{
		Error& error = GetErrorInternal();
		if (!error._errno)
		{
			SetError(kJNI_EXCEPTION_THROWN, "java.lang.IllegalThreadStateException: Unable to determine exception message");

			LocalFrame frame;
			jthrowable t = env->ExceptionOccurred();
			env->ExceptionClear();
			{
				jclass jobject_class = env->FindClass("java/lang/Object");
				jstring jmessage = Op<jstring>::CallMethod(t, env->GetMethodID(jobject_class, "toString", "()Ljava/lang/String;"));

				const char* message = env->GetStringUTFChars(jmessage, NULL);
				strncpy(error.errstr, message, sizeof(error.errstr));
				error.errstr[sizeof(error.errstr) - 1] = 0;

				env->ReleaseStringUTFChars(jmessage, message);
			}
			env->Throw(t); // re-throw exception
			if (!env->ExceptionOccurred())
			{
				int* p = 0; *p = 4711;
			}
		}
		return true;
	}
	return false;
}

// --------------------------------------------------------------------------------------
// Oracle JNI functions (public)
// http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/functions.html#wp9502
// --------------------------------------------------------------------------------------

JavaVM* GetJavaVM()
{
	return g_JavaVM;
}

JNIEnv* GetEnv()
{
	JavaVM* vm = g_JavaVM;
	if (!vm)
		return 0;

	JNIEnv* env(0);
	vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6);
	return env;
}

JNIEnv* AttachCurrentThread()
{
	JavaVM* vm = g_JavaVM;
	if (!vm)
		return 0;

	JNIEnv* env = GetEnv();
	if (!env)
	{
		JavaVMAttachArgs args;
		args.version = JNI_VERSION_1_6;
		args.name = NULL;
		args.group = NULL;
	#if !ANDROID
		vm->AttachCurrentThread(reinterpret_cast<void**>(&env), &args);
	#else
		vm->AttachCurrentThread(&env, &args);
	#endif
	}

	if (!env)
		SetError(kJNI_ATTACH_FAILED, "java.lang.IllegalThreadStateException: Unable to attach to VM");

	return env;
}

void DetachCurrentThread()
{
	JavaVM* vm = g_JavaVM;
	if (!vm)
		return;

	vm->DetachCurrentThread();
}

jclass FindClass(const char* name)
{
	JNI_CALL_RETURN(jclass, name, true, env->FindClass(name));
}

jint Throw(jthrowable object)
{
	JNI_CALL_RETURN(jint, object, true, env->Throw(object));
}

jint ThrowNew(jclass clazz, const char* message)
{
	JNI_CALL_RETURN(jint, clazz && message, true, env->ThrowNew(clazz, message));
}

void FatalError(const char* str)
{
	JNI_CALL(str, false, env->FatalError(str));
}

jobject NewLocalRef(jobject object)
{
	JNI_CALL_RETURN(jobject, object, true, env->NewLocalRef(object));
}

void DeleteLocalRef(jobject object)
{
	JNI_CALL(object, false, env->DeleteLocalRef(object));
}

jobject NewGlobalRef(jobject object)
{
	JNI_CALL_RETURN(jobject, object, true, env->NewGlobalRef(object));
}

void DeleteGlobalRef(jobject object)
{
	JNI_CALL(object, false, env->DeleteGlobalRef(object));
}

jobject NewWeakGlobalRef(jobject object)
{
	JNI_CALL_RETURN(jobject, object, true, env->NewWeakGlobalRef(object));
}

void DeleteWeakGlobalRef(jobject object)
{
	JNI_CALL(object, false, env->DeleteWeakGlobalRef(object));
}

jclass GetObjectClass(jobject object)
{
	JNI_CALL_RETURN(jclass, object, true, env->GetObjectClass(object));
}

jboolean IsInstanceOf(jobject object, jclass clazz)
{
	JNI_CALL_RETURN(jboolean, object && clazz, true, env->IsInstanceOf(object, clazz));
}

jboolean IsSameObject(jobject object1, jobject object2)
{
	JNI_CALL_RETURN(jboolean, object1 && object2, true, env->IsSameObject(object1, object2));
}

jmethodID GetMethodID(jclass clazz, const char* name, const char* signature)
{
	JNI_CALL_RETURN(jmethodID, clazz && name && signature, true, env->GetMethodID(clazz, name, signature));
}

jfieldID GetFieldID(jclass clazz, const char* name, const char* signature)
{
	JNI_CALL_RETURN(jfieldID, clazz && name && signature, true, env->GetFieldID(clazz, name, signature));
}

jmethodID GetStaticMethodID(jclass clazz, const char* name, const char* signature)
{
	JNI_CALL_RETURN(jmethodID, clazz && name && signature, true, env->GetStaticMethodID(clazz, name, signature));
}

jfieldID GetStaticFieldID(jclass clazz, const char* name, const char* signature)
{
	JNI_CALL_RETURN(jfieldID, clazz && name && signature, true, env->GetStaticFieldID(clazz, name, signature));
}

jobject ToReflectedMethod(jclass clazz, jmethodID methodID, bool isStatic)
{
	JNI_CALL_RETURN(jobject, clazz && methodID, true, env->ToReflectedMethod(clazz, methodID, isStatic));
}

jobject NewObject(jclass clazz, jmethodID methodID, ...)
{
	va_list args;
	va_start(args, methodID);
	JNI_CALL_DECLARE(jobject, result, clazz && methodID, true, env->NewObjectV(clazz, methodID, args));
	va_end(args);
	return result;
}

jstring NewStringUTF(const char* str)
{
	JNI_CALL_RETURN(jstring, str, true, env->NewStringUTF(str));
}

jsize GetStringUTFLength(jstring string)
{
	JNI_CALL_RETURN(jsize, string, true, env->GetStringUTFLength(string));
}

const char* GetStringUTFChars(jstring str, jboolean* isCopy)
{
	JNI_CALL_RETURN(const char*, str, true, env->GetStringUTFChars(str, isCopy));
}

void ReleaseStringUTFChars(jstring str, const char* utfchars)
{
	JNI_CALL(str && utfchars, false, env->ReleaseStringUTFChars(str, utfchars));
}

size_t GetArrayLength(jarray obj)
{
	JNI_CALL_RETURN(size_t, obj, true, env->GetArrayLength(obj));
}

jobjectArray NewObjectArray(jsize length, jclass elementClass, jobject initialElement)
{
	JNI_CALL_RETURN(jobjectArray, elementClass, true, env->NewObjectArray(length, elementClass, initialElement));
}

jobject GetObjectArrayElement(jobjectArray obj, size_t index)
{
	JNI_CALL_RETURN(jobject, obj, true, env->GetObjectArrayElement(obj, index));
}

void SetObjectArrayElement(jobjectArray obj, size_t index, jobject val)
{
	JNI_CALL(obj, true, env->SetObjectArrayElement(obj, index, val));
}

void* GetPrimitiveArrayCritical(jarray obj, jboolean *isCopy)
{
	JNI_CALL_RETURN(void*, obj, false, env->GetPrimitiveArrayCritical(obj, isCopy));
}

void ReleasePrimitiveArrayCritical(jarray obj, void *carray, jint mode)
{
	JNI_CALL(obj, false, env->ReleasePrimitiveArrayCritical(obj, carray, mode));
}

jobject NewDirectByteBuffer(void* buffer, jlong size)
{
	JNI_CALL_RETURN(jobject, buffer, true, env->NewDirectByteBuffer(buffer, size));
}

void* GetDirectBufferAddress(jobject byteBuffer)
{
	JNI_CALL_RETURN(void*, byteBuffer, true, env->GetDirectBufferAddress(byteBuffer));
}

jlong GetDirectBufferCapacity(jobject byteBuffer)
{
	JNI_CALL_RETURN(jlong, byteBuffer, true, env->GetDirectBufferCapacity(byteBuffer));
}

// --------------------------------------------------------------------------------------
// ThreadScope
// --------------------------------------------------------------------------------------
ThreadScope::ThreadScope()
{
	m_NeedDetach = !jni::GetEnv();
}

ThreadScope::~ThreadScope()
{
	if (m_NeedDetach)
		jni::DetachCurrentThread();
}

// --------------------------------------------------------------------------------------
// LocalFrame
// --------------------------------------------------------------------------------------
LocalFrame::LocalFrame(jint capacity)
{
	ClearErrors();
	if (PushLocalFrame(capacity) < 0)
		FatalError("Out of memory: Unable to allocate local frame(64)");
	m_FramePushed = (PeekError() == kJNI_NO_ERROR);
}
LocalFrame::~LocalFrame()
{
	if (m_FramePushed)
		PopLocalFrame(NULL);
}

}
<|endoftext|>


<commit_before>#include <limits>
#include <iostream>
#include <fstream>
#include <vector>

#ifdef _WIN32

#ifndef EFU_SIMPLEREADHKLMKEY_H
#include "simple_read_hklm_key.h"
#endif

#ifndef EFU_WINERRORSTRING_H
#include "win_error_string.h"
#endif

#endif

#ifndef EFU_TARGET_H
#include "target.h"
#endif

#ifndef EFU_EFULAUNCHER_H
#include "efulauncher.h"
#endif

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

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';
}

int main(int argc, char *argv[])
{
    CurlGlobalInit curl_global;
    bool arg_errors = false;

#ifdef _WIN32
    std::string nwn_bin("nwmain.exe");
#else
    std::string nwn_bin("nwmain");
#endif
    std::string nwn_root_dir("./");

    std::string cmd_line(" +connect nwn.efupw.com:5121");

    const std::vector<std::string> args(argv + 1, argv + argc);

    std::cout << "Processing command line arguments." << std::endl;
    for (size_t i = 0; i < args.size(); ++i)
    {
        auto arg(args.at(i));

        if (arg.find("-dmpass") == 0)
        {
            auto cmd(split(arg, '='));
            if (cmd.size() == 2)
            {
                cmd_line.append(" -dmc +password " + cmd.at(1));
            }
            else
            {
                std::cout << "-dmpass specified but no value given. Use\n"\
                    "-dmpass=mypassword" <<std::endl;
                arg_errors = true;
            }
        }
        else if (arg.find("-nwn") == 0)
        {
            auto cmd(split(arg, '='));
            if (cmd.size() == 2)
            {
                nwn_root_dir = cmd.at(1);
            }
            else
            {
                std::cout << "-nwn specified but no value given. Use\n"\
                    "-nwn=\"path\\to\\NWN\\directory\\\"" <<std::endl;
                arg_errors = true;
            }
        }
        else
        {
            std::cout << "Ignoring unrecognized argument: " << arg
                << std::endl;
            arg_errors = true;
        }
    }

    if (arg_errors)
    {
        std::cout << "Argument errors. Press a key to continue." << std::endl;
        std::cin.get();
    }

#ifdef _WIN32
    std::ifstream nwn(nwn_root_dir + nwn_bin, std::ios::binary);

    if (!nwn && nwn_root_dir != "./")
    {
        std::cout << nwn_root_dir << " not detected as NWN root directory."\
            "\nTrying current launcher directory...\n";
        nwn_root_dir = "./";
        nwn.open(nwn_root_dir + nwn_bin, std::ios::binary);
    }

    if (!nwn)
    {
        std::cout << "Current launcher directory not detected as NWN root"\
            " directory.";
        nwn_root_dir = "C:/NeverwinterNights/NWN/";
        std::cout << "\nTrying " << nwn_root_dir << "... ";
        nwn.open(nwn_root_dir + nwn_bin, std::ios::binary);

        if (!nwn)
        {
            std::cout << "not found.\nSearching registry... ";
            SimpleReadHKLMKey reg("SOFTWARE\\BioWare\\NWN\\Neverwinter",
                "Location");
            if (reg.good())
            {
                nwn_root_dir = reg.str();
                std::cout << "key found.";
                auto path_sep = nwn_root_dir.at(nwn_root_dir.size() - 1);
                if (path_sep != '/' && path_sep != '\\')
                {
                    nwn_root_dir.append("/");
                }
                std::cout << "\nTrying " << nwn_root_dir << "... ";
                nwn.open(nwn_root_dir + nwn_bin, std::ios::binary);
                if (!nwn)
                {
                    std::cout << "not found.";
                }
            }
            else
            {
                std::cout << "no key found.";
            }
        }
    }

    if (nwn)
    {
        std::cout << nwn_root_dir + nwn_bin << " found." << std::endl;
    }
    else
    {
        std::cout << "\n\nNWN root directory not found, known"\
            " options exhausted."\
            "\nThe launcher will not be able to download files to the correct"\
            " location or"\
            "\nlaunch Neverwinter Nights, however, the launcher"\
            " may still download files to"\
            "\nthe current directory and you can"\
            " move them manually afterwards. To avoid this"\
            "\nin the future"\
            " either move the launcher to the NWN root directory containing"\
            "\nnwmain.exe or pass the -nwn=C:/NeverwinterNights/NWN flag to"\
            " the launcher"\
            "\nexecutable, substituting the correct path, quoted"\
            " if it contains spaces:"\
            "\n\t-nwn=\"X:/Games/Neverwinter Nights/NWN\"."\
            "\n/ and \\ are interchangeable."\
            "\nWould you like to download files anyway (y/n)?" << std::endl;
        if (!confirm())
        {
            std::cout << "Exiting EfU Launcher. Goodbye!" << std::endl;
            return 0;
        }
        nwn_root_dir = "./";
    }
#endif

    EfuLauncher l(nwn_root_dir,
            "https://raw.github.com/commonquail/efulauncher/"\
            "master/versioncheck");

    if (l.has_update())
    {
        std::cout << "A new version of the launcher is available. Please"\
            " download it at https://github.com/commonquail/efulauncher/"\
            "releases. Press any key to exit." << std::endl;
        std::cin.get();
        return 0;
        /*
        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();
        std::cout << "Done." << std::endl;
    }
    catch (std::exception &e)
    {
        std::cerr << e.what() << std::endl;
    }

#ifdef _WIN32
    if (nwn)
    {
        std::cout << "Launching " << nwn_root_dir + nwn_bin << "..." << std::endl;

        STARTUPINFO si;
        PROCESS_INFORMATION pi;
        ::ZeroMemory(&pi, sizeof(pi));
        ::ZeroMemory(&si, sizeof(si));
        si.cb = sizeof(si);

        auto nwn_path(nwn_root_dir + nwn_bin);
        cmd_line = nwn_path + cmd_line;

        BOOL success = ::CreateProcess(
            const_cast<char *>(nwn_path.c_str()),
            const_cast<char *>(cmd_line.c_str()),
            NULL,           // Process handle not inheritable
            NULL,           // Thread handle not inheritable
            FALSE,          // Set handle inheritance to FALSE
            0,              // No creation flags
            NULL,           // Use parent's environment block
            const_cast<char *>(nwn_root_dir.c_str()),           // Starting directory
            &si, &pi);
        if (success)
        {
            ::CloseHandle(pi.hProcess);
            ::CloseHandle(pi.hThread);
        }
        else
        {
            WinErrorString we;
            std::cout << we.str() << std::endl;
        }
    }
#endif

    return 0;
}
<commit_msg>Apply const qualifier.<commit_after>#include <limits>
#include <iostream>
#include <fstream>
#include <vector>

#ifdef _WIN32

#ifndef EFU_SIMPLEREADHKLMKEY_H
#include "simple_read_hklm_key.h"
#endif

#ifndef EFU_WINERRORSTRING_H
#include "win_error_string.h"
#endif

#endif

#ifndef EFU_TARGET_H
#include "target.h"
#endif

#ifndef EFU_EFULAUNCHER_H
#include "efulauncher.h"
#endif

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

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';
}

int main(int argc, char *argv[])
{
    CurlGlobalInit curl_global;
    bool arg_errors = false;

#ifdef _WIN32
    std::string nwn_bin("nwmain.exe");
#else
    std::string nwn_bin("nwmain");
#endif
    std::string nwn_root_dir("./");

    std::string cmd_line(" +connect nwn.efupw.com:5121");

    const std::vector<std::string> args(argv + 1, argv + argc);

    std::cout << "Processing command line arguments." << std::endl;
    for (size_t i = 0; i < args.size(); ++i)
    {
        const auto arg(args.at(i));

        if (arg.find("-dmpass") == 0)
        {
            auto cmd(split(arg, '='));
            if (cmd.size() == 2)
            {
                cmd_line.append(" -dmc +password " + cmd.at(1));
            }
            else
            {
                std::cout << "-dmpass specified but no value given. Use\n"\
                    "-dmpass=mypassword" <<std::endl;
                arg_errors = true;
            }
        }
        else if (arg.find("-nwn") == 0)
        {
            auto cmd(split(arg, '='));
            if (cmd.size() == 2)
            {
                nwn_root_dir = cmd.at(1);
            }
            else
            {
                std::cout << "-nwn specified but no value given. Use\n"\
                    "-nwn=\"path\\to\\NWN\\directory\\\"" <<std::endl;
                arg_errors = true;
            }
        }
        else
        {
            std::cout << "Ignoring unrecognized argument: " << arg
                << std::endl;
            arg_errors = true;
        }
    }

    if (arg_errors)
    {
        std::cout << "Argument errors. Press a key to continue." << std::endl;
        std::cin.get();
    }

#ifdef _WIN32
    std::ifstream nwn(nwn_root_dir + nwn_bin, std::ios::binary);

    if (!nwn && nwn_root_dir != "./")
    {
        std::cout << nwn_root_dir << " not detected as NWN root directory."\
            "\nTrying current launcher directory...\n";
        nwn_root_dir = "./";
        nwn.open(nwn_root_dir + nwn_bin, std::ios::binary);
    }

    if (!nwn)
    {
        std::cout << "Current launcher directory not detected as NWN root"\
            " directory.";
        nwn_root_dir = "C:/NeverwinterNights/NWN/";
        std::cout << "\nTrying " << nwn_root_dir << "... ";
        nwn.open(nwn_root_dir + nwn_bin, std::ios::binary);

        if (!nwn)
        {
            std::cout << "not found.\nSearching registry... ";
            SimpleReadHKLMKey reg("SOFTWARE\\BioWare\\NWN\\Neverwinter",
                "Location");
            if (reg.good())
            {
                nwn_root_dir = reg.str();
                std::cout << "key found.";
                auto path_sep = nwn_root_dir.at(nwn_root_dir.size() - 1);
                if (path_sep != '/' && path_sep != '\\')
                {
                    nwn_root_dir.append("/");
                }
                std::cout << "\nTrying " << nwn_root_dir << "... ";
                nwn.open(nwn_root_dir + nwn_bin, std::ios::binary);
                if (!nwn)
                {
                    std::cout << "not found.";
                }
            }
            else
            {
                std::cout << "no key found.";
            }
        }
    }

    if (nwn)
    {
        std::cout << nwn_root_dir + nwn_bin << " found." << std::endl;
    }
    else
    {
        std::cout << "\n\nNWN root directory not found, known"\
            " options exhausted."\
            "\nThe launcher will not be able to download files to the correct"\
            " location or"\
            "\nlaunch Neverwinter Nights, however, the launcher"\
            " may still download files to"\
            "\nthe current directory and you can"\
            " move them manually afterwards. To avoid this"\
            "\nin the future"\
            " either move the launcher to the NWN root directory containing"\
            "\nnwmain.exe or pass the -nwn=C:/NeverwinterNights/NWN flag to"\
            " the launcher"\
            "\nexecutable, substituting the correct path, quoted"\
            " if it contains spaces:"\
            "\n\t-nwn=\"X:/Games/Neverwinter Nights/NWN\"."\
            "\n/ and \\ are interchangeable."\
            "\nWould you like to download files anyway (y/n)?" << std::endl;
        if (!confirm())
        {
            std::cout << "Exiting EfU Launcher. Goodbye!" << std::endl;
            return 0;
        }
        nwn_root_dir = "./";
    }
#endif

    EfuLauncher l(nwn_root_dir,
            "https://raw.github.com/commonquail/efulauncher/"\
            "master/versioncheck");

    if (l.has_update())
    {
        std::cout << "A new version of the launcher is available. Please"\
            " download it at https://github.com/commonquail/efulauncher/"\
            "releases. Press any key to exit." << std::endl;
        std::cin.get();
        return 0;
        /*
        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();
        std::cout << "Done." << std::endl;
    }
    catch (std::exception &e)
    {
        std::cerr << e.what() << std::endl;
    }

#ifdef _WIN32
    if (nwn)
    {
        std::cout << "Launching " << nwn_root_dir + nwn_bin << "..." << std::endl;

        STARTUPINFO si;
        PROCESS_INFORMATION pi;
        ::ZeroMemory(&pi, sizeof(pi));
        ::ZeroMemory(&si, sizeof(si));
        si.cb = sizeof(si);

        auto nwn_path(nwn_root_dir + nwn_bin);
        cmd_line = nwn_path + cmd_line;

        BOOL success = ::CreateProcess(
            const_cast<char *>(nwn_path.c_str()),
            const_cast<char *>(cmd_line.c_str()),
            NULL,           // Process handle not inheritable
            NULL,           // Thread handle not inheritable
            FALSE,          // Set handle inheritance to FALSE
            0,              // No creation flags
            NULL,           // Use parent's environment block
            const_cast<char *>(nwn_root_dir.c_str()),           // Starting directory
            &si, &pi);
        if (success)
        {
            ::CloseHandle(pi.hProcess);
            ::CloseHandle(pi.hThread);
        }
        else
        {
            WinErrorString we;
            std::cout << we.str() << std::endl;
        }
    }
#endif

    return 0;
}
<|endoftext|>


<commit_before><commit_msg>convert include/svx/numvset.hxx from String to OUString<commit_after><|endoftext|>


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

#include "verilog/analysis/checkers/macro_string_concatenation_rule.h"

#include <string>

#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "common/analysis/citation.h"
#include "common/text/token_info.h"
#include "common/util/value_saver.h"
#include "verilog/analysis/descriptions.h"
#include "verilog/analysis/lint_rule_registry.h"
#include "verilog/parser/verilog_lexer.h"
#include "verilog/parser/verilog_token_classifications.h"

namespace verilog {
namespace analysis {

using verible::GetStyleGuideCitation;
using verible::LintRuleStatus;
using verible::LintViolation;
using verible::TokenInfo;

// Register the lint rule
VERILOG_REGISTER_LINT_RULE(MacroStringConcatenationRule);

absl::string_view MacroStringConcatenationRule::Name() {
  return "macro-string-concatenation";
}
const char MacroStringConcatenationRule::kTopic[] = "defines";
const char MacroStringConcatenationRule::kMessage[] =
    "Token concatenation (``) used inside plain string literal.";

std::string MacroStringConcatenationRule::GetDescription(
    DescriptionType description_type) {
  return absl::StrCat(
      "Concatenation will not be evaluated here. Use `\"...`\" instead. "
      "See ", GetStyleGuideCitation(kTopic), ".");
}

void MacroStringConcatenationRule::HandleToken(const TokenInfo& token) {
  const auto token_enum = static_cast<verilog_tokentype>(token.token_enum());
  const absl::string_view text(token.text());

  // Search only in `define tokens. Ignore state as `defines can be nested.
  if (token_enum == PP_define_body) {
    if (IsUnlexed(verilog_tokentype(token.token_enum()))) {
      verible::ValueSaver<State> state_saver(&state_, State::kInsideDefineBody);
      RecursiveLexText(
          text, [this](const TokenInfo& subtoken) { HandleToken(subtoken); });
    }
  } else if (state_ == State::kInsideDefineBody && token_enum == TK_StringLiteral) {
    size_t pos = 0;
    while((pos = text.find("``", pos)) != absl::string_view::npos) {
      violations_.insert(LintViolation(
          TokenInfo(token_enum, text.substr(pos, 2)), kMessage));
      pos += 2;
    }
  }
}

LintRuleStatus MacroStringConcatenationRule::Report() const {
  return LintRuleStatus(violations_, Name(), GetStyleGuideCitation(kTopic));
}

}  // namespace analysis
}  // namespace verilog
<commit_msg>Use already casted token_enum<commit_after>// Copyright 2017-2020 The Verible Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "verilog/analysis/checkers/macro_string_concatenation_rule.h"

#include <string>

#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "common/analysis/citation.h"
#include "common/text/token_info.h"
#include "common/util/value_saver.h"
#include "verilog/analysis/descriptions.h"
#include "verilog/analysis/lint_rule_registry.h"
#include "verilog/parser/verilog_lexer.h"
#include "verilog/parser/verilog_token_classifications.h"

namespace verilog {
namespace analysis {

using verible::GetStyleGuideCitation;
using verible::LintRuleStatus;
using verible::LintViolation;
using verible::TokenInfo;

// Register the lint rule
VERILOG_REGISTER_LINT_RULE(MacroStringConcatenationRule);

absl::string_view MacroStringConcatenationRule::Name() {
  return "macro-string-concatenation";
}
const char MacroStringConcatenationRule::kTopic[] = "defines";
const char MacroStringConcatenationRule::kMessage[] =
    "Token concatenation (``) used inside plain string literal.";

std::string MacroStringConcatenationRule::GetDescription(
    DescriptionType description_type) {
  return absl::StrCat(
      "Concatenation will not be evaluated here. Use `\"...`\" instead. "
      "See ", GetStyleGuideCitation(kTopic), ".");
}

void MacroStringConcatenationRule::HandleToken(const TokenInfo& token) {
  const auto token_enum = static_cast<verilog_tokentype>(token.token_enum());
  const absl::string_view text(token.text());

  // Search only in `define tokens. Ignore state as `defines can be nested.
  if (token_enum == PP_define_body) {
    if (IsUnlexed(verilog_tokentype(token_enum))) {
      verible::ValueSaver<State> state_saver(&state_, State::kInsideDefineBody);
      RecursiveLexText(
          text, [this](const TokenInfo& subtoken) { HandleToken(subtoken); });
    }
  } else if (state_ == State::kInsideDefineBody && token_enum == TK_StringLiteral) {
    size_t pos = 0;
    while((pos = text.find("``", pos)) != absl::string_view::npos) {
      violations_.insert(LintViolation(
          TokenInfo(token_enum, text.substr(pos, 2)), kMessage));
      pos += 2;
    }
  }
}

LintRuleStatus MacroStringConcatenationRule::Report() const {
  return LintRuleStatus(violations_, Name(), GetStyleGuideCitation(kTopic));
}

}  // namespace analysis
}  // namespace verilog
<|endoftext|>