<commit_before>/**
 * Doit.cpp
 * Doit is a basic exec shell that supports background tasks.
 *
 * @author Arthur Lockman <ajlockman@wpi.edu>
 */

#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <iomanip>
#include <time.h>

using namespace std;

/**
 * Print a stat returned from the getrusage() function.
 */
void printStat(char const *stat, long val)
{
    cout << left << setw(29) << stat << right << setw(10) << val << endl;
}

/**
 * Main function.
 * @param argc The argument count.
 * @param argv The arguments as text.
 */
int main(int argc, char **argv)
{
    if (argc == 1)
    {
        cout << "Executing as shell..." << endl;
        //Exec as shell
    }
    else if (argc > 1)
    {
        int pid;
        struct timeval start;
        gettimeofday(&start, NULL);
        long start_ms = start.tv_sec * 1000 + start.tv_usec / 1000;
        //Exec given command
        if ((pid = fork()) < 0) //fork failed
        {
            cerr << "Fork error!" << endl;
        }
        else if (pid == 0)   //is child
        {
            char *argvNew[argc];
            for (int i = 1; i < argc; i++)
            {
                argvNew[i - 1] = argv[i];
            }
            argvNew[argc - 1] = NULL;
            if (execvp(argvNew[0], argvNew) < 0)
            {
                cerr << "Execvp error!" << endl;
                exit(1);
            }
        }
        else //is parent
        {
            struct rusage childUsage;
            wait(0);
            cout << "Child finished." << endl;
            struct timeval end;
            gettimeofday(&end, NULL);
            long end_ms = end.tv_sec * 1000 + end.tv_usec / 1000;
            getrusage(RUSAGE_CHILDREN, &childUsage);
            printStat("Wall Clock Time:", end_ms - start_ms);
            printStat("User CPU Time:", 345678);
            printStat("System CPU Time:", 134134);
            printStat("Max RSS:", childUsage.ru_maxrss);
            printStat("Integral Shared Memory Size:", childUsage.ru_ixrss);
            printStat("Integral Unshared Data Size:", childUsage.ru_idrss);
            printStat("Integral Unshared Stack Size:", childUsage.ru_isrss);
            printStat("Page Reclaims:", childUsage.ru_minflt);
            printStat("Page Faults:", childUsage.ru_majflt);
            printStat("Swaps:", childUsage.ru_nswap);
            printStat("Block Input Operations:", childUsage.ru_inblock);
            printStat("Block Output Operations:", childUsage.ru_oublock);
            printStat("IPC Messages Sent:", childUsage.ru_msgsnd);
            printStat("IPC Messages Received:", childUsage.ru_msgrcv);
            printStat("Signals Received:", childUsage.ru_nsignals);
            printStat("Voluntary Context Switches:", childUsage.ru_nvcsw);
            printStat("Involuntary Context Switches:", childUsage.ru_nivcsw);

        }
    }
}

<commit_msg>Added basic shell outline.<commit_after>/**
 * Doit.cpp
 * Doit is a basic exec shell that supports background tasks.
 *
 * @author Arthur Lockman <ajlockman@wpi.edu>
 */

#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <iomanip>
#include <time.h>

using namespace std;

/**
 * Print a stat returned from the getrusage() function.
 */
void printStat(char const *stat, long val)
{
    cout << left << setw(29) << stat << right << setw(10) << val << endl;
}

/**
 * Main function.
 * @param argc The argument count.
 * @param argv The arguments as text.
 */
int main(int argc, char **argv)
{
    if (argc == 1)
    {
        cout << "Executing as shell..." << endl;
        int halt = 0;
        while (!halt)
        {
            cout << "% ";
            string cmd;
            getline(cin, cmd);
            cout << "Read: " << cmd << endl;
            if (cmd == "exit")
                halt = 1;
            //TODO: Parse commands
            int pid;
            if ((pid = fork()) < 0) //fork failed
            {
                cerr << "Fork error!" << endl;
            }
            else if (pid == 0) //is child
            {
                //TODO: exec parsed process
            }
            else //is parent
            {
                wait(0);
                //TODO: Does this need to print stats?
            }
        }
    }
    else if (argc > 1)
    {
        int pid;
        struct timeval start;
        gettimeofday(&start, NULL);
        long start_ms = start.tv_sec * 1000 + start.tv_usec / 1000;
        //Exec given command
        if ((pid = fork()) < 0) //fork failed
        {
            cerr << "Fork error!" << endl;
        }
        else if (pid == 0)   //is child
        {
            char *argvNew[argc];
            for (int i = 1; i < argc; i++)
            {
                argvNew[i - 1] = argv[i];
            }
            argvNew[argc - 1] = NULL;
            if (execvp(argvNew[0], argvNew) < 0)
            {
                cerr << "Execvp error!" << endl;
                exit(1);
            }
        }
        else //is parent
        {
            struct rusage childUsage;
            wait(0);
            cout << endl << "Child finished." << endl;
            struct timeval end;
            gettimeofday(&end, NULL);
            long end_ms = end.tv_sec * 1000 + end.tv_usec / 1000;
            getrusage(RUSAGE_CHILDREN, &childUsage);
            printStat("Wall Clock Time:", end_ms - start_ms);
            printStat("User CPU Time:", childUsage.ru_utime.tv_sec * 1000 + childUsage.ru_utime.tv_usec / 1000);
            printStat("System CPU Time:", childUsage.ru_stime.tv_sec * 1000 + childUsage.ru_stime.tv_usec / 1000);
            printStat("Max RSS:", childUsage.ru_maxrss);
            printStat("Integral Shared Memory Size:", childUsage.ru_ixrss);
            printStat("Integral Unshared Data Size:", childUsage.ru_idrss);
            printStat("Integral Unshared Stack Size:", childUsage.ru_isrss);
            printStat("Page Reclaims:", childUsage.ru_minflt);
            printStat("Page Faults:", childUsage.ru_majflt);
            printStat("Swaps:", childUsage.ru_nswap);
            printStat("Block Input Operations:", childUsage.ru_inblock);
            printStat("Block Output Operations:", childUsage.ru_oublock);
            printStat("IPC Messages Sent:", childUsage.ru_msgsnd);
            printStat("IPC Messages Received:", childUsage.ru_msgrcv);
            printStat("Signals Received:", childUsage.ru_nsignals);
            printStat("Voluntary Context Switches:", childUsage.ru_nvcsw);
            printStat("Involuntary Context Switches:", childUsage.ru_nivcsw);

        }
    }
}

<|endoftext|>


<commit_before>/*
 * Copyright 2015 - 2021 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#pragma once

#include <ox/mc/read.hpp>
#ifdef OX_USE_STDLIB
#include <ox/oc/read.hpp>
#endif
#include <ox/std/string.hpp>
#include <ox/std/vector.hpp>

#include "format.hpp"

namespace ox {

namespace detail {

struct ClawHeader {
	String typeName;
	int typeVersion = -1;
	ClawFormat fmt = ClawFormat::None;
	const char *data = nullptr;
	std::size_t dataSize = 0;
};

Result<ClawHeader> readHeader(const char *buff, std::size_t buffLen) noexcept;

}

Result<Vector<char>> stripClawHeader(const char *buff, std::size_t buffLen) noexcept;

template<typename T>
Error readClaw(const char *buff, std::size_t buffLen, T *val) {
	oxRequire(header, detail::readHeader(buff, buffLen));
	switch (header.fmt) {
		case ClawFormat::Metal:
		{
			MetalClawReader reader(bit_cast<uint8_t*>(header.data), buffLen);
			return model(&reader, val);
		}
#ifdef OX_USE_STDLIB
		case ClawFormat::Organic:
		{
			OrganicClawReader reader(bit_cast<uint8_t*>(header.data), buffLen);
			return model(&reader, val);
		}
#endif
		case ClawFormat::None:
			return OxError(1);
	}
	return OxError(1);
}

template<typename T>
Result<T> readClaw(const char *buff, std::size_t buffLen) {
	T val;
	oxReturnError(readClaw(buff, buffLen, &val));
	return ox::move(val);
}

template<typename T>
Result<T> readClaw(const Vector<char> &buff) {
	return readClaw<T>(buff.data(), buff.size());
}

}
<commit_msg>[ox/claw] Cleanup<commit_after>/*
 * Copyright 2015 - 2021 gary@drinkingtea.net
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#pragma once

#include <ox/mc/read.hpp>
#ifdef OX_USE_STDLIB
#include <ox/oc/read.hpp>
#endif
#include <ox/std/string.hpp>
#include <ox/std/vector.hpp>

#include "format.hpp"

namespace ox {

namespace detail {

struct ClawHeader {
	String typeName;
	int typeVersion = -1;
	ClawFormat fmt = ClawFormat::None;
	const char *data = nullptr;
	std::size_t dataSize = 0;
};

Result<ClawHeader> readHeader(const char *buff, std::size_t buffLen) noexcept;

}

Result<Vector<char>> stripClawHeader(const char *buff, std::size_t buffLen) noexcept;

template<typename T>
Error readClaw(const char *buff, std::size_t buffLen, T *val) {
	oxRequire(header, detail::readHeader(buff, buffLen));
	switch (header.fmt) {
		case ClawFormat::Metal:
		{
			MetalClawReader reader(bit_cast<uint8_t*>(header.data), buffLen);
			return model(&reader, val);
		}
#ifdef OX_USE_STDLIB
		case ClawFormat::Organic:
		{
			OrganicClawReader reader(bit_cast<uint8_t*>(header.data), buffLen);
			return model(&reader, val);
		}
#endif
		case ClawFormat::None:
			return OxError(1);
	}
	return OxError(1);
}

template<typename T>
Result<T> readClaw(const char *buff, std::size_t buffLen) {
	T val;
	oxReturnError(readClaw(buff, buffLen, &val));
	return move(val);
}

template<typename T>
Result<T> readClaw(const Vector<char> &buff) {
	return readClaw<T>(buff.data(), buff.size());
}

}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <map>
#include <node.h>

#include "PSATResult.h"
#include "calculator/EstimateFLA.h"

using namespace v8;
using namespace std;

Isolate* iso;
Local<Object> inp;

double Get(const char *nm) {
  auto r = inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue();
  if (isnan(r)) {
    cout << nm;
    assert(!"number");
  }
  return r;
}

void Results(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  inp = args[0]->ToObject();
  auto r = Object::New(iso);

  auto drive = (Pump::Drive)(int)Get("drive");
  auto effCls = (Motor::EfficiencyClass)(int)Get("efficiency_class");
  Pump pump((Pump::Style)(int)Get("pump_style"),Get("pump_specified"),Get("pump_rated_speed"),drive,
      Get("viscosity"),Get("specific_gravity"),Get("stages"),(Pump::Speed)(int)(!Get("fixed_speed")));
  Motor motor((Motor::LineFrequency)(int)(!Get("line")),Get("motor_rated_power"),Get("motor_rated_speed"),
      effCls,Get("efficiency"),Get("motor_rated_voltage"),Get("motor_rated_flc"),Get("margin"));
  Financial fin(Get("fraction"),Get("cost"));
  FieldData fd(Get("flow"),Get("head"),(FieldData::LoadEstimationMethod)(Get("motor_field_power")>0?0:1),
      Get("motor_field_power"),Get("motor_field_current"),Get("motor_field_voltage"));
  PSATResult psat(pump,motor,fin,fd);
  psat.calculateExisting();
  psat.calculateOptimal();
  auto ex = psat.getExisting(), opt = psat.getOptimal();

  map<const char *,vector<double>> out = {
    {"Pump Efficiency",{ex.pumpEfficiency_*100,opt.pumpEfficiency_*100}},
    {"Motor Rated Power",{ex.motorRatedPower_,opt.motorRatedPower_}},
    {"Motor Shaft Power",{ex.motorShaftPower_,opt.motorShaftPower_}},
    {"Pump Shaft Power",{ex.pumpShaftPower_,opt.pumpShaftPower_}},
    {"Motor Efficiency",{ex.motorEfficiency_,opt.motorEfficiency_}},
    {"Motor Power Factor",{ex.motorPowerFactor_,opt.motorPowerFactor_}},
    {"Motor Current",{ex.motorCurrent_,opt.motorCurrent_}},
    {"Motor Power", {ex.motorPower_,opt.motorPower_}},
    {"Annual Energy", {ex.annualEnergy_,opt.annualEnergy_}},
    {"Annual Cost", {ex.annualCost_*1000,opt.annualCost_*1000}},
    {"Savings Potential", {psat.getAnnualSavingsPotential(),0}},
    {"Optimization Rating", {psat.getOptimizationRating(),0}}
  };
  for(auto p: out) {
    auto a = Array::New(iso);
    a->Set(0,Number::New(iso,p.second[0]));
    a->Set(1,Number::New(iso,p.second[1]));
    r->Set(String::NewFromUtf8(iso,p.first),a);
  }
  args.GetReturnValue().Set(r);
}

void EstFLA(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  inp = args[0]->ToObject();

  EstimateFLA fla(Get("motor_rated_power"),Get("motor_rated_speed"),(Motor::LineFrequency)(int)(!Get("line")),(Motor::EfficiencyClass)(int)Get("efficiency_class"),
    Get("efficiency"),Get("motor_rated_voltage"));
  fla.calculate();
  args.GetReturnValue().Set(fla.getEstimatedFLA());
}
//TODO round vs js round; loosen up to make next test case
void Check(double exp, double act, const char* nm="") {
  //cout << "e " << exp << "; a " << act << endl;
  // if (isnan(act) || (abs(exp-act)>.01*exp)) {
  auto p = 10;
  if (isnan(act) || ( (round(exp*p)/p)!=round(act*p)/p)) {
    printf("\"%s\" TEST FAILED: %f %f\n",nm,exp,act);
    assert(!"equal");
  }
}

void Check100(double exp, double act, const char* nm="") {
  Check(exp,act*100,nm);
}

void Test(const FunctionCallbackInfo<Value>& args) {
  EstimateFLA fla(200,1780,(Motor::LineFrequency)1,(Motor::EfficiencyClass)(1),0,460);
  fla.calculate();
  Check(225.8,fla.getEstimatedFLA());

  #define BASE \
    Pump pump(Pump::Style::END_SUCTION_ANSI_API,0,1780,Pump::Drive::DIRECT_DRIVE,\
      1,1,1,Pump::Speed::NOT_FIXED_SPEED);\
    Motor motor(Motor::LineFrequency::FREQ60,200,1780,\
        Motor::EfficiencyClass::ENERGY_EFFICIENT,0,460,225.8,0);\
    Financial fin(1,.05);\
    FieldData fd(2000,277,FieldData::LoadEstimationMethod::POWER,\
        150,0,460);

  #define CALC \
    PSATResult psat(pump,motor,fin,fd);\
    psat.calculateExisting();\
    auto ex = psat.getExisting();

  for (int i=1; i<=10000; i=i+2) {
    BASE
    CALC
    Check(ex.motorShaftPower_,ex.motorShaftPower_,"SAME");
  }

  {
    BASE
    motor.setMotorRpm(1786);
    fd.setMotorPower(80);
    CALC
    Check(101.9,ex.motorShaftPower_);
    Check100(95,ex.motorEfficiency_);
    Check100(79.1,ex.motorPowerFactor_);
    Check(127,ex.motorCurrent_);
  }
  {
    BASE
    fd.setMotorPower(80);
    motor.setMotorRatedPower(100);
    motor.setFullLoadAmps(113.8);
    CALC
    Check(101.8,ex.motorShaftPower_);
    Check100(94.9,ex.motorEfficiency_);
    Check100(86.7,ex.motorPowerFactor_);
    Check(115.8,ex.motorCurrent_);
  }
  {
    BASE
    fd.setMotorPower(80);
    fd.setVoltage(260);
    CALC
    Check(101.9,ex.motorShaftPower_);
    Check100(95,ex.motorEfficiency_);
    Check100(138.8,ex.motorPowerFactor_);
    Check(128,ex.motorCurrent_);
  }
  {
    BASE
    motor.setMotorRpm(1200);
    fd.setMotorPower(80);
    motor.setFullLoadAmps(235.3);
    CALC
    Check(101.4,ex.motorShaftPower_);
    Check100(94.5,ex.motorEfficiency_);
    Check100(74.3,ex.motorPowerFactor_);
    Check(135.1,ex.motorCurrent_);
  }
  {
    BASE
    fd.setMotorPower(111.855);
    CALC
    Check(143.4,ex.motorShaftPower_);
    Check100(95.6,ex.motorEfficiency_);
    Check100(84.3,ex.motorPowerFactor_);
    Check(166.5,ex.motorCurrent_);
  }
  {
    BASE
    fd.setMotorPower(80);
    motor.setMotorRatedVoltage(200);
    motor.setFullLoadAmps(519.3);
    CALC
    Check(101.9,ex.motorShaftPower_);
    Check100(95,ex.motorEfficiency_);
    Check100(35.2,ex.motorPowerFactor_);
    Check(285,ex.motorCurrent_);
  }
  {
    BASE
    CALC
    Check(217.1,ex.motorCurrent_);
  }
  {
    BASE
    fd.setLoadEstimationMethod(FieldData::LoadEstimationMethod::CURRENT);
    fd.setMotorAmps(218);
    fd.setMotorPower(0);
    CALC
    Check(150.7,ex.motorPower_);
    Check100(72.5,ex.pumpEfficiency_);
  }
  {
    BASE
    fd.setMotorPower(80);
    CALC
    Check(700.8,ex.annualEnergy_);
  }
  {
    BASE
    fin.setOperatingFraction(.25);
    CALC
    Check(328.5,ex.annualEnergy_);
    Check(16.4,ex.annualCost_);
  }
  {
    BASE
    motor.setFullLoadAmps(300);
    CALC
    Check(288.9,ex.motorCurrent_);
  }
  {
    BASE
    motor.setEfficiencyClass(Motor::EfficiencyClass(0));
    CALC
    Check(213.7,ex.motorCurrent_);
  }
  {
    BASE
    motor.setEfficiencyClass(Motor::EfficiencyClass(2));
    motor.setSpecifiedEfficiency(75);
    CALC
    Check(173.7,ex.motorCurrent_);
  }
  cout << "done";
}

void Wtf(const FunctionCallbackInfo<Value>& args) {
}

void Init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "results", Results);
  NODE_SET_METHOD(exports, "estFLA", EstFLA);
  NODE_SET_METHOD(exports, "test", Test);
  NODE_SET_METHOD(exports, "wtf", Wtf);
}

NODE_MODULE(bridge, Init)

<commit_msg>no message<commit_after>#include <iostream>
#include <vector>
#include <map>
#include <node.h>

#include "PSATResult.h"
#include "calculator/EstimateFLA.h"

using namespace v8;
using namespace std;

Isolate* iso;
Local<Object> inp;

double Get(const char *nm) {
  auto r = inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue();
  if (isnan(r)) {
    cout << nm;
    assert(!"number");
  }
  return r;
}

void Results(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  inp = args[0]->ToObject();
  auto r = Object::New(iso);

  auto drive = (Pump::Drive)(int)Get("drive");
  auto effCls = (Motor::EfficiencyClass)(int)Get("efficiency_class");
  Pump pump((Pump::Style)(int)Get("pump_style"),Get("pump_specified"),Get("pump_rated_speed"),drive,
      Get("viscosity"),Get("specific_gravity"),Get("stages"),(Pump::Speed)(int)(!Get("fixed_speed")));
  Motor motor((Motor::LineFrequency)(int)(!Get("line")),Get("motor_rated_power"),Get("motor_rated_speed"),
      effCls,Get("efficiency"),Get("motor_rated_voltage"),Get("motor_rated_flc"),Get("margin"));
  Financial fin(Get("fraction"),Get("cost"));
  FieldData fd(Get("flow"),Get("head"),(FieldData::LoadEstimationMethod)(Get("motor_field_power")>0?0:1),
      Get("motor_field_power"),Get("motor_field_current"),Get("motor_field_voltage"));
  PSATResult psat(pump,motor,fin,fd);
  psat.calculateExisting();
  psat.calculateOptimal();
  auto ex = psat.getExisting(), opt = psat.getOptimal();

  map<const char *,vector<double>> out = {
    {"Pump Efficiency",{ex.pumpEfficiency_*100,opt.pumpEfficiency_*100}},
    {"Motor Rated Power",{ex.motorRatedPower_,opt.motorRatedPower_}},
    {"Motor Shaft Power",{ex.motorShaftPower_,opt.motorShaftPower_}},
    {"Pump Shaft Power",{ex.pumpShaftPower_,opt.pumpShaftPower_}},
    {"Motor Efficiency",{ex.motorEfficiency_,opt.motorEfficiency_}},
    {"Motor Power Factor",{ex.motorPowerFactor_,opt.motorPowerFactor_}},
    {"Motor Current",{ex.motorCurrent_,opt.motorCurrent_}},
    {"Motor Power", {ex.motorPower_,opt.motorPower_}},
    {"Annual Energy", {ex.annualEnergy_,opt.annualEnergy_}},
    {"Annual Cost", {ex.annualCost_*1000,opt.annualCost_*1000}},
    {"Savings Potential", {psat.getAnnualSavingsPotential(),0}},
    {"Optimization Rating", {psat.getOptimizationRating(),0}}
  };
  for(auto p: out) {
    auto a = Array::New(iso);
    a->Set(0,Number::New(iso,p.second[0]));
    a->Set(1,Number::New(iso,p.second[1]));
    r->Set(String::NewFromUtf8(iso,p.first),a);
  }
  args.GetReturnValue().Set(r);
}

void EstFLA(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  inp = args[0]->ToObject();

  EstimateFLA fla(Get("motor_rated_power"),Get("motor_rated_speed"),(Motor::LineFrequency)(int)(!Get("line")),(Motor::EfficiencyClass)(int)Get("efficiency_class"),
    Get("efficiency"),Get("motor_rated_voltage"));
  fla.calculate();
  args.GetReturnValue().Set(fla.getEstimatedFLA());
}
//TODO round vs js round; loosen up to make next test case
void Check(double exp, double act, const char* nm="") {
  //cout << "e " << exp << "; a " << act << endl;
  // if (isnan(act) || (abs(exp-act)>.01*exp)) {
  auto p = 10;
  if (isnan(act) || ( (round(exp*p)/p)!=round(act*p)/p)) {
    printf("\"%s\" TEST FAILED: %f %f\n",nm,exp,act);
    assert(!"equal");
  }
}

void Check100(double exp, double act, const char* nm="") {
  Check(exp,act*100,nm);
}

void Test(const FunctionCallbackInfo<Value>& args) {
  EstimateFLA fla(200,1780,(Motor::LineFrequency)1,(Motor::EfficiencyClass)(1),0,460);
  fla.calculate();
  Check(225.8,fla.getEstimatedFLA());

  #define BASE \
    Pump pump(Pump::Style::END_SUCTION_ANSI_API,0,1780,Pump::Drive::DIRECT_DRIVE,\
      1,1,1,Pump::Speed::NOT_FIXED_SPEED);\
    Motor motor(Motor::LineFrequency::FREQ60,200,1780,\
        Motor::EfficiencyClass::ENERGY_EFFICIENT,0,460,225.8,0);\
    Financial fin(1,.05);\
    FieldData fd(2000,277,FieldData::LoadEstimationMethod::POWER,\
        150,0,460);

  #define CALC \
    PSATResult psat(pump,motor,fin,fd);\
    psat.calculateExisting();\
    auto ex = psat.getExisting();

  for (int i=1; i<=10000; i=i+2) {
    BASE
    CALC
    Check(ex.motorShaftPower_,ex.motorShaftPower_,"SAME");
  }

  {
    BASE
    motor.setMotorRpm(1786);
    fd.setMotorPower(80);
    CALC
    Check(101.9,ex.motorShaftPower_);
    Check100(95,ex.motorEfficiency_);
    Check100(79.1,ex.motorPowerFactor_);
    Check(127,ex.motorCurrent_);
  }
  {
    BASE
    fd.setMotorPower(80);
    motor.setMotorRatedPower(100);
    motor.setFullLoadAmps(113.8);
    CALC
    Check(101.8,ex.motorShaftPower_);
    Check100(94.9,ex.motorEfficiency_);
    Check100(86.7,ex.motorPowerFactor_);
    Check(115.8,ex.motorCurrent_);
  }
  {
    BASE
    fd.setMotorPower(80);
    fd.setVoltage(260);
    CALC
    Check(101.9,ex.motorShaftPower_);
    Check100(95,ex.motorEfficiency_);
    Check100(138.8,ex.motorPowerFactor_);
    Check(128,ex.motorCurrent_);
  }
  {
    BASE
    motor.setMotorRpm(1200);
    fd.setMotorPower(80);
    motor.setFullLoadAmps(235.3);
    CALC
    Check(101.4,ex.motorShaftPower_);
    Check100(94.5,ex.motorEfficiency_);
    Check100(74.3,ex.motorPowerFactor_);
    Check(135.1,ex.motorCurrent_);
  }
  {
    BASE
    fd.setMotorPower(111.855);
    CALC
    Check(143.4,ex.motorShaftPower_);
    Check100(95.6,ex.motorEfficiency_);
    Check100(84.3,ex.motorPowerFactor_);
    Check(166.5,ex.motorCurrent_);
  }
  {
    BASE
    fd.setMotorPower(80);
    motor.setMotorRatedVoltage(200);
    motor.setFullLoadAmps(519.3);
    CALC
    Check(101.9,ex.motorShaftPower_);
    Check100(95,ex.motorEfficiency_);
    Check100(35.2,ex.motorPowerFactor_);
    Check(284.9,ex.motorCurrent_);
  }
  {
    BASE
    CALC
    Check(217.5,ex.motorCurrent_);
  }
  {
    BASE
    fd.setLoadEstimationMethod(FieldData::LoadEstimationMethod::CURRENT);
    fd.setMotorAmps(218);
    fd.setMotorPower(0);
    CALC
    Check(150.4,ex.motorPower_);
    Check100(72.5,ex.pumpEfficiency_);
  }
  {
    BASE
    fd.setMotorPower(80);
    CALC
    Check(700.8,ex.annualEnergy_);
  }
  {
    BASE
    fin.setOperatingFraction(.25);
    CALC
    Check(328.5,ex.annualEnergy_);
    Check(16.4,ex.annualCost_);
  }
  {
    BASE
    motor.setFullLoadAmps(300);
    CALC
    Check(288.9,ex.motorCurrent_);
  }
  {
    BASE
    motor.setEfficiencyClass(Motor::EfficiencyClass(0));
    CALC
    Check(213.7,ex.motorCurrent_);
  }
  {
    BASE
    motor.setEfficiencyClass(Motor::EfficiencyClass(2));
    motor.setSpecifiedEfficiency(75);
    CALC
    Check(173.7,ex.motorCurrent_);
  }
  cout << "done";
}

void Wtf(const FunctionCallbackInfo<Value>& args) {
}

void Init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "results", Results);
  NODE_SET_METHOD(exports, "estFLA", EstFLA);
  NODE_SET_METHOD(exports, "test", Test);
  NODE_SET_METHOD(exports, "wtf", Wtf);
}

NODE_MODULE(bridge, Init)

<|endoftext|>


<commit_before>#include <node.h>
#include <initializer_list>

#include "Pump.h"
#include "calculator/PumpEfficiency.h"
#include "calculator/OptimalPumpEfficiency.h"
#include "calculator/MotorRatedPower.h"
#include "calculator/OptimalMotorRatedPower.h"
#include "calculator/MotorShaftPower.h"
#include "calculator/OptimalMotorShaftPower.h"
#include "calculator/PumpShaftPower.h"
#include "calculator/OptimalPumpShaftPower.h"
#include "calculator/MotorEfficiency.h"
#include "calculator/OptimalMotorEfficiency.h"
#include "calculator/MotorPowerFactor.h"
#include "calculator/OptimalMotorPowerFactor.h"
#include "calculator/MotorCurrent.h"
#include "calculator/OptimalMotorCurrent.h"
#include "calculator/MotorPower.h"
#include "calculator/OptimalMotorPower.h"
#include "AnnualEnergy.h"
#include "AnnualCost.h"
#include "AnnualSavingsPotential.h"
#include "OptimizationRating.h"

using namespace v8;

Local<Array> r;
Isolate* iso;
Local<Object> inp;

void set(std::initializer_list <double> args) {
  for (auto d : args) {
    r->Set(r->Length(),Number::New(iso,d));
  }
}
double get(const char *nm) {
  return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue();
}
void Results(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  r = Array::New(iso);
  inp = args[0]->ToObject();

  auto loadMeth = get("motor_field_power")>0 ? FieldData::LoadEstimationMethod::POWER : FieldData::LoadEstimationMethod::CURRENT;
  auto drive = static_cast<Pump::Drive>(get("drive"));
  auto effCls = static_cast<Motor::EfficiencyClass>(get("efficiency_class"));
  set({
    (new PumpEfficiency(get("specific_gravity"),get("flow"),get("head"),0))->calculate(),//pumpShaftPower
    (new OptimalPumpEfficiency(static_cast<Pump::Style>(get("style")),get("pump_rated_speed"),get("viscosity"),get("stages"),get("flow"),get("head"),static_cast<Pump::Speed>(!get("speed"))))->calculate(),//
    get("motor_rated_power"),
    (new OptimalMotorRatedPower(0,get("margin")))->calculate(),//motorshaftpower
    (new MotorShaftPower(0,0))->calculate(),//motor eff, motor power (sometimes inp? sometimes calc)
    (new OptimalMotorShaftPower(0,drive))->calculate(),//pumpshaftpower
    (new PumpShaftPower(0,drive))->calculate(),//motorshaftpower
    (new OptimalPumpShaftPower(get("flow"),get("head"),get("specific_gravity"),0))->calculate(),//pumpeff
    (new MotorEfficiency(get("line"),get("motor_rated_speed"),effCls,get("motor_rated_power"),
      loadMeth,0,0,get("field_voltage")))->calculate(),//motorKwh??, motor amps
    (new OptimalMotorEfficiency(get("motor_rated_power"),0))->calculate(),//motor shaft power
    (new MotorPowerFactor(get("line"),get("rpm"),effCls,get("power_rating"),
      loadMeth,0,0,get("field_voltage")))->calculate(),//motor kwh,motor a
    (new OptimalMotorPowerFactor(get("motor_rated_power"),0))->calculate(),//motor power
    (new MotorCurrent(0,0,get("field_voltage")))->calculate(),//motor a, motor power
    (new OptimalMotorCurrent(0,get("field_voltage")))->calculate(),//motor power
    (new MotorPower(0,0,0,get("field_voltage")))->calculate(),//motor power (makes no sense, it IS motor power), motor a, motorpf
    (new OptimalMotorPower(0,0))->calculate(),//motorshaftpower, motor eff
    (new AnnualEnergy(0,get("fraction")))->calculate(),//motorpower
    (new AnnualEnergy(0,get("fraction")))->calculate(),//motorpower
    (new AnnualCost(0,get("cost")))->calculate(),//ex ann energy
    (new AnnualCost(0,get("cost")))->calculate(),//opt ann energy
    -1,
    (new AnnualSavingsPotential(0,0))->calculate(),//ex an cost, opt an cost
    -1,
    (new OptimizationRating(0,0))->calculate()//ex an cost, opt an cost
  });
  args.GetReturnValue().Set(r);
}

void init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "results", Results);
}

NODE_MODULE(bridge, init)

<commit_msg>no message<commit_after>#include <node.h>
#include <initializer_list>

#include "Pump.h"
#include "calculator/PumpEfficiency.h"
#include "calculator/OptimalPumpEfficiency.h"
#include "calculator/MotorRatedPower.h"
#include "calculator/OptimalMotorRatedPower.h"
#include "calculator/MotorShaftPower.h"
#include "calculator/OptimalMotorShaftPower.h"
#include "calculator/PumpShaftPower.h"
#include "calculator/OptimalPumpShaftPower.h"
#include "calculator/MotorEfficiency.h"
#include "calculator/OptimalMotorEfficiency.h"
#include "calculator/MotorPowerFactor.h"
#include "calculator/OptimalMotorPowerFactor.h"
#include "calculator/MotorCurrent.h"
#include "calculator/OptimalMotorCurrent.h"
#include "calculator/MotorPower.h"
#include "calculator/OptimalMotorPower.h"
#include "AnnualEnergy.h"
#include "AnnualCost.h"
#include "AnnualSavingsPotential.h"
#include "OptimizationRating.h"

using namespace v8;

Local<Array> r;
Isolate* iso;
Local<Object> inp;

void set(std::initializer_list <double> args) {
  for (auto d : args) {
    r->Set(r->Length(),Number::New(iso,d));
  }
}
double get(const char *nm) {
  return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue();
}
void Results(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  r = Array::New(iso);
  inp = args[0]->ToObject();

  auto loadMeth = get("motor_field_power")>0 ? FieldData::LoadEstimationMethod::POWER : FieldData::LoadEstimationMethod::CURRENT;
  auto drive = static_cast<Pump::Drive>(get("drive"));
  auto effCls = static_cast<Motor::EfficiencyClass>(get("efficiency_class"));
  double mp = get("motor_field_power")>0 ? get("motor_field_power") : (new MotorPower(0,get("motor_field_current"),0,get("field_voltage")))->calculate();//motor power (makes no sense, it IS motor power), motor a, motorpf
  double mc = get("motor_field_current")>0 ? get("motor_field_current") : (new MotorCurrent(0,get("motor_field_power"),get("field_voltage")))->calculate();//motor a, motor power, recursive arg!!
  set({
    (new PumpEfficiency(get("specific_gravity"),get("flow"),get("head"),0))->calculate(),//pumpShaftPower
    (new OptimalPumpEfficiency(static_cast<Pump::Style>(get("style")),get("pump_rated_speed"),get("viscosity"),get("stages"),get("flow"),get("head"),static_cast<Pump::Speed>(!get("speed"))))->calculate(),//
    get("motor_rated_power"),
    (new OptimalMotorRatedPower(0,get("margin")))->calculate(),//motorshaftpower
    (new MotorShaftPower(0,0))->calculate(),//motor eff, motor power (sometimes inp? sometimes calc)
    (new OptimalMotorShaftPower(0,drive))->calculate(),//pumpshaftpower
    (new PumpShaftPower(0,drive))->calculate(),//motorshaftpower
    (new OptimalPumpShaftPower(get("flow"),get("head"),get("specific_gravity"),0))->calculate(),//pumpeff
    (new MotorEfficiency(get("line"),get("motor_rated_speed"),effCls,get("motor_rated_power"),
      loadMeth,0,0,get("field_voltage")))->calculate(),//motorKwh??, motor amps
    (new OptimalMotorEfficiency(get("motor_rated_power"),0))->calculate(),//motor shaft power
    (new MotorPowerFactor(get("line"),get("rpm"),effCls,get("power_rating"),
      loadMeth,0,0,get("field_voltage")))->calculate(),//motor kwh,motor a
    (new OptimalMotorPowerFactor(get("motor_rated_power"),0))->calculate(),//motor power
    mc,
    (new OptimalMotorCurrent(0,get("field_voltage")))->calculate(),//opt motor power
    mp,
    (new OptimalMotorPower(0,0))->calculate(),//motorshaftpower, motor eff
    (new AnnualEnergy(mp,get("fraction")))->calculate(),//motorpower
    (new AnnualEnergy(0,get("fraction")))->calculate(),//opt motorpower
    (new AnnualCost(0,get("cost")))->calculate(),//ex ann energy
    (new AnnualCost(0,get("cost")))->calculate(),//opt ann energy
    -1,
    (new AnnualSavingsPotential(0,0))->calculate(),//ex an cost, opt an cost
    -1,
    (new OptimizationRating(0,0))->calculate()//ex an cost, opt an cost
  });
  args.GetReturnValue().Set(r);
}

void init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "results", Results);
}

NODE_MODULE(bridge, init)

<|endoftext|>


<commit_before>#include <node.h>
#include "../api//Pump.h"
#include "../api/Calculator/PumpEfficiency.h"
#include "../api/Calculator/OptimalPumpEfficiency.h"
#include "../api/Calculator/MotorRatedPower.h"
#include "../api/Calculator/OptimalMotorRatedPower.h"
#include "../api/Calculator/MotorShaftPower.h"
#include "../api/Calculator/OptimalMotorShaftPower.h"
#include "../api/Calculator/PumpShaftPower.h"
#include "../api/Calculator/OptimalPumpShaftPower.h"

using namespace v8;

Local<Array> r;
Isolate* iso;

void set(double v1, double v2) {
  r->Set(r->Length(),Number::New(iso,v1));
  r->Set(r->Length(),Number::New(iso,v2));
}
void Results(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  r = Array::New(iso);

  set((new PumpEfficiency(0,0,0,0))->calculate(),
    (new OptimalPumpEfficiency(Pump::Style::END_SUCTION_SLURRY,0,0,0,0,0,Pump::Speed::FIXED_SPECIFIC_SPEED))->calculate());
  set((new MotorRatedPower(0))->calculate(),(new OptimalMotorRatedPower(0,0))->calculate());
  set((new MotorShaftPower(0,0))->calculate(),(new OptimalMotorShaftPower(0,Pump::Drive::DIRECT_DRIVE))->calculate());
  set((new PumpShaftPower(0,Pump::Drive::DIRECT_DRIVE))->calculate(),(new OptimalPumpShaftPower(0,0,0,0))->calculate());

  args.GetReturnValue().Set(r);
}

void init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "results", Results);
}

NODE_MODULE(bridge, init)

<commit_msg>no message<commit_after>#include <node.h>
#include "../api//Pump.h"
#include "../api/Calculator/PumpEfficiency.h"
#include "../api/Calculator/OptimalPumpEfficiency.h"
#include "../api/Calculator/MotorRatedPower.h"
#include "../api/Calculator/OptimalMotorRatedPower.h"
#include "../api/Calculator/MotorShaftPower.h"
#include "../api/Calculator/OptimalMotorShaftPower.h"
#include "../api/Calculator/PumpShaftPower.h"
#include "../api/Calculator/OptimalPumpShaftPower.h"
#include "../api/Calculator/MotorEfficiency.h"
#include "../api/Calculator/OptimalMotorEfficiency.h"

using namespace v8;

Local<Array> r;
Isolate* iso;

void set(double v1, double v2) {
  r->Set(r->Length(),Number::New(iso,v1));
  r->Set(r->Length(),Number::New(iso,v2));
}
void Results(const FunctionCallbackInfo<Value>& args) {
  iso = args.GetIsolate();
  r = Array::New(iso);

  set((new PumpEfficiency(0,0,0,0))->calculate(),
    (new OptimalPumpEfficiency(Pump::Style::END_SUCTION_SLURRY,0,0,0,0,0,Pump::Speed::FIXED_SPECIFIC_SPEED))->calculate());
  set((new MotorRatedPower(0))->calculate(),(new OptimalMotorRatedPower(0,0))->calculate());
  set((new MotorShaftPower(0,0))->calculate(),(new OptimalMotorShaftPower(0,Pump::Drive::DIRECT_DRIVE))->calculate());
  set((new PumpShaftPower(0,Pump::Drive::DIRECT_DRIVE))->calculate(),(new OptimalPumpShaftPower(0,0,0,0))->calculate());
  set((new MotorEfficiency(0,0,Motor::EfficiencyClass::STANDARD,0,FieldData::LoadEstimationMethod::POWER,0,0,0))->calculate(),
    (new OptimalMotorEfficiency(0,0))->calculate());

  args.GetReturnValue().Set(r);
}

void init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "results", Results);
}

NODE_MODULE(bridge, init)

<|endoftext|>


<commit_before>#include "Board.h"
#include "Pawn.h"
#include "Rook.h"
#include "Knight.h"
#include "Bishop.h"
#include "Queen.h"
#include "King.h"
#include <iostream>
#include <sstream>

namespace Chess {
	Board::Board() {
		for (int x = 0; x < 8; x++) {
			for (int y = 0; y < 8; y++) {
				pieces[x][y] = nullptr;
			}
		}

		// Black pawns
		for (int x = 0; x < 8; x++) {
			pieces[x][6] = new Pawn(Position(x, 6), false);
		}

		// White pawns
		for (int x = 0; x < 8; x++) {
			pieces[x][1] = new Pawn(Position(x, 1), true);
		}

		// Rooks
		pieces[0][7] = new Rook(Position(0, 7), false);
		pieces[7][7] = new Rook(Position(7, 7), false);
		pieces[0][0] = new Rook(Position(0, 0), true);
		pieces[7][0] = new Rook(Position(7, 0), true);

		// Knights
		pieces[1][7] = new Knight(Position(1, 7), false);
		pieces[6][7] = new Knight(Position(6, 7), false);
		pieces[1][0] = new Knight(Position(1, 0), true);
		pieces[6][0] = new Knight(Position(6, 0), true);

		// Bishops
		pieces[2][7] = new Bishop(Position(2, 7), false);
		pieces[5][7] = new Bishop(Position(5, 7), false);
		pieces[2][0] = new Bishop(Position(2, 0), true);
		pieces[5][0] = new Bishop(Position(5, 0), true);

		// Queens
		pieces[3][7] = new Queen(Position(3, 7), false);
		pieces[3][0] = new Queen(Position(3, 0), true);

		// Kings
		pieces[4][7] = new King(Position(4, 7), false);
		pieces[4][0] = new King(Position(4, 0), true);
		addBoardToMap();
	}

	Board::~Board() {
		for (int x = 0; x < 8; x++) {
			for (int y = 0; y < 8; y++) {
				if (pieces[x][y] != nullptr)
					delete pieces[x][y];
			}
		}
	}

	GameState Board::getState() const {
		return state;
	}

	Piece* Board::getPiece(const Position& position) const {
		return pieces[position.x][position.y];
	}

	bool Board::mustPromote() {
		return needsToPromote;
	}

	bool Board::move(const Position& oldPosition, const Position& newPosition) {
		Piece* piece = getPiece(oldPosition);
		Piece* targetPiece = getPiece(newPosition);

		if (piece != nullptr) {
			// Check if the piece is of the right color.
			if (piece->isWhite() == (turn % 2 == 0)) {
				halfMovesSinceCapture++;
				// Check if the move is legal.
				if (piece->isLegal(*this, newPosition)) {
					pieces[oldPosition.x][oldPosition.y] = nullptr;

					// En passant.
					if (pieces[newPosition.x][newPosition.y] == nullptr && (piece->notation() == 'p' || piece->notation() == 'P') && newPosition.x != oldPosition.x){
						if (piece->isWhite()) {
							delete pieces[newPosition.x][newPosition.y - 1];
							pieces[newPosition.x][newPosition.y - 1] = nullptr;
							halfMovesSinceCapture = 0;
						} else {
							delete pieces[newPosition.x][newPosition.y + 1];
							pieces[newPosition.x][newPosition.y + 1] = nullptr;
							halfMovesSinceCapture = 0;
						}
					}

					// Castling
					if (piece->notation() == 'k' || piece->notation() == 'K') {
						if (newPosition.x - oldPosition.x == 2){
							Piece* tempPiece = getPiece(Position(7, newPosition.y));
							pieces[7][newPosition.y] = nullptr;
							pieces[5][newPosition.y] = tempPiece;
							tempPiece->move(Position(5, newPosition.y));
						} else if (newPosition.x - oldPosition.x == -2) {
							Piece* tempPiece = getPiece(Position(0, newPosition.y));
							pieces[0][newPosition.y] = nullptr;
							pieces[3][newPosition.y] = tempPiece;
							tempPiece->move(Position(3, newPosition.y));
						}
					}

					// Delete captured enemy piece.
					if (pieces[newPosition.x][newPosition.y] != nullptr){
						delete pieces[newPosition.x][newPosition.y];
						halfMovesSinceCapture = 0;
					}
					// Update pieces and piece position
					pieces[newPosition.x][newPosition.y] = piece;
					if (piece->notation() == 'p' || piece->notation() == 'P')
						halfMovesSinceCapture = 0;
					piece->move(newPosition);

					// Promote pawns
					if(newPosition.y == 7 || newPosition.y == 0){
						if (piece->notation() == 'p' || piece->notation() == 'P'){
							needsToPromote = true;
						}
					}

					// Set and reset lastMovedPiece
					if (lastMovedPawn != nullptr){
						if (lastMovedPawn->getLastMoveWasDouble()){
							//lastMovedPawn->resetLastMoveWasDouble(); //orsakar krasch..
						}
					}
					lastMovedPawn = dynamic_cast<Pawn*>(getPiece(newPosition));

					turn++;
					if (state == GameState::BLACKPLAYS)
						state = GameState::WHITEPLAYS;
					else
						state = GameState::BLACKPLAYS;

					std::string tempstring = toFENString(false);
					std::cout << tempstring << '\n';
					addBoardToMap();
					if(isThreeFoldRepitition())
						state = GameState::DRAW;
					if (isFiftyMoveSincePawnOrCapture())
						state = GameState::DRAW;
					checkWin();
					return true;
				}
			}
		}

		return false;
	}

	bool Board::willLeaveKingChecked(const Position& oldPosition, const Position& newPosition) {
		Piece* oldPiece = getPiece(oldPosition);
		Piece* newPiece = getPiece(newPosition);

		Piece* piece;
		switch (oldPiece->notation()) {
		case 'Q':
		case 'q':
			piece = new Queen(oldPiece->getPosition(), oldPiece->isWhite());
			break;
		case 'K':
		case 'k':
			piece = new King(oldPiece->getPosition(), oldPiece->isWhite());
			break;
		case 'P':
		case 'p':
			piece = new Pawn(oldPiece->getPosition(), oldPiece->isWhite());
			break;
		case 'R':
		case 'r':
			piece = new Rook(oldPiece->getPosition(), oldPiece->isWhite());
			break;
		case 'B':
		case 'b':
			piece = new Bishop(oldPiece->getPosition(), oldPiece->isWhite());
			break;
		case 'N':
		case 'n':
			piece = new Knight(oldPiece->getPosition(), oldPiece->isWhite());
			break;
		}

		pieces[newPosition.x][newPosition.y] = piece;
		piece->move(newPosition);
		pieces[oldPosition.x][oldPosition.y] = nullptr;

		King* king = getKing((turn % 2 == 0));
		bool checked = king->isChecked(*this);

		delete piece;
		pieces[newPosition.x][newPosition.y] = newPiece;
		pieces[oldPosition.x][oldPosition.y] = oldPiece;

		return checked;
	}

	void Board::promotePawn(Piece* pawn, PromoteTypes type) {
		Position position = pawn->getPosition();
		bool white = pawn->isWhite();
		delete pawn;

		switch (type) {
		case PromoteTypes::QUEEN:
			pieces[position.x][position.y] = new Queen(position, white);
			break;
		case PromoteTypes::ROOK:
			pieces[position.x][position.y] = new Rook(position, white);
			break;
		case PromoteTypes::BISHOP:
			pieces[position.x][position.y] = new Bishop(position, white);
			break;
		case PromoteTypes::KNIGHT:
			pieces[position.x][position.y] = new Knight(position, white);
			break;
		}
		needsToPromote = false;
	}
	void Board::addBoardToMap() {
		std::string tempstring = toFENString(false);
		if (previousBoards.find(tempstring) == previousBoards.end()) {
			previousBoards[tempstring] = 0;
		} else{
			previousBoards[tempstring] += 1;
		}
	}

	std::string Board::toFENString(bool addExtraData) const {
		std::string tempstring;
		int emptyCounter = 0;
		for (int y = 7; y >= 0; y--) {
			for (int x = 0; x < 8; x++){
				if (pieces[x][y] == nullptr)
					emptyCounter++;
				else {
					if (emptyCounter != 0)
						tempstring += std::to_string(emptyCounter);
					tempstring.append(1, pieces[x][y]->notation());
					emptyCounter = 0;
				}
			}
			if (emptyCounter != 0) {
				tempstring += std::to_string(emptyCounter);
				emptyCounter = 0;
			}
			tempstring += '/';
		}
		// Who played the turn?
		if (state == GameState::BLACKPLAYS)
			tempstring += "w";
		else
			tempstring += "b";

		if (addExtraData) {
			// Number of half turns since last capture or pawn move.
			tempstring += ' ' + std::to_string(halfMovesSinceCapture) + ' ';
			// Number of full moves.
			tempstring += std::to_string((turn+1) / 2);
		}
		return tempstring;
	}

	bool Board::isThreeFoldRepitition() {
		return previousBoards[toFENString(false)] == 3;
	}

	bool Board::isFiftyMoveSincePawnOrCapture() const{
		if (halfMovesSinceCapture >= 100)
			return true;
		return false;
	}

	void Board::checkWin() {
		bool white = (state == GameState::WHITEPLAYS);

		bool canMove = false;
		for (int x = 0; x < 8; x++) {
			for (int y = 0; y < 8; y++) {
				Piece* piece = getPiece(Position(x, y));
				if (piece != nullptr && piece->isWhite() == white) {
					if (!piece->legalMoves(*this).empty()) {
						canMove = true;
						break;
					}
				}
			}
		}

		if (!canMove) {
			if (getKing(white)->isChecked(*this)) {
				if (white)
					state = GameState::BLACKWIN;
				else
					state = GameState::WHITEWIN;
			} else {
				state = GameState::DRAW;
			}
		}
	}

	King* Board::getKing(bool white) const {
		for (int x = 0; x < 8; x++) {
			for (int y = 0; y < 8; y++) {
				Piece* piece = getPiece(Position(x, y));
				if (piece != nullptr && piece->notation() == (white ? 'K' : 'k'))
					return dynamic_cast<King*>(piece);
			}
		}

		return nullptr;
	}
}<commit_msg>Simplify isFiftyMovesSincePawnOrCapture<commit_after>#include "Board.h"
#include "Pawn.h"
#include "Rook.h"
#include "Knight.h"
#include "Bishop.h"
#include "Queen.h"
#include "King.h"
#include <iostream>
#include <sstream>

namespace Chess {
	Board::Board() {
		for (int x = 0; x < 8; x++) {
			for (int y = 0; y < 8; y++) {
				pieces[x][y] = nullptr;
			}
		}

		// Black pawns
		for (int x = 0; x < 8; x++) {
			pieces[x][6] = new Pawn(Position(x, 6), false);
		}

		// White pawns
		for (int x = 0; x < 8; x++) {
			pieces[x][1] = new Pawn(Position(x, 1), true);
		}

		// Rooks
		pieces[0][7] = new Rook(Position(0, 7), false);
		pieces[7][7] = new Rook(Position(7, 7), false);
		pieces[0][0] = new Rook(Position(0, 0), true);
		pieces[7][0] = new Rook(Position(7, 0), true);

		// Knights
		pieces[1][7] = new Knight(Position(1, 7), false);
		pieces[6][7] = new Knight(Position(6, 7), false);
		pieces[1][0] = new Knight(Position(1, 0), true);
		pieces[6][0] = new Knight(Position(6, 0), true);

		// Bishops
		pieces[2][7] = new Bishop(Position(2, 7), false);
		pieces[5][7] = new Bishop(Position(5, 7), false);
		pieces[2][0] = new Bishop(Position(2, 0), true);
		pieces[5][0] = new Bishop(Position(5, 0), true);

		// Queens
		pieces[3][7] = new Queen(Position(3, 7), false);
		pieces[3][0] = new Queen(Position(3, 0), true);

		// Kings
		pieces[4][7] = new King(Position(4, 7), false);
		pieces[4][0] = new King(Position(4, 0), true);
		addBoardToMap();
	}

	Board::~Board() {
		for (int x = 0; x < 8; x++) {
			for (int y = 0; y < 8; y++) {
				if (pieces[x][y] != nullptr)
					delete pieces[x][y];
			}
		}
	}

	GameState Board::getState() const {
		return state;
	}

	Piece* Board::getPiece(const Position& position) const {
		return pieces[position.x][position.y];
	}

	bool Board::mustPromote() {
		return needsToPromote;
	}

	bool Board::move(const Position& oldPosition, const Position& newPosition) {
		Piece* piece = getPiece(oldPosition);
		Piece* targetPiece = getPiece(newPosition);

		if (piece != nullptr) {
			// Check if the piece is of the right color.
			if (piece->isWhite() == (turn % 2 == 0)) {
				halfMovesSinceCapture++;
				// Check if the move is legal.
				if (piece->isLegal(*this, newPosition)) {
					pieces[oldPosition.x][oldPosition.y] = nullptr;

					// En passant.
					if (pieces[newPosition.x][newPosition.y] == nullptr && (piece->notation() == 'p' || piece->notation() == 'P') && newPosition.x != oldPosition.x){
						if (piece->isWhite()) {
							delete pieces[newPosition.x][newPosition.y - 1];
							pieces[newPosition.x][newPosition.y - 1] = nullptr;
							halfMovesSinceCapture = 0;
						} else {
							delete pieces[newPosition.x][newPosition.y + 1];
							pieces[newPosition.x][newPosition.y + 1] = nullptr;
							halfMovesSinceCapture = 0;
						}
					}

					// Castling
					if (piece->notation() == 'k' || piece->notation() == 'K') {
						if (newPosition.x - oldPosition.x == 2){
							Piece* tempPiece = getPiece(Position(7, newPosition.y));
							pieces[7][newPosition.y] = nullptr;
							pieces[5][newPosition.y] = tempPiece;
							tempPiece->move(Position(5, newPosition.y));
						} else if (newPosition.x - oldPosition.x == -2) {
							Piece* tempPiece = getPiece(Position(0, newPosition.y));
							pieces[0][newPosition.y] = nullptr;
							pieces[3][newPosition.y] = tempPiece;
							tempPiece->move(Position(3, newPosition.y));
						}
					}

					// Delete captured enemy piece.
					if (pieces[newPosition.x][newPosition.y] != nullptr){
						delete pieces[newPosition.x][newPosition.y];
						halfMovesSinceCapture = 0;
					}
					// Update pieces and piece position
					pieces[newPosition.x][newPosition.y] = piece;
					if (piece->notation() == 'p' || piece->notation() == 'P')
						halfMovesSinceCapture = 0;
					piece->move(newPosition);

					// Promote pawns
					if(newPosition.y == 7 || newPosition.y == 0){
						if (piece->notation() == 'p' || piece->notation() == 'P'){
							needsToPromote = true;
						}
					}

					// Set and reset lastMovedPiece
					if (lastMovedPawn != nullptr){
						if (lastMovedPawn->getLastMoveWasDouble()){
							//lastMovedPawn->resetLastMoveWasDouble(); //orsakar krasch..
						}
					}
					lastMovedPawn = dynamic_cast<Pawn*>(getPiece(newPosition));

					turn++;
					if (state == GameState::BLACKPLAYS)
						state = GameState::WHITEPLAYS;
					else
						state = GameState::BLACKPLAYS;

					std::string tempstring = toFENString(false);
					std::cout << tempstring << '\n';
					addBoardToMap();
					if(isThreeFoldRepitition())
						state = GameState::DRAW;
					if (isFiftyMoveSincePawnOrCapture())
						state = GameState::DRAW;
					checkWin();
					return true;
				}
			}
		}

		return false;
	}

	bool Board::willLeaveKingChecked(const Position& oldPosition, const Position& newPosition) {
		Piece* oldPiece = getPiece(oldPosition);
		Piece* newPiece = getPiece(newPosition);

		Piece* piece;
		switch (oldPiece->notation()) {
		case 'Q':
		case 'q':
			piece = new Queen(oldPiece->getPosition(), oldPiece->isWhite());
			break;
		case 'K':
		case 'k':
			piece = new King(oldPiece->getPosition(), oldPiece->isWhite());
			break;
		case 'P':
		case 'p':
			piece = new Pawn(oldPiece->getPosition(), oldPiece->isWhite());
			break;
		case 'R':
		case 'r':
			piece = new Rook(oldPiece->getPosition(), oldPiece->isWhite());
			break;
		case 'B':
		case 'b':
			piece = new Bishop(oldPiece->getPosition(), oldPiece->isWhite());
			break;
		case 'N':
		case 'n':
			piece = new Knight(oldPiece->getPosition(), oldPiece->isWhite());
			break;
		}

		pieces[newPosition.x][newPosition.y] = piece;
		piece->move(newPosition);
		pieces[oldPosition.x][oldPosition.y] = nullptr;

		King* king = getKing((turn % 2 == 0));
		bool checked = king->isChecked(*this);

		delete piece;
		pieces[newPosition.x][newPosition.y] = newPiece;
		pieces[oldPosition.x][oldPosition.y] = oldPiece;

		return checked;
	}

	void Board::promotePawn(Piece* pawn, PromoteTypes type) {
		Position position = pawn->getPosition();
		bool white = pawn->isWhite();
		delete pawn;

		switch (type) {
		case PromoteTypes::QUEEN:
			pieces[position.x][position.y] = new Queen(position, white);
			break;
		case PromoteTypes::ROOK:
			pieces[position.x][position.y] = new Rook(position, white);
			break;
		case PromoteTypes::BISHOP:
			pieces[position.x][position.y] = new Bishop(position, white);
			break;
		case PromoteTypes::KNIGHT:
			pieces[position.x][position.y] = new Knight(position, white);
			break;
		}
		needsToPromote = false;
	}
	void Board::addBoardToMap() {
		std::string tempstring = toFENString(false);
		if (previousBoards.find(tempstring) == previousBoards.end()) {
			previousBoards[tempstring] = 0;
		} else{
			previousBoards[tempstring] += 1;
		}
	}

	std::string Board::toFENString(bool addExtraData) const {
		std::string tempstring;
		int emptyCounter = 0;
		for (int y = 7; y >= 0; y--) {
			for (int x = 0; x < 8; x++){
				if (pieces[x][y] == nullptr)
					emptyCounter++;
				else {
					if (emptyCounter != 0)
						tempstring += std::to_string(emptyCounter);
					tempstring.append(1, pieces[x][y]->notation());
					emptyCounter = 0;
				}
			}
			if (emptyCounter != 0) {
				tempstring += std::to_string(emptyCounter);
				emptyCounter = 0;
			}
			tempstring += '/';
		}
		// Who played the turn?
		if (state == GameState::BLACKPLAYS)
			tempstring += "w";
		else
			tempstring += "b";

		if (addExtraData) {
			// Number of half turns since last capture or pawn move.
			tempstring += ' ' + std::to_string(halfMovesSinceCapture) + ' ';
			// Number of full moves.
			tempstring += std::to_string((turn+1) / 2);
		}
		return tempstring;
	}

	bool Board::isThreeFoldRepitition() {
		return previousBoards[toFENString(false)] == 3;
	}

	bool Board::isFiftyMoveSincePawnOrCapture() const {
		return halfMovesSinceCapture >= 100;
	}

	void Board::checkWin() {
		bool white = (state == GameState::WHITEPLAYS);

		bool canMove = false;
		for (int x = 0; x < 8; x++) {
			for (int y = 0; y < 8; y++) {
				Piece* piece = getPiece(Position(x, y));
				if (piece != nullptr && piece->isWhite() == white) {
					if (!piece->legalMoves(*this).empty()) {
						canMove = true;
						break;
					}
				}
			}
		}

		if (!canMove) {
			if (getKing(white)->isChecked(*this)) {
				if (white)
					state = GameState::BLACKWIN;
				else
					state = GameState::WHITEWIN;
			} else {
				state = GameState::DRAW;
			}
		}
	}

	King* Board::getKing(bool white) const {
		for (int x = 0; x < 8; x++) {
			for (int y = 0; y < 8; y++) {
				Piece* piece = getPiece(Position(x, y));
				if (piece != nullptr && piece->notation() == (white ? 'K' : 'k'))
					return dynamic_cast<King*>(piece);
			}
		}

		return nullptr;
	}
}<|endoftext|>


<commit_before>#include "BTU/btu_PID_lite.cpp"
#include "mbed.h"

#define NUM_FLOATS 4
#define TIMESTEP 0.05
#define DEPTH_THRESHOLD 0.1
#define MISSION_TIMEOUT 10.0
#define ERROR_THRESHOLD 0.15
#define SUCCESS_TIME 5.0
#define UNWOUND_POS 91.0

#include "MODSERIAL.h"
#include "SerialComm.h"

MODSERIAL pcSerial(USBTX, USBRX);
// AnalogIn pot1(p15);
DigitalOut TestLED(LED1);
DigitalOut TestLED2(LED2);
DigitalOut inMission(LED3);
DigitalOut missionSuccess(LED4);

// LocalFileSystem local("local");

// bool clk = true;
BTU btu = BTU();
int counter = 0;
int mode = 2;
float Kc = 1.0;
float TauI = 0.0;
float TauD = 0.0;
float setVal = 0.0;             // meters
Ticker Mission;
float timeout = 0.0;
float successTime = 0.0;
int missionDepth = 0.0;
bool missionStarted = false;

void terminateMission() {
    Mission.detach();
    counter = 0;
    inMission = 0;
    timeout = 0.0;
    successTime = 0.0;
    missionStarted = false;
    btu.updateAndRunCycle(POSITION_CTRL_MODE, UNWOUND_POS);
}

bool checkThreshold() {
    float error = btu.getDepth() - missionDepth;
    // float error = btu.getServoPos() - missionDepth;
    float absError = (error > 0) ? error : (-1 * error);
    return (absError <= ERROR_THRESHOLD);
}

void runMission() {
    counter = (counter + 1) % 20;
    if(!counter) {
        TestLED = !TestLED;
    }
    if(btu.getDepth() >= DEPTH_THRESHOLD) {
        inMission = 1;
        missionStarted = true;
    }
    if(!missionStarted) {
        return;
    }
    btu.runCycle(missionDepth);
    successTime += ((int) checkThreshold() * TIMESTEP);
    if (successTime >= SUCCESS_TIME) {
        missionSuccess = 1;
        terminateMission();
        return;
    }
    if (timeout >= MISSION_TIMEOUT) {
        missionSuccess = 0;
        terminateMission();
        return;
    }
    timeout += TIMESTEP;
}

void startMission(float kc, float taui, float taud, float setDepth) {
    terminateMission();
    missionSuccess = 0;
    missionDepth = setDepth;
    btu.update(DEPTH_CTRL_MODE, kc, taui, taud);
    // btu.update(SPEC_POSITION_CTRL_MODE, kc, taui, taud);
    Mission.attach(&runMission, TIMESTEP);
}

int main() {
  pcSerial.printf("Start!\n");

  SerialComm serialComm(&pcSerial);

  btu.init();
  pcSerial.printf("pressure at start: %.6f\r\n", btu.getPressure());
  TestLED = 0;
  float valueFloats[NUM_FLOATS];

  while(1) {
      // depth = btu.getDepth();
      // if (mode == DEPTH_CTRL_MODE) {
      //     pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, depth_er:%.4f\r\n",
      //                 btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), depth, setVal - depth);
      // } else if (mode == SPEC_POSITION_CTRL_MODE) {
      //     pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, pos_er:%.4f\r\n",
      //                           btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), depth, setVal - btu.getServoPos());
      // } else {
      //     pcSerial.printf("m:%d, s:%.2f, cu:%.2f, de:%.2f\r\n", btu.getMode(), setVal, btu.getServoPos(), depth);
      // }
      // pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, pos_er:%.4f, th:%d, to:%.2f, st:%.2f\r\n", btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), setVal - btu.getServoPos(), checkThreshold(), timeout, successTime);
      if(serialComm.checkIfNewMessage()) {
          serialComm.getFloats(valueFloats, NUM_FLOATS);

          // mode = (int) valueFloats[0];
          Kc = valueFloats[0];
          TauI = valueFloats[1];
          TauD = valueFloats[2];
          setVal = valueFloats[3];

          startMission(Kc, TauI, TauD, setVal);
      }
      wait_ms(500);
      TestLED2 = !TestLED2;
  }
}
<commit_msg>added logging<commit_after>#include "BTU/btu_PID_lite.cpp"
#include "mbed.h"

#define NUM_FLOATS 4
#define TIMESTEP 0.05
#define DEPTH_THRESHOLD 0.1
#define MISSION_TIMEOUT 60.0
#define ERROR_THRESHOLD 0.15
#define SUCCESS_TIME 5.0
#define UNWOUND_POS 91.0

#include "MODSERIAL.h"
#include "SerialComm.h"

MODSERIAL pcSerial(USBTX, USBRX);
// AnalogIn pot1(p15);
DigitalOut TestLED(LED1);
DigitalOut TestLED2(LED2);
DigitalOut inMission(LED3);
DigitalOut missionSuccess(LED4);

LocalFileSystem local("local");

// bool clk = true;
BTU btu = BTU();
int counter = 0;
int mode = 2;
float Kc = 1.0;
float TauI = 0.0;
float TauD = 0.0;
float setVal = 0.0;             // meters
Ticker Mission;
float timeout = 0.0;
float successTime = 0.0;
int missionDepth = 0.0;
bool missionStarted = false;
FILE *fp;

void terminateMission() {
    Mission.detach();
    fclose(fp);
    counter = 0;
    inMission = 0;
    timeout = 0.0;
    successTime = 0.0;
    missionStarted = false;
    btu.updateAndRunCycle(POSITION_CTRL_MODE, UNWOUND_POS);
}

bool checkThreshold() {
    float error = btu.getDepth() - missionDepth;
    // float error = btu.getServoPos() - missionDepth;
    float absError = (error > 0) ? error : (-1 * error);
    return (absError <= ERROR_THRESHOLD);
}

void runMission() {
    counter = (counter + 1) % 20;
    if(!counter) {
        TestLED = !TestLED;
    }
    if(btu.getDepth() >= DEPTH_THRESHOLD) {
        inMission = 1;
        missionStarted = true;
    }
    if(!missionStarted) {
        return;
    }
    btu.runCycle(missionDepth);
    successTime += ((int) checkThreshold() * TIMESTEP);
    if (successTime >= SUCCESS_TIME) {
        missionSuccess = 1;
        terminateMission();
        return;
    }
    if (timeout >= MISSION_TIMEOUT) {
        missionSuccess = 0;
        terminateMission();
        return;
    }
    timeout += TIMESTEP;
}

void startMission(float kc, float taui, float taud, float setDepth) {
    terminateMission();
    fp = fopen("/local/log", "w");
    fprintf(fp, "MISSION START, TARGET: %.2f\r\n", setDepth);

    missionSuccess = 0;
    missionDepth = setDepth;
    btu.update(DEPTH_CTRL_MODE, kc, taui, taud);
    // btu.update(SPEC_POSITION_CTRL_MODE, kc, taui, taud);
    Mission.attach(&runMission, TIMESTEP);
}

int main() {
  pcSerial.printf("Start!\n");

  SerialComm serialComm(&pcSerial);

  btu.init();
  pcSerial.printf("pressure at start: %.6f\r\n", btu.getPressure());
  TestLED = 0;
  float valueFloats[NUM_FLOATS];

  while(1) {
      // depth = btu.getDepth();
      // if (mode == DEPTH_CTRL_MODE) {
      //     pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, depth_er:%.4f\r\n",
      //                 btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), depth, setVal - depth);
      // } else if (mode == SPEC_POSITION_CTRL_MODE) {
      //     pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, pos_er:%.4f\r\n",
      //                           btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), depth, setVal - btu.getServoPos());
      // } else {
      //     pcSerial.printf("m:%d, s:%.2f, cu:%.2f, de:%.2f\r\n", btu.getMode(), setVal, btu.getServoPos(), depth);
      // }
      // pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, pos_er:%.4f, th:%d, to:%.2f, st:%.2f\r\n", btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), setVal - btu.getServoPos(), checkThreshold(), timeout, successTime);
      if(inMission) {
          float depth = btu.getDepth();
          fprintf(fp, "m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, depth_er:%.4f, to:%.2f\r\n",
                  btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), depth, setVal - depth, timeout);
      }
      if(serialComm.checkIfNewMessage()) {
          serialComm.getFloats(valueFloats, NUM_FLOATS);

          // mode = (int) valueFloats[0];
          Kc = valueFloats[0];
          TauI = valueFloats[1];
          TauD = valueFloats[2];
          setVal = valueFloats[3];
          startMission(Kc, TauI, TauD, setVal);
      }
      wait_ms(500);
      TestLED2 = !TestLED2;
  }
}
<|endoftext|>


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

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

#ifndef __FRAMEWORK_UIELEMENT_COMBOBOXTOOLBARCONTROLLER_HXX
#include "uielement/comboboxtoolbarcontroller.hxx"
#endif

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_TOOLBAR_HXX_
#include "uielement/toolbar.hxx"
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATUS_HPP_
#include <com/sun/star/frame/status/ItemStatus.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATE_HPP_
#include <com/sun/star/frame/status/ItemState.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_VISIBILITY_HPP_
#include <com/sun/star/frame/status/Visibility.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLNOTIFICATIONLISTENER_HPP_
#include <com/sun/star/frame/XControlNotificationListener.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _SVTOOLS_TOOLBOXCONTROLLER_HXX
#include <svtools/toolboxcontroller.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _VCL_MNEMONIC_HXX_
#include <vcl/mnemonic.hxx>
#endif
#include <vcl/toolbox.hxx>
#include <vcl/combobox.hxx>
#include <tools/urlobj.hxx>

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::frame::status;
using namespace ::com::sun::star::util;

namespace framework
{

// ------------------------------------------------------------------

// Wrapper class to notify controller about events from combobox.
// Unfortunaltly the events are notifed through virtual methods instead
// of Listeners.

class ComboBoxControl : public ComboBox
{
    public:
        ComboBoxControl( Window* pParent, WinBits nStyle, IComboBoxListener* pComboBoxListener );
        virtual ~ComboBoxControl();

        virtual void Select();
        virtual void DoubleClick();
        virtual void Modify();
        virtual void KeyInput( const ::KeyEvent& rKEvt );
        virtual void GetFocus();
        virtual void LoseFocus();
        virtual long PreNotify( NotifyEvent& rNEvt );

    private:
        IComboBoxListener* m_pComboBoxListener;
};

ComboBoxControl::ComboBoxControl( Window* pParent, WinBits nStyle, IComboBoxListener* pComboBoxListener ) :
    ComboBox( pParent, nStyle )
    , m_pComboBoxListener( pComboBoxListener )
{
}

ComboBoxControl::~ComboBoxControl()
{
    m_pComboBoxListener = 0;
}

void ComboBoxControl::Select()
{
    ComboBox::Select();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->Select();
}

void ComboBoxControl::DoubleClick()
{
    ComboBox::DoubleClick();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->DoubleClick();
}

void ComboBoxControl::Modify()
{
    ComboBox::Modify();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->Modify();
}

void ComboBoxControl::KeyInput( const ::KeyEvent& rKEvt )
{
    ComboBox::KeyInput( rKEvt );
    if ( m_pComboBoxListener )
        m_pComboBoxListener->KeyInput( rKEvt );
}

void ComboBoxControl::GetFocus()
{
    ComboBox::GetFocus();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->GetFocus();
}

void ComboBoxControl::LoseFocus()
{
    ComboBox::LoseFocus();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->LoseFocus();
}

long ComboBoxControl::PreNotify( NotifyEvent& rNEvt )
{
    long nRet( 0 );
    if ( m_pComboBoxListener )
        nRet = m_pComboBoxListener->PreNotify( rNEvt );
    if ( nRet == 0 )
        nRet = ComboBox::PreNotify( rNEvt );

    return nRet;
}

// ------------------------------------------------------------------

ComboboxToolbarController::ComboboxToolbarController(
    const Reference< XMultiServiceFactory >& rServiceManager,
    const Reference< XFrame >&               rFrame,
    ToolBar*                                 pToolbar,
    USHORT                                   nID,
    sal_Int32                                nWidth,
    const OUString&                          aCommand ) :
    ComplexToolbarController( rServiceManager, rFrame, pToolbar, nID, aCommand )
    ,   m_pComboBox( 0 )
{
    m_pComboBox = new ComboBoxControl( m_pToolbar, WB_DROPDOWN, this );
    if ( nWidth == 0 )
        nWidth = 100;

    // default dropdown size
    ::Size aLogicalSize( 8, 160 );
    ::Size aPixelSize = m_pComboBox->LogicToPixel( aLogicalSize, MAP_APPFONT );

    m_pComboBox->SetSizePixel( ::Size( nWidth, aPixelSize.Height() ));
    m_pToolbar->SetItemWindow( m_nID, m_pComboBox );
    m_pComboBox->SetDropDownLineCount( 5 );
}

// ------------------------------------------------------------------

ComboboxToolbarController::~ComboboxToolbarController()
{
}

// ------------------------------------------------------------------

void SAL_CALL ComboboxToolbarController::dispose()
throw ( RuntimeException )
{
    vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

    m_pToolbar->SetItemWindow( m_nID, 0 );
    delete m_pComboBox;

    ComplexToolbarController::dispose();

    m_pComboBox = 0;
}

// ------------------------------------------------------------------

void SAL_CALL ComboboxToolbarController::execute( sal_Int16 KeyModifier )
throw ( RuntimeException )
{
    Reference< XDispatch >       xDispatch;
    Reference< XURLTransformer > xURLTransformer;
    OUString                     aCommandURL;
    OUString                     aSelectedText;
    ::com::sun::star::util::URL  aTargetURL;

    {
        vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

        if ( m_bDisposed )
            throw DisposedException();

        if ( m_bInitialized &&
             m_xFrame.is() &&
             m_xServiceManager.is() &&
             m_aCommandURL.getLength() )
        {
            xURLTransformer = m_xURLTransformer;
            xDispatch = getDispatchFromCommand( m_aCommandURL );
            aCommandURL = m_aCommandURL;
            aTargetURL = getInitializedURL();
            aSelectedText = m_pComboBox->GetText();
        }
    }

    if ( xDispatch.is() && aTargetURL.Complete.getLength() > 0 )
    {
        Sequence<PropertyValue>   aArgs( 2 );

        // Add key modifier to argument list
        aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "KeyModifier" ));
        aArgs[0].Value <<= KeyModifier;
        aArgs[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Text" ));
        aArgs[1].Value <<= aSelectedText;

        // Execute dispatch asynchronously
        ExecuteInfo* pExecuteInfo = new ExecuteInfo;
        pExecuteInfo->xDispatch     = xDispatch;
        pExecuteInfo->aTargetURL    = aTargetURL;
        pExecuteInfo->aArgs         = aArgs;
        Application::PostUserEvent( STATIC_LINK(0, ComplexToolbarController , ExecuteHdl_Impl), pExecuteInfo );
    }
}

// ------------------------------------------------------------------

void ComboboxToolbarController::Select()
{
    if ( m_pComboBox->GetEntryCount() > 0 )
    {
        Window::PointerState aState = m_pComboBox->GetPointerState();

        sal_uInt16 nKeyModifier = sal_uInt16( aState.mnState & KEY_MODTYPE );
        execute( nKeyModifier );
    }
}

void ComboboxToolbarController::DoubleClick()
{
}

void ComboboxToolbarController::Modify()
{
    notifyTextChanged( m_pComboBox->GetText() );
}

void ComboboxToolbarController::KeyInput( const ::KeyEvent& )
{
}

void ComboboxToolbarController::GetFocus()
{
    notifyFocusGet();
}

void ComboboxToolbarController::LoseFocus()
{
    notifyFocusLost();
}

long ComboboxToolbarController::PreNotify( NotifyEvent& rNEvt )
{
    if( rNEvt.GetType() == EVENT_KEYINPUT )
    {
        const ::KeyEvent* pKeyEvent = rNEvt.GetKeyEvent();
        const KeyCode& rKeyCode = pKeyEvent->GetKeyCode();
        if(( rKeyCode.GetModifier() | rKeyCode.GetCode()) == KEY_RETURN )
        {
            // Call execute only with non-empty text
            if ( m_pComboBox->GetText().Len() > 0 )
                execute( rKeyCode.GetModifier() );
            return 1;
        }
    }

    return 0;
}

// --------------------------------------------------------

void ComboboxToolbarController::executeControlCommand( const ::com::sun::star::frame::ControlCommand& rControlCommand )
{
    if ( rControlCommand.Command.equalsAsciiL( "SetText", 7 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
            {
                rtl::OUString aText;
                rControlCommand.Arguments[i].Value >>= aText;
                m_pComboBox->SetText( aText );

                // send notification
                notifyTextChanged( aText );
                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "SetList", 7 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "List", 4 ))
            {
                Sequence< OUString > aList;
                m_pComboBox->Clear();

                rControlCommand.Arguments[i].Value >>= aList;
                for ( sal_Int32 j = 0; j < aList.getLength(); j++ )
                    m_pComboBox->InsertEntry( aList[j] );

                // send notification
                uno::Sequence< beans::NamedValue > aInfo( 1 );
                aInfo[0].Name  = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "List" ));
                aInfo[0].Value <<= aList;
                addNotifyInfo( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ListChanged" )),
                               getDispatchFromCommand( m_aCommandURL ),
                               aInfo );

                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "AddEntry", 8 ))
    {
        sal_uInt16      nPos( COMBOBOX_APPEND );
        rtl::OUString   aText;
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
            {
                if ( rControlCommand.Arguments[i].Value >>= aText )
                    m_pComboBox->InsertEntry( aText, nPos );
                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "InsertEntry", 11 ))
    {
        sal_uInt16      nPos( COMBOBOX_APPEND );
        rtl::OUString   aText;
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
            {
                sal_Int32 nTmpPos;
                if ( rControlCommand.Arguments[i].Value >>= nTmpPos )
                {
                    if (( nTmpPos >= 0 ) &&
                        ( nTmpPos < sal_Int32( m_pComboBox->GetEntryCount() )))
                        nPos = sal_uInt16( nTmpPos );
                }
            }
            else if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
                rControlCommand.Arguments[i].Value >>= aText;
        }

        m_pComboBox->InsertEntry( aText, nPos );
    }
    else if ( rControlCommand.Command.equalsAsciiL( "RemoveEntryPos", 14 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
            {
                sal_Int32 nPos( -1 );
                if ( rControlCommand.Arguments[i].Value >>= nPos )
                {
                    if ( nPos < sal_Int32( m_pComboBox->GetEntryCount() ))
                        m_pComboBox->RemoveEntry( sal_uInt16( nPos ));
                }
                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "RemoveEntryText", 15 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
            {
                rtl::OUString aText;
                if ( rControlCommand.Arguments[i].Value >>= aText )
                    m_pComboBox->RemoveEntry( aText );
                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "SetDropDownLines", 16 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Lines", 5 ))
            {
                sal_Int32 nValue( 5 );
                rControlCommand.Arguments[i].Value >>= nValue;
                m_pComboBox->SetDropDownLineCount( sal_uInt16( nValue ));
                break;
            }
        }
    }
}

} // namespace
<commit_msg>INTEGRATION: CWS pj65 (1.6.32); FILE MERGED 2006/10/31 14:05:51 pjanik 1.6.32.1: #i71027#: prevent warnings on Mac OS X with gcc 4.0.1.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: comboboxtoolbarcontroller.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2006-11-21 17:21:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef __FRAMEWORK_UIELEMENT_COMBOBOXTOOLBARCONTROLLER_HXX
#include "uielement/comboboxtoolbarcontroller.hxx"
#endif

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_TOOLBAR_HXX_
#include "uielement/toolbar.hxx"
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATUS_HPP_
#include <com/sun/star/frame/status/ItemStatus.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATE_HPP_
#include <com/sun/star/frame/status/ItemState.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_VISIBILITY_HPP_
#include <com/sun/star/frame/status/Visibility.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLNOTIFICATIONLISTENER_HPP_
#include <com/sun/star/frame/XControlNotificationListener.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _SVTOOLS_TOOLBOXCONTROLLER_HXX
#include <svtools/toolboxcontroller.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _VCL_MNEMONIC_HXX_
#include <vcl/mnemonic.hxx>
#endif
#include <vcl/toolbox.hxx>
#include <vcl/combobox.hxx>
#include <tools/urlobj.hxx>

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::frame::status;
using namespace ::com::sun::star::util;

namespace framework
{

// ------------------------------------------------------------------

// Wrapper class to notify controller about events from combobox.
// Unfortunaltly the events are notifed through virtual methods instead
// of Listeners.

class ComboBoxControl : public ComboBox
{
    public:
        ComboBoxControl( Window* pParent, WinBits nStyle, IComboBoxListener* pComboBoxListener );
        virtual ~ComboBoxControl();

        virtual void Select();
        virtual void DoubleClick();
        virtual void Modify();
        virtual void KeyInput( const ::KeyEvent& rKEvt );
        virtual void GetFocus();
        virtual void LoseFocus();
        virtual long PreNotify( NotifyEvent& rNEvt );

    private:
        IComboBoxListener* m_pComboBoxListener;
};

ComboBoxControl::ComboBoxControl( Window* pParent, WinBits nStyle, IComboBoxListener* pComboBoxListener ) :
    ComboBox( pParent, nStyle )
    , m_pComboBoxListener( pComboBoxListener )
{
}

ComboBoxControl::~ComboBoxControl()
{
    m_pComboBoxListener = 0;
}

void ComboBoxControl::Select()
{
    ComboBox::Select();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->Select();
}

void ComboBoxControl::DoubleClick()
{
    ComboBox::DoubleClick();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->DoubleClick();
}

void ComboBoxControl::Modify()
{
    ComboBox::Modify();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->Modify();
}

void ComboBoxControl::KeyInput( const ::KeyEvent& rKEvt )
{
    ComboBox::KeyInput( rKEvt );
    if ( m_pComboBoxListener )
        m_pComboBoxListener->KeyInput( rKEvt );
}

void ComboBoxControl::GetFocus()
{
    ComboBox::GetFocus();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->GetFocus();
}

void ComboBoxControl::LoseFocus()
{
    ComboBox::LoseFocus();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->LoseFocus();
}

long ComboBoxControl::PreNotify( NotifyEvent& rNEvt )
{
    long nRet( 0 );
    if ( m_pComboBoxListener )
        nRet = m_pComboBoxListener->PreNotify( rNEvt );
    if ( nRet == 0 )
        nRet = ComboBox::PreNotify( rNEvt );

    return nRet;
}

// ------------------------------------------------------------------

ComboboxToolbarController::ComboboxToolbarController(
    const Reference< XMultiServiceFactory >& rServiceManager,
    const Reference< XFrame >&               rFrame,
    ToolBar*                                 pToolbar,
    USHORT                                   nID,
    sal_Int32                                nWidth,
    const OUString&                          aCommand ) :
    ComplexToolbarController( rServiceManager, rFrame, pToolbar, nID, aCommand )
    ,   m_pComboBox( 0 )
{
    m_pComboBox = new ComboBoxControl( m_pToolbar, WB_DROPDOWN, this );
    if ( nWidth == 0 )
        nWidth = 100;

    // default dropdown size
    ::Size aLogicalSize( 8, 160 );
    ::Size aPixelSize = m_pComboBox->LogicToPixel( aLogicalSize, MAP_APPFONT );

    m_pComboBox->SetSizePixel( ::Size( nWidth, aPixelSize.Height() ));
    m_pToolbar->SetItemWindow( m_nID, m_pComboBox );
    m_pComboBox->SetDropDownLineCount( 5 );
}

// ------------------------------------------------------------------

ComboboxToolbarController::~ComboboxToolbarController()
{
}

// ------------------------------------------------------------------

void SAL_CALL ComboboxToolbarController::dispose()
throw ( RuntimeException )
{
    vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

    m_pToolbar->SetItemWindow( m_nID, 0 );
    delete m_pComboBox;

    ComplexToolbarController::dispose();

    m_pComboBox = 0;
}

// ------------------------------------------------------------------

void SAL_CALL ComboboxToolbarController::execute( sal_Int16 KeyModifier )
throw ( RuntimeException )
{
    Reference< XDispatch >       xDispatch;
    Reference< XURLTransformer > xURLTransformer;
    OUString                     aCommandURL;
    OUString                     aSelectedText;
    ::com::sun::star::util::URL  aTargetURL;

    {
        vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

        if ( m_bDisposed )
            throw DisposedException();

        if ( m_bInitialized &&
             m_xFrame.is() &&
             m_xServiceManager.is() &&
             m_aCommandURL.getLength() )
        {
            xURLTransformer = m_xURLTransformer;
            xDispatch = getDispatchFromCommand( m_aCommandURL );
            aCommandURL = m_aCommandURL;
            aTargetURL = getInitializedURL();
            aSelectedText = m_pComboBox->GetText();
        }
    }

    if ( xDispatch.is() && aTargetURL.Complete.getLength() > 0 )
    {
        Sequence<PropertyValue>   aArgs( 2 );

        // Add key modifier to argument list
        aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "KeyModifier" ));
        aArgs[0].Value <<= KeyModifier;
        aArgs[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Text" ));
        aArgs[1].Value <<= aSelectedText;

        // Execute dispatch asynchronously
        ExecuteInfo* pExecuteInfo = new ExecuteInfo;
        pExecuteInfo->xDispatch     = xDispatch;
        pExecuteInfo->aTargetURL    = aTargetURL;
        pExecuteInfo->aArgs         = aArgs;
        Application::PostUserEvent( STATIC_LINK(0, ComplexToolbarController , ExecuteHdl_Impl), pExecuteInfo );
    }
}

// ------------------------------------------------------------------

void ComboboxToolbarController::Select()
{
    if ( m_pComboBox->GetEntryCount() > 0 )
    {
        Window::PointerState aState = m_pComboBox->GetPointerState();

        sal_uInt16 nKeyModifier = sal_uInt16( aState.mnState & KEY_MODTYPE );
        execute( nKeyModifier );
    }
}

void ComboboxToolbarController::DoubleClick()
{
}

void ComboboxToolbarController::Modify()
{
    notifyTextChanged( m_pComboBox->GetText() );
}

void ComboboxToolbarController::KeyInput( const ::KeyEvent& )
{
}

void ComboboxToolbarController::GetFocus()
{
    notifyFocusGet();
}

void ComboboxToolbarController::LoseFocus()
{
    notifyFocusLost();
}

long ComboboxToolbarController::PreNotify( NotifyEvent& rNEvt )
{
    if( rNEvt.GetType() == EVENT_KEYINPUT )
    {
        const ::KeyEvent* pKeyEvent = rNEvt.GetKeyEvent();
        const KeyCode& rKeyCode = pKeyEvent->GetKeyCode();
        if(( rKeyCode.GetModifier() | rKeyCode.GetCode()) == KEY_RETURN )
        {
            // Call execute only with non-empty text
            if ( m_pComboBox->GetText().Len() > 0 )
                execute( rKeyCode.GetModifier() );
            return 1;
        }
    }

    return 0;
}

// --------------------------------------------------------

void ComboboxToolbarController::executeControlCommand( const ::com::sun::star::frame::ControlCommand& rControlCommand )
{
    if ( rControlCommand.Command.equalsAsciiL( "SetText", 7 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
            {
                rtl::OUString aText;
                rControlCommand.Arguments[i].Value >>= aText;
                m_pComboBox->SetText( aText );

                // send notification
                notifyTextChanged( aText );
                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "SetList", 7 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "List", 4 ))
            {
                Sequence< OUString > aList;
                m_pComboBox->Clear();

                rControlCommand.Arguments[i].Value >>= aList;
                for ( sal_Int32 j = 0; j < aList.getLength(); j++ )
                    m_pComboBox->InsertEntry( aList[j] );

                // send notification
                uno::Sequence< beans::NamedValue > aInfo( 1 );
                aInfo[0].Name  = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "List" ));
                aInfo[0].Value <<= aList;
                addNotifyInfo( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ListChanged" )),
                               getDispatchFromCommand( m_aCommandURL ),
                               aInfo );

                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "AddEntry", 8 ))
    {
        sal_uInt16      nPos( COMBOBOX_APPEND );
        rtl::OUString   aText;
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
            {
                if ( rControlCommand.Arguments[i].Value >>= aText )
                    m_pComboBox->InsertEntry( aText, nPos );
                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "InsertEntry", 11 ))
    {
        sal_uInt16      nPos( COMBOBOX_APPEND );
        rtl::OUString   aText;
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
            {
                sal_Int32 nTmpPos = 0;
                if ( rControlCommand.Arguments[i].Value >>= nTmpPos )
                {
                    if (( nTmpPos >= 0 ) &&
                        ( nTmpPos < sal_Int32( m_pComboBox->GetEntryCount() )))
                        nPos = sal_uInt16( nTmpPos );
                }
            }
            else if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
                rControlCommand.Arguments[i].Value >>= aText;
        }

        m_pComboBox->InsertEntry( aText, nPos );
    }
    else if ( rControlCommand.Command.equalsAsciiL( "RemoveEntryPos", 14 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
            {
                sal_Int32 nPos( -1 );
                if ( rControlCommand.Arguments[i].Value >>= nPos )
                {
                    if ( nPos < sal_Int32( m_pComboBox->GetEntryCount() ))
                        m_pComboBox->RemoveEntry( sal_uInt16( nPos ));
                }
                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "RemoveEntryText", 15 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
            {
                rtl::OUString aText;
                if ( rControlCommand.Arguments[i].Value >>= aText )
                    m_pComboBox->RemoveEntry( aText );
                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "SetDropDownLines", 16 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Lines", 5 ))
            {
                sal_Int32 nValue( 5 );
                rControlCommand.Arguments[i].Value >>= nValue;
                m_pComboBox->SetDropDownLineCount( sal_uInt16( nValue ));
                break;
            }
        }
    }
}

} // namespace
<|endoftext|>