<commit_before>#pragma once
#ifndef OPENGM_STRUCT_PERCEPTRON_LEARNER_HXX
#define OPENGM_STRUCT_PERCEPTRON_LEARNER_HXX

#include <vector>
#include <opengm/inference/inference.hxx>
#include <opengm/graphicalmodel/weights.hxx>
#include <opengm/utilities/random.hxx>
#include <opengm/learning/gradient-accumulator.hxx>
#include <omp.h>

namespace opengm {
    namespace learning {

    template<class DATASET>
    class StructuredPerceptron
    {
    public:
        typedef DATASET DatasetType;
        typedef typename DATASET::GMType   GMType;
        typedef typename DATASET::LossType LossType;
        typedef typename GMType::ValueType ValueType;
        typedef typename GMType::IndexType IndexType;
        typedef typename GMType::LabelType LabelType;

        typedef typename std::vector<LabelType>::const_iterator LabelIterator;
        typedef FeatureAccumulator<GMType, LabelIterator> FeatureAcc;

        class Parameter{
        public:

            enum LearningMode{
                Online = 0,
                Batch = 2
            };

            Parameter(){
                eps_ = 0.00001;
                maxIterations_ = 10000;
                stopLoss_ = 0.0;
                decayExponent_ = 0.0;
                decayT0_ = 0.0;
                learningMode_ = Online;
            }

            double eps_;
            size_t maxIterations_;
            double stopLoss_;
            double decayExponent_;
            double decayT0_;
            LearningMode learningMode_;
        };

        StructuredPerceptron(DATASET&, const Parameter& );

        template<class INF>
        void learn(const typename INF::Parameter& para);
        //template<class INF, class VISITOR>
        //void learn(typename INF::Parameter para, VITITOR vis);

        const opengm::learning::Weights<double>& getWeights(){return weights_;}
        Parameter& getLerningParameters(){return para_;}

        double getLearningRate( )const{
            if(para_.decayExponent_<=0.000000001 && para_.decayExponent_>=-0.000000001 ){
                return 1.0;
            }
            else{
                return std::pow(para_.decayT0_ + static_cast<double>(iteration_+1),para_.decayExponent_);
            }
        }

    private:

        double updateWeights();

        DATASET& dataset_;
        opengm::learning::Weights<double> weights_;
        Parameter para_;
        size_t iteration_;
        FeatureAcc featureAcc_;
    };

    template<class DATASET>
    StructuredPerceptron<DATASET>::StructuredPerceptron(DATASET& ds, const Parameter& p )
    : dataset_(ds), para_(p),iteration_(0),featureAcc_(ds.getNumberOfWeights(),false)
    {
        featureAcc_.resetWeights();
        weights_ = opengm::learning::Weights<double>(ds.getNumberOfWeights());

    }

    template<class DATASET>
    template<class INF>
    void StructuredPerceptron<DATASET>::learn(const typename INF::Parameter& para){

        const size_t nModels = dataset_.getNumberOfModels();
        const size_t nWegihts = dataset_.getNumberOfWeights();

        if(para_.learningMode_ == Parameter::Online){
            RandomUniform<size_t> randModel(0, nModels);
            std::cout<<"online mode\n";
            for(iteration_=0 ; iteration_<para_.maxIterations_; ++iteration_){

                if(iteration_%nModels==0){
                    std::cout<<"loss :"<<dataset_. template getTotalLoss<INF>(para)<<"\n";
                }

                // get random model
                const size_t gmi = randModel();
                // lock the model
                dataset_.lockModel(gmi);
                const GMType & gm = dataset_.getModel(gmi);

                // do inference
                std::vector<LabelType> arg;
                opengm::infer<INF>(gm, para, arg);
                featureAcc_.resetWeights();
                featureAcc_.accumulateModelFeatures(gm, dataset_.getGT(gmi).begin(), arg.begin());
                dataset_.unlockModel(gmi);

                // update weights
                const double wChange =updateWeights();

            }
        }
        else if(para_.learningMode_ == Parameter::Batch){
            std::cout<<"batch mode\n";
            for(iteration_=0 ; iteration_<para_.maxIterations_; ++iteration_){
                // this
                if(iteration_%1==0){
                    std::cout<<"loss :"<<dataset_. template getTotalLoss<INF>(para)<<"\n";
                }

                // reset the weights
                featureAcc_.resetWeights();

                omp_lock_t modelLockUnlock;
                omp_init_lock(&modelLockUnlock);

                omp_lock_t featureAccLock;
                omp_init_lock(&featureAccLock);

                #pragma omp parallel for
                for(size_t gmi=0; gmi<nModels; ++gmi)
                {

                    // lock the model
                    omp_set_lock(&modelLockUnlock);
                    dataset_.lockModel(gmi);
                    omp_unset_lock(&modelLockUnlock);

                    const GMType & gm = dataset_.getModel(gmi);
                    //run inference
                    std::vector<LabelType> arg;
                    opengm::infer<INF>(gm, para, arg);

                    //
                    FeatureAcc featureAcc(nWegihts,false);
                    featureAcc.accumulateModelFeatures(gm, dataset_.getGT(gmi).begin(), arg.begin());

                    // acc features
                    omp_set_lock(&featureAccLock);
                    featureAcc_.accumulateFromOther(featureAcc);
                    omp_unset_lock(&featureAccLock);

                    // unlock the model
                    omp_set_lock(&modelLockUnlock);
                    dataset_.unlockModel(gmi);
                    omp_unset_lock(&modelLockUnlock);
                }

                // update the weights
                const double wChange =updateWeights();

            }
        }

        weights_ = dataset_.getWeights();
    }

    template<class DATASET>
    double StructuredPerceptron<DATASET>::updateWeights(){
        double wChange = 0.0;
        const size_t nWegihts = dataset_.getNumberOfWeights();
        for(size_t wi=0; wi<nWegihts; ++wi){
            const double wOld = dataset_.getWeights().getWeight(wi);
            const double wNew = wOld + getLearningRate()*featureAcc_.getWeight(wi);
            wChange += std::pow(wOld-wNew,2);
            dataset_.getWeights().setWeight(wi, wNew);
        }
        weights_ = dataset_.getWeights();
        return wChange;
    }
}
}
#endif
<commit_msg>update struct. perceptron<commit_after>#pragma once
#ifndef OPENGM_STRUCT_PERCEPTRON_LEARNER_HXX
#define OPENGM_STRUCT_PERCEPTRON_LEARNER_HXX

#include <vector>
#include <opengm/inference/inference.hxx>
#include <opengm/graphicalmodel/weights.hxx>
#include <opengm/utilities/random.hxx>
#include <opengm/learning/gradient-accumulator.hxx>
#include <omp.h>

namespace opengm {
    namespace learning {

    template<class DATASET>
    class StructuredPerceptron
    {
    public:
        typedef DATASET DatasetType;
        typedef typename DATASET::GMType   GMType;
        typedef typename DATASET::LossType LossType;
        typedef typename GMType::ValueType ValueType;
        typedef typename GMType::IndexType IndexType;
        typedef typename GMType::LabelType LabelType;

        typedef typename std::vector<LabelType>::const_iterator LabelIterator;
        typedef FeatureAccumulator<GMType, LabelIterator> FeatureAcc;

        class Parameter{
        public:

            enum LearningMode{
                Online = 0,
                Batch = 2
            };

            Parameter(){
                eps_ = 0.00001;
                maxIterations_ = 10000;
                stopLoss_ = 0.0;
                decayExponent_ = 0.0;
                decayT0_ = 0.0;
                learningMode_ = Online;
            }

            double eps_;
            size_t maxIterations_;
            double stopLoss_;
            double decayExponent_;
            double decayT0_;
            LearningMode learningMode_;
        };

        StructuredPerceptron(DATASET&, const Parameter& );

        template<class INF>
        void learn(const typename INF::Parameter& para);
        //template<class INF, class VISITOR>
        //void learn(typename INF::Parameter para, VITITOR vis);

        const opengm::learning::Weights<double>& getWeights(){return weights_;}
        Parameter& getLerningParameters(){return para_;}

        double getLearningRate( )const{
            if(para_.decayExponent_<=0.000000001 && para_.decayExponent_>=-0.000000001 ){
                return 1.0;
            }
            else{
                return std::pow(para_.decayT0_ + static_cast<double>(iteration_+1),para_.decayExponent_);
            }
        }

    private:

        double updateWeights();

        DATASET& dataset_;
        opengm::learning::Weights<double> weights_;
        Parameter para_;
        size_t iteration_;
        FeatureAcc featureAcc_;
    };

    template<class DATASET>
    StructuredPerceptron<DATASET>::StructuredPerceptron(DATASET& ds, const Parameter& p )
    : dataset_(ds), para_(p),iteration_(0),featureAcc_(ds.getNumberOfWeights(),false)
    {
        featureAcc_.resetWeights();
        weights_ = opengm::learning::Weights<double>(ds.getNumberOfWeights());

    }

    template<class DATASET>
    template<class INF>
    void StructuredPerceptron<DATASET>::learn(const typename INF::Parameter& para){

        const size_t nModels = dataset_.getNumberOfModels();
        const size_t nWegihts = dataset_.getNumberOfWeights();

        if(para_.learningMode_ == Parameter::Online){
            RandomUniform<size_t> randModel(0, nModels);
            std::cout<<"online mode\n";
            for(iteration_=0 ; iteration_<para_.maxIterations_; ++iteration_){

                if(iteration_%nModels==0){
                    std::cout<<"loss :"<<dataset_. template getTotalLoss<INF>(para)<<"\n";
                }

                // get random model
                const size_t gmi = randModel();
                // lock the model
                dataset_.lockModel(gmi);
                const GMType & gm = dataset_.getModel(gmi);

                // do inference
                std::vector<LabelType> arg;
                opengm::infer<INF>(gm, para, arg);
                featureAcc_.resetWeights();
                featureAcc_.accumulateModelFeatures(gm, dataset_.getGT(gmi).begin(), arg.begin());
                dataset_.unlockModel(gmi);

                // update weights
                const double wChange =updateWeights();

            }
        }
        else if(para_.learningMode_ == Parameter::Batch){
            std::cout<<"batch mode\n";
            for(iteration_=0 ; iteration_<para_.maxIterations_; ++iteration_){
                // this
                if(iteration_%1==0){
                    std::cout<<"loss :"<<dataset_. template getTotalLoss<INF>(para)<<"\n";
                }

                // reset the weights
                featureAcc_.resetWeights();

                #ifndef CI
                omp_lock_t modelLockUnlock;
                omp_init_lock(&modelLockUnlock);

                omp_lock_t featureAccLock;
                omp_init_lock(&featureAccLock);
                #endif

                #pragma omp parallel for
                for(size_t gmi=0; gmi<nModels; ++gmi)
                {

                    // lock the model
                    omp_set_lock(&modelLockUnlock);
                    dataset_.lockModel(gmi);
                    omp_unset_lock(&modelLockUnlock);

                    const GMType & gm = dataset_.getModel(gmi);
                    //run inference
                    std::vector<LabelType> arg;
                    opengm::infer<INF>(gm, para, arg);

                    //
                    FeatureAcc featureAcc(nWegihts,false);
                    featureAcc.accumulateModelFeatures(gm, dataset_.getGT(gmi).begin(), arg.begin());

                    // acc features
                    #ifndef CI
                    omp_set_lock(&featureAccLock);
                    featureAcc_.accumulateFromOther(featureAcc);
                    omp_unset_lock(&featureAccLock);

                    // unlock the model
                    omp_set_lock(&modelLockUnlock);
                    dataset_.unlockModel(gmi);
                    omp_unset_lock(&modelLockUnlock);
                    #else
                    featureAcc_.accumulateFromOther(featureAcc);
                    dataset_.unlockModel(gmi);
                    #endif

                }

                // update the weights
                const double wChange =updateWeights();

            }
        }

        weights_ = dataset_.getWeights();
    }

    template<class DATASET>
    double StructuredPerceptron<DATASET>::updateWeights(){
        double wChange = 0.0;
        const size_t nWegihts = dataset_.getNumberOfWeights();
        for(size_t wi=0; wi<nWegihts; ++wi){
            const double wOld = dataset_.getWeights().getWeight(wi);
            const double wNew = wOld + getLearningRate()*featureAcc_.getWeight(wi);
            wChange += std::pow(wOld-wNew,2);
            dataset_.getWeights().setWeight(wi, wNew);
        }
        weights_ = dataset_.getWeights();
        return wChange;
    }
}
}
#endif
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2011 Couchbase, 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
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
#include <cassert>
#include <cstdio>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <cerrno>
#include <sys/stat.h>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <map>

#include <ctype.h>

#include "cJSON.h"

using namespace std;

stringstream prototypes;
stringstream initialization;
stringstream implementation;

typedef string (*getValidatorCode)(const std::string &, cJSON*);

std::map<string, getValidatorCode> validators;
map<string, string> getters;
map<string, string> datatypes;

std::ostream& operator <<(std::ostream &out, const cJSON *o) {
    switch (o->type) {
    case cJSON_Number:
        if (o->valueint != o->valuedouble) {
            out << (float)o->valuedouble;
        } else {
            out << o->valueint;
        }
        break;
    case cJSON_String:
        out << '"' << o->valuestring << '"';
        break;
    default:
        cerr << "Internal error.. unknow json code" << endl;
        abort();
    }
    return out;
}

bool isFloat(const cJSON *o) {
    return o->valueint != o->valuedouble;
}

string getRangeValidatorCode(const std::string &key, cJSON *o) {
    // the range validator should contain a "min" and "max" element
    cJSON *min = cJSON_GetObjectItem(o, "min");
    cJSON *max = cJSON_GetObjectItem(o, "max");

    if (min == 0 || max == 0) {
        cerr << "Incorrect syntax for a range validator specified for"
             << "\"" << key << "\"." << endl
             <<"You need both a min and max clause." << endl;
        exit(1);
    }

    if (min->type != max->type || min->type != cJSON_Number) {
        cerr << "Incorrect datatype for the range validator specified for "
             << "\"" << key << "\"." << endl
             << "Only numbers are supported." << endl;
        exit(1);
    }

    stringstream ss;
    if (isFloat(min) || isFloat(max)) {
        ss << "(new FloatRangeValidator())->min((float)" << min << ")->max((float)" << max << ")";
    } else {
        ss << "(new SizeRangeValidator())->min(" << min << ")->max(" << max << ")";
    }

    return ss.str();
}

static void initialize() {
    prototypes << "// ###########################################" << endl
               << "// # DO NOT EDIT! THIS IS A GENERATED FILE " << endl
               << "// ###########################################" << endl;

    implementation << "// ###########################################" << endl
                   << "// # DO NOT EDIT! THIS IS A GENERATED FILE " << endl
                   << "// ###########################################" << endl;
    validators["range"] = getRangeValidatorCode;
    getters["std::string"] = "getString";
    getters["bool"] = "getBool";
    getters["size_t"] = "getInteger";
    getters["float"] = "getFloat";
    datatypes["bool"] = "bool";
    datatypes["size_t"] = "size_t";
    datatypes["float"] = "float";
    datatypes["string"] = "std::string";
    datatypes["std::string"] = "std::string";
}

static string getString(cJSON *i) {
    if (i == NULL) {
        return "";
    }
    assert(i->type == cJSON_String);
    return i->valuestring;
}

static bool isReadOnly(cJSON *o) {
    cJSON *i = cJSON_GetObjectItem(o, "dynamic");
    if (i == NULL || i->type == cJSON_False) {
        return false;
    }

    assert(i->type == cJSON_True);
    return true;
}

static string getDatatype(const std::string &key, cJSON *o) {
    cJSON *i = cJSON_GetObjectItem(o, "type");
    assert(i != NULL && i->type == cJSON_String);
    string ret = i->valuestring;

    map<string, string>::iterator iter = datatypes.find(ret);
    if (iter == datatypes.end()) {
        cerr << "Invalid datatype specified for \"" << key << "\": "
             << i->valuestring << endl;
        exit(1);
    }

    return iter->second;
}

static string getValidator(const std::string &key, cJSON *o) {
    if (o == NULL) {
        return "";
    }

    cJSON *n = cJSON_GetArrayItem(o, 0);
    if (n == NULL) {
        return "";
    }

    std::map<string, getValidatorCode>::iterator iter;
    iter = validators.find(string(n->string));
    if (iter == validators.end()) {
        cerr << "Unknown validator specified for \"" << key
             << "\": \"" << n->string << "\""
             << endl;
        exit(1);
    }

    return (iter->second)(key, n);
}

static string getGetterPrefix(const string &str) {
    if (str.compare("bool") == 0) {
        return "is";
    } else {
        return "get";
    }
}

static string getCppName(const string &str) {
    stringstream ss;
    bool doUpper = true;

    string::const_iterator iter;
    for (iter = str.begin(); iter != str.end(); ++iter) {
        if (*iter == '_') {
            doUpper = true;
        } else {
            if (doUpper) {
                ss << (char)toupper(*iter);
                doUpper = false;
            } else {
                ss << (char)*iter;
            }
        }
    }
    return ss.str();
}

static void generate(cJSON *o) {
    assert(o != NULL);

    string config_name = o->string;
    string cppname = getCppName(config_name);
    string type = getDatatype(config_name, o);
    string defaultVal = getString(cJSON_GetObjectItem(o, "default"));
    string validator = getValidator(config_name,
                                    cJSON_GetObjectItem(o, "validator"));

    // Generate prototypes
    prototypes << "    " << type
               << " " << getGetterPrefix(type)
               << cppname << "() const;" << endl;
    if  (!isReadOnly(o)) {
        prototypes << "    void set" << cppname << "(const " << type
                   << " &nval);" << endl;
    }

    // Generate initialization code
    initialization << "    setParameter(\"" << config_name << "\", ";
    if (type.compare("std::string") == 0) {
        initialization << "(const char*)\"" << defaultVal << "\");" << endl;
    } else {
        initialization << "(" << type << ")" << defaultVal << ");" << endl;
    }
    if (!validator.empty()) {
        initialization << "    setValueValidator(\"" << config_name
                       << "\", " << validator << ");" << endl;
    }

    // Generate the getter
    implementation << type << " Configuration::" << getGetterPrefix(type)
                   << cppname << "() const {" << endl
                   << "    return " << getters[type] << "(\""
                   << config_name << "\");" << endl << "}" << endl;

    if  (!isReadOnly(o)) {
        // generate the setter
        implementation << "void Configuration::set" << cppname
                       << "(const " << type << " &nval) {" << endl
                       << "    setParameter(\"" << config_name
                       << "\", nval);" << endl
                       << "}" << endl;
    }
}

/**
 * Read "configuration.json" and generate getters and setters
 * for the parameters in there
 */
int main(int argc, char **argv) {
    (void)argc;
    (void)argv;

    initialize();

    struct stat st;
    if (stat("configuration.json", &st) == -1) {
        cerr << "Failed to look up configuration.json: "
             << strerror(errno) << endl;
        return 1;
    }

    char *data = new char[st.st_size + 1];
    data[st.st_size] = 0;
    ifstream input("configuration.json");
    input.read(data, st.st_size);
    input.close();

    cJSON *c = cJSON_Parse(data);
    if (c == NULL) {
        cerr << "Failed to parse JSON.. probably syntax error" << endl;
        return 1;
    }

    cJSON *params = cJSON_GetObjectItem(c, "params");
    if (params == NULL) {
        cerr << "FATAL: could not find \"params\" section" << endl;
        return 1;
    }

    int num = cJSON_GetArraySize(params);
    for (int ii = 0; ii < num; ++ii) {
        generate(cJSON_GetArrayItem(params, ii));
    }

    ofstream headerfile("generated_configuration.hh");
    headerfile << prototypes.str();
    headerfile.close();

    ofstream implfile("generated_configuration.cc");
    implfile << implementation.str() << endl
             << "void Configuration::initialize() {" << endl
             << initialization.str()
             << "}" << endl;
    implfile.close();

    cJSON_Delete(c);
    delete []data;

    return 0;
}
<commit_msg>Fix compile failure due to missing static keyword<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2011 Couchbase, 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
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
#include <cassert>
#include <cstdio>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <cerrno>
#include <sys/stat.h>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <map>

#include <ctype.h>

#include "cJSON.h"

using namespace std;

stringstream prototypes;
stringstream initialization;
stringstream implementation;

typedef string (*getValidatorCode)(const std::string &, cJSON*);

std::map<string, getValidatorCode> validators;
map<string, string> getters;
map<string, string> datatypes;

static std::ostream& operator <<(std::ostream &out, const cJSON *o) {
    switch (o->type) {
    case cJSON_Number:
        if (o->valueint != o->valuedouble) {
            out << (float)o->valuedouble;
        } else {
            out << o->valueint;
        }
        break;
    case cJSON_String:
        out << '"' << o->valuestring << '"';
        break;
    default:
        cerr << "Internal error.. unknow json code" << endl;
        abort();
    }
    return out;
}

static bool isFloat(const cJSON *o) {
    return o->valueint != o->valuedouble;
}

static string getRangeValidatorCode(const std::string &key, cJSON *o) {
    // the range validator should contain a "min" and "max" element
    cJSON *min = cJSON_GetObjectItem(o, "min");
    cJSON *max = cJSON_GetObjectItem(o, "max");

    if (min == 0 || max == 0) {
        cerr << "Incorrect syntax for a range validator specified for"
             << "\"" << key << "\"." << endl
             <<"You need both a min and max clause." << endl;
        exit(1);
    }

    if (min->type != max->type || min->type != cJSON_Number) {
        cerr << "Incorrect datatype for the range validator specified for "
             << "\"" << key << "\"." << endl
             << "Only numbers are supported." << endl;
        exit(1);
    }

    stringstream ss;
    if (isFloat(min) || isFloat(max)) {
        ss << "(new FloatRangeValidator())->min((float)" << min << ")->max((float)" << max << ")";
    } else {
        ss << "(new SizeRangeValidator())->min(" << min << ")->max(" << max << ")";
    }

    return ss.str();
}

static void initialize() {
    prototypes << "// ###########################################" << endl
               << "// # DO NOT EDIT! THIS IS A GENERATED FILE " << endl
               << "// ###########################################" << endl;

    implementation << "// ###########################################" << endl
                   << "// # DO NOT EDIT! THIS IS A GENERATED FILE " << endl
                   << "// ###########################################" << endl;
    validators["range"] = getRangeValidatorCode;
    getters["std::string"] = "getString";
    getters["bool"] = "getBool";
    getters["size_t"] = "getInteger";
    getters["float"] = "getFloat";
    datatypes["bool"] = "bool";
    datatypes["size_t"] = "size_t";
    datatypes["float"] = "float";
    datatypes["string"] = "std::string";
    datatypes["std::string"] = "std::string";
}

static string getString(cJSON *i) {
    if (i == NULL) {
        return "";
    }
    assert(i->type == cJSON_String);
    return i->valuestring;
}

static bool isReadOnly(cJSON *o) {
    cJSON *i = cJSON_GetObjectItem(o, "dynamic");
    if (i == NULL || i->type == cJSON_False) {
        return false;
    }

    assert(i->type == cJSON_True);
    return true;
}

static string getDatatype(const std::string &key, cJSON *o) {
    cJSON *i = cJSON_GetObjectItem(o, "type");
    assert(i != NULL && i->type == cJSON_String);
    string ret = i->valuestring;

    map<string, string>::iterator iter = datatypes.find(ret);
    if (iter == datatypes.end()) {
        cerr << "Invalid datatype specified for \"" << key << "\": "
             << i->valuestring << endl;
        exit(1);
    }

    return iter->second;
}

static string getValidator(const std::string &key, cJSON *o) {
    if (o == NULL) {
        return "";
    }

    cJSON *n = cJSON_GetArrayItem(o, 0);
    if (n == NULL) {
        return "";
    }

    std::map<string, getValidatorCode>::iterator iter;
    iter = validators.find(string(n->string));
    if (iter == validators.end()) {
        cerr << "Unknown validator specified for \"" << key
             << "\": \"" << n->string << "\""
             << endl;
        exit(1);
    }

    return (iter->second)(key, n);
}

static string getGetterPrefix(const string &str) {
    if (str.compare("bool") == 0) {
        return "is";
    } else {
        return "get";
    }
}

static string getCppName(const string &str) {
    stringstream ss;
    bool doUpper = true;

    string::const_iterator iter;
    for (iter = str.begin(); iter != str.end(); ++iter) {
        if (*iter == '_') {
            doUpper = true;
        } else {
            if (doUpper) {
                ss << (char)toupper(*iter);
                doUpper = false;
            } else {
                ss << (char)*iter;
            }
        }
    }
    return ss.str();
}

static void generate(cJSON *o) {
    assert(o != NULL);

    string config_name = o->string;
    string cppname = getCppName(config_name);
    string type = getDatatype(config_name, o);
    string defaultVal = getString(cJSON_GetObjectItem(o, "default"));
    string validator = getValidator(config_name,
                                    cJSON_GetObjectItem(o, "validator"));

    // Generate prototypes
    prototypes << "    " << type
               << " " << getGetterPrefix(type)
               << cppname << "() const;" << endl;
    if  (!isReadOnly(o)) {
        prototypes << "    void set" << cppname << "(const " << type
                   << " &nval);" << endl;
    }

    // Generate initialization code
    initialization << "    setParameter(\"" << config_name << "\", ";
    if (type.compare("std::string") == 0) {
        initialization << "(const char*)\"" << defaultVal << "\");" << endl;
    } else {
        initialization << "(" << type << ")" << defaultVal << ");" << endl;
    }
    if (!validator.empty()) {
        initialization << "    setValueValidator(\"" << config_name
                       << "\", " << validator << ");" << endl;
    }

    // Generate the getter
    implementation << type << " Configuration::" << getGetterPrefix(type)
                   << cppname << "() const {" << endl
                   << "    return " << getters[type] << "(\""
                   << config_name << "\");" << endl << "}" << endl;

    if  (!isReadOnly(o)) {
        // generate the setter
        implementation << "void Configuration::set" << cppname
                       << "(const " << type << " &nval) {" << endl
                       << "    setParameter(\"" << config_name
                       << "\", nval);" << endl
                       << "}" << endl;
    }
}

/**
 * Read "configuration.json" and generate getters and setters
 * for the parameters in there
 */
int main(int argc, char **argv) {
    (void)argc;
    (void)argv;

    initialize();

    struct stat st;
    if (stat("configuration.json", &st) == -1) {
        cerr << "Failed to look up configuration.json: "
             << strerror(errno) << endl;
        return 1;
    }

    char *data = new char[st.st_size + 1];
    data[st.st_size] = 0;
    ifstream input("configuration.json");
    input.read(data, st.st_size);
    input.close();

    cJSON *c = cJSON_Parse(data);
    if (c == NULL) {
        cerr << "Failed to parse JSON.. probably syntax error" << endl;
        return 1;
    }

    cJSON *params = cJSON_GetObjectItem(c, "params");
    if (params == NULL) {
        cerr << "FATAL: could not find \"params\" section" << endl;
        return 1;
    }

    int num = cJSON_GetArraySize(params);
    for (int ii = 0; ii < num; ++ii) {
        generate(cJSON_GetArrayItem(params, ii));
    }

    ofstream headerfile("generated_configuration.hh");
    headerfile << prototypes.str();
    headerfile.close();

    ofstream implfile("generated_configuration.cc");
    implfile << implementation.str() << endl
             << "void Configuration::initialize() {" << endl
             << initialization.str()
             << "}" << endl;
    implfile.close();

    cJSON_Delete(c);
    delete []data;

    return 0;
}
<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Manuel Yguel <manuel.yguel@gmail.com>
//
// 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/.

#include "main.h"
#include <unsupported/Eigen/Polynomials>
#include <iostream>
#include <algorithm>

using namespace std;

namespace Eigen {
namespace internal {
template<int Size>
struct increment_if_fixed_size
{
  enum {
    ret = (Size == Dynamic) ? Dynamic : Size+1
  };
};
}
}

template<int Deg, typename POLYNOMIAL, typename SOLVER>
bool aux_evalSolver( const POLYNOMIAL& pols, SOLVER& psolve )
{
  typedef typename POLYNOMIAL::Index Index;
  typedef typename POLYNOMIAL::Scalar Scalar;

  typedef typename SOLVER::RootsType    RootsType;
  typedef Matrix<Scalar,Deg,1>          EvalRootsType;

  const Index deg = pols.size()-1;

  psolve.compute( pols );
  const RootsType& roots( psolve.roots() );
  EvalRootsType evr( deg );
  for( int i=0; i<roots.size(); ++i ){
    evr[i] = std::abs( poly_eval( pols, roots[i] ) ); }

  bool evalToZero = evr.isZero( test_precision<Scalar>() );
  if( !evalToZero )
  {
    cerr << "WRONG root: " << endl;
    cerr << "Polynomial: " << pols.transpose() << endl;
    cerr << "Roots found: " << roots.transpose() << endl;
    cerr << "Abs value of the polynomial at the roots: " << evr.transpose() << endl;
    cerr << endl;
  }

  std::vector<Scalar> rootModuli( roots.size() );
  Map< EvalRootsType > aux( &rootModuli[0], roots.size() );
  aux = roots.array().abs();
  std::sort( rootModuli.begin(), rootModuli.end() );
  bool distinctModuli=true;
  for( size_t i=1; i<rootModuli.size() && distinctModuli; ++i )
  {
    if( internal::isApprox( rootModuli[i], rootModuli[i-1] ) ){
      distinctModuli = false; }
  }
  VERIFY( evalToZero || !distinctModuli );

  return distinctModuli;
}

template<int Deg, typename POLYNOMIAL>
void evalSolver( const POLYNOMIAL& pols )
{
  typedef typename POLYNOMIAL::Scalar Scalar;

  typedef PolynomialSolver<Scalar, Deg >              PolynomialSolverType;

  PolynomialSolverType psolve;
  aux_evalSolver<Deg, POLYNOMIAL, PolynomialSolverType>( pols, psolve );
}

template< int Deg, typename POLYNOMIAL, typename ROOTS, typename REAL_ROOTS >
void evalSolverSugarFunction( const POLYNOMIAL& pols, const ROOTS& roots, const REAL_ROOTS& real_roots )
{
  using std::sqrt;
  typedef typename POLYNOMIAL::Scalar Scalar;

  typedef PolynomialSolver<Scalar, Deg >              PolynomialSolverType;

  PolynomialSolverType psolve;
  if( aux_evalSolver<Deg, POLYNOMIAL, PolynomialSolverType>( pols, psolve ) )
  {
    //It is supposed that
    // 1) the roots found are correct
    // 2) the roots have distinct moduli

    typedef typename POLYNOMIAL::Scalar                 Scalar;
    typedef typename REAL_ROOTS::Scalar                 Real;
    typedef PolynomialSolver<Scalar, Deg >              PolynomialSolverType;

    //Test realRoots
    std::vector< Real > calc_realRoots;
    psolve.realRoots( calc_realRoots );
    VERIFY( calc_realRoots.size() == (size_t)real_roots.size() );

    const Scalar psPrec = sqrt( test_precision<Scalar>() );

    for( size_t i=0; i<calc_realRoots.size(); ++i )
    {
      bool found = false;
      for( size_t j=0; j<calc_realRoots.size()&& !found; ++j )
      {
        if( internal::isApprox( calc_realRoots[i], real_roots[j] ), psPrec ){
          found = true; }
      }
      VERIFY( found );
    }

    //Test greatestRoot
    VERIFY( internal::isApprox( roots.array().abs().maxCoeff(),
          abs( psolve.greatestRoot() ), psPrec ) );

    //Test smallestRoot
    VERIFY( internal::isApprox( roots.array().abs().minCoeff(),
          abs( psolve.smallestRoot() ), psPrec ) );

    bool hasRealRoot;
    //Test absGreatestRealRoot
    Real r = psolve.absGreatestRealRoot( hasRealRoot );
    VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
    if( hasRealRoot ){
      VERIFY( internal::isApprox( real_roots.array().abs().maxCoeff(), abs(r), psPrec ) );  }

    //Test absSmallestRealRoot
    r = psolve.absSmallestRealRoot( hasRealRoot );
    VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
    if( hasRealRoot ){
      VERIFY( internal::isApprox( real_roots.array().abs().minCoeff(), abs( r ), psPrec ) ); }

    //Test greatestRealRoot
    r = psolve.greatestRealRoot( hasRealRoot );
    VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
    if( hasRealRoot ){
      VERIFY( internal::isApprox( real_roots.array().maxCoeff(), r, psPrec ) ); }

    //Test smallestRealRoot
    r = psolve.smallestRealRoot( hasRealRoot );
    VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
    if( hasRealRoot ){
    VERIFY( internal::isApprox( real_roots.array().minCoeff(), r, psPrec ) ); }
  }
}

template<typename _Scalar, int _Deg>
void polynomialsolver(int deg)
{
  typedef internal::increment_if_fixed_size<_Deg>            Dim;
  typedef Matrix<_Scalar,Dim::ret,1>                  PolynomialType;
  typedef Matrix<_Scalar,_Deg,1>                      EvalRootsType;

  cout << "Standard cases" << endl;
  PolynomialType pols = PolynomialType::Random(deg+1);
  evalSolver<_Deg,PolynomialType>( pols );

  cout << "Hard cases" << endl;
  _Scalar multipleRoot = internal::random<_Scalar>();
  EvalRootsType allRoots = EvalRootsType::Constant(deg,multipleRoot);
  roots_to_monicPolynomial( allRoots, pols );
  evalSolver<_Deg,PolynomialType>( pols );

  cout << "Test sugar" << endl;
  EvalRootsType realRoots = EvalRootsType::Random(deg);
  roots_to_monicPolynomial( realRoots, pols );
  evalSolverSugarFunction<_Deg>(
      pols,
      realRoots.template cast <
                    std::complex<
                         typename NumTraits<_Scalar>::Real
                         >
                    >(),
      realRoots );
}

void test_polynomialsolver()
{
  for(int i = 0; i < g_repeat; i++)
  {
    CALL_SUBTEST_1( (polynomialsolver<float,1>(1)) );
    CALL_SUBTEST_2( (polynomialsolver<double,2>(2)) );
    CALL_SUBTEST_3( (polynomialsolver<double,3>(3)) );
    CALL_SUBTEST_4( (polynomialsolver<float,4>(4)) );
    CALL_SUBTEST_5( (polynomialsolver<double,5>(5)) );
    CALL_SUBTEST_6( (polynomialsolver<float,6>(6)) );
    CALL_SUBTEST_7( (polynomialsolver<float,7>(7)) );
    CALL_SUBTEST_8( (polynomialsolver<double,8>(8)) );

    CALL_SUBTEST_9( (polynomialsolver<float,Dynamic>(
            internal::random<int>(9,13)
            )) );
    CALL_SUBTEST_10((polynomialsolver<double,Dynamic>(
            internal::random<int>(9,13)
            )) );
  }
}
<commit_msg>fix typo in evalSolverSugarFunction()<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Manuel Yguel <manuel.yguel@gmail.com>
//
// 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/.

#include "main.h"
#include <unsupported/Eigen/Polynomials>
#include <iostream>
#include <algorithm>

using namespace std;

namespace Eigen {
namespace internal {
template<int Size>
struct increment_if_fixed_size
{
  enum {
    ret = (Size == Dynamic) ? Dynamic : Size+1
  };
};
}
}

template<int Deg, typename POLYNOMIAL, typename SOLVER>
bool aux_evalSolver( const POLYNOMIAL& pols, SOLVER& psolve )
{
  typedef typename POLYNOMIAL::Index Index;
  typedef typename POLYNOMIAL::Scalar Scalar;

  typedef typename SOLVER::RootsType    RootsType;
  typedef Matrix<Scalar,Deg,1>          EvalRootsType;

  const Index deg = pols.size()-1;

  psolve.compute( pols );
  const RootsType& roots( psolve.roots() );
  EvalRootsType evr( deg );
  for( int i=0; i<roots.size(); ++i ){
    evr[i] = std::abs( poly_eval( pols, roots[i] ) ); }

  bool evalToZero = evr.isZero( test_precision<Scalar>() );
  if( !evalToZero )
  {
    cerr << "WRONG root: " << endl;
    cerr << "Polynomial: " << pols.transpose() << endl;
    cerr << "Roots found: " << roots.transpose() << endl;
    cerr << "Abs value of the polynomial at the roots: " << evr.transpose() << endl;
    cerr << endl;
  }

  std::vector<Scalar> rootModuli( roots.size() );
  Map< EvalRootsType > aux( &rootModuli[0], roots.size() );
  aux = roots.array().abs();
  std::sort( rootModuli.begin(), rootModuli.end() );
  bool distinctModuli=true;
  for( size_t i=1; i<rootModuli.size() && distinctModuli; ++i )
  {
    if( internal::isApprox( rootModuli[i], rootModuli[i-1] ) ){
      distinctModuli = false; }
  }
  VERIFY( evalToZero || !distinctModuli );

  return distinctModuli;
}

template<int Deg, typename POLYNOMIAL>
void evalSolver( const POLYNOMIAL& pols )
{
  typedef typename POLYNOMIAL::Scalar Scalar;

  typedef PolynomialSolver<Scalar, Deg >              PolynomialSolverType;

  PolynomialSolverType psolve;
  aux_evalSolver<Deg, POLYNOMIAL, PolynomialSolverType>( pols, psolve );
}

template< int Deg, typename POLYNOMIAL, typename ROOTS, typename REAL_ROOTS >
void evalSolverSugarFunction( const POLYNOMIAL& pols, const ROOTS& roots, const REAL_ROOTS& real_roots )
{
  using std::sqrt;
  typedef typename POLYNOMIAL::Scalar Scalar;

  typedef PolynomialSolver<Scalar, Deg >              PolynomialSolverType;

  PolynomialSolverType psolve;
  if( aux_evalSolver<Deg, POLYNOMIAL, PolynomialSolverType>( pols, psolve ) )
  {
    //It is supposed that
    // 1) the roots found are correct
    // 2) the roots have distinct moduli

    typedef typename POLYNOMIAL::Scalar                 Scalar;
    typedef typename REAL_ROOTS::Scalar                 Real;
    typedef PolynomialSolver<Scalar, Deg >              PolynomialSolverType;

    //Test realRoots
    std::vector< Real > calc_realRoots;
    psolve.realRoots( calc_realRoots );
    VERIFY( calc_realRoots.size() == (size_t)real_roots.size() );

    const Scalar psPrec = sqrt( test_precision<Scalar>() );

    for( size_t i=0; i<calc_realRoots.size(); ++i )
    {
      bool found = false;
      for( size_t j=0; j<calc_realRoots.size()&& !found; ++j )
      {
        if( internal::isApprox( calc_realRoots[i], real_roots[j], psPrec ) ){
          found = true; }
      }
      VERIFY( found );
    }

    //Test greatestRoot
    VERIFY( internal::isApprox( roots.array().abs().maxCoeff(),
          abs( psolve.greatestRoot() ), psPrec ) );

    //Test smallestRoot
    VERIFY( internal::isApprox( roots.array().abs().minCoeff(),
          abs( psolve.smallestRoot() ), psPrec ) );

    bool hasRealRoot;
    //Test absGreatestRealRoot
    Real r = psolve.absGreatestRealRoot( hasRealRoot );
    VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
    if( hasRealRoot ){
      VERIFY( internal::isApprox( real_roots.array().abs().maxCoeff(), abs(r), psPrec ) );  }

    //Test absSmallestRealRoot
    r = psolve.absSmallestRealRoot( hasRealRoot );
    VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
    if( hasRealRoot ){
      VERIFY( internal::isApprox( real_roots.array().abs().minCoeff(), abs( r ), psPrec ) ); }

    //Test greatestRealRoot
    r = psolve.greatestRealRoot( hasRealRoot );
    VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
    if( hasRealRoot ){
      VERIFY( internal::isApprox( real_roots.array().maxCoeff(), r, psPrec ) ); }

    //Test smallestRealRoot
    r = psolve.smallestRealRoot( hasRealRoot );
    VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
    if( hasRealRoot ){
    VERIFY( internal::isApprox( real_roots.array().minCoeff(), r, psPrec ) ); }
  }
}

template<typename _Scalar, int _Deg>
void polynomialsolver(int deg)
{
  typedef internal::increment_if_fixed_size<_Deg>            Dim;
  typedef Matrix<_Scalar,Dim::ret,1>                  PolynomialType;
  typedef Matrix<_Scalar,_Deg,1>                      EvalRootsType;

  cout << "Standard cases" << endl;
  PolynomialType pols = PolynomialType::Random(deg+1);
  evalSolver<_Deg,PolynomialType>( pols );

  cout << "Hard cases" << endl;
  _Scalar multipleRoot = internal::random<_Scalar>();
  EvalRootsType allRoots = EvalRootsType::Constant(deg,multipleRoot);
  roots_to_monicPolynomial( allRoots, pols );
  evalSolver<_Deg,PolynomialType>( pols );

  cout << "Test sugar" << endl;
  EvalRootsType realRoots = EvalRootsType::Random(deg);
  roots_to_monicPolynomial( realRoots, pols );
  evalSolverSugarFunction<_Deg>(
      pols,
      realRoots.template cast <
                    std::complex<
                         typename NumTraits<_Scalar>::Real
                         >
                    >(),
      realRoots );
}

void test_polynomialsolver()
{
  for(int i = 0; i < g_repeat; i++)
  {
    CALL_SUBTEST_1( (polynomialsolver<float,1>(1)) );
    CALL_SUBTEST_2( (polynomialsolver<double,2>(2)) );
    CALL_SUBTEST_3( (polynomialsolver<double,3>(3)) );
    CALL_SUBTEST_4( (polynomialsolver<float,4>(4)) );
    CALL_SUBTEST_5( (polynomialsolver<double,5>(5)) );
    CALL_SUBTEST_6( (polynomialsolver<float,6>(6)) );
    CALL_SUBTEST_7( (polynomialsolver<float,7>(7)) );
    CALL_SUBTEST_8( (polynomialsolver<double,8>(8)) );

    CALL_SUBTEST_9( (polynomialsolver<float,Dynamic>(
            internal::random<int>(9,13)
            )) );
    CALL_SUBTEST_10((polynomialsolver<double,Dynamic>(
            internal::random<int>(9,13)
            )) );
  }
}
<|endoftext|>


<commit_before>#include "Archs/SuperH/CShInstruction.h"

#include "Archs/SuperH/SuperH.h"
#include "Archs/SuperH/ShOpcodes.h"
#include "Archs/SuperH/ShParser.h"
#include "Core/Common.h"
#include "Core/FileManager.h"
#include "Core/Misc.h"

CShInstruction::CShInstruction(ShOpcodeData& opcode, ShImmediateData& immediate, ShRegisterData& registers)
{
	this->opcodeData = opcode;
	this->immediateData = immediate;
	this->registerData = registers;
}

CShInstruction::~CShInstruction()
{

}

int getImmediateBits(ShImmediateType type)
{
	switch (type)
	{
	case ShImmediateType::Immediate4:
		return 4;
	case ShImmediateType::Immediate8:
		return 8;
	case ShImmediateType::Immediate12:
		return 12;
	default:
		return 0;
	}
}

bool CShInstruction::Validate(const ValidateState &state)
{
	//bool Result = false;

	//bool previousNop = addNop;
	//addNop = false;

	RamPos = g_fileManager->getVirtualAddress();
	if (RamPos % 2)
	{
		Logger::queueError(Logger::Error, "opcode not aligned to word boundary");
		return false;
	}

	// check immediates
	if (immediateData.primary.type != ShImmediateType::None)
	{
		if (immediateData.primary.expression.isLoaded())
		{
			if (!immediateData.primary.expression.evaluateInteger(immediateData.primary.value))
			{
				Logger::queueError(Logger::Error, "Invalid immediate expression");
				return false;
			}

			immediateData.primary.originalValue = immediateData.primary.value;
		}

		if (opcodeData.opcode.flags & SH_MUSTBEALIGNED)	// immediate must be aligned
		{
			if ((opcodeData.opcode.flags & SH_IMM16) && (immediateData.primary.value % 2))
			{
				Logger::queueError(Logger::Error, "Immediate must be 2-byte aligned");
				return false;
			}

			if ((opcodeData.opcode.flags & SH_IMM32) && (immediateData.primary.value % 4))
			{
				Logger::queueError(Logger::Error, "Immediate must be 4-byte aligned");
				return false;
			}
		}

		int immediateBits = getImmediateBits(immediateData.primary.type);
		int maxImmediate = ((1 << immediateBits) - 1);

		if (opcodeData.opcode.flags & SH_IMMREL)	// relative
		{
			int ldSize = (opcodeData.opcode.flags & SH_IMM32) ? 4 : 2;
			int rPos = (opcodeData.opcode.flags & SH_IMM32) ? ((RamPos+4) & 0xFFFFFFFFFFFFFFFC) : (RamPos+4);
			int range = maxImmediate*ldSize;
			int hiRange = (opcodeData.opcode.flags & SH_IMMSIGNED) ? (range/2) : range;
			int lowRange = (opcodeData.opcode.flags & SH_IMMSIGNED) ? -(range/2) : 0;

			int num = (int) (immediateData.primary.value-rPos);

			if (num > hiRange || num < lowRange)
			{
				Logger::queueError(Logger::Error, "Branch/move target %08X out of range", immediateData.primary.value);
				return false;
			}
			immediateData.primary.value = num;
		}

		if (opcodeData.opcode.flags & SH_IMM16)
			immediateData.primary.value = immediateData.primary.value >> 1;
		else if (opcodeData.opcode.flags & SH_IMM32)
			immediateData.primary.value = immediateData.primary.value >> 2;

		unsigned int mask = (0xFFFFFFFF << (32-immediateBits)) >> (32-immediateBits);
		int digits = (immediateBits+3) / 4;

		if ((unsigned int)std::abs(immediateData.primary.value) > mask)
		{
			Logger::queueError(Logger::Error, "Immediate value 0x%0*X out of range",digits,immediateData.primary.value);
			return false;
		}

		immediateData.primary.value &= mask;
	}

    //
    // NOTE: SuperH *does* have delayed instructions, but
    //       I'm not entirely sure how they work exactly yet,
    //       so leaving this functionality off.
    //

#if 0
	// check load delay
	if (Sh.hasLoadDelay() && Sh.GetLoadDelay() && !IgnoreLoadDelay)
	{
		bool fix = false;

		if (registerData.grd.num != -1 && registerData.grd.num == Sh.GetLoadDelayRegister())
		{
			Logger::queueError(Logger::Warning, "register %S may not be available due to load delay",registerData.grd.name);
			fix = true;
		} else if (registerData.grs.num != -1 && registerData.grs.num == Sh.GetLoadDelayRegister())
		{
			Logger::queueError(Logger::Warning, "register %S may not be available due to load delay",registerData.grs.name);
			fix = true;
		} else if (registerData.grt.num != -1 && registerData.grt.num == Sh.GetLoadDelayRegister()
			&& !(opcodeData.opcode.flags & MO_IGNORERTD))
		{
			Logger::queueError(Logger::Warning, "register %S may not be available due to load delay",registerData.grt.name);
			fix = true;
		}

		if (Sh.GetFixLoadDelay() && fix)
		{
			addNop = true;
			Logger::queueError(Logger::Notice, "added nop to ensure correct behavior");
		}
	}

	if ((opcodeData.opcode.flags & MO_NODELAYSLOT) && Sh.GetDelaySlot() && !IgnoreLoadDelay)
	{
		Logger::queueError(Logger::Error, "This instruction can't be in a delay slot");
	}

	Sh.SetDelaySlot((opcodeData.opcode.flags & MO_DELAY) != 0);

	// now check if this opcode causes a load delay
	if (Sh.hasLoadDelay())
		Sh.SetLoadDelay((opcodeData.opcode.flags & MO_DELAYRT) != 0,registerData.grt.num);

	if (previousNop != addNop)
		Result = true;
#endif

	g_fileManager->advanceMemory(2); //addNop ? 4 : 2
	return false;
}

void CShInstruction::Encode() const
{
	//if (addNop)
	//	g_fileManager->writeU32(0);

	uint16_t encoding = opcodeData.opcode.base;

	switch (opcodeData.opcode.format)
	{
	case SHFMT_0:     // xxxx xxxx xxxx xxxx
		break;
	case SHFMT_N:     // xxxx nnnn xxxx xxxx
		encoding |= (registerData.grt.num & 0xF) << 8;
		break;
	case SHFMT_M:     // xxxx mmmm xxxx xxxx
		encoding |= (registerData.grs.num & 0xF) << 8;
		break;
	case SHFMT_NM:    // xxxx nnnn mmmm xxxx
		encoding |= (registerData.grt.num & 0xF) << 8;
		encoding |= (registerData.grs.num & 0xF) << 4;
		break;
	case SHFMT_MD:    // xxxx xxxx mmmm dddd
		encoding |= (registerData.grs.num & 0xF) << 4;
		encoding |= immediateData.primary.value;
		break;
	case SHFMT_ND4:   // xxxx xxxx nnnn dddd
		encoding |= (registerData.grt.num & 0xF) << 4;
		encoding |= immediateData.primary.value;
		break;
	case SHFMT_NMD:   // xxxx nnnn mmmm dddd
		encoding |= (registerData.grt.num & 0xF) << 8;
		encoding |= (registerData.grs.num & 0xF) << 4;
		encoding |= immediateData.primary.value;
		break;
	case SHFMT_D:     // xxxx xxxx dddd dddd
	case SHFMT_D12:   // xxxx dddd dddd dddd
		encoding |= immediateData.primary.value;
		break;
	case SHFMT_ND8:   // xxxx nnnn dddd dddd
		encoding |= (registerData.grt.num & 0xF) << 8;
		encoding |= immediateData.primary.value;
		break;
	case SHFMT_I:     // xxxx xxxx iiii iiii
		encoding |= immediateData.primary.value;
		break;
	case SHFMT_NI:    // xxxx nnnn iiii iiii
		encoding |= (registerData.grt.num & 0xF) << 8;
		encoding |= immediateData.primary.value;
		break;
	}

	g_fileManager->writeU16((uint16_t)encoding);
}

void CShInstruction::writeTempData(TempData& tempData) const
{
	ShOpcodeFormatter formatter;
	tempData.writeLine(RamPos, formatter.formatOpcode(opcodeData,registerData,immediateData));
}
<commit_msg>Note that delayed opcodes are marked<commit_after>#include "Archs/SuperH/CShInstruction.h"

#include "Archs/SuperH/SuperH.h"
#include "Archs/SuperH/ShOpcodes.h"
#include "Archs/SuperH/ShParser.h"
#include "Core/Common.h"
#include "Core/FileManager.h"
#include "Core/Misc.h"

CShInstruction::CShInstruction(ShOpcodeData& opcode, ShImmediateData& immediate, ShRegisterData& registers)
{
	this->opcodeData = opcode;
	this->immediateData = immediate;
	this->registerData = registers;
}

CShInstruction::~CShInstruction()
{

}

int getImmediateBits(ShImmediateType type)
{
	switch (type)
	{
	case ShImmediateType::Immediate4:
		return 4;
	case ShImmediateType::Immediate8:
		return 8;
	case ShImmediateType::Immediate12:
		return 12;
	default:
		return 0;
	}
}

bool CShInstruction::Validate(const ValidateState &state)
{
	//bool Result = false;

	//bool previousNop = addNop;
	//addNop = false;

	RamPos = g_fileManager->getVirtualAddress();
	if (RamPos % 2)
	{
		Logger::queueError(Logger::Error, "opcode not aligned to word boundary");
		return false;
	}

	// check immediates
	if (immediateData.primary.type != ShImmediateType::None)
	{
		if (immediateData.primary.expression.isLoaded())
		{
			if (!immediateData.primary.expression.evaluateInteger(immediateData.primary.value))
			{
				Logger::queueError(Logger::Error, "Invalid immediate expression");
				return false;
			}

			immediateData.primary.originalValue = immediateData.primary.value;
		}

		if (opcodeData.opcode.flags & SH_MUSTBEALIGNED)	// immediate must be aligned
		{
			if ((opcodeData.opcode.flags & SH_IMM16) && (immediateData.primary.value % 2))
			{
				Logger::queueError(Logger::Error, "Immediate must be 2-byte aligned");
				return false;
			}

			if ((opcodeData.opcode.flags & SH_IMM32) && (immediateData.primary.value % 4))
			{
				Logger::queueError(Logger::Error, "Immediate must be 4-byte aligned");
				return false;
			}
		}

		int immediateBits = getImmediateBits(immediateData.primary.type);
		int maxImmediate = ((1 << immediateBits) - 1);

		if (opcodeData.opcode.flags & SH_IMMREL)	// relative
		{
			int ldSize = (opcodeData.opcode.flags & SH_IMM32) ? 4 : 2;
			int rPos = (opcodeData.opcode.flags & SH_IMM32) ? ((RamPos+4) & 0xFFFFFFFFFFFFFFFC) : (RamPos+4);
			int range = maxImmediate*ldSize;
			int hiRange = (opcodeData.opcode.flags & SH_IMMSIGNED) ? (range/2) : range;
			int lowRange = (opcodeData.opcode.flags & SH_IMMSIGNED) ? -(range/2) : 0;

			int num = (int) (immediateData.primary.value-rPos);

			if (num > hiRange || num < lowRange)
			{
				Logger::queueError(Logger::Error, "Branch/move target %08X out of range", immediateData.primary.value);
				return false;
			}
			immediateData.primary.value = num;
		}

		if (opcodeData.opcode.flags & SH_IMM16)
			immediateData.primary.value = immediateData.primary.value >> 1;
		else if (opcodeData.opcode.flags & SH_IMM32)
			immediateData.primary.value = immediateData.primary.value >> 2;

		unsigned int mask = (0xFFFFFFFF << (32-immediateBits)) >> (32-immediateBits);
		int digits = (immediateBits+3) / 4;

		if ((unsigned int)std::abs(immediateData.primary.value) > mask)
		{
			Logger::queueError(Logger::Error, "Immediate value 0x%0*X out of range",digits,immediateData.primary.value);
			return false;
		}

		immediateData.primary.value &= mask;
	}

    //
    // NOTE: SuperH *does* have delayed instructions, but
    //       I'm not entirely sure how they work exactly yet,
    //       so leaving this functionality off (it was originally
    //       taken from the MIPS parser.)
    //       Delayed opcodes are currently marked with the
    //       SH_DELAYED flag.
    //

#if 0
	// check load delay
	if (Sh.hasLoadDelay() && Sh.GetLoadDelay() && !IgnoreLoadDelay)
	{
		bool fix = false;

		if (registerData.grd.num != -1 && registerData.grd.num == Sh.GetLoadDelayRegister())
		{
			Logger::queueError(Logger::Warning, "register %S may not be available due to load delay",registerData.grd.name);
			fix = true;
		} else if (registerData.grs.num != -1 && registerData.grs.num == Sh.GetLoadDelayRegister())
		{
			Logger::queueError(Logger::Warning, "register %S may not be available due to load delay",registerData.grs.name);
			fix = true;
		} else if (registerData.grt.num != -1 && registerData.grt.num == Sh.GetLoadDelayRegister()
			&& !(opcodeData.opcode.flags & MO_IGNORERTD))
		{
			Logger::queueError(Logger::Warning, "register %S may not be available due to load delay",registerData.grt.name);
			fix = true;
		}

		if (Sh.GetFixLoadDelay() && fix)
		{
			addNop = true;
			Logger::queueError(Logger::Notice, "added nop to ensure correct behavior");
		}
	}

	if ((opcodeData.opcode.flags & MO_NODELAYSLOT) && Sh.GetDelaySlot() && !IgnoreLoadDelay)
	{
		Logger::queueError(Logger::Error, "This instruction can't be in a delay slot");
	}

	Sh.SetDelaySlot((opcodeData.opcode.flags & MO_DELAY) != 0);

	// now check if this opcode causes a load delay
	if (Sh.hasLoadDelay())
		Sh.SetLoadDelay((opcodeData.opcode.flags & MO_DELAYRT) != 0,registerData.grt.num);

	if (previousNop != addNop)
		Result = true;
#endif

	g_fileManager->advanceMemory(2); //addNop ? 4 : 2
	return false;
}

void CShInstruction::Encode() const
{
	//if (addNop)
	//	g_fileManager->writeU32(0);

	uint16_t encoding = opcodeData.opcode.base;

	switch (opcodeData.opcode.format)
	{
	case SHFMT_0:     // xxxx xxxx xxxx xxxx
		break;
	case SHFMT_N:     // xxxx nnnn xxxx xxxx
		encoding |= (registerData.grt.num & 0xF) << 8;
		break;
	case SHFMT_M:     // xxxx mmmm xxxx xxxx
		encoding |= (registerData.grs.num & 0xF) << 8;
		break;
	case SHFMT_NM:    // xxxx nnnn mmmm xxxx
		encoding |= (registerData.grt.num & 0xF) << 8;
		encoding |= (registerData.grs.num & 0xF) << 4;
		break;
	case SHFMT_MD:    // xxxx xxxx mmmm dddd
		encoding |= (registerData.grs.num & 0xF) << 4;
		encoding |= immediateData.primary.value;
		break;
	case SHFMT_ND4:   // xxxx xxxx nnnn dddd
		encoding |= (registerData.grt.num & 0xF) << 4;
		encoding |= immediateData.primary.value;
		break;
	case SHFMT_NMD:   // xxxx nnnn mmmm dddd
		encoding |= (registerData.grt.num & 0xF) << 8;
		encoding |= (registerData.grs.num & 0xF) << 4;
		encoding |= immediateData.primary.value;
		break;
	case SHFMT_D:     // xxxx xxxx dddd dddd
	case SHFMT_D12:   // xxxx dddd dddd dddd
		encoding |= immediateData.primary.value;
		break;
	case SHFMT_ND8:   // xxxx nnnn dddd dddd
		encoding |= (registerData.grt.num & 0xF) << 8;
		encoding |= immediateData.primary.value;
		break;
	case SHFMT_I:     // xxxx xxxx iiii iiii
		encoding |= immediateData.primary.value;
		break;
	case SHFMT_NI:    // xxxx nnnn iiii iiii
		encoding |= (registerData.grt.num & 0xF) << 8;
		encoding |= immediateData.primary.value;
		break;
	}

	g_fileManager->writeU16((uint16_t)encoding);
}

void CShInstruction::writeTempData(TempData& tempData) const
{
	ShOpcodeFormatter formatter;
	tempData.writeLine(RamPos, formatter.formatOpcode(opcodeData,registerData,immediateData));
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Initial Developer of the Original Code is
 *       Albert Thuswaldner <albert.thuswaldner@gmail.com>
 * Portions created by the Initial Developer are Copyright (C) 2012 the
 * Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#ifndef SC_FORMULAOPT_HXX
#define SC_FORMULAOPT_HXX

#include <svl/poolitem.hxx>
#include <unotools/configitem.hxx>
#include <unotools/localedatawrapper.hxx>
#include "formula/grammar.hxx"
#include "scdllapi.h"
#include "global.hxx"
#include "calcconfig.hxx"

// have to match the registry values
enum SC_DLLPUBLIC ScRecalcOptions
{
    RECALC_ALWAYS = 0,
    RECALC_ASK = 1,
    RECALC_NEVER = 2
};

class SC_DLLPUBLIC ScFormulaOptions
{
private:
    bool bUseEnglishFuncName;     // use English function name even if the locale is not English.
    formula::FormulaGrammar::Grammar eFormulaGrammar;  // formula grammar used to switch different formula syntax
    ScCalcConfig aCalcConfig;

    ::rtl::OUString aFormulaSepArg;
    ::rtl::OUString aFormulaSepArrayRow;
    ::rtl::OUString aFormulaSepArrayCol;

    ScRecalcOptions meOOXMLRecalc;

public:
    ScFormulaOptions();
    ScFormulaOptions( const ScFormulaOptions& rCpy );
    ~ScFormulaOptions();

    void SetDefaults();

    void SetFormulaSyntax( ::formula::FormulaGrammar::Grammar eGram ) { eFormulaGrammar = eGram; }
    ::formula::FormulaGrammar::Grammar GetFormulaSyntax() const { return eFormulaGrammar; }

    ScCalcConfig& GetCalcConfig() { return aCalcConfig; }
    const ScCalcConfig& GetCalcConfig() const { return aCalcConfig; }
    void SetCalcConfig(const ScCalcConfig& rConfig) { aCalcConfig = rConfig; }

    void SetUseEnglishFuncName( bool bVal ) { bUseEnglishFuncName = bVal; }
    bool GetUseEnglishFuncName() const { return bUseEnglishFuncName; }

    void SetFormulaSepArg(const ::rtl::OUString& rSep) { aFormulaSepArg = rSep; }
    ::rtl::OUString GetFormulaSepArg() const { return aFormulaSepArg; }

    void SetFormulaSepArrayRow(const ::rtl::OUString& rSep) { aFormulaSepArrayRow = rSep; }
    ::rtl::OUString GetFormulaSepArrayRow() const { return aFormulaSepArrayRow; }

    void SetFormulaSepArrayCol(const ::rtl::OUString& rSep) { aFormulaSepArrayCol = rSep; }
    ::rtl::OUString GetFormulaSepArrayCol() const { return aFormulaSepArrayCol; }

    void SetOOXMLRecalcOptions( ScRecalcOptions eOpt ) { meOOXMLRecalc = eOpt; }
    ScRecalcOptions GetOOXMLRecalcOptions() const { return meOOXMLRecalc; }

    void ResetFormulaSeparators();

    static void GetDefaultFormulaSeparators(rtl::OUString& rSepArg, rtl::OUString& rSepArrayCol, rtl::OUString& rSepArrayRow);

    static const LocaleDataWrapper& GetLocaleDataWrapper();

    ScFormulaOptions&  operator=  ( const ScFormulaOptions& rCpy );
    bool               operator== ( const ScFormulaOptions& rOpt ) const;
    bool               operator!= ( const ScFormulaOptions& rOpt ) const;
};

//==================================================================
// item for the dialog / options page
//==================================================================

class SC_DLLPUBLIC ScTpFormulaItem : public SfxPoolItem
{
public:
    TYPEINFO();
    ScTpFormulaItem( sal_uInt16 nWhich,
                   const ScFormulaOptions& rOpt );
    ScTpFormulaItem( const ScTpFormulaItem& rItem );
    ~ScTpFormulaItem();

    virtual String          GetValueText() const;
    virtual int             operator==( const SfxPoolItem& ) const;
    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;

    const ScFormulaOptions& GetFormulaOptions() const { return theOptions; }

private:
    ScFormulaOptions theOptions;
};

//==================================================================
// config item
//==================================================================

class ScFormulaCfg : public ScFormulaOptions, public utl::ConfigItem
{
    com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();
public:
    ScFormulaCfg();

    void SetOptions( const ScFormulaOptions& rNew );

    virtual void Commit();
    virtual void Notify( const ::com::sun::star::uno::Sequence< rtl::OUString >& aPropertyNames );
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>enum is not something that has external linkage, so no point in visibility<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * Version: MPL 1.1 / GPLv3+ / LGPLv3+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Initial Developer of the Original Code is
 *       Albert Thuswaldner <albert.thuswaldner@gmail.com>
 * Portions created by the Initial Developer are Copyright (C) 2012 the
 * Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 3 or later (the "GPLv3+"), or
 * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
 * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
 * instead of those above.
 */

#ifndef SC_FORMULAOPT_HXX
#define SC_FORMULAOPT_HXX

#include <svl/poolitem.hxx>
#include <unotools/configitem.hxx>
#include <unotools/localedatawrapper.hxx>
#include "formula/grammar.hxx"
#include "scdllapi.h"
#include "global.hxx"
#include "calcconfig.hxx"

// have to match the registry values
enum ScRecalcOptions
{
    RECALC_ALWAYS = 0,
    RECALC_ASK = 1,
    RECALC_NEVER = 2
};

class SC_DLLPUBLIC ScFormulaOptions
{
private:
    bool bUseEnglishFuncName;     // use English function name even if the locale is not English.
    formula::FormulaGrammar::Grammar eFormulaGrammar;  // formula grammar used to switch different formula syntax
    ScCalcConfig aCalcConfig;

    ::rtl::OUString aFormulaSepArg;
    ::rtl::OUString aFormulaSepArrayRow;
    ::rtl::OUString aFormulaSepArrayCol;

    ScRecalcOptions meOOXMLRecalc;

public:
    ScFormulaOptions();
    ScFormulaOptions( const ScFormulaOptions& rCpy );
    ~ScFormulaOptions();

    void SetDefaults();

    void SetFormulaSyntax( ::formula::FormulaGrammar::Grammar eGram ) { eFormulaGrammar = eGram; }
    ::formula::FormulaGrammar::Grammar GetFormulaSyntax() const { return eFormulaGrammar; }

    ScCalcConfig& GetCalcConfig() { return aCalcConfig; }
    const ScCalcConfig& GetCalcConfig() const { return aCalcConfig; }
    void SetCalcConfig(const ScCalcConfig& rConfig) { aCalcConfig = rConfig; }

    void SetUseEnglishFuncName( bool bVal ) { bUseEnglishFuncName = bVal; }
    bool GetUseEnglishFuncName() const { return bUseEnglishFuncName; }

    void SetFormulaSepArg(const ::rtl::OUString& rSep) { aFormulaSepArg = rSep; }
    ::rtl::OUString GetFormulaSepArg() const { return aFormulaSepArg; }

    void SetFormulaSepArrayRow(const ::rtl::OUString& rSep) { aFormulaSepArrayRow = rSep; }
    ::rtl::OUString GetFormulaSepArrayRow() const { return aFormulaSepArrayRow; }

    void SetFormulaSepArrayCol(const ::rtl::OUString& rSep) { aFormulaSepArrayCol = rSep; }
    ::rtl::OUString GetFormulaSepArrayCol() const { return aFormulaSepArrayCol; }

    void SetOOXMLRecalcOptions( ScRecalcOptions eOpt ) { meOOXMLRecalc = eOpt; }
    ScRecalcOptions GetOOXMLRecalcOptions() const { return meOOXMLRecalc; }

    void ResetFormulaSeparators();

    static void GetDefaultFormulaSeparators(rtl::OUString& rSepArg, rtl::OUString& rSepArrayCol, rtl::OUString& rSepArrayRow);

    static const LocaleDataWrapper& GetLocaleDataWrapper();

    ScFormulaOptions&  operator=  ( const ScFormulaOptions& rCpy );
    bool               operator== ( const ScFormulaOptions& rOpt ) const;
    bool               operator!= ( const ScFormulaOptions& rOpt ) const;
};

//==================================================================
// item for the dialog / options page
//==================================================================

class SC_DLLPUBLIC ScTpFormulaItem : public SfxPoolItem
{
public:
    TYPEINFO();
    ScTpFormulaItem( sal_uInt16 nWhich,
                   const ScFormulaOptions& rOpt );
    ScTpFormulaItem( const ScTpFormulaItem& rItem );
    ~ScTpFormulaItem();

    virtual String          GetValueText() const;
    virtual int             operator==( const SfxPoolItem& ) const;
    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;

    const ScFormulaOptions& GetFormulaOptions() const { return theOptions; }

private:
    ScFormulaOptions theOptions;
};

//==================================================================
// config item
//==================================================================

class ScFormulaCfg : public ScFormulaOptions, public utl::ConfigItem
{
    com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames();
public:
    ScFormulaCfg();

    void SetOptions( const ScFormulaOptions& rNew );

    virtual void Commit();
    virtual void Notify( const ::com::sun::star::uno::Sequence< rtl::OUString >& aPropertyNames );
};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: gtkobject.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-24 10:30:41 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _VCL_GTKOBJECT_HXX
#define _VCL_GTKOBJECT_HXX

#ifndef _SV_SV_H
#include <vcl/sv.h>
#endif
#ifndef _SV_SYSDATA_HXX
#include <vcl/sysdata.hxx>
#endif
#ifndef _SV_SALOBJ_HXX
#include <vcl/salobj.hxx>
#endif
#ifndef _VCL_GTKFRAME_HXX
#include <plugins/gtk/gtkframe.hxx>
#endif

class GtkSalObject : public SalObject
{
    SystemChildData     m_aSystemData;
    GtkWidget*          m_pSocket;
    GdkRegion*          m_pRegion;

    // signals
    static gboolean     signalButton( GtkWidget*, GdkEventButton*, gpointer );
    static gboolean     signalFocus( GtkWidget*, GdkEventFocus*, gpointer );
    static void         signalDestroy( GtkObject*, gpointer );
public:
    GtkSalObject( GtkSalFrame* pParent );
    virtual ~GtkSalObject();

    // overload all pure virtual methods
     virtual void                   ResetClipRegion();
    virtual USHORT                  GetClipRegionType();
    virtual void                    BeginSetClipRegion( ULONG nRects );
    virtual void                    UnionClipRegion( long nX, long nY, long nWidth, long nHeight );
    virtual void                    EndSetClipRegion();

    virtual void                    SetPosSize( long nX, long nY, long nWidth, long nHeight );
    virtual void                    Show( BOOL bVisible );
    virtual void                    Enable( BOOL nEnable );
    virtual void                    GrabFocus();

    virtual void                    SetBackground();
    virtual void                    SetBackground( SalColor nSalColor );

    virtual const SystemEnvData*    GetSystemData() const;

};

#endif // _SV_SALOBJ_H
<commit_msg>INTEGRATION: CWS transogl02 (1.6.144); FILE MERGED 2007/12/10 19:00:18 radekdoulik 1.6.144.1: add BOOL bShow parameter to SystemChildWindow constructor to allow creating of unmapped window with possibility to show it (map it) later to avoid flicker<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: gtkobject.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2008-01-29 08:39:34 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _VCL_GTKOBJECT_HXX
#define _VCL_GTKOBJECT_HXX

#ifndef _SV_SV_H
#include <vcl/sv.h>
#endif
#ifndef _SV_SYSDATA_HXX
#include <vcl/sysdata.hxx>
#endif
#ifndef _SV_SALOBJ_HXX
#include <vcl/salobj.hxx>
#endif
#ifndef _VCL_GTKFRAME_HXX
#include <plugins/gtk/gtkframe.hxx>
#endif

class GtkSalObject : public SalObject
{
    SystemChildData     m_aSystemData;
    GtkWidget*          m_pSocket;
    GdkRegion*          m_pRegion;

    // signals
    static gboolean     signalButton( GtkWidget*, GdkEventButton*, gpointer );
    static gboolean     signalFocus( GtkWidget*, GdkEventFocus*, gpointer );
    static void         signalDestroy( GtkObject*, gpointer );
public:
    GtkSalObject( GtkSalFrame* pParent, BOOL bShow = TRUE );
    virtual ~GtkSalObject();

    // overload all pure virtual methods
     virtual void                   ResetClipRegion();
    virtual USHORT                  GetClipRegionType();
    virtual void                    BeginSetClipRegion( ULONG nRects );
    virtual void                    UnionClipRegion( long nX, long nY, long nWidth, long nHeight );
    virtual void                    EndSetClipRegion();

    virtual void                    SetPosSize( long nX, long nY, long nWidth, long nHeight );
    virtual void                    Show( BOOL bVisible );
    virtual void                    Enable( BOOL nEnable );
    virtual void                    GrabFocus();

    virtual void                    SetBackground();
    virtual void                    SetBackground( SalColor nSalColor );

    virtual const SystemEnvData*    GetSystemData() const;

};

#endif // _SV_SALOBJ_H
<|endoftext|>


<commit_before>/*  -*- mode: C++; c-file-style: "gnu" -*-
    aboutdata.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB

    Kleopatra is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Kleopatra is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "aboutdata.h"

#include <klocale.h>

static const char * kleopatra_version = "0.10";
static const char * description = I18N_NOOP("KDE Key Manager");

namespace {
  struct about_data {
    const char * name;
    const char * desc;
    const char * email;
    const char * web;
  };
}

static const about_data authors[] = {
  { "Marc Mutz", I18N_NOOP("Current Maintainer"), "mutz@kde.org", 0 },
  { "Steffen Hansen", I18N_NOOP("Former Maintainer"), "hansen@kde.org", 0 },
  { "Kalle Dalheimer", I18N_NOOP("Original Author"), "kalle@kde.org", 0 },
  { "Jesper Petersen", I18N_NOOP("Original Author"), "blackie@kde.org", 0 },
};

static const about_data credits[] = {
  { "Daniel Molkentin",
    I18N_NOOP("Certificate Wizard KIOSK integration, infrastructure"),
    "molkentin@kde.org", 0 },
  { "Ralf Nolden",
    I18N_NOOP("Support for obsolete EMAIL RDN in Certificate Wizard"),
    "nolden@kde.org", 0 },
  { "Karl-Heinz Zimmer",
    I18N_NOOP("DN display ordering support, infrastructure"),
    "khz@kde.org", 0 },
};

AboutData::AboutData()
  : KAboutData( "kgpgcertmanager", I18N_NOOP("KGpgCertManager"),
		kleopatra_version, description, License_GPL,
		"(c) 2002 Steffen Hansen, Jesper Pedersen,\n"
		"Kalle Dalheimer, Klar\xC3\xA4lvdalens Datakonsult AB\n\n"
		"(c) 2004 Marc Mutz, Klar\xC3\xA4lvdalens Datakonsult AB" )
{
  using ::authors;
  using ::credits;
  for ( unsigned int i = 0 ; i < sizeof authors / sizeof *authors ; ++i )
    addAuthor( authors[i].name, authors[i].desc,
	       authors[i].email, authors[i].web );
  for ( unsigned int i = 0 ; i < sizeof credits / sizeof *credits ; ++i )
    addCredit( credits[i].name, credits[i].desc,
	       credits[i].email, credits[i].web );
}
<commit_msg>up the version<commit_after>/*  -*- mode: C++; c-file-style: "gnu" -*-
    aboutdata.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2001,2002,2004 Klarlvdalens Datakonsult AB

    Kleopatra is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Kleopatra is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "aboutdata.h"

#include <klocale.h>

static const char * kleopatra_version = "0.11";
static const char * description = I18N_NOOP("KDE Key Manager");

namespace {
  struct about_data {
    const char * name;
    const char * desc;
    const char * email;
    const char * web;
  };
}

static const about_data authors[] = {
  { "Marc Mutz", I18N_NOOP("Current Maintainer"), "mutz@kde.org", 0 },
  { "Steffen Hansen", I18N_NOOP("Former Maintainer"), "hansen@kde.org", 0 },
  { "Kalle Dalheimer", I18N_NOOP("Original Author"), "kalle@kde.org", 0 },
  { "Jesper Petersen", I18N_NOOP("Original Author"), "blackie@kde.org", 0 },
};

static const about_data credits[] = {
  { "Daniel Molkentin",
    I18N_NOOP("Certificate Wizard KIOSK integration, infrastructure"),
    "molkentin@kde.org", 0 },
  { "Ralf Nolden",
    I18N_NOOP("Support for obsolete EMAIL RDN in Certificate Wizard"),
    "nolden@kde.org", 0 },
  { "Karl-Heinz Zimmer",
    I18N_NOOP("DN display ordering support, infrastructure"),
    "khz@kde.org", 0 },
};

AboutData::AboutData()
  : KAboutData( "kgpgcertmanager", I18N_NOOP("KGpgCertManager"),
		kleopatra_version, description, License_GPL,
		"(c) 2002 Steffen Hansen, Jesper Pedersen,\n"
		"Kalle Dalheimer, Klar\xC3\xA4lvdalens Datakonsult AB\n\n"
		"(c) 2004 Marc Mutz, Klar\xC3\xA4lvdalens Datakonsult AB" )
{
  using ::authors;
  using ::credits;
  for ( unsigned int i = 0 ; i < sizeof authors / sizeof *authors ; ++i )
    addAuthor( authors[i].name, authors[i].desc,
	       authors[i].email, authors[i].web );
  for ( unsigned int i = 0 ; i < sizeof credits / sizeof *credits ; ++i )
    addCredit( credits[i].name, credits[i].desc,
	       credits[i].email, credits[i].web );
}
<|endoftext|>