<commit_before>#include "taskwallfollowing.h"
#include "taskwallfollowingform.h"
#include <QtGui>
#include <Module_Simulation/module_simulation.h>
#include <Module_Navigation/module_navigation.h>
#include <Behaviour_WallFollowing/behaviour_wallfollowing.h>
#include <Behaviour_TurnOneEighty/behaviour_turnoneeighty.h>

TaskWallFollowing::TaskWallFollowing(QString id, Behaviour_WallFollowing *w, Module_Simulation *sim, Module_Navigation *n, Behaviour_TurnOneEighty *o180)
    : RobotBehaviour(id)
{
    this->sim = sim;
    this->wall = w;
    this->turn180 = o180;
    this->navi = n;

}

bool TaskWallFollowing::isActive(){
    return active;
}

void TaskWallFollowing::init(){
    logger->debug("taskwallfollowing init");
    active = false;
    setEnabled(false);
    // Default task settings
    this->setDefaultValue("taskStopTime",120000);
    this->setDefaultValue("signalTimer",1000);
    this->setDefaultValue("timerActivated", true);

    // Default navigation settings
    this->setDefaultValue("taskStartPoint", "SP");
    this->setDefaultValue("wallAdjustPoint", "AP");
    this->setDefaultValue("useAdjustPoint", true);
    this->setDefaultValue("goal1point1", "go1p1");
    this->setDefaultValue("goal1point2", "go2p2");
    this->setDefaultValue("apDist" , 1.5);

    // Default turn180 settings
    this->setDefaultValue("hysteresis", 10);
    this->setDefaultValue("p", 0.4);
    this->setDefaultValue("degree", 180);

    taskStopTimer.setSingleShot(true);
    taskStopTimer.moveToThread(this);
    calcTimer.moveToThread(this);

    connect(this, SIGNAL(enabled(bool)), this, SLOT(controlEnabledChanged(bool)));
    connect(navi, SIGNAL(reachedWaypoint(QString)), this, SLOT(controlFinishedWaypoints(QString)));
    //connect(turn180, SIGNAL(turn180finished(QString)), this, SLOT(controlFinishedWaypoints(QString)));
    connect(&calcTimer,SIGNAL(timeout()),this,SLOT(controlAngleDistance()));
}

void TaskWallFollowing::reset() {
    RobotModule::reset();

    taskState = TASK_STATE_START;
}

void TaskWallFollowing::startBehaviour(){
    if (isActive()){
        logger->info("Already active!");
        return;
    }

    reset();
    setHealthToOk();

    taskState = TASK_STATE_START;
    showTaskState();

    emit updateSettings();

    calcTimer.start(100);

    active = true;
    if(!isEnabled()){
        setEnabled(true);
    }
    emit started(this);

    if(!this->navi->isEnabled()){
        logger->info("Activate navigation");
        this->navi->setEnabled(true);
    }

    emit newStateOverview(TASK_STATE_MOVE_TO_TASK_START);
    emit newStateOverview(TASK_STATE_WALLFOLLOW_PART1);
    if(this->getSettingsValue("v").toBool()){
        emit newStateOverview(TASK_STATE_ADJUST_HEADING);
        emit newStateOverview(TASK_STATE_WALLFOLLOW_PART2);
    }

    if(this->getSettingsValue("timerActivated").toBool()){
        logger->info("TaskWallFollowing with timer stop");
        taskStopTimer.singleShot(this->getSettingsValue("taskStopTime").toInt(),this, SLOT(timeoutStop()));
        taskStopTimer.start();
    }

    taskState = TASK_STATE_MOVE_TO_TASK_START;
    controlTaskStates();
}

void TaskWallFollowing::controlTaskStates(){
    if(!isActive()){
        return;
    }

    if(taskState == TASK_STATE_MOVE_TO_TASK_START){
        showTaskState();
        this->navi->gotoWayPoint(this->getSettingsValue("taskStartPoint").toString());

    } else if(taskState == TASK_STATE_WALLFOLLOW_PART1){
        showTaskState();
        if(this->wall->getHealthStatus().isHealthOk()){
            if (!this->wall->isActive()) {
                logger->info("Activate wallfollowing");
                QTimer::singleShot(0, wall, SLOT(startBehaviour()));
            } else {
                QTimer::singleShot(0, wall, SLOT(reset()));
            }
        } else {
            logger->info("Wallfollowing not possible");
            taskState = TASK_STATE_ADJUST_HEADING;
            controlTaskStates();
        }

    } else if(taskState == TASK_STATE_ADJUST_HEADING){
        showTaskState();
        this->navi->gotoWayPoint(this->getSettingsValue("wallAdjustPoint").toString());

    } else if(taskState == TASK_STATE_WALLFOLLOW_PART2){
        showTaskState();

    } else if(taskState == TASK_STATE_END){
        showTaskState();
        if(wall->isActive()){
            QTimer::singleShot(0, wall, SLOT(stop()));
        }
        stop();
    }
}

void TaskWallFollowing::showTaskState(){
    logger->info(taskState);
    emit newState(taskState);

    addData("taskStartPoint", this->getSettingsValue("taskStartPoint").toString());
    addData("wallAdjustPoint", this->getSettingsValue("wallAdjustPoint").toString());
    addData("useAdjustPoint", this->getSettingsValue("useAdjustPoint").toString());
    addData("apDist", this->getSettingsValue("apDist").toString());
    addData("timerActivated", this->getSettingsValue("timerActivated").toString());
    addData("taskStopTime", this->getSettingsValue("taskStopTime").toString());
    addData("goal1point1", this->getSettingsValue("goal1point1").toString());
    addData("goal1point2", this->getSettingsValue("goal1point2").toString());

    addData("taskState", taskState);
    emit dataChanged(this);
}

void TaskWallFollowing::controlFinishedWaypoints(QString waypoint){
    if(!isActive()){
        return;
    }

    if(waypoint == this->getSettingsValue("taskStartPoint").toString()){
        logger->info(this->getSettingsValue("taskStartPoint").toString() +" reached");
        taskState = TASK_STATE_WALLFOLLOW_PART1;
        controlTaskStates();

    } else if(waypoint ==  this->getSettingsValue("wallAdjustPoint").toString()){
        logger->info(this->getSettingsValue("wallAdjustPoint").toString() +" reached");
        QTimer::singleShot(0, navi, SLOT(clearGoal()));
        taskState = TASK_STATE_WALLFOLLOW_PART2;
        controlTaskStates();

    } else {
        // None of current task waypoints reached oO
        logger->info("Something is wrong with navigation waypoints, abort...");
        emergencyStop();
    }
}

void TaskWallFollowing::controlAngleDistance(){
    if(!isActive()){
        return;
    }

    double alpha = 0.0;
    double dist = 0.0;

    if(this->getSettingsValue("useAdjustPoint").toBool()){

        if(taskState == TASK_STATE_WALLFOLLOW_PART1){
            dist = this->navi->getDistance(this->getSettingsValue("wallAdjustPoint").toString());
            if(dist < this->getSettingsValue("apDist").toDouble()){
                taskState = TASK_STATE_WALLFOLLOW_PART2;
                controlTaskStates();
            }
        } else if(taskState == TASK_STATE_WALLFOLLOW_PART2){
            alpha = this->navi->getAlpha(this->getSettingsValue("goal1point1").toString(), this->getSettingsValue("goal1point2").toString());
            dist = this->navi->getDistance(this->getSettingsValue("goal1point2").toString());
            if(alpha < 0 && dist < 3){
                taskState = TASK_STATE_END;
                controlTaskStates();
            }
        }

    } else {

        if(taskState == TASK_STATE_WALLFOLLOW_PART1){
            alpha = this->navi->getAlpha(this->getSettingsValue("goal1point1").toString(), this->getSettingsValue("goal1point2").toString());
            dist = this->navi->getDistance(this->getSettingsValue("goal1point2").toString());
            if(alpha < 0 && dist < 3){
                taskState = TASK_STATE_END;
                controlTaskStates();
            }
        }

    }
    addData("Alpha", alpha);
    addData("Dist", dist);
    emit dataChanged(this);

}

void TaskWallFollowing::stop(){
    if(!isActive()){
        logger->info("Not active!");
        return;
    }

    taskStopTimer.stop();
    taskState = TASK_STATE_END;
    showTaskState();

    calcTimer.stop();

    logger->info("Taskwallfollowing stopped");
    if(navi->hasGoal()){
        QTimer::singleShot(0, navi, SLOT(clearGoal()));
    }

    if(wall->isActive()){
        QTimer::singleShot(0, wall, SLOT(stop()));
    }

    active = false;
    setEnabled(false);
    emit finished(this,true);
}

void TaskWallFollowing::timeoutStop(){
    if(!isActive()){
        return;
    }

    taskStopTimer.stop();
    taskState = TASK_STATE_END_FAILED;
    showTaskState();

    calcTimer.stop();

    logger->info("Taskwallfollowing timeout stopped");
    if(navi->hasGoal()){
        QTimer::singleShot(0, navi, SLOT(clearGoal()));
    }

    if(wall->isActive()){
        QTimer::singleShot(0, wall, SLOT(stop()));
    }

    active = false;
    setEnabled(false);
    emit finished(this,false);
}

void TaskWallFollowing::emergencyStop(){
    if (!isActive()){
        logger->info("Not active, no emergency stop needed");
        return;
    }

    taskStopTimer.stop();
    taskState = TASK_STATE_END_FAILED;
    showTaskState();

    calcTimer.stop();

    logger->info("Taskwallfollowing emergency stopped");
    if(navi->hasGoal()){
        QTimer::singleShot(0, navi, SLOT(clearGoal()));
    }

    if(wall->isActive()){
        QTimer::singleShot(0, wall, SLOT(stop()));
    }

    active = false;
    setEnabled(false);
    emit finished(this,false);
}

void TaskWallFollowing::controlEnabledChanged(bool enabled){
    if(!enabled && isActive()){
        logger->info("Disable and deactivate TaskWallFollowing");
        stop();
    } else if(!enabled && !isActive()){
        //logger->info("Still deactivated");
    } else if(enabled && !isActive()){
        //logger->info("Enable and activate TaskWallFollowing");
        //startBehaviour();
    } else {
        //logger->info("Still activated");
    }
}

void TaskWallFollowing::terminate()
{
    this->stop();
    RobotModule::terminate();
}

QWidget* TaskWallFollowing::createView(QWidget *parent)
{
    return new TaskWallFollowingForm(this, parent);
}

QList<RobotModule*> TaskWallFollowing::getDependencies()
{
    QList<RobotModule*> ret;
    ret.append(wall);
    ret.append(navi);
    ret.append(sim);
    return ret;
}

QString TaskWallFollowing::getTaskState(){
    return taskState;
}
<commit_msg>TaskWallFollowing changed<commit_after>#include "taskwallfollowing.h"
#include "taskwallfollowingform.h"
#include <QtGui>
#include <Module_Simulation/module_simulation.h>
#include <Module_Navigation/module_navigation.h>
#include <Behaviour_WallFollowing/behaviour_wallfollowing.h>
#include <Behaviour_TurnOneEighty/behaviour_turnoneeighty.h>

TaskWallFollowing::TaskWallFollowing(QString id, Behaviour_WallFollowing *w, Module_Simulation *sim, Module_Navigation *n, Behaviour_TurnOneEighty *o180)
    : RobotBehaviour(id)
{
    this->sim = sim;
    this->wall = w;
    this->turn180 = o180;
    this->navi = n;

}

bool TaskWallFollowing::isActive(){
    return active;
}

void TaskWallFollowing::init(){
    logger->debug("taskwallfollowing init");
    active = false;
    setEnabled(false);
    // Default task settings
    this->setDefaultValue("taskStopTime",120000);
    this->setDefaultValue("signalTimer",1000);
    this->setDefaultValue("timerActivated", true);

    // Default navigation settings
    this->setDefaultValue("taskStartPoint", "SP");
    this->setDefaultValue("wallAdjustPoint", "AP");
    this->setDefaultValue("useAdjustPoint", true);
    this->setDefaultValue("goal1point1", "go1p1");
    this->setDefaultValue("goal1point2", "go2p2");
    this->setDefaultValue("apDist" , 1.5);

    // Default turn180 settings
    this->setDefaultValue("hysteresis", 10);
    this->setDefaultValue("p", 0.4);
    this->setDefaultValue("degree", 180);

    taskStopTimer.setSingleShot(true);
    taskStopTimer.moveToThread(this);
    calcTimer.moveToThread(this);

    connect(this, SIGNAL(enabled(bool)), this, SLOT(controlEnabledChanged(bool)));
    connect(navi, SIGNAL(reachedWaypoint(QString)), this, SLOT(controlFinishedWaypoints(QString)));
    //connect(turn180, SIGNAL(turn180finished(QString)), this, SLOT(controlFinishedWaypoints(QString)));
    connect(&calcTimer,SIGNAL(timeout()),this,SLOT(controlAngleDistance()));
}

void TaskWallFollowing::reset() {
    RobotModule::reset();

    taskState = TASK_STATE_START;
}

void TaskWallFollowing::startBehaviour(){
    if (isActive()){
        logger->info("Already active!");
        return;
    }

    reset();
    setHealthToOk();

    taskState = TASK_STATE_START;
    showTaskState();

    emit updateSettings();

    calcTimer.start(100);

    active = true;
    if(!isEnabled()){
        setEnabled(true);
    }
    emit started(this);

    if(!this->navi->isEnabled()){
        logger->info("Activate navigation");
        this->navi->setEnabled(true);
    }

    emit newStateOverview(TASK_STATE_MOVE_TO_TASK_START);
    emit newStateOverview(TASK_STATE_WALLFOLLOW_PART1);
    if(this->getSettingsValue("v").toBool()){
        emit newStateOverview(TASK_STATE_ADJUST_HEADING);
        emit newStateOverview(TASK_STATE_WALLFOLLOW_PART2);
    }

    if(this->getSettingsValue("timerActivated").toBool()){
        logger->info("TaskWallFollowing with timer stop");
        taskStopTimer.singleShot(this->getSettingsValue("taskStopTime").toInt(),this, SLOT(timeoutStop()));
        taskStopTimer.start();
    }

    taskState = TASK_STATE_MOVE_TO_TASK_START;
    controlTaskStates();
}

void TaskWallFollowing::controlTaskStates(){
    if(!isActive()){
        return;
    }

    if(taskState == TASK_STATE_MOVE_TO_TASK_START){
        showTaskState();
        this->navi->gotoWayPoint(this->getSettingsValue("taskStartPoint").toString());

    } else if(taskState == TASK_STATE_WALLFOLLOW_PART1){
        showTaskState();
        if(this->wall->getHealthStatus().isHealthOk()){
            if (!this->wall->isActive()) {
                logger->info("Activate wallfollowing");
                QTimer::singleShot(0, wall, SLOT(startBehaviour()));
            } else {
                QTimer::singleShot(0, wall, SLOT(reset()));
            }
        } else {
            logger->info("Wallfollowing not possible");
            taskState = TASK_STATE_ADJUST_HEADING;
            controlTaskStates();
        }

    } else if(taskState == TASK_STATE_ADJUST_HEADING){
        showTaskState();
        this->navi->gotoWayPoint(this->getSettingsValue("wallAdjustPoint").toString());

    } else if(taskState == TASK_STATE_WALLFOLLOW_PART2){
        showTaskState();

    } else if(taskState == TASK_STATE_END){
        showTaskState();
        if(wall->isActive()){
            QTimer::singleShot(0, wall, SLOT(stop()));
        }
        stop();
    }
}

void TaskWallFollowing::showTaskState(){
    logger->info(taskState);
    emit newState(taskState);

    addData("taskStartPoint", this->getSettingsValue("taskStartPoint").toString());
    addData("wallAdjustPoint", this->getSettingsValue("wallAdjustPoint").toString());
    addData("useAdjustPoint", this->getSettingsValue("useAdjustPoint").toString());
    addData("apDist", this->getSettingsValue("apDist").toString());
    addData("timerActivated", this->getSettingsValue("timerActivated").toString());
    addData("taskStopTime", this->getSettingsValue("taskStopTime").toString());
    addData("goal1point1", this->getSettingsValue("goal1point1").toString());
    addData("goal1point2", this->getSettingsValue("goal1point2").toString());

    addData("taskState", taskState);
    emit dataChanged(this);
}

void TaskWallFollowing::controlFinishedWaypoints(QString waypoint){
    if(!isActive()){
        return;
    }

    if(waypoint == this->getSettingsValue("taskStartPoint").toString()){
        logger->info(this->getSettingsValue("taskStartPoint").toString() +" reached");
        taskState = TASK_STATE_WALLFOLLOW_PART1;
        controlTaskStates();

    } else if(waypoint ==  this->getSettingsValue("wallAdjustPoint").toString()){
        logger->info(this->getSettingsValue("wallAdjustPoint").toString() +" reached");
        QTimer::singleShot(0, navi, SLOT(clearGoal()));
        taskState = TASK_STATE_WALLFOLLOW_PART2;
        controlTaskStates();

    } else {
        // None of current task waypoints reached oO
        logger->info("Something is wrong with navigation waypoints, abort...");
        emergencyStop();
    }
}

void TaskWallFollowing::controlAngleDistance(){
    if(!isActive()){
        return;
    }

    double alpha = 0.0;
    double dist = 0.0;

    if(this->getSettingsValue("useAdjustPoint").toBool()){

        if(taskState == TASK_STATE_WALLFOLLOW_PART1){
            dist = this->navi->getDistance(this->getSettingsValue("wallAdjustPoint").toString());
            if(dist < this->getSettingsValue("apDist").toDouble()){
                taskState = TASK_STATE_WALLFOLLOW_PART2;
                controlTaskStates();
            }
        } else if(taskState == TASK_STATE_WALLFOLLOW_PART2){
            alpha = this->navi->getAlpha(this->getSettingsValue("goal1point1").toString(), this->getSettingsValue("goal1point2").toString());
            dist = this->navi->getDistance(this->getSettingsValue("goal1point2").toString());
            if(alpha < 0 && dist < 7){
                taskState = TASK_STATE_END;
                controlTaskStates();
            }
        }

    } else {

        if(taskState == TASK_STATE_WALLFOLLOW_PART1){
            alpha = this->navi->getAlpha(this->getSettingsValue("goal1point1").toString(), this->getSettingsValue("goal1point2").toString());
            dist = this->navi->getDistance(this->getSettingsValue("goal1point2").toString());
            if(alpha < 0 && dist < 3){
                taskState = TASK_STATE_END;
                controlTaskStates();
            }
        }

    }
    addData("Alpha", alpha);
    addData("Dist", dist);
    emit dataChanged(this);

}

void TaskWallFollowing::stop(){
    if(!isActive()){
        logger->info("Not active!");
        return;
    }

    taskStopTimer.stop();
    taskState = TASK_STATE_END;
    showTaskState();

    calcTimer.stop();

    logger->info("Taskwallfollowing stopped");
    if(navi->hasGoal()){
        QTimer::singleShot(0, navi, SLOT(clearGoal()));
    }

    if(wall->isActive()){
        QTimer::singleShot(0, wall, SLOT(stop()));
    }

    active = false;
    setEnabled(false);
    emit finished(this,true);
}

void TaskWallFollowing::timeoutStop(){
    if(!isActive()){
        return;
    }

    taskStopTimer.stop();
    taskState = TASK_STATE_END_FAILED;
    showTaskState();

    calcTimer.stop();

    logger->info("Taskwallfollowing timeout stopped");
    if(navi->hasGoal()){
        QTimer::singleShot(0, navi, SLOT(clearGoal()));
    }

    if(wall->isActive()){
        QTimer::singleShot(0, wall, SLOT(stop()));
    }

    active = false;
    setEnabled(false);
    emit finished(this,false);
}

void TaskWallFollowing::emergencyStop(){
    if (!isActive()){
        logger->info("Not active, no emergency stop needed");
        return;
    }

    taskStopTimer.stop();
    taskState = TASK_STATE_END_FAILED;
    showTaskState();

    calcTimer.stop();

    logger->info("Taskwallfollowing emergency stopped");
    if(navi->hasGoal()){
        QTimer::singleShot(0, navi, SLOT(clearGoal()));
    }

    if(wall->isActive()){
        QTimer::singleShot(0, wall, SLOT(stop()));
    }

    active = false;
    setEnabled(false);
    emit finished(this,false);
}

void TaskWallFollowing::controlEnabledChanged(bool enabled){
    if(!enabled && isActive()){
        logger->info("Disable and deactivate TaskWallFollowing");
        stop();
    } else if(!enabled && !isActive()){
        //logger->info("Still deactivated");
    } else if(enabled && !isActive()){
        //logger->info("Enable and activate TaskWallFollowing");
        //startBehaviour();
    } else {
        //logger->info("Still activated");
    }
}

void TaskWallFollowing::terminate()
{
    this->stop();
    RobotModule::terminate();
}

QWidget* TaskWallFollowing::createView(QWidget *parent)
{
    return new TaskWallFollowingForm(this, parent);
}

QList<RobotModule*> TaskWallFollowing::getDependencies()
{
    QList<RobotModule*> ret;
    ret.append(wall);
    ret.append(navi);
    ret.append(sim);
    return ret;
}

QString TaskWallFollowing::getTaskState(){
    return taskState;
}
<|endoftext|>


<commit_before>#include "FLTKKeyboardWindow.hpp"

static void allNotesOff(Fl_Widget *widget, void * v) {
	FLTKKeyboardWindow *win = (FLTKKeyboardWindow *)v;
	win->keyboard->allNotesOff();
}

static void channelChange(Fl_Widget *widget, void * v) {
	Fl_Spinner *spinner = (Fl_Spinner *)widget;
	FLTKKeyboardWindow *win = (FLTKKeyboardWindow *)v;

	win->lock();
	win->channel = (int)spinner->value() - 1;

	win->programSpinner->value(win->program[win->channel] + 1);

	win->unlock();
}

static void programChange(Fl_Widget *widget, void * v) {
	Fl_Spinner *spinner = (Fl_Spinner *)widget;
	FLTKKeyboardWindow *win = (FLTKKeyboardWindow *)v;

	win->lock();
	win->program[win->channel] = (int)spinner->value() - 1;
	win->unlock();
}

FLTKKeyboardWindow::FLTKKeyboardWindow(CSOUND *csound, int W, int H, const char *L = 0)
    : Fl_Double_Window(W, H, L)
{

	this->csound = csound;
	this->mutex = csound->Create_Mutex(0);

    this->begin();

    this->channelSpinner = new Fl_Spinner(60, 0, 80, 20, "Channel");
    channelSpinner->maximum(128);
    channelSpinner->minimum(1);
    this->channelSpinner->callback((Fl_Callback*) channelChange, this);

    this->programSpinner = new Fl_Spinner(210, 0, 80, 20, "Program");
    programSpinner->maximum(128);
    programSpinner->minimum(1);
    this->programSpinner->callback((Fl_Callback*) programChange, this);

    this->allNotesOffButton = new Fl_Button(0, 20, W, 20, "All Notes Off");
    this->allNotesOffButton->callback((Fl_Callback*) allNotesOff, this);

    this->keyboard = new FLTKKeyboard(csound, 0, 40, W, 80, "Keyboard");

    this->end();

	channel = 0;

    for(int i = 0; i < 16; i++) {
    	program[i] = 0;
    	previousProgram[i] = 0;
    }

}

FLTKKeyboardWindow::~FLTKKeyboardWindow() {
	if (mutex) {
      	csound->DestroyMutex(mutex);
      	mutex = (void*) 0;
    }
}

int FLTKKeyboardWindow::handle(int event) {
    //this->csound->Message(this->csound, "Keyboard event: %d\n", event);

    switch(event) {
    	case FL_KEYDOWN:
    		return this->keyboard->handle(event);
    	case FL_KEYUP:
      		return this->keyboard->handle(event);
//        case FL_DEACTIVATE:
//        	this->keyboard->allNotesOff();
//        	csound->Message(csound, "Deactivate\n");
//        	return 1;
        default:
            return Fl_Double_Window::handle(event);
    }

}

void FLTKKeyboardWindow::lock() {
	if(mutex) {
      	csound->LockMutex(mutex);
	}
}

void FLTKKeyboardWindow::unlock() {
	if(mutex) {
      	csound->UnlockMutex(mutex);
	}
}
<commit_msg>limit channels to 1-16<commit_after>#include "FLTKKeyboardWindow.hpp"

static void allNotesOff(Fl_Widget *widget, void * v) {
	FLTKKeyboardWindow *win = (FLTKKeyboardWindow *)v;
	win->keyboard->allNotesOff();
}

static void channelChange(Fl_Widget *widget, void * v) {
	Fl_Spinner *spinner = (Fl_Spinner *)widget;
	FLTKKeyboardWindow *win = (FLTKKeyboardWindow *)v;

	win->lock();
	win->channel = (int)spinner->value() - 1;

	win->programSpinner->value(win->program[win->channel] + 1);

	win->unlock();
}

static void programChange(Fl_Widget *widget, void * v) {
	Fl_Spinner *spinner = (Fl_Spinner *)widget;
	FLTKKeyboardWindow *win = (FLTKKeyboardWindow *)v;

	win->lock();
	win->program[win->channel] = (int)spinner->value() - 1;
	win->unlock();
}

FLTKKeyboardWindow::FLTKKeyboardWindow(CSOUND *csound, int W, int H, const char *L = 0)
    : Fl_Double_Window(W, H, L)
{

	this->csound = csound;
	this->mutex = csound->Create_Mutex(0);

    this->begin();

    this->channelSpinner = new Fl_Spinner(60, 0, 80, 20, "Channel");
    channelSpinner->maximum(16);
    channelSpinner->minimum(1);
    this->channelSpinner->callback((Fl_Callback*) channelChange, this);

    this->programSpinner = new Fl_Spinner(210, 0, 80, 20, "Program");
    programSpinner->maximum(128);
    programSpinner->minimum(1);
    this->programSpinner->callback((Fl_Callback*) programChange, this);

    this->allNotesOffButton = new Fl_Button(0, 20, W, 20, "All Notes Off");
    this->allNotesOffButton->callback((Fl_Callback*) allNotesOff, this);

    this->keyboard = new FLTKKeyboard(csound, 0, 40, W, 80, "Keyboard");

    this->end();

	channel = 0;

    for(int i = 0; i < 16; i++) {
    	program[i] = 0;
    	previousProgram[i] = 0;
    }

}

FLTKKeyboardWindow::~FLTKKeyboardWindow() {
	if (mutex) {
      	csound->DestroyMutex(mutex);
      	mutex = (void*) 0;
    }
}

int FLTKKeyboardWindow::handle(int event) {
    //this->csound->Message(this->csound, "Keyboard event: %d\n", event);

    switch(event) {
    	case FL_KEYDOWN:
    		return this->keyboard->handle(event);
    	case FL_KEYUP:
      		return this->keyboard->handle(event);
//        case FL_DEACTIVATE:
//        	this->keyboard->allNotesOff();
//        	csound->Message(csound, "Deactivate\n");
//        	return 1;
        default:
            return Fl_Double_Window::handle(event);
    }

}

void FLTKKeyboardWindow::lock() {
	if(mutex) {
      	csound->LockMutex(mutex);
	}
}

void FLTKKeyboardWindow::unlock() {
	if(mutex) {
      	csound->UnlockMutex(mutex);
	}
}
<|endoftext|>


<commit_before>/*=========================================================================

  Library:   CTK

  Copyright (c) Kitware Inc.

  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.txt

  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.

=========================================================================*/

// Qt includes
#include <QApplication>
#include <QDialog>
#include <QMainWindow>
#include <QTimer>

// CTK includes
#include "ctkSettings.h"

// STD includes
#include <cstdlib>
#include <iostream>

//-----------------------------------------------------------------------------
int ctkSettingsTest1(int argc, char * argv [] )
{
  QApplication app(argc, argv);
  app.setOrganizationName("CommonToolkit");
  app.setOrganizationDomain("www.commontk.org");
  app.setApplicationName("CTK");
  QSettings::setDefaultFormat(QSettings::IniFormat);
  // Test all the settings constructors
  ctkSettings settings("CommonToolkit", "CTK", 0);
  ctkSettings settings2(QSettings::UserScope, "CommonToolkit", "CTK", 0);
  ctkSettings settings3(QSettings::IniFormat, QSettings::UserScope, "CommonToolkit", "CTK", 0);
  ctkSettings settings4("foo", QSettings::IniFormat, 0);
  ctkSettings settings5(0);

  QMainWindow mainWindow(0);
  mainWindow.show();

  mainWindow.move(123, 123);
  mainWindow.resize(640, 470);

  settings.saveState(mainWindow,"");
  mainWindow.move(100, 100);
  mainWindow.resize(300, 200);
  settings.saveState(mainWindow, "key");

  settings.restoreState("", mainWindow);
  if (mainWindow.pos() != QPoint(123,123) ||
      mainWindow.size() != QSize(640, 470))
    {
    std::cerr << "ctkSettings::restoreState failed" << std::endl;
    return EXIT_FAILURE;
    }
  settings.restoreState("key", mainWindow);
  if (mainWindow.pos() != QPoint(100,100) ||
      mainWindow.size() != QSize(300, 200))
    {
    std::cerr << "ctkSettings::restoreState failed" << std::endl;
    return EXIT_FAILURE;
    }

  QDialog dialog(0);
  dialog.show();
  dialog.move(456, 456);
  dialog.resize(320, 222);

  settings.saveState(dialog,"key2");
  dialog.move(50, 50);
  dialog.resize(432, 743);
  settings.saveState(dialog, "key3");

  settings.restoreState("key2", dialog);
  if (dialog.pos() != QPoint(456,456) ||
      dialog.size() != QSize(320, 222))
    {
    std::cerr << "ctkSettings::restoreState failed" << std::endl;
    return EXIT_FAILURE;
    }
  settings.restoreState("key3", dialog);
  if (dialog.pos() != QPoint(50,50) ||
      dialog.size() != QSize(432, 743))
    {
    std::cerr << "ctkSettings::restoreState failed" << std::endl;
    return EXIT_FAILURE;
    }

  if (argc < 2 || QString(argv[1]) != "-I" )
    {
    QTimer::singleShot(200, &app, SLOT(quit()));
    }

  return app.exec();
}

<commit_msg>ENH: Make ctkSettingsTest1 more robust<commit_after>/*=========================================================================

  Library:   CTK

  Copyright (c) Kitware Inc.

  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.txt

  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.

=========================================================================*/

// Qt includes
#include <QApplication>
#include <QDesktopWidget>
#include <QDialog>
#include <QMainWindow>
#include <QTimer>

// CTK includes
#include "ctkSettings.h"

// STD includes
#include <cstdlib>
#include <iostream>

//-----------------------------------------------------------------------------
int ctkSettingsTest1(int argc, char * argv [] )
{
  QApplication app(argc, argv);
  app.setOrganizationName("CommonToolkit");
  app.setOrganizationDomain("www.commontk.org");
  app.setApplicationName("CTK");
  QSettings::setDefaultFormat(QSettings::IniFormat);
  // Test all the settings constructors
  ctkSettings settings("CommonToolkit", "CTK", 0);
  ctkSettings settings2(QSettings::UserScope, "CommonToolkit", "CTK", 0);
  ctkSettings settings3(QSettings::IniFormat, QSettings::UserScope, "CommonToolkit", "CTK", 0);
  ctkSettings settings4("foo", QSettings::IniFormat, 0);
  ctkSettings settings5(0);

  QMainWindow mainWindow(0);
  mainWindow.show();

  QDesktopWidget desktop;
  QRect desktopRect = desktop.availableGeometry(&mainWindow);
  const QPoint origin = desktopRect.topLeft();

  mainWindow.move(origin);
  mainWindow.resize(640, 470);

  settings.saveState(mainWindow,"");
  mainWindow.move(origin + QPoint(30, 20));
  mainWindow.resize(300, 200);
  settings.saveState(mainWindow, "key");

  settings.restoreState("", mainWindow);
  if (mainWindow.pos() != origin ||
      mainWindow.size() != QSize(640, 470))
    {
    std::cerr << "ctkSettings::restoreState failed" << std::endl;
    return EXIT_FAILURE;
    }
  settings.restoreState("key", mainWindow);
  if (mainWindow.pos() != (origin + QPoint(30, 20)) ||
      mainWindow.size() != QSize(300, 200))
    {
    std::cerr << "ctkSettings::restoreState failed" << std::endl;
    return EXIT_FAILURE;
    }

  QDialog dialog(0);
  dialog.show();
  dialog.move(456, 456);
  dialog.resize(320, 222);

  settings.saveState(dialog,"key2");
  dialog.move(50, 50);
  dialog.resize(432, 743);
  settings.saveState(dialog, "key3");

  settings.restoreState("key2", dialog);
  if (dialog.pos() != QPoint(456,456) ||
      dialog.size() != QSize(320, 222))
    {
    std::cerr << "ctkSettings::restoreState failed" << std::endl;
    return EXIT_FAILURE;
    }
  settings.restoreState("key3", dialog);
  if (dialog.pos() != QPoint(50,50) ||
      dialog.size() != QSize(432, 743))
    {
    std::cerr << "ctkSettings::restoreState failed" << std::endl;
    return EXIT_FAILURE;
    }

  if (argc < 2 || QString(argv[1]) != "-I" )
    {
    QTimer::singleShot(200, &app, SLOT(quit()));
    }

  return app.exec();
}

<|endoftext|>


<commit_before>#include <cassert>
#include <map>

#include "WeaponAnimation.h"

#include "../Items/WeaponType.h"
#include "../Utilities/Debug.h"

namespace
{
	// Mappings of weapon types to .CIF filenames.
	const std::map<WeaponType, std::string> WeaponTypeFilenames =
	{
		{ WeaponType::BattleAxe, "AXE" },
		{ WeaponType::Broadsword, "SWORD" },
		{ WeaponType::Claymore, "SWORD" },
		{ WeaponType::Dagger, "SWORD" },
		{ WeaponType::DaiKatana, "SWORD" },
		{ WeaponType::Fists, "HAND" },
		{ WeaponType::Flail, "STAR" },
		{ WeaponType::Katana, "SWORD" },
		{ WeaponType::LongBow, "" }, // Bows have no animations.
		{ WeaponType::Longsword, "SWORD" },
		{ WeaponType::Mace, "MACE" },
		{ WeaponType::Saber, "SWORD" },
		{ WeaponType::ShortBow, "" }, // Bows have no animations.
		{ WeaponType::Shortsword, "SWORD" },
		{ WeaponType::Staff, "STAFF" },
		{ WeaponType::Tanto, "SWORD" },
		{ WeaponType::Wakizashi, "SWORD" },
		{ WeaponType::WarAxe, "AXE" },
		{ WeaponType::Warhammer, "HAMMER" }
	};

	// Mappings of weapon animation states to ranges of frame indices, excluding fists.
	const std::map<WeaponAnimation::State, std::vector<int>> WeaponAnimationRanges =
	{
		{ WeaponAnimation::State::Sheathed, { } },
		{ WeaponAnimation::State::Unsheathing, { 30, 31, 32 } },
		{ WeaponAnimation::State::Idle, { 32 } },
		{ WeaponAnimation::State::Forward, { 25, 26, 27, 28, 29 } },
		{ WeaponAnimation::State::Down, { 0, 1, 2, 3, 4 } },
		{ WeaponAnimation::State::Right, { 15, 16, 17, 18, 19 } },
		{ WeaponAnimation::State::Left, { 10, 11, 12, 13, 14 } },
		{ WeaponAnimation::State::DownRight, { 20, 21, 22, 23, 24 } },
		{ WeaponAnimation::State::DownLeft, { 5, 6, 7, 8, 9 } },
		{ WeaponAnimation::State::Sheathing, { 32, 31, 30 } }
	};

	// Mappings of fists animation states to ranges of frame indices.
	const std::map<WeaponAnimation::State, std::vector<int>> FistsAnimationRanges =
	{
		{ WeaponAnimation::State::Sheathed, { } },
		{ WeaponAnimation::State::Unsheathing, { 10, 11, 12 } },
		{ WeaponAnimation::State::Idle, { 12 } },
		{ WeaponAnimation::State::Forward, { 5, 6, 7, 8, 9 } },
		{ WeaponAnimation::State::Down, { 0, 1, 2, 3, 4 } },
		{ WeaponAnimation::State::Right, { 5, 6, 7, 8, 9 } },
		{ WeaponAnimation::State::Left, { 0, 1, 2, 3, 4 } },
		{ WeaponAnimation::State::DownRight, { 5, 6, 7, 8, 9 } },
		{ WeaponAnimation::State::DownLeft, { 0, 1, 2, 3, 4 } },
		{ WeaponAnimation::State::Sheathing, { 12, 11, 10 } }
	};
}

const double WeaponAnimation::DEFAULT_TIME_PER_FRAME = 1.0 / 18.0;

WeaponAnimation::WeaponAnimation(WeaponType weaponType)
{
	// Bows are not allowed because they have no animation.
	DebugAssert((weaponType != WeaponType::LongBow) && (weaponType != WeaponType::ShortBow),
		"Bows do not have weapon animations.");

	this->state = WeaponAnimation::State::Sheathed;
	this->weaponType = weaponType;
	this->currentTime = 0.0;
	this->timePerFrame = WeaponAnimation::DEFAULT_TIME_PER_FRAME;
	this->rangeIndex = 0;
}

WeaponAnimation::~WeaponAnimation()
{

}

const std::vector<int> &WeaponAnimation::getCurrentRange() const
{
	const std::vector<int> &indices = (this->weaponType == WeaponType::Fists) ?
		FistsAnimationRanges.at(this->state) : WeaponAnimationRanges.at(this->state);
	return indices;
}

bool WeaponAnimation::isSheathed() const
{
	return this->state == WeaponAnimation::State::Sheathed;
}

bool WeaponAnimation::isIdle() const
{
	return this->state == WeaponAnimation::State::Idle;
}

const std::string &WeaponAnimation::getAnimationFilename() const
{
	const std::string &filename = WeaponTypeFilenames.at(this->weaponType);
	return filename;
}

int WeaponAnimation::getFrameIndex() const
{
	// The sheathe animation's frame index should not be used.
	assert(!this->isSheathed());

	const std::vector<int> &indices = this->getCurrentRange();
	return indices.at(this->rangeIndex);
}

void WeaponAnimation::setState(WeaponAnimation::State state)
{
	// Switch to the beginning of the new range of indices. The combination of
	// the state and range index will return a frame index. Do not retrieve the
	// frame index when in the sheathed state.
	this->state = state;
	this->rangeIndex = 0;
}

void WeaponAnimation::tick(double dt)
{
	// Tick if not idle and not sheathed.
	if ((this->state != WeaponAnimation::State::Idle) &&
		(this->state != WeaponAnimation::State::Sheathed))
	{
		this->currentTime += dt;

		// Update the index if current time has passed the time per frame.
		while (this->currentTime >= this->timePerFrame)
		{
			this->currentTime -= this->timePerFrame;
			this->rangeIndex++;

			// Get the current range of frame indices.
			const std::vector<int> &indices = this->getCurrentRange();

			// If the index is outside the range, decide which state is next.
			if (this->rangeIndex >= indices.size())
			{
				// Start at the beginning of the new range. The range index is not
				// used in the sheathed state.
				this->rangeIndex = 0;

				if (this->state == WeaponAnimation::State::Sheathing)
				{
					// Switching from sheathing to sheathed.
					this->state = WeaponAnimation::State::Sheathed;
				}
				else
				{
					// Switching from unsheathing to idle, or from swing to idle.
					this->state = WeaponAnimation::State::Idle;
				}
			}
		}
	}
}
<commit_msg>Slowed swinging speed to match original.<commit_after>#include <cassert>
#include <map>

#include "WeaponAnimation.h"

#include "../Items/WeaponType.h"
#include "../Utilities/Debug.h"

namespace
{
	// Mappings of weapon types to .CIF filenames.
	const std::map<WeaponType, std::string> WeaponTypeFilenames =
	{
		{ WeaponType::BattleAxe, "AXE" },
		{ WeaponType::Broadsword, "SWORD" },
		{ WeaponType::Claymore, "SWORD" },
		{ WeaponType::Dagger, "SWORD" },
		{ WeaponType::DaiKatana, "SWORD" },
		{ WeaponType::Fists, "HAND" },
		{ WeaponType::Flail, "STAR" },
		{ WeaponType::Katana, "SWORD" },
		{ WeaponType::LongBow, "" }, // Bows have no animations.
		{ WeaponType::Longsword, "SWORD" },
		{ WeaponType::Mace, "MACE" },
		{ WeaponType::Saber, "SWORD" },
		{ WeaponType::ShortBow, "" }, // Bows have no animations.
		{ WeaponType::Shortsword, "SWORD" },
		{ WeaponType::Staff, "STAFF" },
		{ WeaponType::Tanto, "SWORD" },
		{ WeaponType::Wakizashi, "SWORD" },
		{ WeaponType::WarAxe, "AXE" },
		{ WeaponType::Warhammer, "HAMMER" }
	};

	// Mappings of weapon animation states to ranges of frame indices, excluding fists.
	const std::map<WeaponAnimation::State, std::vector<int>> WeaponAnimationRanges =
	{
		{ WeaponAnimation::State::Sheathed, { } },
		{ WeaponAnimation::State::Unsheathing, { 30, 31, 32 } },
		{ WeaponAnimation::State::Idle, { 32 } },
		{ WeaponAnimation::State::Forward, { 25, 26, 27, 28, 29 } },
		{ WeaponAnimation::State::Down, { 0, 1, 2, 3, 4 } },
		{ WeaponAnimation::State::Right, { 15, 16, 17, 18, 19 } },
		{ WeaponAnimation::State::Left, { 10, 11, 12, 13, 14 } },
		{ WeaponAnimation::State::DownRight, { 20, 21, 22, 23, 24 } },
		{ WeaponAnimation::State::DownLeft, { 5, 6, 7, 8, 9 } },
		{ WeaponAnimation::State::Sheathing, { 32, 31, 30 } }
	};

	// Mappings of fists animation states to ranges of frame indices.
	const std::map<WeaponAnimation::State, std::vector<int>> FistsAnimationRanges =
	{
		{ WeaponAnimation::State::Sheathed, { } },
		{ WeaponAnimation::State::Unsheathing, { 10, 11, 12 } },
		{ WeaponAnimation::State::Idle, { 12 } },
		{ WeaponAnimation::State::Forward, { 5, 6, 7, 8, 9 } },
		{ WeaponAnimation::State::Down, { 0, 1, 2, 3, 4 } },
		{ WeaponAnimation::State::Right, { 5, 6, 7, 8, 9 } },
		{ WeaponAnimation::State::Left, { 0, 1, 2, 3, 4 } },
		{ WeaponAnimation::State::DownRight, { 5, 6, 7, 8, 9 } },
		{ WeaponAnimation::State::DownLeft, { 0, 1, 2, 3, 4 } },
		{ WeaponAnimation::State::Sheathing, { 12, 11, 10 } }
	};
}

const double WeaponAnimation::DEFAULT_TIME_PER_FRAME = 1.0 / 16.0;

WeaponAnimation::WeaponAnimation(WeaponType weaponType)
{
	// Bows are not allowed because they have no animation.
	DebugAssert((weaponType != WeaponType::LongBow) && (weaponType != WeaponType::ShortBow),
		"Bows do not have weapon animations.");

	this->state = WeaponAnimation::State::Sheathed;
	this->weaponType = weaponType;
	this->currentTime = 0.0;
	this->timePerFrame = WeaponAnimation::DEFAULT_TIME_PER_FRAME;
	this->rangeIndex = 0;
}

WeaponAnimation::~WeaponAnimation()
{

}

const std::vector<int> &WeaponAnimation::getCurrentRange() const
{
	const std::vector<int> &indices = (this->weaponType == WeaponType::Fists) ?
		FistsAnimationRanges.at(this->state) : WeaponAnimationRanges.at(this->state);
	return indices;
}

bool WeaponAnimation::isSheathed() const
{
	return this->state == WeaponAnimation::State::Sheathed;
}

bool WeaponAnimation::isIdle() const
{
	return this->state == WeaponAnimation::State::Idle;
}

const std::string &WeaponAnimation::getAnimationFilename() const
{
	const std::string &filename = WeaponTypeFilenames.at(this->weaponType);
	return filename;
}

int WeaponAnimation::getFrameIndex() const
{
	// The sheathe animation's frame index should not be used.
	assert(!this->isSheathed());

	const std::vector<int> &indices = this->getCurrentRange();
	return indices.at(this->rangeIndex);
}

void WeaponAnimation::setState(WeaponAnimation::State state)
{
	// Switch to the beginning of the new range of indices. The combination of
	// the state and range index will return a frame index. Do not retrieve the
	// frame index when in the sheathed state.
	this->state = state;
	this->rangeIndex = 0;
}

void WeaponAnimation::tick(double dt)
{
	// Tick if not idle and not sheathed.
	if ((this->state != WeaponAnimation::State::Idle) &&
		(this->state != WeaponAnimation::State::Sheathed))
	{
		this->currentTime += dt;

		// Update the index if current time has passed the time per frame.
		while (this->currentTime >= this->timePerFrame)
		{
			this->currentTime -= this->timePerFrame;
			this->rangeIndex++;

			// Get the current range of frame indices.
			const std::vector<int> &indices = this->getCurrentRange();

			// If the index is outside the range, decide which state is next.
			if (this->rangeIndex >= indices.size())
			{
				// Start at the beginning of the new range. The range index is not
				// used in the sheathed state.
				this->rangeIndex = 0;

				if (this->state == WeaponAnimation::State::Sheathing)
				{
					// Switching from sheathing to sheathed.
					this->state = WeaponAnimation::State::Sheathed;
				}
				else
				{
					// Switching from unsheathing to idle, or from swing to idle.
					this->state = WeaponAnimation::State::Idle;
				}
			}
		}
	}
}
<|endoftext|>


<commit_before>#include "LocationDefinition.h"

#include "components/debug/Debug.h"

void LocationDefinition::CityDefinition::init(CityDefinition::Type type, uint32_t citySeed,
	uint32_t wildSeed, uint32_t provinceSeed, uint32_t rulerSeed, uint32_t distantSkySeed,
	bool coastal, bool premade)
{
	this->type = type;
	this->citySeed = citySeed;
	this->wildSeed = wildSeed;
	this->provinceSeed = provinceSeed;
	this->rulerSeed = rulerSeed;
	this->distantSkySeed = distantSkySeed;
	this->coastal = coastal;
	this->premade = premade;
}

uint32_t LocationDefinition::CityDefinition::getWildDungeonSeed(int wildBlockX, int wildBlockY) const
{
	return (this->provinceSeed + (((wildBlockY << 6) + wildBlockX) & 0xFFFF)) & 0xFFFFFFFF;
}

void LocationDefinition::DungeonDefinition::init()
{
	// Do nothing
}

void LocationDefinition::MainQuestDungeonDefinition::init(MainQuestDungeonDefinition::Type type)
{
	this->type = type;
}

void LocationDefinition::init(LocationDefinition::Type type,
	const CityDataFile::ProvinceData::LocationData &locationData)
{
	this->name = locationData.name;
	this->x = locationData.x;
	this->y = locationData.y;
	this->visibleByDefault = type == LocationDefinition::Type::City;
	this->type = type;
}

void LocationDefinition::initCity(int localCityID, int provinceID, bool coastal, bool premade,
	CityDefinition::Type type, const CityDataFile &cityData)
{
	const auto &provinceData = cityData.getProvinceData(provinceID);
	const auto &locationData = provinceData.getLocationData(localCityID);
	this->init(LocationDefinition::Type::City, locationData);

	const uint32_t citySeed = cityData.getCitySeed(localCityID, provinceID);
	const uint32_t wildSeed = cityData.getWildernessSeed(localCityID, provinceID);
	const uint32_t provinceSeed = cityData.getProvinceSeed(provinceID);
	const uint32_t rulerSeed = cityData.getRulerSeed(localCityID, provinceID);
	const uint32_t distantSkySeed = cityData.getDistantSkySeed(localCityID, provinceID);
	this->city.init(type, citySeed, wildSeed, provinceSeed, rulerSeed, distantSkySeed, coastal, premade);
}

void LocationDefinition::initDungeon(const CityDataFile::ProvinceData::LocationData &locationData)
{
	this->init(LocationDefinition::Type::Dungeon, locationData);
	this->dungeon.init();
}

void LocationDefinition::initMainQuestDungeon(MainQuestDungeonDefinition::Type type,
	const CityDataFile::ProvinceData::LocationData &locationData)
{
	this->init(LocationDefinition::Type::MainQuestDungeon, locationData);
	this->mainQuest.init(type);
}

const std::string &LocationDefinition::getName() const
{
	return this->name;
}

int LocationDefinition::getScreenX() const
{
	return this->x;
}

int LocationDefinition::getScreenY() const
{
	return this->y;
}

bool LocationDefinition::isVisibleByDefault() const
{
	return this->visibleByDefault;
}

LocationDefinition::Type LocationDefinition::getType() const
{
	return this->type;
}

const LocationDefinition::CityDefinition &LocationDefinition::getCityDefinition() const
{
	DebugAssert(this->type == LocationDefinition::Type::City);
	return this->city;
}

const LocationDefinition::DungeonDefinition &LocationDefinition::getDungeonDefinition() const
{
	DebugAssert(this->type == LocationDefinition::Type::Dungeon);
	return this->dungeon;
}

const LocationDefinition::MainQuestDungeonDefinition &LocationDefinition::getMainQuestDungeonDefinition() const
{
	DebugAssert(this->type == LocationDefinition::Type::MainQuestDungeon);
	return this->mainQuest;
}
<commit_msg>Locations need a name to be visible by default.<commit_after>#include "LocationDefinition.h"

#include "components/debug/Debug.h"

void LocationDefinition::CityDefinition::init(CityDefinition::Type type, uint32_t citySeed,
	uint32_t wildSeed, uint32_t provinceSeed, uint32_t rulerSeed, uint32_t distantSkySeed,
	bool coastal, bool premade)
{
	this->type = type;
	this->citySeed = citySeed;
	this->wildSeed = wildSeed;
	this->provinceSeed = provinceSeed;
	this->rulerSeed = rulerSeed;
	this->distantSkySeed = distantSkySeed;
	this->coastal = coastal;
	this->premade = premade;
}

uint32_t LocationDefinition::CityDefinition::getWildDungeonSeed(int wildBlockX, int wildBlockY) const
{
	return (this->provinceSeed + (((wildBlockY << 6) + wildBlockX) & 0xFFFF)) & 0xFFFFFFFF;
}

void LocationDefinition::DungeonDefinition::init()
{
	// Do nothing
}

void LocationDefinition::MainQuestDungeonDefinition::init(MainQuestDungeonDefinition::Type type)
{
	this->type = type;
}

void LocationDefinition::init(LocationDefinition::Type type,
	const CityDataFile::ProvinceData::LocationData &locationData)
{
	this->name = locationData.name;
	this->x = locationData.x;
	this->y = locationData.y;
	this->visibleByDefault = (locationData.name.size() > 0) && (type == LocationDefinition::Type::City);
	this->type = type;
}

void LocationDefinition::initCity(int localCityID, int provinceID, bool coastal, bool premade,
	CityDefinition::Type type, const CityDataFile &cityData)
{
	const auto &provinceData = cityData.getProvinceData(provinceID);
	const auto &locationData = provinceData.getLocationData(localCityID);
	this->init(LocationDefinition::Type::City, locationData);

	const uint32_t citySeed = cityData.getCitySeed(localCityID, provinceID);
	const uint32_t wildSeed = cityData.getWildernessSeed(localCityID, provinceID);
	const uint32_t provinceSeed = cityData.getProvinceSeed(provinceID);
	const uint32_t rulerSeed = cityData.getRulerSeed(localCityID, provinceID);
	const uint32_t distantSkySeed = cityData.getDistantSkySeed(localCityID, provinceID);
	this->city.init(type, citySeed, wildSeed, provinceSeed, rulerSeed, distantSkySeed, coastal, premade);
}

void LocationDefinition::initDungeon(const CityDataFile::ProvinceData::LocationData &locationData)
{
	this->init(LocationDefinition::Type::Dungeon, locationData);
	this->dungeon.init();
}

void LocationDefinition::initMainQuestDungeon(MainQuestDungeonDefinition::Type type,
	const CityDataFile::ProvinceData::LocationData &locationData)
{
	this->init(LocationDefinition::Type::MainQuestDungeon, locationData);
	this->mainQuest.init(type);
}

const std::string &LocationDefinition::getName() const
{
	return this->name;
}

int LocationDefinition::getScreenX() const
{
	return this->x;
}

int LocationDefinition::getScreenY() const
{
	return this->y;
}

bool LocationDefinition::isVisibleByDefault() const
{
	return this->visibleByDefault;
}

LocationDefinition::Type LocationDefinition::getType() const
{
	return this->type;
}

const LocationDefinition::CityDefinition &LocationDefinition::getCityDefinition() const
{
	DebugAssert(this->type == LocationDefinition::Type::City);
	return this->city;
}

const LocationDefinition::DungeonDefinition &LocationDefinition::getDungeonDefinition() const
{
	DebugAssert(this->type == LocationDefinition::Type::Dungeon);
	return this->dungeon;
}

const LocationDefinition::MainQuestDungeonDefinition &LocationDefinition::getMainQuestDungeonDefinition() const
{
	DebugAssert(this->type == LocationDefinition::Type::MainQuestDungeon);
	return this->mainQuest;
}
<|endoftext|>


<commit_before>AliAnalysisVertexingHF* ConfigVertexingHF_highmult() {

  printf("Call to AliAnalysisVertexingHF parameters setting :\n");
  vHF = new AliAnalysisVertexingHF();

  //--- switch-off candidates finding (default: all on)
  //vHF->SetD0toKpiOff();
  //vHF->SetJPSItoEleOff();
  vHF->Set3ProngOff();
  vHF->SetLikeSignOn(); // like-sign pairs and triplets
  vHF->Set4ProngOff();
  //vHF->SetDstarOff();
  vHF->SetFindVertexForDstar(kFALSE);
  //--- secondary vertex with KF?
  //vHF->SetSecVtxWithKF();

  //--- set cuts for single-track selection
  //     displaced tracks
  AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCuts->SetRequireTPCRefit(kTRUE);
  esdTrackCuts->SetRequireITSRefit(kTRUE);
  esdTrackCuts->SetMinNClustersITS(5);
  esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
					 AliESDtrackCuts::kBoth);
  esdTrackCuts->SetMinDCAToVertexXY(0.);
  esdTrackCuts->SetPtRange(0.3,1.e10);
  AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter");
  trkFilter->AddCuts(esdTrackCuts);
  vHF->SetTrackFilter(trkFilter);
  //     D* soft pion tracks
  AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCutsSoftPi->SetMinNClustersITS(4);
  AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi");
  trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi);
  vHF->SetTrackFilterSoftPi(trkFilterSoftPi);
  //--- set cuts for candidates selection
  vHF->SetD0toKpiCuts(0.3,999999.,1.1,0.,0.,999999.,999999.,999999.,0.);
  vHF->SetBtoJPSICuts(0.350);
  vHF->SetDplusCuts(0.2,0.4,0.4,0.,0.,0.01,0.06,0.02,0.,0.85);
  vHF->SetDsCuts(0.2,0.4,0.4,0.,0.,0.005,0.06,0.,0.,0.85,0.,0.1,0.1);
  vHF->SetLcCuts(0.2,0.4,0.4,0.,0.,0.01,0.06,0.,0.,0.85);
  vHF->SetD0to4ProngsCuts(0.2,0.04,0.00,0.01,0.02,0.8,0.,0.1,0.);
  vHF->SetDstarCuts(0.3, 0.1, 0.05, 100000000000.0, 0.5);
  vHF->SetD0fromDstarCuts(0.3,999999.,1.1,0.,0.,999999.,999999.,999999.,0.);
  //--- set this if you want to reconstruct primary vertex candidate by
  //    candidate using other tracks in the event (for pp, broad
  //    interaction region)
  //vHF->SetRecoPrimVtxSkippingTrks();
  //--- OR set this if you want to remove the candidate daughters from
  //    the primary vertex, without recostructing it from scratch
  //vHF->SetRmTrksFromPrimVtx();

  //--- check the settings
  vHF->PrintStatus();
  //--- verbose
  //AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2);

  return vHF;
}

<commit_msg>Fix function name<commit_after>AliAnalysisVertexingHF* ConfigVertexingHF() {

  printf("Call to AliAnalysisVertexingHF parameters setting :\n");
  vHF = new AliAnalysisVertexingHF();

  //--- switch-off candidates finding (default: all on)
  //vHF->SetD0toKpiOff();
  //vHF->SetJPSItoEleOff();
  vHF->Set3ProngOff();
  vHF->SetLikeSignOn(); // like-sign pairs and triplets
  vHF->Set4ProngOff();
  //vHF->SetDstarOff();
  vHF->SetFindVertexForDstar(kFALSE);
  //--- secondary vertex with KF?
  //vHF->SetSecVtxWithKF();

  //--- set cuts for single-track selection
  //     displaced tracks
  AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCuts->SetRequireTPCRefit(kTRUE);
  esdTrackCuts->SetRequireITSRefit(kTRUE);
  esdTrackCuts->SetMinNClustersITS(5);
  esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
					 AliESDtrackCuts::kBoth);
  esdTrackCuts->SetMinDCAToVertexXY(0.);
  esdTrackCuts->SetPtRange(0.3,1.e10);
  AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter");
  trkFilter->AddCuts(esdTrackCuts);
  vHF->SetTrackFilter(trkFilter);
  //     D* soft pion tracks
  AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCutsSoftPi->SetMinNClustersITS(4);
  AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi");
  trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi);
  vHF->SetTrackFilterSoftPi(trkFilterSoftPi);
  //--- set cuts for candidates selection
  vHF->SetD0toKpiCuts(0.3,999999.,1.1,0.,0.,999999.,999999.,999999.,0.);
  vHF->SetBtoJPSICuts(0.350);
  vHF->SetDplusCuts(0.2,0.4,0.4,0.,0.,0.01,0.06,0.02,0.,0.85);
  vHF->SetDsCuts(0.2,0.4,0.4,0.,0.,0.005,0.06,0.,0.,0.85,0.,0.1,0.1);
  vHF->SetLcCuts(0.2,0.4,0.4,0.,0.,0.01,0.06,0.,0.,0.85);
  vHF->SetD0to4ProngsCuts(0.2,0.04,0.00,0.01,0.02,0.8,0.,0.1,0.);
  vHF->SetDstarCuts(0.3, 0.1, 0.05, 100000000000.0, 0.5);
  vHF->SetD0fromDstarCuts(0.3,999999.,1.1,0.,0.,999999.,999999.,999999.,0.);
  //--- set this if you want to reconstruct primary vertex candidate by
  //    candidate using other tracks in the event (for pp, broad
  //    interaction region)
  //vHF->SetRecoPrimVtxSkippingTrks();
  //--- OR set this if you want to remove the candidate daughters from
  //    the primary vertex, without recostructing it from scratch
  //vHF->SetRmTrksFromPrimVtx();

  //--- check the settings
  vHF->PrintStatus();
  //--- verbose
  //AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2);

  return vHF;
}

<|endoftext|>


<commit_before>/*
  ==============================================================================

    GridCell.cpp
    Created: 23 Jan 2015 7:02:25pm
    Author:  Daniel Lindenfelser

  ==============================================================================
*/

#include "GridCell.h"

SoundboardGridCell::SoundboardGridCell(Player *p) : player(p), index(-1), progressState(true)
{
    setRepaintsOnMouseActivity(true);
    if (player)
    {
        player->getThumbnail()->addChangeListener(this);
        player->addChangeListener(this);
    }
}

SoundboardGridCell::~SoundboardGridCell()
{
    player->getThumbnail()->removeChangeListener(this);
    player->removeChangeListener(this);
}

void SoundboardGridCell::mouseUp(const MouseEvent &event)
{
    if (player)
    {
        Rectangle<float> loopArea(0.0f, 0.0f, getHeight() * 0.5f, getHeight() * 0.5f);
        Rectangle<float> timerArea(0.0f, getHeight() - getHeight() * 0.5f, getHeight() * 0.5f, getHeight() * 0.5f);
        Rectangle<float> fadeoutArea(getWidth() - getHeight() * 0.5f, 0.0f, getHeight() * 0.5f, getHeight() * 0.5f);
        Rectangle<float> stopArea(getWidth() - getHeight() * 0.5f,  getHeight() - getHeight() * 0.5f,  getHeight() * 0.5f, getHeight() * 0.5f);

        if (loopArea.contains(event.position))
        {
            player->setLooping(!player->isLooping());
        }
        else if (fadeoutArea.contains(event.position))
        {
            if (player->isPlaying()) {
                player->startFadeOut();
            } else if (player->isStopped() || player->isPaused()) {
                player->startFadeIn();
            }
        }
        else if (stopArea.contains(event.position))
        {
            player->stop();
        }
        else if (timerArea.contains(event.position))
        {
            progressState = !progressState;
        }
        else
        {
            if (player->isPlaying())
            {
                player->pause();
            }
            else
            {
                player->play();
            }
        }
        repaint();
    }
}

void SoundboardGridCell::paint(Graphics &g)
{
    auto border = g.getClipBounds().reduced(1).toFloat();
    auto cell   = border.reduced(2).toFloat();

    g.setColour(ThemeBackground1);
    g.fillAll();

    g.setColour(ThemeBackground3);
    g.fillRect(border);

    if (player)
    {
        Colour colour;
        if (player->isPlayed())
        {
            colour = ThemeGreen;
        }
        else if (player->isFading())
        {
            colour = ThemeOrange;
        }
        else if (player->isLooping())
        {
            colour = ThemeBlue;
        }
        else
        {
            colour = ThemeYellow;
        }

        g.setColour(colour.withAlpha(0.2f));
        g.fillRoundedRectangle(cell, 2);

        g.setColour(colour.withAlpha(0.2f));
        auto thumbArea = cell.reduced(0, 5).toType<int>();
        if (player->getThumbnail()->getTotalLength() > 0.0)
        {
            player->getThumbnail()->drawChannel(g, thumbArea, 0, player->getThumbnail()->getTotalLength(), 1, 1.0f);
        }

        g.setColour(colour.brighter(0.4f));
        g.drawHorizontalLine(static_cast<int>(g.getClipBounds().getHeight() * 0.5f - 1),
                             g.getClipBounds().getX() + 3.0f,
                             g.getClipBounds().getWidth() - 3.0f);

        if (player->isPlayed())
        {
            g.setColour(colour.withAlpha(0.9f));
            g.setFont(getFontAwesome(getHeight() * 0.5f));
            g.drawText(FontAwesome_Play,
                       thumbArea.getX(),
                       thumbArea.getY(),
                       thumbArea.getWidth(),
                       thumbArea.getHeight(),
                       Justification::centred,
                       false);
        }
        else if (player->isFading())
        {
            g.setColour(colour.withAlpha(0.5f));
            g.fillRoundedRectangle(cell.getX(), cell.getY(), cell.getWidth() * player->getGain(), cell.getHeight(), 2);

            g.setColour(colour.withAlpha(0.9f));
            g.setFont(getFontAwesome(getHeight() * 0.5f));
            g.drawText(FontAwesome_Pause,
                       thumbArea.getX(),
                       thumbArea.getY(),
                       thumbArea.getWidth(),
                       thumbArea.getHeight(),
                       Justification::centred,
                       false);
        }
        else if (player->isLooping())
        {
            g.setColour(colour.withAlpha(0.5f));
            g.fillRoundedRectangle(cell.getX(),
                                   cell.getY(),
                                   cell.getWidth() * player->getProgress(),
                                   cell.getHeight(),
                                   2);

            g.setColour(colour.withAlpha(0.9f));
            g.setFont(getFontAwesome(getHeight() * 0.5f));
            if (player->isPlaying())
            {
                g.drawText(FontAwesome_Pause,
                           thumbArea.getX(),
                           thumbArea.getY(),
                           thumbArea.getWidth(),
                           thumbArea.getHeight(),
                           Justification::centred,
                           false);
            }
            else
            {
                g.drawText(FontAwesome_Play,
                           thumbArea.getX(),
                           thumbArea.getY(),
                           thumbArea.getWidth(),
                           thumbArea.getHeight(),
                           Justification::centred,
                           false);
            }
        }
        else
        {
            g.setColour(colour.withAlpha(0.5f));
            g.fillRoundedRectangle(cell.getX(),
                                   cell.getY(),
                                   cell.getWidth() * player->getProgress(),
                                   cell.getHeight(),
                                   2);

            g.setColour(colour.withAlpha(0.9f));
            g.setFont(getFontAwesome(getHeight() * 0.5f));
            if (player->isPlaying())
            {
                g.drawText(FontAwesome_Pause,
                           thumbArea.getX(),
                           thumbArea.getY(),
                           thumbArea.getWidth(),
                           thumbArea.getHeight(),
                           Justification::centred,
                           false);
            }
            else
            {
                g.drawText(FontAwesome_Play,
                           thumbArea.getX(),
                           thumbArea.getY(),
                           thumbArea.getWidth(),
                           thumbArea.getHeight(),
                           Justification::centred,
                           false);
            }
        }

        auto info = cell.reduced(1).toType<int>();
        g.resetToDefaultState();
        g.setFont(getHeight() * 0.15f);
        g.setColour(ThemeForeground1);
        g.drawText(player->getProgressString(progressState),
                   info.getX(),
                   info.getY(),
                   info.getWidth(),
                   info.getHeight(),
                   Justification::bottomLeft,
                   false);
        g.drawText(player->getTitle(),
                   info.getX(),
                   info.getY(),
                   info.getWidth(),
                   info.getHeight(),
                   Justification::centredTop,
                   false);

        if (isMouseOver(true))
        {
            auto helperRect = cell.reduced(3).toType<int>();
            if (player->isLooping())
            {
                g.setColour(colour);
            }
            else
            {
                g.setColour(ThemeForeground1.withAlpha(0.5f));
            }
            g.setFont(getFontAwesome(getHeight() * 0.25f));
            g.drawText(FontAwesome_Refresh,
                       helperRect.getX(),
                       helperRect.getY(),
                       helperRect.getWidth(),
                       helperRect.getHeight(),
                       Justification::topLeft,
                       false);

            if (player->isPlayed())
            {
                g.setColour(colour);
                g.drawText(FontAwesome_Square_O,
                           helperRect.getX(),
                           helperRect.getY(),
                           helperRect.getWidth(),
                           helperRect.getHeight(),
                           Justification::bottomRight,
                           false);
            }
            else
            {
                if (!player->isPaused() && !player->isPlaying())
                {
                    g.setColour(ThemeForeground1.withAlpha(0.25f));
                }
                else
                {
                    g.setColour(ThemeForeground1.withAlpha(0.5f));
                }
                g.drawText(FontAwesome_Square,
                           helperRect.getX(),
                           helperRect.getY(),
                           helperRect.getWidth(),
                           helperRect.getHeight(),
                           Justification::bottomRight,
                           false);
            }

            float iconSize = getHeight() * 0.25f;
            Colour iconColour;
            Icon icon;
            g.setColour(ThemeForeground1);
            if (player->isFading())
            {
                iconColour = colour;
            }
            else
            {
                iconColour = ThemeForeground1.withAlpha(0.5f);
            }

            if (player->isPlaying()) {
                icon = FontAwesome_Sort_Amount_Desc;
            } else {
                icon = FontAwesome_Sort_Amount_Asc;
            }

            g.drawImageAt(FontAwesome.getRotatedIcon(icon, iconSize, iconColour, 0.5f), helperRect.getWidth() - iconSize + helperRect.getX(), helperRect.getX());
        }
    }
    else
    {
        g.setColour(ThemeForeground2);
        g.drawHorizontalLine(static_cast<int>(g.getClipBounds().getHeight() * 0.5f - 1),
                             g.getClipBounds().getX() + 3.0f,
                             g.getClipBounds().getWidth() - 3.0f);
    }
}

void SoundboardGridCell::changeListenerCallback(ChangeBroadcaster * /*source*/)
{
    repaint();
}

void SoundboardGridCell::setIndex(int value)
{
    index = value;
}

int SoundboardGridCell::getIndex()
{
    return index;
}
<commit_msg>add missing null check<commit_after>/*
  ==============================================================================

    GridCell.cpp
    Created: 23 Jan 2015 7:02:25pm
    Author:  Daniel Lindenfelser

  ==============================================================================
*/

#include "GridCell.h"

SoundboardGridCell::SoundboardGridCell(Player *p) : player(p), index(-1), progressState(true)
{
    setRepaintsOnMouseActivity(true);
    if (player)
    {
        player->getThumbnail()->addChangeListener(this);
        player->addChangeListener(this);
    }
}

SoundboardGridCell::~SoundboardGridCell()
{
    if (player)
    {
        player->getThumbnail()->removeChangeListener(this);
        player->removeChangeListener(this);
    }
}

void SoundboardGridCell::mouseUp(const MouseEvent &event)
{
    if (player)
    {
        Rectangle<float> loopArea(0.0f, 0.0f, getHeight() * 0.5f, getHeight() * 0.5f);
        Rectangle<float> timerArea(0.0f, getHeight() - getHeight() * 0.5f, getHeight() * 0.5f, getHeight() * 0.5f);
        Rectangle<float> fadeoutArea(getWidth() - getHeight() * 0.5f, 0.0f, getHeight() * 0.5f, getHeight() * 0.5f);
        Rectangle<float> stopArea(getWidth() - getHeight() * 0.5f,  getHeight() - getHeight() * 0.5f,  getHeight() * 0.5f, getHeight() * 0.5f);

        if (loopArea.contains(event.position))
        {
            player->setLooping(!player->isLooping());
        }
        else if (fadeoutArea.contains(event.position))
        {
            if (player->isPlaying()) {
                player->startFadeOut();
            } else if (player->isStopped() || player->isPaused()) {
                player->startFadeIn();
            }
        }
        else if (stopArea.contains(event.position))
        {
            player->stop();
        }
        else if (timerArea.contains(event.position))
        {
            progressState = !progressState;
        }
        else
        {
            if (player->isPlaying())
            {
                player->pause();
            }
            else
            {
                player->play();
            }
        }
        repaint();
    }
}

void SoundboardGridCell::paint(Graphics &g)
{
    auto border = g.getClipBounds().reduced(1).toFloat();
    auto cell   = border.reduced(2).toFloat();

    g.setColour(ThemeBackground1);
    g.fillAll();

    g.setColour(ThemeBackground3);
    g.fillRect(border);

    if (player)
    {
        Colour colour;
        if (player->isPlayed())
        {
            colour = ThemeGreen;
        }
        else if (player->isFading())
        {
            colour = ThemeOrange;
        }
        else if (player->isLooping())
        {
            colour = ThemeBlue;
        }
        else
        {
            colour = ThemeYellow;
        }

        g.setColour(colour.withAlpha(0.2f));
        g.fillRoundedRectangle(cell, 2);

        g.setColour(colour.withAlpha(0.2f));
        auto thumbArea = cell.reduced(0, 5).toType<int>();
        if (player->getThumbnail()->getTotalLength() > 0.0)
        {
            player->getThumbnail()->drawChannel(g, thumbArea, 0, player->getThumbnail()->getTotalLength(), 1, 1.0f);
        }

        g.setColour(colour.brighter(0.4f));
        g.drawHorizontalLine(static_cast<int>(g.getClipBounds().getHeight() * 0.5f - 1),
                             g.getClipBounds().getX() + 3.0f,
                             g.getClipBounds().getWidth() - 3.0f);

        if (player->isPlayed())
        {
            g.setColour(colour.withAlpha(0.9f));
            g.setFont(getFontAwesome(getHeight() * 0.5f));
            g.drawText(FontAwesome_Play,
                       thumbArea.getX(),
                       thumbArea.getY(),
                       thumbArea.getWidth(),
                       thumbArea.getHeight(),
                       Justification::centred,
                       false);
        }
        else if (player->isFading())
        {
            g.setColour(colour.withAlpha(0.5f));
            g.fillRoundedRectangle(cell.getX(), cell.getY(), cell.getWidth() * player->getGain(), cell.getHeight(), 2);

            g.setColour(colour.withAlpha(0.9f));
            g.setFont(getFontAwesome(getHeight() * 0.5f));
            g.drawText(FontAwesome_Pause,
                       thumbArea.getX(),
                       thumbArea.getY(),
                       thumbArea.getWidth(),
                       thumbArea.getHeight(),
                       Justification::centred,
                       false);
        }
        else if (player->isLooping())
        {
            g.setColour(colour.withAlpha(0.5f));
            g.fillRoundedRectangle(cell.getX(),
                                   cell.getY(),
                                   cell.getWidth() * player->getProgress(),
                                   cell.getHeight(),
                                   2);

            g.setColour(colour.withAlpha(0.9f));
            g.setFont(getFontAwesome(getHeight() * 0.5f));
            if (player->isPlaying())
            {
                g.drawText(FontAwesome_Pause,
                           thumbArea.getX(),
                           thumbArea.getY(),
                           thumbArea.getWidth(),
                           thumbArea.getHeight(),
                           Justification::centred,
                           false);
            }
            else
            {
                g.drawText(FontAwesome_Play,
                           thumbArea.getX(),
                           thumbArea.getY(),
                           thumbArea.getWidth(),
                           thumbArea.getHeight(),
                           Justification::centred,
                           false);
            }
        }
        else
        {
            g.setColour(colour.withAlpha(0.5f));
            g.fillRoundedRectangle(cell.getX(),
                                   cell.getY(),
                                   cell.getWidth() * player->getProgress(),
                                   cell.getHeight(),
                                   2);

            g.setColour(colour.withAlpha(0.9f));
            g.setFont(getFontAwesome(getHeight() * 0.5f));
            if (player->isPlaying())
            {
                g.drawText(FontAwesome_Pause,
                           thumbArea.getX(),
                           thumbArea.getY(),
                           thumbArea.getWidth(),
                           thumbArea.getHeight(),
                           Justification::centred,
                           false);
            }
            else
            {
                g.drawText(FontAwesome_Play,
                           thumbArea.getX(),
                           thumbArea.getY(),
                           thumbArea.getWidth(),
                           thumbArea.getHeight(),
                           Justification::centred,
                           false);
            }
        }

        auto info = cell.reduced(1).toType<int>();
        g.resetToDefaultState();
        g.setFont(getHeight() * 0.15f);
        g.setColour(ThemeForeground1);
        g.drawText(player->getProgressString(progressState),
                   info.getX(),
                   info.getY(),
                   info.getWidth(),
                   info.getHeight(),
                   Justification::bottomLeft,
                   false);
        g.drawText(player->getTitle(),
                   info.getX(),
                   info.getY(),
                   info.getWidth(),
                   info.getHeight(),
                   Justification::centredTop,
                   false);

        if (isMouseOver(true))
        {
            auto helperRect = cell.reduced(3).toType<int>();
            if (player->isLooping())
            {
                g.setColour(colour);
            }
            else
            {
                g.setColour(ThemeForeground1.withAlpha(0.5f));
            }
            g.setFont(getFontAwesome(getHeight() * 0.25f));
            g.drawText(FontAwesome_Refresh,
                       helperRect.getX(),
                       helperRect.getY(),
                       helperRect.getWidth(),
                       helperRect.getHeight(),
                       Justification::topLeft,
                       false);

            if (player->isPlayed())
            {
                g.setColour(colour);
                g.drawText(FontAwesome_Square_O,
                           helperRect.getX(),
                           helperRect.getY(),
                           helperRect.getWidth(),
                           helperRect.getHeight(),
                           Justification::bottomRight,
                           false);
            }
            else
            {
                if (!player->isPaused() && !player->isPlaying())
                {
                    g.setColour(ThemeForeground1.withAlpha(0.25f));
                }
                else
                {
                    g.setColour(ThemeForeground1.withAlpha(0.5f));
                }
                g.drawText(FontAwesome_Square,
                           helperRect.getX(),
                           helperRect.getY(),
                           helperRect.getWidth(),
                           helperRect.getHeight(),
                           Justification::bottomRight,
                           false);
            }

            float iconSize = getHeight() * 0.25f;
            Colour iconColour;
            Icon icon;
            g.setColour(ThemeForeground1);
            if (player->isFading())
            {
                iconColour = colour;
            }
            else
            {
                iconColour = ThemeForeground1.withAlpha(0.5f);
            }

            if (player->isPlaying()) {
                icon = FontAwesome_Sort_Amount_Desc;
            } else {
                icon = FontAwesome_Sort_Amount_Asc;
            }

            g.drawImageAt(FontAwesome.getRotatedIcon(icon, iconSize, iconColour, 0.5f), helperRect.getWidth() - iconSize + helperRect.getX(), helperRect.getX());
        }
    }
    else
    {
        g.setColour(ThemeForeground2);
        g.drawHorizontalLine(static_cast<int>(g.getClipBounds().getHeight() * 0.5f - 1),
                             g.getClipBounds().getX() + 3.0f,
                             g.getClipBounds().getWidth() - 3.0f);
    }
}

void SoundboardGridCell::changeListenerCallback(ChangeBroadcaster * /*source*/)
{
    repaint();
}

void SoundboardGridCell::setIndex(int value)
{
    index = value;
}

int SoundboardGridCell::getIndex()
{
    return index;
}
<|endoftext|>


<commit_before>// Copyright 2016 Vladimir Alyamkin. All Rights Reserved.

#include "VaRestLibrary.h"
#include "VaRestRequestJSON.h"
#include "VaRestJsonObject.h"
#include "VaRestPluginPrivatePCH.h"
#include "Base64.h"

//////////////////////////////////////////////////////////////////////////
// Helpers

FString UVaRestLibrary::PercentEncode(const FString& Source)
{
	FString OutText = Source;

	OutText = OutText.Replace(TEXT(" "), TEXT("%20"));
	OutText = OutText.Replace(TEXT("!"), TEXT("%21"));
	OutText = OutText.Replace(TEXT("\""), TEXT("%22"));
	OutText = OutText.Replace(TEXT("#"), TEXT("%23"));
	OutText = OutText.Replace(TEXT("$"), TEXT("%24"));
	OutText = OutText.Replace(TEXT("&"), TEXT("%26"));
	OutText = OutText.Replace(TEXT("'"), TEXT("%27"));
	OutText = OutText.Replace(TEXT("("), TEXT("%28"));
	OutText = OutText.Replace(TEXT(")"), TEXT("%29"));
	OutText = OutText.Replace(TEXT("*"), TEXT("%2A"));
	OutText = OutText.Replace(TEXT("+"), TEXT("%2B"));
	OutText = OutText.Replace(TEXT(","), TEXT("%2C"));
	OutText = OutText.Replace(TEXT("/"), TEXT("%2F"));
	OutText = OutText.Replace(TEXT(":"), TEXT("%3A"));
	OutText = OutText.Replace(TEXT(";"), TEXT("%3B"));
	OutText = OutText.Replace(TEXT("="), TEXT("%3D"));
	OutText = OutText.Replace(TEXT("?"), TEXT("%3F"));
	OutText = OutText.Replace(TEXT("@"), TEXT("%40"));
	OutText = OutText.Replace(TEXT("["), TEXT("%5B"));
	OutText = OutText.Replace(TEXT("]"), TEXT("%5D"));
	OutText = OutText.Replace(TEXT("{"), TEXT("%7B"));
	OutText = OutText.Replace(TEXT("}"), TEXT("%7D"));

	return OutText;
}

FString UVaRestLibrary::Base64Encode(const FString& Source)
{
	return FBase64::Encode(Source);
}

bool UVaRestLibrary::Base64Decode(const FString& Source, FString& Dest)
{
	return FBase64::Decode(Source, Dest);
}

bool UVaRestLibrary::Base64EncodeData(const TArray<uint8>& Data, FString& Dest)
{
	if (Data.Num() > 0)
	{
		Dest = FBase64::Encode(Data);
		return true;
	}

	return false;
}

bool UVaRestLibrary::Base64DecodeData(const FString& Source, TArray<uint8>& Dest)
{
	return FBase64::Decode(Source, Dest);
}

//////////////////////////////////////////////////////////////////////////
// File system integration

class UVaRestJsonObject* UVaRestLibrary::LoadJsonFromFile(UObject* WorldContextObject, const FString& Path)
{
	UVaRestJsonObject* Json = UVaRestJsonObject::ConstructJsonObject(WorldContextObject);

	FString JSONString;
	if (FFileHelper::LoadFileToString(JSONString, *(FPaths::ProjectContentDir() + Path)))
	{
		if (Json->DecodeJson(JSONString))
		{
			return Json;
		}
		else
		{
			UE_LOG(LogVaRest, Error, TEXT("%s: Can't decode json from file %s"), *VA_FUNC_LINE, *Path);
		}
	}
	else
	{
		UE_LOG(LogVaRest, Error, TEXT("%s: Can't open file %s"), *VA_FUNC_LINE, *Path);
	}

	return nullptr;
}

//////////////////////////////////////////////////////////////////////////
// Easy URL processing

TMap<UVaRestRequestJSON*, FVaRestCallResponse> UVaRestLibrary::RequestMap;

void UVaRestLibrary::CallURL(UObject* WorldContextObject, const FString& URL, ERequestVerb Verb, ERequestContentType ContentType, UVaRestJsonObject* VaRestJson, const FVaRestCallDelegate& Callback)
{
	UWorld* World = GEngine->GetWorldFromContextObjectChecked(WorldContextObject);
	if (World == nullptr)
	{
		UE_LOG(LogVaRest, Error, TEXT("UVaRestLibrary: Wrong world context"))
		return;
	}

	// Check we have valid data json
	if (VaRestJson == nullptr)
	{
		VaRestJson = UVaRestJsonObject::ConstructJsonObject(WorldContextObject);
	}

	UVaRestRequestJSON* Request = NewObject<UVaRestRequestJSON>();

	Request->SetVerb(Verb);
	Request->SetContentType(ContentType);
	Request->SetRequestObject(VaRestJson);

	FVaRestCallResponse Response;
	Response.Request = Request;
	Response.WorldContextObject = WorldContextObject;
	Response.Callback = Callback;

	Response.CompleteDelegateHandle = Request->OnStaticRequestComplete.AddStatic(&UVaRestLibrary::OnCallComplete);
	Response.FailDelegateHandle = Request->OnStaticRequestFail.AddStatic(&UVaRestLibrary::OnCallComplete);

	RequestMap.Add(Request, Response);

	Request->ResetResponseData();
	Request->ProcessURL(URL);
}

void UVaRestLibrary::OnCallComplete(UVaRestRequestJSON* Request)
{
	if (!RequestMap.Contains(Request))
	{
		return;
	}

	FVaRestCallResponse* Response = RequestMap.Find(Request);

	Request->OnStaticRequestComplete.Remove(Response->CompleteDelegateHandle);
	Request->OnStaticRequestFail.Remove(Response->FailDelegateHandle);

	Response->Callback.ExecuteIfBound(Request);

	Response->WorldContextObject = nullptr;
	Response->Request = nullptr;
	RequestMap.Remove(Request);
}
<commit_msg>Use percent encoding function from FGenericPlatformHttp.<commit_after>// Copyright 2016 Vladimir Alyamkin. All Rights Reserved.

#include "VaRestLibrary.h"
#include "VaRestRequestJSON.h"
#include "VaRestJsonObject.h"
#include "VaRestPluginPrivatePCH.h"
#include "Base64.h"

//////////////////////////////////////////////////////////////////////////
// Helpers

FString UVaRestLibrary::PercentEncode(const FString& Source)
{
	return FGenericPlatformHttp::UrlEncode(Source);
}

FString UVaRestLibrary::Base64Encode(const FString& Source)
{
	return FBase64::Encode(Source);
}

bool UVaRestLibrary::Base64Decode(const FString& Source, FString& Dest)
{
	return FBase64::Decode(Source, Dest);
}

bool UVaRestLibrary::Base64EncodeData(const TArray<uint8>& Data, FString& Dest)
{
	if (Data.Num() > 0)
	{
		Dest = FBase64::Encode(Data);
		return true;
	}

	return false;
}

bool UVaRestLibrary::Base64DecodeData(const FString& Source, TArray<uint8>& Dest)
{
	return FBase64::Decode(Source, Dest);
}

//////////////////////////////////////////////////////////////////////////
// File system integration

class UVaRestJsonObject* UVaRestLibrary::LoadJsonFromFile(UObject* WorldContextObject, const FString& Path)
{
	UVaRestJsonObject* Json = UVaRestJsonObject::ConstructJsonObject(WorldContextObject);

	FString JSONString;
	if (FFileHelper::LoadFileToString(JSONString, *(FPaths::ProjectContentDir() + Path)))
	{
		if (Json->DecodeJson(JSONString))
		{
			return Json;
		}
		else
		{
			UE_LOG(LogVaRest, Error, TEXT("%s: Can't decode json from file %s"), *VA_FUNC_LINE, *Path);
		}
	}
	else
	{
		UE_LOG(LogVaRest, Error, TEXT("%s: Can't open file %s"), *VA_FUNC_LINE, *Path);
	}

	return nullptr;
}

//////////////////////////////////////////////////////////////////////////
// Easy URL processing

TMap<UVaRestRequestJSON*, FVaRestCallResponse> UVaRestLibrary::RequestMap;

void UVaRestLibrary::CallURL(UObject* WorldContextObject, const FString& URL, ERequestVerb Verb, ERequestContentType ContentType, UVaRestJsonObject* VaRestJson, const FVaRestCallDelegate& Callback)
{
	UWorld* World = GEngine->GetWorldFromContextObjectChecked(WorldContextObject);
	if (World == nullptr)
	{
		UE_LOG(LogVaRest, Error, TEXT("UVaRestLibrary: Wrong world context"))
		return;
	}

	// Check we have valid data json
	if (VaRestJson == nullptr)
	{
		VaRestJson = UVaRestJsonObject::ConstructJsonObject(WorldContextObject);
	}

	UVaRestRequestJSON* Request = NewObject<UVaRestRequestJSON>();

	Request->SetVerb(Verb);
	Request->SetContentType(ContentType);
	Request->SetRequestObject(VaRestJson);

	FVaRestCallResponse Response;
	Response.Request = Request;
	Response.WorldContextObject = WorldContextObject;
	Response.Callback = Callback;

	Response.CompleteDelegateHandle = Request->OnStaticRequestComplete.AddStatic(&UVaRestLibrary::OnCallComplete);
	Response.FailDelegateHandle = Request->OnStaticRequestFail.AddStatic(&UVaRestLibrary::OnCallComplete);

	RequestMap.Add(Request, Response);

	Request->ResetResponseData();
	Request->ProcessURL(URL);
}

void UVaRestLibrary::OnCallComplete(UVaRestRequestJSON* Request)
{
	if (!RequestMap.Contains(Request))
	{
		return;
	}

	FVaRestCallResponse* Response = RequestMap.Find(Request);

	Request->OnStaticRequestComplete.Remove(Response->CompleteDelegateHandle);
	Request->OnStaticRequestFail.Remove(Response->FailDelegateHandle);

	Response->Callback.ExecuteIfBound(Request);

	Response->WorldContextObject = nullptr;
	Response->Request = nullptr;
	RequestMap.Remove(Request);
}
<|endoftext|>