<commit_before>#ifndef slic3r_Config_hpp_
#define slic3r_Config_hpp_

#include <map>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#include <myinit.h>
#include "Point.hpp"

namespace Slic3r {

typedef std::string t_config_option_key;
typedef std::vector<std::string> t_config_option_keys;

class ConfigOption {
    public:
    virtual ~ConfigOption() {};
    virtual std::string serialize() const = 0;
    virtual bool deserialize(std::string str) = 0;
    virtual int getInt() const { return 0; };
    virtual void setInt(int val) {};
};

template <class T>
class ConfigOptionVector
{
    public:
    virtual ~ConfigOptionVector() {};
    std::vector<T> values;

    T get_at(size_t i) const {
        try {
            return this->values.at(i);
        } catch (const std::out_of_range& oor) {
            return this->values.front();
        }
    };
};

class ConfigOptionFloat : public ConfigOption
{
    public:
    double value;  // use double instead of float for preserving compatibility with values coming from Perl
    ConfigOptionFloat() : value(0) {};

    operator float() const { return this->value; };
    operator double() const { return this->value; };

    std::string serialize() const {
        std::ostringstream ss;
        ss << this->value;
        return ss.str();
    };

    bool deserialize(std::string str) {
        std::istringstream iss(str);
        return iss >> this->value;
    };
};

class ConfigOptionFloats : public ConfigOption, public ConfigOptionVector<double>
{
    public:

    std::string serialize() const {
        std::ostringstream ss;
        for (std::vector<double>::const_iterator it = this->values.begin(); it != this->values.end(); ++it) {
            if (it - this->values.begin() != 0) ss << ",";
            ss << *it;
        }
        return ss.str();
    };

    bool deserialize(std::string str) {
        this->values.clear();
        std::istringstream is(str);
        std::string item_str;
        while (std::getline(is, item_str, ',')) {
            std::istringstream iss(item_str);
            double value;
            iss >> value;
            this->values.push_back(value);
        }
        return true;
    };
};

class ConfigOptionInt : public ConfigOption
{
    public:
    int value;
    ConfigOptionInt() : value(0) {};

    operator int() const { return this->value; };
    int getInt() const { return this->value; };
    void setInt(int val) { this->value = val; };

    std::string serialize() const {
        std::ostringstream ss;
        ss << this->value;
        return ss.str();
    };

    bool deserialize(std::string str) {
        std::istringstream iss(str);
        return iss >> this->value;
    };
};

class ConfigOptionInts : public ConfigOption, public ConfigOptionVector<int>
{
    public:

    std::string serialize() const {
        std::ostringstream ss;
        for (std::vector<int>::const_iterator it = this->values.begin(); it != this->values.end(); ++it) {
            if (it - this->values.begin() != 0) ss << ",";
            ss << *it;
        }
        return ss.str();
    };

    bool deserialize(std::string str) {
        this->values.clear();
        std::istringstream is(str);
        std::string item_str;
        while (std::getline(is, item_str, ',')) {
            std::istringstream iss(item_str);
            int value;
            iss >> value;
            this->values.push_back(value);
        }
        return true;
    };
};

class ConfigOptionString : public ConfigOption
{
    public:
    std::string value;
    ConfigOptionString() : value("") {};

    operator std::string() const { return this->value; };

    std::string serialize() const {
        std::string str = this->value;

        // s/\R/\\n/g
        size_t pos = 0;
        while ((pos = str.find("\n", pos)) != std::string::npos || (pos = str.find("\r", pos)) != std::string::npos) {
            str.replace(pos, 1, "\\n");
            pos += 2; // length of "\\n"
        }

        return str;
    };

    bool deserialize(std::string str) {
        // s/\\n/\n/g
        size_t pos = 0;
        while ((pos = str.find("\\n", pos)) != std::string::npos) {
            str.replace(pos, 2, "\n");
            pos += 1; // length of "\n"
        }

        this->value = str;
        return true;
    };
};

// semicolon-separated strings
class ConfigOptionStrings : public ConfigOption, public ConfigOptionVector<std::string>
{
    public:

    std::string serialize() const {
        std::ostringstream ss;
        for (std::vector<std::string>::const_iterator it = this->values.begin(); it != this->values.end(); ++it) {
            if (it - this->values.begin() != 0) ss << ";";
            ss << *it;
        }
        return ss.str();
    };

    bool deserialize(std::string str) {
        this->values.clear();
        std::istringstream is(str);
        std::string item_str;
        while (std::getline(is, item_str, ';')) {
            this->values.push_back(item_str);
        }
        return true;
    };
};

class ConfigOptionPercent : public ConfigOption
{
    public:
    double value;
    ConfigOptionPercent() : value(0) {};

    double get_abs_value(double ratio_over) const {
        return ratio_over * this->value / 100;
    };

    std::string serialize() const {
        std::ostringstream ss;
        ss << this->value;
        std::string s(ss.str());
        s += "%";
        return s;
    };

    bool deserialize(std::string str) {
        // don't try to parse the trailing % since it's optional
        std::istringstream iss(str);
        return iss >> this->value;
    };
};

class ConfigOptionFloatOrPercent : public ConfigOption
{
    public:
    double value;
    bool percent;
    ConfigOptionFloatOrPercent() : value(0), percent(false) {};

    double get_abs_value(double ratio_over) const {
        if (this->percent) {
            return ratio_over * this->value / 100;
        } else {
            return this->value;
        }
    };

    std::string serialize() const {
        std::ostringstream ss;
        ss << this->value;
        std::string s(ss.str());
        if (this->percent) s += "%";
        return s;
    };

    bool deserialize(std::string str) {
        this->percent = str.find_first_of("%") != std::string::npos;
        std::istringstream iss(str);
        return iss >> this->value;
    };
};

class ConfigOptionPoint : public ConfigOption
{
    public:
    Pointf point;
    ConfigOptionPoint() : point(Pointf(0,0)) {};

    operator Pointf() const { return this->point; };

    std::string serialize() const {
        std::ostringstream ss;
        ss << this->point.x;
        ss << ",";
        ss << this->point.y;
        return ss.str();
    };

    bool deserialize(std::string str) {
        std::istringstream iss(str);
        iss >> this->point.x;
        iss.ignore(std::numeric_limits<std::streamsize>::max(), ',');
        iss.ignore(std::numeric_limits<std::streamsize>::max(), 'x');
        iss >> this->point.y;
        return true;
    };
};

class ConfigOptionPoints : public ConfigOption, public ConfigOptionVector<Pointf>
{
    public:

    std::string serialize() const {
        std::ostringstream ss;
        for (Pointfs::const_iterator it = this->values.begin(); it != this->values.end(); ++it) {
            if (it - this->values.begin() != 0) ss << ",";
            ss << it->x;
            ss << "x";
            ss << it->y;
        }
        return ss.str();
    };

    bool deserialize(std::string str) {
        std::vector<Pointf> values;
        std::istringstream is(str);
        std::string point_str;
        while (std::getline(is, point_str, ',')) {
            Pointf point;
            std::istringstream iss(point_str);
            iss >> point.x;
            iss.ignore(std::numeric_limits<std::streamsize>::max(), 'x');
            iss >> point.y;
            values.push_back(point);
        }
        this->values = values;
        return true;
    };
};

class ConfigOptionBool : public ConfigOption
{
    public:
    bool value;
    ConfigOptionBool() : value(false) {};

    operator bool() const { return this->value; };

    std::string serialize() const {
        return std::string(this->value ? "1" : "0");
    };

    bool deserialize(std::string str) {
        this->value = (str.compare("1") == 0);
        return true;
    };
};

class ConfigOptionBools : public ConfigOption, public ConfigOptionVector<bool>
{
    public:

    std::string serialize() const {
        std::ostringstream ss;
        for (std::vector<bool>::const_iterator it = this->values.begin(); it != this->values.end(); ++it) {
            if (it - this->values.begin() != 0) ss << ",";
            ss << (*it ? "1" : "0");
        }
        return ss.str();
    };

    bool deserialize(std::string str) {
        this->values.clear();
        std::istringstream is(str);
        std::string item_str;
        while (std::getline(is, item_str, ',')) {
            this->values.push_back(item_str.compare("1") == 0);
        }
        return true;
    };
};

typedef std::map<std::string,int> t_config_enum_values;

template <class T>
class ConfigOptionEnum : public ConfigOption
{
    public:
    T value;

    operator T() const { return this->value; };

    std::string serialize() const {
        t_config_enum_values enum_keys_map = ConfigOptionEnum<T>::get_enum_values();
        for (t_config_enum_values::iterator it = enum_keys_map.begin(); it != enum_keys_map.end(); ++it) {
            if (it->second == static_cast<int>(this->value)) return it->first;
        }
        return "";
    };

    bool deserialize(std::string str) {
        t_config_enum_values enum_keys_map = ConfigOptionEnum<T>::get_enum_values();
        if (enum_keys_map.count(str) == 0) return false;
        this->value = static_cast<T>(enum_keys_map[str]);
        return true;
    };

    static t_config_enum_values get_enum_values();
};

/* We use this one in DynamicConfig objects, otherwise it's better to use
   the specialized ConfigOptionEnum<T> containers. */
class ConfigOptionEnumGeneric : public ConfigOption
{
    public:
    int value;
    t_config_enum_values* keys_map;

    operator int() const { return this->value; };

    std::string serialize() const {
        for (t_config_enum_values::iterator it = this->keys_map->begin(); it != this->keys_map->end(); ++it) {
            if (it->second == this->value) return it->first;
        }
        return "";
    };

    bool deserialize(std::string str) {
        if (this->keys_map->count(str) == 0) return false;
        this->value = (*this->keys_map)[str];
        return true;
    };
};

enum ConfigOptionType {
    coFloat,
    coFloats,
    coInt,
    coInts,
    coString,
    coStrings,
    coPercent,
    coFloatOrPercent,
    coPoint,
    coPoints,
    coBool,
    coBools,
    coEnum,
};

class ConfigOptionDef
{
    public:
    ConfigOptionType type;
    std::string gui_type;
    std::string gui_flags;
    std::string label;
    std::string full_label;
    std::string category;
    std::string tooltip;
    std::string sidetext;
    std::string cli;
    t_config_option_key ratio_over;
    bool multiline;
    bool full_width;
    bool readonly;
    int height;
    int width;
    int min;
    int max;
    std::vector<t_config_option_key> aliases;
    std::vector<t_config_option_key> shortcut;
    std::vector<std::string> enum_values;
    std::vector<std::string> enum_labels;
    t_config_enum_values enum_keys_map;

    ConfigOptionDef() : multiline(false), full_width(false), readonly(false),
                        height(-1), width(-1), min(INT_MIN), max(INT_MAX) {};
};

typedef std::map<t_config_option_key,ConfigOptionDef> t_optiondef_map;

class ConfigBase
{
    public:
    t_optiondef_map* def;

    ConfigBase() : def(NULL) {};
    bool has(const t_config_option_key opt_key);
    virtual ConfigOption* option(const t_config_option_key opt_key, bool create = false) = 0;
    virtual const ConfigOption* option(const t_config_option_key opt_key) const = 0;
    virtual void keys(t_config_option_keys *keys) const = 0;
    void apply(const ConfigBase &other, bool ignore_nonexistent = false);
    bool equals(ConfigBase &other);
    t_config_option_keys diff(ConfigBase &other);
    std::string serialize(const t_config_option_key opt_key);
    bool set_deserialize(const t_config_option_key opt_key, std::string str);
    void set_ifndef(t_config_option_key opt_key, SV* value, bool deserialize = false);
    double get_abs_value(const t_config_option_key opt_key);
    double get_abs_value(const t_config_option_key opt_key, double ratio_over);

    #ifdef SLIC3RXS
    SV* as_hash();
    SV* get(t_config_option_key opt_key);
    SV* get_at(t_config_option_key opt_key, size_t i);
    bool set(t_config_option_key opt_key, SV* value);
    bool set_deserialize(const t_config_option_key opt_key, SV* str);
    #endif
};

class DynamicConfig : public ConfigBase
{
    public:
    DynamicConfig() {};
    DynamicConfig(const DynamicConfig& other);
    DynamicConfig& operator= (DynamicConfig other);
    void swap(DynamicConfig &other);
    ~DynamicConfig();
    template<class T> T* opt(const t_config_option_key opt_key, bool create = false);
    ConfigOption* option(const t_config_option_key opt_key, bool create = false);
    const ConfigOption* option(const t_config_option_key opt_key) const;
    void keys(t_config_option_keys *keys) const;
    void erase(const t_config_option_key opt_key);

    private:
    typedef std::map<t_config_option_key,ConfigOption*> t_options_map;
    t_options_map options;
};

class StaticConfig : public ConfigBase
{
    public:
    void keys(t_config_option_keys *keys) const;
    virtual ConfigOption* option(const t_config_option_key opt_key, bool create = false) = 0;
    const ConfigOption* option(const t_config_option_key opt_key) const;

    #ifdef SLIC3RXS
    bool set(t_config_option_key opt_key, SV* value);
    #endif
};

}

#endif
<commit_msg>Use std::getline to deserialize point list coords, fixes #2318<commit_after>#ifndef slic3r_Config_hpp_
#define slic3r_Config_hpp_

#include <map>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#include <myinit.h>
#include "Point.hpp"

namespace Slic3r {

typedef std::string t_config_option_key;
typedef std::vector<std::string> t_config_option_keys;

class ConfigOption {
    public:
    virtual ~ConfigOption() {};
    virtual std::string serialize() const = 0;
    virtual bool deserialize(std::string str) = 0;
    virtual int getInt() const { return 0; };
    virtual void setInt(int val) {};
};

template <class T>
class ConfigOptionVector
{
    public:
    virtual ~ConfigOptionVector() {};
    std::vector<T> values;

    T get_at(size_t i) const {
        try {
            return this->values.at(i);
        } catch (const std::out_of_range& oor) {
            return this->values.front();
        }
    };
};

class ConfigOptionFloat : public ConfigOption
{
    public:
    double value;  // use double instead of float for preserving compatibility with values coming from Perl
    ConfigOptionFloat() : value(0) {};

    operator float() const { return this->value; };
    operator double() const { return this->value; };

    std::string serialize() const {
        std::ostringstream ss;
        ss << this->value;
        return ss.str();
    };

    bool deserialize(std::string str) {
        std::istringstream iss(str);
        return iss >> this->value;
    };
};

class ConfigOptionFloats : public ConfigOption, public ConfigOptionVector<double>
{
    public:

    std::string serialize() const {
        std::ostringstream ss;
        for (std::vector<double>::const_iterator it = this->values.begin(); it != this->values.end(); ++it) {
            if (it - this->values.begin() != 0) ss << ",";
            ss << *it;
        }
        return ss.str();
    };

    bool deserialize(std::string str) {
        this->values.clear();
        std::istringstream is(str);
        std::string item_str;
        while (std::getline(is, item_str, ',')) {
            std::istringstream iss(item_str);
            double value;
            iss >> value;
            this->values.push_back(value);
        }
        return true;
    };
};

class ConfigOptionInt : public ConfigOption
{
    public:
    int value;
    ConfigOptionInt() : value(0) {};

    operator int() const { return this->value; };
    int getInt() const { return this->value; };
    void setInt(int val) { this->value = val; };

    std::string serialize() const {
        std::ostringstream ss;
        ss << this->value;
        return ss.str();
    };

    bool deserialize(std::string str) {
        std::istringstream iss(str);
        return iss >> this->value;
    };
};

class ConfigOptionInts : public ConfigOption, public ConfigOptionVector<int>
{
    public:

    std::string serialize() const {
        std::ostringstream ss;
        for (std::vector<int>::const_iterator it = this->values.begin(); it != this->values.end(); ++it) {
            if (it - this->values.begin() != 0) ss << ",";
            ss << *it;
        }
        return ss.str();
    };

    bool deserialize(std::string str) {
        this->values.clear();
        std::istringstream is(str);
        std::string item_str;
        while (std::getline(is, item_str, ',')) {
            std::istringstream iss(item_str);
            int value;
            iss >> value;
            this->values.push_back(value);
        }
        return true;
    };
};

class ConfigOptionString : public ConfigOption
{
    public:
    std::string value;
    ConfigOptionString() : value("") {};

    operator std::string() const { return this->value; };

    std::string serialize() const {
        std::string str = this->value;

        // s/\R/\\n/g
        size_t pos = 0;
        while ((pos = str.find("\n", pos)) != std::string::npos || (pos = str.find("\r", pos)) != std::string::npos) {
            str.replace(pos, 1, "\\n");
            pos += 2; // length of "\\n"
        }

        return str;
    };

    bool deserialize(std::string str) {
        // s/\\n/\n/g
        size_t pos = 0;
        while ((pos = str.find("\\n", pos)) != std::string::npos) {
            str.replace(pos, 2, "\n");
            pos += 1; // length of "\n"
        }

        this->value = str;
        return true;
    };
};

// semicolon-separated strings
class ConfigOptionStrings : public ConfigOption, public ConfigOptionVector<std::string>
{
    public:

    std::string serialize() const {
        std::ostringstream ss;
        for (std::vector<std::string>::const_iterator it = this->values.begin(); it != this->values.end(); ++it) {
            if (it - this->values.begin() != 0) ss << ";";
            ss << *it;
        }
        return ss.str();
    };

    bool deserialize(std::string str) {
        this->values.clear();
        std::istringstream is(str);
        std::string item_str;
        while (std::getline(is, item_str, ';')) {
            this->values.push_back(item_str);
        }
        return true;
    };
};

class ConfigOptionPercent : public ConfigOption
{
    public:
    double value;
    ConfigOptionPercent() : value(0) {};

    double get_abs_value(double ratio_over) const {
        return ratio_over * this->value / 100;
    };

    std::string serialize() const {
        std::ostringstream ss;
        ss << this->value;
        std::string s(ss.str());
        s += "%";
        return s;
    };

    bool deserialize(std::string str) {
        // don't try to parse the trailing % since it's optional
        std::istringstream iss(str);
        return iss >> this->value;
    };
};

class ConfigOptionFloatOrPercent : public ConfigOption
{
    public:
    double value;
    bool percent;
    ConfigOptionFloatOrPercent() : value(0), percent(false) {};

    double get_abs_value(double ratio_over) const {
        if (this->percent) {
            return ratio_over * this->value / 100;
        } else {
            return this->value;
        }
    };

    std::string serialize() const {
        std::ostringstream ss;
        ss << this->value;
        std::string s(ss.str());
        if (this->percent) s += "%";
        return s;
    };

    bool deserialize(std::string str) {
        this->percent = str.find_first_of("%") != std::string::npos;
        std::istringstream iss(str);
        return iss >> this->value;
    };
};

class ConfigOptionPoint : public ConfigOption
{
    public:
    Pointf point;
    ConfigOptionPoint() : point(Pointf(0,0)) {};

    operator Pointf() const { return this->point; };

    std::string serialize() const {
        std::ostringstream ss;
        ss << this->point.x;
        ss << ",";
        ss << this->point.y;
        return ss.str();
    };

    bool deserialize(std::string str) {
        std::istringstream iss(str);
        iss >> this->point.x;
        iss.ignore(std::numeric_limits<std::streamsize>::max(), ',');
        iss.ignore(std::numeric_limits<std::streamsize>::max(), 'x');
        iss >> this->point.y;
        return true;
    };
};

class ConfigOptionPoints : public ConfigOption, public ConfigOptionVector<Pointf>
{
    public:

    std::string serialize() const {
        std::ostringstream ss;
        for (Pointfs::const_iterator it = this->values.begin(); it != this->values.end(); ++it) {
            if (it - this->values.begin() != 0) ss << ",";
            ss << it->x;
            ss << "x";
            ss << it->y;
        }
        return ss.str();
    };

    bool deserialize(std::string str) {
        this->values.clear();
        std::istringstream is(str);
        std::string point_str;
        while (std::getline(is, point_str, ',')) {
            Pointf point;
            std::istringstream iss(point_str);
            std::string coord_str;
            if (std::getline(iss, coord_str, 'x')) {
                std::istringstream(coord_str) >> point.x;
                if (std::getline(iss, coord_str, 'x')) {
                    std::istringstream(coord_str) >> point.y;
                }
            }
            this->values.push_back(point);
        }
        return true;
    };
};

class ConfigOptionBool : public ConfigOption
{
    public:
    bool value;
    ConfigOptionBool() : value(false) {};

    operator bool() const { return this->value; };

    std::string serialize() const {
        return std::string(this->value ? "1" : "0");
    };

    bool deserialize(std::string str) {
        this->value = (str.compare("1") == 0);
        return true;
    };
};

class ConfigOptionBools : public ConfigOption, public ConfigOptionVector<bool>
{
    public:

    std::string serialize() const {
        std::ostringstream ss;
        for (std::vector<bool>::const_iterator it = this->values.begin(); it != this->values.end(); ++it) {
            if (it - this->values.begin() != 0) ss << ",";
            ss << (*it ? "1" : "0");
        }
        return ss.str();
    };

    bool deserialize(std::string str) {
        this->values.clear();
        std::istringstream is(str);
        std::string item_str;
        while (std::getline(is, item_str, ',')) {
            this->values.push_back(item_str.compare("1") == 0);
        }
        return true;
    };
};

typedef std::map<std::string,int> t_config_enum_values;

template <class T>
class ConfigOptionEnum : public ConfigOption
{
    public:
    T value;

    operator T() const { return this->value; };

    std::string serialize() const {
        t_config_enum_values enum_keys_map = ConfigOptionEnum<T>::get_enum_values();
        for (t_config_enum_values::iterator it = enum_keys_map.begin(); it != enum_keys_map.end(); ++it) {
            if (it->second == static_cast<int>(this->value)) return it->first;
        }
        return "";
    };

    bool deserialize(std::string str) {
        t_config_enum_values enum_keys_map = ConfigOptionEnum<T>::get_enum_values();
        if (enum_keys_map.count(str) == 0) return false;
        this->value = static_cast<T>(enum_keys_map[str]);
        return true;
    };

    static t_config_enum_values get_enum_values();
};

/* We use this one in DynamicConfig objects, otherwise it's better to use
   the specialized ConfigOptionEnum<T> containers. */
class ConfigOptionEnumGeneric : public ConfigOption
{
    public:
    int value;
    t_config_enum_values* keys_map;

    operator int() const { return this->value; };

    std::string serialize() const {
        for (t_config_enum_values::iterator it = this->keys_map->begin(); it != this->keys_map->end(); ++it) {
            if (it->second == this->value) return it->first;
        }
        return "";
    };

    bool deserialize(std::string str) {
        if (this->keys_map->count(str) == 0) return false;
        this->value = (*this->keys_map)[str];
        return true;
    };
};

enum ConfigOptionType {
    coFloat,
    coFloats,
    coInt,
    coInts,
    coString,
    coStrings,
    coPercent,
    coFloatOrPercent,
    coPoint,
    coPoints,
    coBool,
    coBools,
    coEnum,
};

class ConfigOptionDef
{
    public:
    ConfigOptionType type;
    std::string gui_type;
    std::string gui_flags;
    std::string label;
    std::string full_label;
    std::string category;
    std::string tooltip;
    std::string sidetext;
    std::string cli;
    t_config_option_key ratio_over;
    bool multiline;
    bool full_width;
    bool readonly;
    int height;
    int width;
    int min;
    int max;
    std::vector<t_config_option_key> aliases;
    std::vector<t_config_option_key> shortcut;
    std::vector<std::string> enum_values;
    std::vector<std::string> enum_labels;
    t_config_enum_values enum_keys_map;

    ConfigOptionDef() : multiline(false), full_width(false), readonly(false),
                        height(-1), width(-1), min(INT_MIN), max(INT_MAX) {};
};

typedef std::map<t_config_option_key,ConfigOptionDef> t_optiondef_map;

class ConfigBase
{
    public:
    t_optiondef_map* def;

    ConfigBase() : def(NULL) {};
    bool has(const t_config_option_key opt_key);
    virtual ConfigOption* option(const t_config_option_key opt_key, bool create = false) = 0;
    virtual const ConfigOption* option(const t_config_option_key opt_key) const = 0;
    virtual void keys(t_config_option_keys *keys) const = 0;
    void apply(const ConfigBase &other, bool ignore_nonexistent = false);
    bool equals(ConfigBase &other);
    t_config_option_keys diff(ConfigBase &other);
    std::string serialize(const t_config_option_key opt_key);
    bool set_deserialize(const t_config_option_key opt_key, std::string str);
    void set_ifndef(t_config_option_key opt_key, SV* value, bool deserialize = false);
    double get_abs_value(const t_config_option_key opt_key);
    double get_abs_value(const t_config_option_key opt_key, double ratio_over);

    #ifdef SLIC3RXS
    SV* as_hash();
    SV* get(t_config_option_key opt_key);
    SV* get_at(t_config_option_key opt_key, size_t i);
    bool set(t_config_option_key opt_key, SV* value);
    bool set_deserialize(const t_config_option_key opt_key, SV* str);
    #endif
};

class DynamicConfig : public ConfigBase
{
    public:
    DynamicConfig() {};
    DynamicConfig(const DynamicConfig& other);
    DynamicConfig& operator= (DynamicConfig other);
    void swap(DynamicConfig &other);
    ~DynamicConfig();
    template<class T> T* opt(const t_config_option_key opt_key, bool create = false);
    ConfigOption* option(const t_config_option_key opt_key, bool create = false);
    const ConfigOption* option(const t_config_option_key opt_key) const;
    void keys(t_config_option_keys *keys) const;
    void erase(const t_config_option_key opt_key);

    private:
    typedef std::map<t_config_option_key,ConfigOption*> t_options_map;
    t_options_map options;
};

class StaticConfig : public ConfigBase
{
    public:
    void keys(t_config_option_keys *keys) const;
    virtual ConfigOption* option(const t_config_option_key opt_key, bool create = false) = 0;
    const ConfigOption* option(const t_config_option_key opt_key) const;

    #ifdef SLIC3RXS
    bool set(t_config_option_key opt_key, SV* value);
    #endif
};

}

#endif
<|endoftext|>


<commit_before><commit_msg>refactor SvxXConnectionPreview to use RenderContext<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: eventdlg.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: kz $ $Date: 2007-10-09 15:17:38 $
 *
 *  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_svx.hxx"

// include ***************************************************************

#ifndef _SVEDIT_HXX //autogen
#include <svtools/svmedit.hxx>
#endif
#ifndef TOOLS_DIAGNOSE_EX_H
#include <tools/diagnose_ex.h>
#endif

#ifndef  _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP_
#include <com/sun/star/document/XEventsSupplier.hpp>
#endif
#ifndef  _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_
#include <com/sun/star/frame/XModuleManager.hpp>
#endif

#include <comphelper/processfactory.hxx>
#include <comphelper/documentinfo.hxx>
#include <unotools/configmgr.hxx>
#include <rtl/ustring.hxx>

#include "eventdlg.hxx"

#include <sfx2/viewfrm.hxx>
#include <sfx2/evntconf.hxx>
#include <sfx2/macrconf.hxx>
#include <sfx2/minfitem.hxx>
#include <sfx2/app.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/docfac.hxx>
#include <sfx2/fcontnr.hxx>
#include <svtools/eventcfg.hxx>

#ifndef _HEADERTABLISTBOX_HXX
#include "headertablistbox.hxx"
#endif
#ifndef _MACROPG_IMPL_HXX
#include "macropg_impl.hxx"
#endif

#include <svx/dialmgr.hxx>
#include <svx/dialogs.hrc>
#include "eventdlg.hrc"
#include "helpid.hrc"
#include "selector.hxx"
#include "cfg.hxx"

using ::rtl::OUString;
using namespace ::com::sun::star;
// -----------------------------------------------------------------------

SvxEventConfigPage::SvxEventConfigPage( Window *pParent, const SfxItemSet& rSet, SvxEventConfigPage::EarlyInit ) :

    _SvxMacroTabPage( pParent, SVX_RES(RID_SVXPAGE_EVENTS), rSet ),
    aSaveInText( this, SVX_RES( TXT_SAVEIN ) ),
    aSaveInListBox( this, SVX_RES( LB_SAVEIN ) ),
    bAppConfig  ( TRUE )
{
    mpImpl->pStrEvent           = new String( SVX_RES( STR_EVENT ));
    mpImpl->pAssignedMacro      = new String( SVX_RES( STR_ASSMACRO ));
    mpImpl->pEventLB            = new _HeaderTabListBox( this, SVX_RES( LB_EVENT ));
    mpImpl->pAssignFT           = new FixedText( this,  SVX_RES( FT_ASSIGN ));
    mpImpl->pAssignPB           = new PushButton( this, SVX_RES( PB_ASSIGN ));
    mpImpl->pDeletePB           = new PushButton( this, SVX_RES( PB_DELETE ));
    mpImpl->pMacroImg           = new Image( SVX_RES( IMG_MACRO) );
    mpImpl->pComponentImg       = new Image( SVX_RES( IMG_COMPONENT) );
    mpImpl->pMacroImg_h         = new Image( SVX_RES( IMG_MACRO_H) );
    mpImpl->pComponentImg_h     = new Image( SVX_RES( IMG_COMPONENT_H) );

    FreeResource();

    // must be done after FreeResource is called
    InitResources();

    mpImpl->pEventLB->GetListBox().SetHelpId( HID_SVX_MACRO_LB_EVENT );

    aSaveInListBox.SetSelectHdl( LINK( this, SvxEventConfigPage,
                SelectHdl_Impl ) );

    uno::Reference< document::XEventsSupplier > xSupplier;

//    xSupplier = uno::Reference< document::XEventsSupplier >( new GlobalEventConfig());
    xSupplier = uno::Reference< document::XEventsSupplier > (
        ::comphelper::getProcessServiceFactory()->createInstance(
            OUString::createFromAscii(
                "com.sun.star.frame.GlobalEventBroadcaster" ) ),
        uno::UNO_QUERY );

    USHORT nPos(0);
    if ( xSupplier.is() )
    {
        m_xAppEvents = xSupplier->getEvents();
        OUString label;
        utl::ConfigManager::GetDirectConfigProperty(
            utl::ConfigManager::PRODUCTNAME ) >>= label;
        nPos = aSaveInListBox.InsertEntry( label );
        aSaveInListBox.SetEntryData( nPos, new bool(true) );
        aSaveInListBox.SelectEntryPos( nPos, TRUE );
    }
}

// -----------------------------------------------------------------------
void SvxEventConfigPage::LateInit( const uno::Reference< frame::XFrame >& _rxFrame  )
{
    SetFrame( _rxFrame );
    ImplInitDocument();

    InitAndSetHandler( m_xAppEvents, m_xDocumentEvents, m_xDocumentModifiable );

    SelectHdl_Impl( NULL );
}

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

SvxEventConfigPage::~SvxEventConfigPage()
{
    //DF Do I need to delete bools?
}

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

void SvxEventConfigPage::ImplInitDocument()
{
    uno::Reference< frame::XFrame > xFrame( GetFrame() );
    OUString aModuleId = SvxConfigPage::GetFrameWithDefaultAndIdentify( xFrame );
    if ( !xFrame.is() )
        return;

    try
    {
        uno::Reference< frame::XModel > xModel;
        if ( !SvxConfigPage::CanConfig( aModuleId ) )
            return;

        uno::Reference< frame::XController > xController =
            xFrame->getController();

        if ( xController.is() )
        {
            xModel = xController->getModel();
        }

        if ( !xModel.is() )
            return;

        uno::Reference< document::XEventsSupplier > xSupplier( xModel, uno::UNO_QUERY );

        if ( xSupplier.is() )
        {
            m_xDocumentEvents = xSupplier->getEvents();
            m_xDocumentModifiable = m_xDocumentModifiable.query( xModel );

            OUString aTitle = ::comphelper::DocumentInfo::getDocumentTitle( xModel );
            USHORT nPos = aSaveInListBox.InsertEntry( aTitle );

            aSaveInListBox.SetEntryData( nPos, new bool(false) );
            aSaveInListBox.SelectEntryPos( nPos, TRUE );

            bAppConfig = false;
        }
    }
    catch( const uno::Exception& )
    {
        DBG_UNHANDLED_EXCEPTION();
    }
}

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

IMPL_LINK( SvxEventConfigPage, SelectHdl_Impl, ListBox *, pBox )
{
    (void)pBox;

    bool* bApp = (bool*) aSaveInListBox.GetEntryData(
            aSaveInListBox.GetSelectEntryPos());

    mpImpl->pEventLB->SetUpdateMode( FALSE );
    bAppConfig = *bApp;
    if ( *bApp )
    {
        SetReadOnly( FALSE );
        _SvxMacroTabPage::DisplayAppEvents( true );
    }
    else
    {
        bool isReadonly = FALSE;

        uno::Reference< frame::XFramesSupplier > xFramesSupplier(
            ::comphelper::getProcessServiceFactory()->createInstance(
                OUString::createFromAscii( "com.sun.star.frame.Desktop" ) ),
            uno::UNO_QUERY );

        uno::Reference< frame::XFrame > xFrame =
            xFramesSupplier->getActiveFrame();

        if ( xFrame.is() )
        {
            uno::Reference< frame::XController > xController =
                xFrame->getController();

            if ( xController.is() )
            {
                uno::Reference< frame::XStorable > xStorable(
                    xController->getModel(), uno::UNO_QUERY );
                isReadonly = xStorable->isReadonly();
            }
        }

        SetReadOnly( isReadonly );
        _SvxMacroTabPage::DisplayAppEvents( false );
    }

    mpImpl->pEventLB->SetUpdateMode( TRUE );
    return TRUE;
}

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

BOOL SvxEventConfigPage::FillItemSet( SfxItemSet& rSet )
{
    return _SvxMacroTabPage::FillItemSet( rSet );
}

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

void SvxEventConfigPage::Reset( const SfxItemSet& )
{
    _SvxMacroTabPage::Reset();
}

<commit_msg>INTEGRATION: CWS changefileheader (1.15.236); FILE MERGED 2008/04/01 15:50:19 thb 1.15.236.3: #i85898# Stripping all external header guards 2008/04/01 12:48:11 thb 1.15.236.2: #i85898# Stripping all external header guards 2008/03/31 14:19:24 rt 1.15.236.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: eventdlg.cxx,v $
 * $Revision: 1.16 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

// include ***************************************************************
#include <svtools/svmedit.hxx>
#include <tools/diagnose_ex.h>
#include <com/sun/star/document/XEventsSupplier.hpp>
#include <com/sun/star/frame/XModuleManager.hpp>

#include <comphelper/processfactory.hxx>
#include <comphelper/documentinfo.hxx>
#include <unotools/configmgr.hxx>
#include <rtl/ustring.hxx>

#include "eventdlg.hxx"

#include <sfx2/viewfrm.hxx>
#include <sfx2/evntconf.hxx>
#include <sfx2/macrconf.hxx>
#include <sfx2/minfitem.hxx>
#include <sfx2/app.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/docfac.hxx>
#include <sfx2/fcontnr.hxx>
#include <svtools/eventcfg.hxx>

#include "headertablistbox.hxx"
#include "macropg_impl.hxx"

#include <svx/dialmgr.hxx>
#include <svx/dialogs.hrc>
#include "eventdlg.hrc"
#include "helpid.hrc"
#include "selector.hxx"
#include "cfg.hxx"

using ::rtl::OUString;
using namespace ::com::sun::star;
// -----------------------------------------------------------------------

SvxEventConfigPage::SvxEventConfigPage( Window *pParent, const SfxItemSet& rSet, SvxEventConfigPage::EarlyInit ) :

    _SvxMacroTabPage( pParent, SVX_RES(RID_SVXPAGE_EVENTS), rSet ),
    aSaveInText( this, SVX_RES( TXT_SAVEIN ) ),
    aSaveInListBox( this, SVX_RES( LB_SAVEIN ) ),
    bAppConfig  ( TRUE )
{
    mpImpl->pStrEvent           = new String( SVX_RES( STR_EVENT ));
    mpImpl->pAssignedMacro      = new String( SVX_RES( STR_ASSMACRO ));
    mpImpl->pEventLB            = new _HeaderTabListBox( this, SVX_RES( LB_EVENT ));
    mpImpl->pAssignFT           = new FixedText( this,  SVX_RES( FT_ASSIGN ));
    mpImpl->pAssignPB           = new PushButton( this, SVX_RES( PB_ASSIGN ));
    mpImpl->pDeletePB           = new PushButton( this, SVX_RES( PB_DELETE ));
    mpImpl->pMacroImg           = new Image( SVX_RES( IMG_MACRO) );
    mpImpl->pComponentImg       = new Image( SVX_RES( IMG_COMPONENT) );
    mpImpl->pMacroImg_h         = new Image( SVX_RES( IMG_MACRO_H) );
    mpImpl->pComponentImg_h     = new Image( SVX_RES( IMG_COMPONENT_H) );

    FreeResource();

    // must be done after FreeResource is called
    InitResources();

    mpImpl->pEventLB->GetListBox().SetHelpId( HID_SVX_MACRO_LB_EVENT );

    aSaveInListBox.SetSelectHdl( LINK( this, SvxEventConfigPage,
                SelectHdl_Impl ) );

    uno::Reference< document::XEventsSupplier > xSupplier;

//    xSupplier = uno::Reference< document::XEventsSupplier >( new GlobalEventConfig());
    xSupplier = uno::Reference< document::XEventsSupplier > (
        ::comphelper::getProcessServiceFactory()->createInstance(
            OUString::createFromAscii(
                "com.sun.star.frame.GlobalEventBroadcaster" ) ),
        uno::UNO_QUERY );

    USHORT nPos(0);
    if ( xSupplier.is() )
    {
        m_xAppEvents = xSupplier->getEvents();
        OUString label;
        utl::ConfigManager::GetDirectConfigProperty(
            utl::ConfigManager::PRODUCTNAME ) >>= label;
        nPos = aSaveInListBox.InsertEntry( label );
        aSaveInListBox.SetEntryData( nPos, new bool(true) );
        aSaveInListBox.SelectEntryPos( nPos, TRUE );
    }
}

// -----------------------------------------------------------------------
void SvxEventConfigPage::LateInit( const uno::Reference< frame::XFrame >& _rxFrame  )
{
    SetFrame( _rxFrame );
    ImplInitDocument();

    InitAndSetHandler( m_xAppEvents, m_xDocumentEvents, m_xDocumentModifiable );

    SelectHdl_Impl( NULL );
}

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

SvxEventConfigPage::~SvxEventConfigPage()
{
    //DF Do I need to delete bools?
}

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

void SvxEventConfigPage::ImplInitDocument()
{
    uno::Reference< frame::XFrame > xFrame( GetFrame() );
    OUString aModuleId = SvxConfigPage::GetFrameWithDefaultAndIdentify( xFrame );
    if ( !xFrame.is() )
        return;

    try
    {
        uno::Reference< frame::XModel > xModel;
        if ( !SvxConfigPage::CanConfig( aModuleId ) )
            return;

        uno::Reference< frame::XController > xController =
            xFrame->getController();

        if ( xController.is() )
        {
            xModel = xController->getModel();
        }

        if ( !xModel.is() )
            return;

        uno::Reference< document::XEventsSupplier > xSupplier( xModel, uno::UNO_QUERY );

        if ( xSupplier.is() )
        {
            m_xDocumentEvents = xSupplier->getEvents();
            m_xDocumentModifiable = m_xDocumentModifiable.query( xModel );

            OUString aTitle = ::comphelper::DocumentInfo::getDocumentTitle( xModel );
            USHORT nPos = aSaveInListBox.InsertEntry( aTitle );

            aSaveInListBox.SetEntryData( nPos, new bool(false) );
            aSaveInListBox.SelectEntryPos( nPos, TRUE );

            bAppConfig = false;
        }
    }
    catch( const uno::Exception& )
    {
        DBG_UNHANDLED_EXCEPTION();
    }
}

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

IMPL_LINK( SvxEventConfigPage, SelectHdl_Impl, ListBox *, pBox )
{
    (void)pBox;

    bool* bApp = (bool*) aSaveInListBox.GetEntryData(
            aSaveInListBox.GetSelectEntryPos());

    mpImpl->pEventLB->SetUpdateMode( FALSE );
    bAppConfig = *bApp;
    if ( *bApp )
    {
        SetReadOnly( FALSE );
        _SvxMacroTabPage::DisplayAppEvents( true );
    }
    else
    {
        bool isReadonly = FALSE;

        uno::Reference< frame::XFramesSupplier > xFramesSupplier(
            ::comphelper::getProcessServiceFactory()->createInstance(
                OUString::createFromAscii( "com.sun.star.frame.Desktop" ) ),
            uno::UNO_QUERY );

        uno::Reference< frame::XFrame > xFrame =
            xFramesSupplier->getActiveFrame();

        if ( xFrame.is() )
        {
            uno::Reference< frame::XController > xController =
                xFrame->getController();

            if ( xController.is() )
            {
                uno::Reference< frame::XStorable > xStorable(
                    xController->getModel(), uno::UNO_QUERY );
                isReadonly = xStorable->isReadonly();
            }
        }

        SetReadOnly( isReadonly );
        _SvxMacroTabPage::DisplayAppEvents( false );
    }

    mpImpl->pEventLB->SetUpdateMode( TRUE );
    return TRUE;
}

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

BOOL SvxEventConfigPage::FillItemSet( SfxItemSet& rSet )
{
    return _SvxMacroTabPage::FillItemSet( rSet );
}

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

void SvxEventConfigPage::Reset( const SfxItemSet& )
{
    _SvxMacroTabPage::Reset();
}

<|endoftext|>


<commit_before>// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.

#include "gp.h"
#include "rprop.h"
#include "cg.h"
#include "gp_utils.h"

#include <cmath>
#include <iostream>
#include <gtest/gtest.h>

class OptimizerTest : public testing::Test {
  protected:
    virtual void SetUp() {
      input_dim = 3, param_dim = 3;
      gp = new libgp::GaussianProcess(input_dim, "CovSum ( CovSEiso, CovNoise)");
      Eigen::VectorXd params(param_dim);
      params << 0, 0, log(0.01);
      gp->covf().set_loghyper(params);
      n = 500;
      Eigen::MatrixXd X(n, input_dim);
      X.setRandom();
      X = X*10;
      Eigen::VectorXd y = gp->covf().draw_random_sample(X);
      for(size_t i = 0; i < n; ++i) {
        double x[input_dim];
        for(int j = 0; j < input_dim; ++j) x[j] = X(i,j);
        gp->add_pattern(x, y(i));
      }
    }

    virtual void TearDown() {
      delete gp;
    }

    int input_dim, param_dim;
    libgp::GaussianProcess * gp;
    size_t n;
};

TEST_F(OptimizerTest, Rprop)
{
  Eigen::VectorXd params(param_dim);
  params << -1, -1, -1;
  gp->covf().set_loghyper(params);

  libgp::RProp rprop;
  rprop.init();
  rprop.maximize(gp, 50, 0);

  ASSERT_NEAR(0, gp->covf().get_loghyper()(0), 0.1);
  ASSERT_NEAR(0, gp->covf().get_loghyper()(1), 0.1);
}

TEST_F(OptimizerTest, CG)
{
  Eigen::VectorXd params(param_dim);
  params << -1, -1, -1;
  gp->covf().set_loghyper(params);

  libgp::CG cg;
  cg.maximize(gp, 50, 0);

  ASSERT_NEAR(0, gp->covf().get_loghyper()(0), 0.1);
  ASSERT_NEAR(0, gp->covf().get_loghyper()(1), 0.1);
}

<commit_msg>increasing the threshold for the optimizer test<commit_after>// libgp - Gaussian process library for Machine Learning
// Copyright (c) 2013, Manuel Blum <mblum@informatik.uni-freiburg.de>
// All rights reserved.

#include "gp.h"
#include "rprop.h"
#include "cg.h"
#include "gp_utils.h"

#include <cmath>
#include <iostream>
#include <gtest/gtest.h>

class OptimizerTest : public testing::Test {
  protected:
    virtual void SetUp() {
      input_dim = 3, param_dim = 3;
      gp = new libgp::GaussianProcess(input_dim, "CovSum ( CovSEiso, CovNoise)");
      Eigen::VectorXd params(param_dim);
      params << 0, 0, log(0.01);
      gp->covf().set_loghyper(params);
      n = 500;
      Eigen::MatrixXd X(n, input_dim);
      X.setRandom();
      X = X*10;
      Eigen::VectorXd y = gp->covf().draw_random_sample(X);
      for(size_t i = 0; i < n; ++i) {
        double x[input_dim];
        for(int j = 0; j < input_dim; ++j) x[j] = X(i,j);
        gp->add_pattern(x, y(i));
      }
    }

    virtual void TearDown() {
      delete gp;
    }

    int input_dim, param_dim;
    libgp::GaussianProcess * gp;
    size_t n;
};

TEST_F(OptimizerTest, Rprop)
{
  Eigen::VectorXd params(param_dim);
  params << -1, -1, -1;
  gp->covf().set_loghyper(params);

  libgp::RProp rprop;
  rprop.init();
  rprop.maximize(gp, 50, 0);

  ASSERT_NEAR(0, gp->covf().get_loghyper()(0), 0.2);
  ASSERT_NEAR(0, gp->covf().get_loghyper()(1), 0.2);
}

TEST_F(OptimizerTest, CG)
{
  Eigen::VectorXd params(param_dim);
  params << -1, -1, -1;
  gp->covf().set_loghyper(params);

  libgp::CG cg;
  cg.maximize(gp, 50, 0);

  ASSERT_NEAR(0, gp->covf().get_loghyper()(0), 0.2);
  ASSERT_NEAR(0, gp->covf().get_loghyper()(1), 0.2);
}

<|endoftext|>


<commit_before>#include <graphics/texture/texture.h>
#include <core/video/context.h>

namespace fd {
namespace graphics {
namespace texture {

using namespace FD;
using namespace utils;
using namespace buffer;
using namespace core::video;

Texture2D::Texture2D(const String& filename) {
	Header header;
	TextureHeader texHeader;

	byte* pixels = nullptr;

	LoadImageFile(filename, &header, &texHeader, &pixels);

	if (pixels == nullptr) return;

	width = texHeader.width;
	height = texHeader.height;

	VkFormat format = VK_FORMAT_UNDEFINED;

	switch (texHeader.pixelLayout) {
		case TextureChannel::R:
			format = VK_FORMAT_R8_UNORM;
		case TextureChannel::RG:
			format = VK_FORMAT_R8G8_UNORM;
		case TextureChannel::RGBA:
			format = VK_FORMAT_R8G8B8A8_UNORM;
	}

	CreateImage(width, height, 0, VK_IMAGE_TYPE_2D, format, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);

	Buffer tmpBuffer(VK_BUFFER_USAGE_TRANSFER_SRC_BIT, pixels, header.size - sizeof(TextureHeader), true);

	Context::CopyBufferToImage(image, width, height, tmpBuffer.GetBuffer());

	Context::TransitionImage(image, VK_FORMAT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);

	VkImageViewCreateInfo vinfo;

	vinfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
	vinfo.pNext = nullptr;
	vinfo.flags = 0;
	vinfo.image = image;
	vinfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
	vinfo.format = format;
	vinfo.components.r = VK_COMPONENT_SWIZZLE_R;
	vinfo.components.g = VK_COMPONENT_SWIZZLE_G;
	vinfo.components.b = VK_COMPONENT_SWIZZLE_B;
	vinfo.components.a = VK_COMPONENT_SWIZZLE_A;
	vinfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
	vinfo.subresourceRange.baseArrayLayer = 0;
	vinfo.subresourceRange.baseMipLevel = 0;
	vinfo.subresourceRange.layerCount = 1;
	vinfo.subresourceRange.levelCount = 1;

	VK(vkCreateImageView(Context::GetDevice(), &vinfo, nullptr, &imageView));

}

}
}
}<commit_msg>VK: fixed incorrect sType in VkImageViewCreateInfo<commit_after>#include <graphics/texture/texture.h>
#include <core/video/context.h>

namespace fd {
namespace graphics {
namespace texture {

using namespace FD;
using namespace utils;
using namespace buffer;
using namespace core::video;

Texture2D::Texture2D(const String& filename) {
	Header header;
	TextureHeader texHeader;

	byte* pixels = nullptr;

	LoadImageFile(filename, &header, &texHeader, &pixels);

	if (pixels == nullptr) return;

	width = texHeader.width;
	height = texHeader.height;

	VkFormat format = VK_FORMAT_UNDEFINED;

	switch (texHeader.pixelLayout) {
		case TextureChannel::R:
			format = VK_FORMAT_R8_UNORM;
		case TextureChannel::RG:
			format = VK_FORMAT_R8G8_UNORM;
		case TextureChannel::RGBA:
			format = VK_FORMAT_R8G8B8A8_UNORM;
	}

	CreateImage(width, height, 0, VK_IMAGE_TYPE_2D, format, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);

	Buffer tmpBuffer(VK_BUFFER_USAGE_TRANSFER_SRC_BIT, pixels, header.size - sizeof(TextureHeader), true);

	Context::CopyBufferToImage(image, width, height, tmpBuffer.GetBuffer());

	Context::TransitionImage(image, VK_FORMAT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);

	VkImageViewCreateInfo vinfo;

	vinfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
	vinfo.pNext = nullptr;
	vinfo.flags = 0;
	vinfo.image = image;
	vinfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
	vinfo.format = format;
	vinfo.components.r = VK_COMPONENT_SWIZZLE_R;
	vinfo.components.g = VK_COMPONENT_SWIZZLE_G;
	vinfo.components.b = VK_COMPONENT_SWIZZLE_B;
	vinfo.components.a = VK_COMPONENT_SWIZZLE_A;
	vinfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
	vinfo.subresourceRange.baseArrayLayer = 0;
	vinfo.subresourceRange.baseMipLevel = 0;
	vinfo.subresourceRange.layerCount = 1;
	vinfo.subresourceRange.levelCount = 1;

	VK(vkCreateImageView(Context::GetDevice(), &vinfo, nullptr, &imageView));

}

}
}
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: multipat.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 17:22:03 $
 *
 *  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_svx.hxx"

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

// include ---------------------------------------------------------------

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif

#include "multipat.hxx"
#include <svx/dialmgr.hxx>

#include "multipat.hrc"
#include <svx/dialogs.hrc>

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef  _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFOLDERPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFolderPicker.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif

#include <unotools/localfilehelper.hxx>
#include <svtools/pathoptions.hxx>

using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::com::sun::star::uno;

// struct MultiPath_Impl -------------------------------------------------

struct MultiPath_Impl
{
    BOOL    bEmptyAllowed;
    BOOL    bIsClassPathMode;
    bool    bIsRadioButtonMode;

    MultiPath_Impl( BOOL bAllowed ) :
        bEmptyAllowed( bAllowed ), bIsClassPathMode( FALSE ), bIsRadioButtonMode( false )  {}
};

// class SvxMultiPathDialog ----------------------------------------------

IMPL_LINK( SvxMultiPathDialog, SelectHdl_Impl, void *, EMPTYARG )
{
    ULONG nCount = pImpl->bIsRadioButtonMode ? aRadioLB.GetEntryCount() : aPathLB.GetEntryCount();
    bool bIsSelected = pImpl->bIsRadioButtonMode
        ? aRadioLB.FirstSelected() != NULL
        : aPathLB.GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND;
    BOOL bEnable = ( pImpl->bEmptyAllowed || nCount > 1 );
    aDelBtn.Enable( bEnable && bIsSelected );
    return 0;
}

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

IMPL_LINK( SvxMultiPathDialog, CheckHdl_Impl, svx::SvxRadioButtonListBox *, pBox )
{
    SvLBoxEntry* pEntry =
        pBox ? pBox->GetEntry( pBox->GetCurMousePoint() ) : aRadioLB.FirstSelected();
    if ( pEntry )
        aRadioLB.HandleEntryChecked( pEntry );
    return 0;
}

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

IMPL_LINK( SvxMultiPathDialog, AddHdl_Impl, PushButton *, EMPTYARG )
{
    rtl::OUString aService( RTL_CONSTASCII_USTRINGPARAM( FOLDER_PICKER_SERVICE_NAME ) );
    Reference < XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
    Reference < XFolderPicker > xFolderPicker( xFactory->createInstance( aService ), UNO_QUERY );

    if ( xFolderPicker->execute() == ExecutableDialogResults::OK )
    {
        INetURLObject aPath( xFolderPicker->getDirectory() );
        aPath.removeFinalSlash();
        String aURL = aPath.GetMainURL( INetURLObject::NO_DECODE );
        String sInsPath;
        ::utl::LocalFileHelper::ConvertURLToSystemPath( aURL, sInsPath );

        if ( pImpl->bIsRadioButtonMode )
        {
            ULONG nPos = aRadioLB.GetEntryPos( sInsPath, 1 );
            if ( (ULONG)-1 == nPos )
            {
                String sNewEntry( '\t' );
                sNewEntry += sInsPath;
                SvLBoxEntry* pEntry = aRadioLB.InsertEntry( sNewEntry );
                String* pData = new String( aURL );
                pEntry->SetUserData( pData );
            }
            else
            {
                String sMsg( SVX_RES( RID_MULTIPATH_DBL_ERR ) );
                sMsg.SearchAndReplaceAscii( "%1", sInsPath );
                InfoBox( this, sMsg ).Execute();
            }
        }
        else
        {
            if ( LISTBOX_ENTRY_NOTFOUND != aPathLB.GetEntryPos( sInsPath ) )
            {
                String sMsg( SVX_RES( RID_MULTIPATH_DBL_ERR ) );
                sMsg.SearchAndReplaceAscii( "%1", sInsPath );
                InfoBox( this, sMsg ).Execute();
            }
            else
            {
                USHORT nPos = aPathLB.InsertEntry( sInsPath, LISTBOX_APPEND );
                aPathLB.SetEntryData( nPos, (void*)new String( aURL ) );
            }
        }
        SelectHdl_Impl( NULL );
    }
    return 0;
}

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

IMPL_LINK( SvxMultiPathDialog, DelHdl_Impl, PushButton *, EMPTYARG )
{
    if ( pImpl->bIsRadioButtonMode )
    {
        SvLBoxEntry* pEntry = aRadioLB.FirstSelected();
        delete (String*)pEntry->GetUserData();
        bool bChecked = aRadioLB.GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED;
        ULONG nPos = aRadioLB.GetEntryPos( pEntry );
        aRadioLB.RemoveEntry( pEntry );
        ULONG nCnt = aRadioLB.GetEntryCount();
        if ( nCnt )
        {
            nCnt--;
            if ( nPos > nCnt )
                nPos = nCnt;
            pEntry = aRadioLB.GetEntry( nPos );
            if ( bChecked )
            {
                aRadioLB.SetCheckButtonState( pEntry, SV_BUTTON_CHECKED );
                aRadioLB.HandleEntryChecked( pEntry );
            }
            else
                aRadioLB.Select( pEntry );
        }
    }
    else
    {
        USHORT nPos = aPathLB.GetSelectEntryPos();
        aPathLB.RemoveEntry( nPos );
        USHORT nCnt = aPathLB.GetEntryCount();

        if ( nCnt )
        {
            nCnt--;

            if ( nPos > nCnt )
                nPos = nCnt;
            aPathLB.SelectEntryPos( nPos );
        }
    }
    SelectHdl_Impl( NULL );
    return 0;
}

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

SvxMultiPathDialog::SvxMultiPathDialog( Window* pParent, BOOL bEmptyAllowed ) :

    ModalDialog( pParent, SVX_RES( RID_SVXDLG_MULTIPATH ) ),

    aPathFL     ( this, SVX_RES( FL_MULTIPATH) ),
    aPathLB     ( this, SVX_RES( LB_MULTIPATH ) ),
    aRadioLB    ( this, SVX_RES( LB_RADIOBUTTON ) ),
    aRadioFT    ( this, SVX_RES( FT_RADIOBUTTON ) ),
    aAddBtn     ( this, SVX_RES( BTN_ADD_MULTIPATH ) ),
    aDelBtn     ( this, SVX_RES( BTN_DEL_MULTIPATH ) ),
    aOKBtn      ( this, SVX_RES( BTN_MULTIPATH_OK ) ),
    aCancelBtn  ( this, SVX_RES( BTN_MULTIPATH_CANCEL ) ),
    aHelpButton ( this, SVX_RES( BTN_MULTIPATH_HELP ) ),
    pImpl       ( new MultiPath_Impl( bEmptyAllowed ) )

{
    static long aStaticTabs[]= { 2, 0, 12 };
    aRadioLB.SvxSimpleTable::SetTabs( aStaticTabs );
    String sHeader( SVX_RES( STR_HEADER_PATHS ) );
    aRadioLB.SetQuickHelpText( sHeader );
    sHeader.Insert( '\t', 0 );
    aRadioLB.InsertHeaderEntry( sHeader, HEADERBAR_APPEND, HIB_LEFT );

    FreeResource();

    aPathLB.SetSelectHdl( LINK( this, SvxMultiPathDialog, SelectHdl_Impl ) );
    aRadioLB.SetSelectHdl( LINK( this, SvxMultiPathDialog, SelectHdl_Impl ) );
    aRadioLB.SetCheckButtonHdl( LINK( this, SvxMultiPathDialog, CheckHdl_Impl ) );
    aAddBtn.SetClickHdl( LINK( this, SvxMultiPathDialog, AddHdl_Impl ) );
    aDelBtn.SetClickHdl( LINK( this, SvxMultiPathDialog, DelHdl_Impl ) );

    SelectHdl_Impl( NULL );
}

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

SvxMultiPathDialog::~SvxMultiPathDialog()
{
    USHORT nPos = aPathLB.GetEntryCount();
    while ( nPos-- )
        delete (String*)aPathLB.GetEntryData(nPos);
    nPos = (USHORT)aRadioLB.GetEntryCount();
    while ( nPos-- )
    {
        SvLBoxEntry* pEntry = aRadioLB.GetEntry( nPos );
        delete (String*)pEntry->GetUserData();
    }
    delete pImpl;
}

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

String SvxMultiPathDialog::GetPath() const
{
    String sNewPath;
    sal_Unicode cDelim = pImpl->bIsClassPathMode ? CLASSPATH_DELIMITER : SVT_SEARCHPATH_DELIMITER;

    if ( pImpl->bIsRadioButtonMode )
    {
        String sWritable;
        for ( USHORT i = 0; i < aRadioLB.GetEntryCount(); ++i )
        {
            SvLBoxEntry* pEntry = aRadioLB.GetEntry(i);
            if ( aRadioLB.GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED )
                sWritable = *(String*)pEntry->GetUserData();
            else
            {
                if ( sNewPath.Len() > 0 )
                    sNewPath += cDelim;
                sNewPath += *(String*)pEntry->GetUserData();
            }
        }
        if ( sNewPath.Len() > 0 )
            sNewPath += cDelim;
        sNewPath += sWritable;
    }
    else
    {
        for ( USHORT i = 0; i < aPathLB.GetEntryCount(); ++i )
        {
            if ( sNewPath.Len() > 0 )
                sNewPath += cDelim;
            sNewPath += *(String*)aPathLB.GetEntryData(i);
        }
    }
    return sNewPath;
}

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

void SvxMultiPathDialog::SetPath( const String& rPath )
{
    sal_Unicode cDelim = pImpl->bIsClassPathMode ? CLASSPATH_DELIMITER : SVT_SEARCHPATH_DELIMITER;
    USHORT nPos, nCount = rPath.GetTokenCount( cDelim );

    for ( USHORT i = 0; i < nCount; ++i )
    {
        String sPath = rPath.GetToken( i, cDelim );
        String sSystemPath;
        sal_Bool bIsSystemPath =
            ::utl::LocalFileHelper::ConvertURLToSystemPath( sPath, sSystemPath );

        if ( pImpl->bIsRadioButtonMode )
        {
            String sEntry( '\t' );
            sEntry += bIsSystemPath ? sSystemPath : sPath;
            SvLBoxEntry* pEntry = aRadioLB.InsertEntry( sEntry );
            String* pURL = new String( sPath );
            pEntry->SetUserData( pURL );
        }
        else
        {
            if ( bIsSystemPath )
                nPos = aPathLB.InsertEntry( sSystemPath, LISTBOX_APPEND );
            else
                nPos = aPathLB.InsertEntry( sPath, LISTBOX_APPEND );
            aPathLB.SetEntryData( nPos, (void*)new String( sPath ) );
        }
    }

    if ( pImpl->bIsRadioButtonMode && nCount > 0 )
    {
        SvLBoxEntry* pEntry = aRadioLB.GetEntry( nCount - 1 );
        if ( pEntry )
        {
            aRadioLB.SetCheckButtonState( pEntry, SV_BUTTON_CHECKED );
            aRadioLB.HandleEntryChecked( pEntry );
        }
    }

    SelectHdl_Impl( NULL );
}

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

void SvxMultiPathDialog::SetClassPathMode()
{
    pImpl->bIsClassPathMode = TRUE;
    SetText( SVX_RES( RID_SVXSTR_ARCHIVE_TITLE ));
    aPathFL.SetText( SVX_RES( RID_SVXSTR_ARCHIVE_HEADLINE ) );
}

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

sal_Bool SvxMultiPathDialog::IsClassPathMode() const
{
    return pImpl->bIsClassPathMode;
}

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

void SvxMultiPathDialog::EnableRadioButtonMode()
{
    pImpl->bIsRadioButtonMode = true;

    aPathFL.Hide();
    aPathLB.Hide();

    aRadioLB.ShowTable();
    aRadioFT.Show();

    Point aNewPos = aAddBtn.GetPosPixel();
    long nDelta = aNewPos.Y() - aRadioLB.GetPosPixel().Y();
    aNewPos.Y() -= nDelta;
    aAddBtn.SetPosPixel( aNewPos );
    aNewPos = aDelBtn.GetPosPixel();
    aNewPos.Y() -= nDelta;
    aDelBtn.SetPosPixel( aNewPos );
}

<commit_msg>INTEGRATION: CWS cmcfixes42 (1.11.306); FILE MERGED 2008/02/15 10:36:40 cmc 1.11.306.1: #i85931# inconsistent GetEntryPos return value<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: multipat.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: rt $ $Date: 2008-02-19 12:40:00 $
 *
 *  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_svx.hxx"

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

// include ---------------------------------------------------------------

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif

#include "multipat.hxx"
#include <svx/dialmgr.hxx>

#include "multipat.hrc"
#include <svx/dialogs.hrc>

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef  _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFOLDERPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFolderPicker.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif

#include <unotools/localfilehelper.hxx>
#include <svtools/pathoptions.hxx>

using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::com::sun::star::uno;

// struct MultiPath_Impl -------------------------------------------------

struct MultiPath_Impl
{
    BOOL    bEmptyAllowed;
    BOOL    bIsClassPathMode;
    bool    bIsRadioButtonMode;

    MultiPath_Impl( BOOL bAllowed ) :
        bEmptyAllowed( bAllowed ), bIsClassPathMode( FALSE ), bIsRadioButtonMode( false )  {}
};

// class SvxMultiPathDialog ----------------------------------------------

IMPL_LINK( SvxMultiPathDialog, SelectHdl_Impl, void *, EMPTYARG )
{
    ULONG nCount = pImpl->bIsRadioButtonMode ? aRadioLB.GetEntryCount() : aPathLB.GetEntryCount();
    bool bIsSelected = pImpl->bIsRadioButtonMode
        ? aRadioLB.FirstSelected() != NULL
        : aPathLB.GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND;
    BOOL bEnable = ( pImpl->bEmptyAllowed || nCount > 1 );
    aDelBtn.Enable( bEnable && bIsSelected );
    return 0;
}

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

IMPL_LINK( SvxMultiPathDialog, CheckHdl_Impl, svx::SvxRadioButtonListBox *, pBox )
{
    SvLBoxEntry* pEntry =
        pBox ? pBox->GetEntry( pBox->GetCurMousePoint() ) : aRadioLB.FirstSelected();
    if ( pEntry )
        aRadioLB.HandleEntryChecked( pEntry );
    return 0;
}

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

IMPL_LINK( SvxMultiPathDialog, AddHdl_Impl, PushButton *, EMPTYARG )
{
    rtl::OUString aService( RTL_CONSTASCII_USTRINGPARAM( FOLDER_PICKER_SERVICE_NAME ) );
    Reference < XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
    Reference < XFolderPicker > xFolderPicker( xFactory->createInstance( aService ), UNO_QUERY );

    if ( xFolderPicker->execute() == ExecutableDialogResults::OK )
    {
        INetURLObject aPath( xFolderPicker->getDirectory() );
        aPath.removeFinalSlash();
        String aURL = aPath.GetMainURL( INetURLObject::NO_DECODE );
        String sInsPath;
        ::utl::LocalFileHelper::ConvertURLToSystemPath( aURL, sInsPath );

        if ( pImpl->bIsRadioButtonMode )
        {
            ULONG nPos = aRadioLB.GetEntryPos( sInsPath, 1 );
            if ( 0xffffffff == nPos ) //See svtools/source/contnr/svtabbx.cxx SvTabListBox::GetEntryPos
            {
                String sNewEntry( '\t' );
                sNewEntry += sInsPath;
                SvLBoxEntry* pEntry = aRadioLB.InsertEntry( sNewEntry );
                String* pData = new String( aURL );
                pEntry->SetUserData( pData );
            }
            else
            {
                String sMsg( SVX_RES( RID_MULTIPATH_DBL_ERR ) );
                sMsg.SearchAndReplaceAscii( "%1", sInsPath );
                InfoBox( this, sMsg ).Execute();
            }
        }
        else
        {
            if ( LISTBOX_ENTRY_NOTFOUND != aPathLB.GetEntryPos( sInsPath ) )
            {
                String sMsg( SVX_RES( RID_MULTIPATH_DBL_ERR ) );
                sMsg.SearchAndReplaceAscii( "%1", sInsPath );
                InfoBox( this, sMsg ).Execute();
            }
            else
            {
                USHORT nPos = aPathLB.InsertEntry( sInsPath, LISTBOX_APPEND );
                aPathLB.SetEntryData( nPos, (void*)new String( aURL ) );
            }
        }
        SelectHdl_Impl( NULL );
    }
    return 0;
}

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

IMPL_LINK( SvxMultiPathDialog, DelHdl_Impl, PushButton *, EMPTYARG )
{
    if ( pImpl->bIsRadioButtonMode )
    {
        SvLBoxEntry* pEntry = aRadioLB.FirstSelected();
        delete (String*)pEntry->GetUserData();
        bool bChecked = aRadioLB.GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED;
        ULONG nPos = aRadioLB.GetEntryPos( pEntry );
        aRadioLB.RemoveEntry( pEntry );
        ULONG nCnt = aRadioLB.GetEntryCount();
        if ( nCnt )
        {
            nCnt--;
            if ( nPos > nCnt )
                nPos = nCnt;
            pEntry = aRadioLB.GetEntry( nPos );
            if ( bChecked )
            {
                aRadioLB.SetCheckButtonState( pEntry, SV_BUTTON_CHECKED );
                aRadioLB.HandleEntryChecked( pEntry );
            }
            else
                aRadioLB.Select( pEntry );
        }
    }
    else
    {
        USHORT nPos = aPathLB.GetSelectEntryPos();
        aPathLB.RemoveEntry( nPos );
        USHORT nCnt = aPathLB.GetEntryCount();

        if ( nCnt )
        {
            nCnt--;

            if ( nPos > nCnt )
                nPos = nCnt;
            aPathLB.SelectEntryPos( nPos );
        }
    }
    SelectHdl_Impl( NULL );
    return 0;
}

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

SvxMultiPathDialog::SvxMultiPathDialog( Window* pParent, BOOL bEmptyAllowed ) :

    ModalDialog( pParent, SVX_RES( RID_SVXDLG_MULTIPATH ) ),

    aPathFL     ( this, SVX_RES( FL_MULTIPATH) ),
    aPathLB     ( this, SVX_RES( LB_MULTIPATH ) ),
    aRadioLB    ( this, SVX_RES( LB_RADIOBUTTON ) ),
    aRadioFT    ( this, SVX_RES( FT_RADIOBUTTON ) ),
    aAddBtn     ( this, SVX_RES( BTN_ADD_MULTIPATH ) ),
    aDelBtn     ( this, SVX_RES( BTN_DEL_MULTIPATH ) ),
    aOKBtn      ( this, SVX_RES( BTN_MULTIPATH_OK ) ),
    aCancelBtn  ( this, SVX_RES( BTN_MULTIPATH_CANCEL ) ),
    aHelpButton ( this, SVX_RES( BTN_MULTIPATH_HELP ) ),
    pImpl       ( new MultiPath_Impl( bEmptyAllowed ) )

{
    static long aStaticTabs[]= { 2, 0, 12 };
    aRadioLB.SvxSimpleTable::SetTabs( aStaticTabs );
    String sHeader( SVX_RES( STR_HEADER_PATHS ) );
    aRadioLB.SetQuickHelpText( sHeader );
    sHeader.Insert( '\t', 0 );
    aRadioLB.InsertHeaderEntry( sHeader, HEADERBAR_APPEND, HIB_LEFT );

    FreeResource();

    aPathLB.SetSelectHdl( LINK( this, SvxMultiPathDialog, SelectHdl_Impl ) );
    aRadioLB.SetSelectHdl( LINK( this, SvxMultiPathDialog, SelectHdl_Impl ) );
    aRadioLB.SetCheckButtonHdl( LINK( this, SvxMultiPathDialog, CheckHdl_Impl ) );
    aAddBtn.SetClickHdl( LINK( this, SvxMultiPathDialog, AddHdl_Impl ) );
    aDelBtn.SetClickHdl( LINK( this, SvxMultiPathDialog, DelHdl_Impl ) );

    SelectHdl_Impl( NULL );
}

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

SvxMultiPathDialog::~SvxMultiPathDialog()
{
    USHORT nPos = aPathLB.GetEntryCount();
    while ( nPos-- )
        delete (String*)aPathLB.GetEntryData(nPos);
    nPos = (USHORT)aRadioLB.GetEntryCount();
    while ( nPos-- )
    {
        SvLBoxEntry* pEntry = aRadioLB.GetEntry( nPos );
        delete (String*)pEntry->GetUserData();
    }
    delete pImpl;
}

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

String SvxMultiPathDialog::GetPath() const
{
    String sNewPath;
    sal_Unicode cDelim = pImpl->bIsClassPathMode ? CLASSPATH_DELIMITER : SVT_SEARCHPATH_DELIMITER;

    if ( pImpl->bIsRadioButtonMode )
    {
        String sWritable;
        for ( USHORT i = 0; i < aRadioLB.GetEntryCount(); ++i )
        {
            SvLBoxEntry* pEntry = aRadioLB.GetEntry(i);
            if ( aRadioLB.GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED )
                sWritable = *(String*)pEntry->GetUserData();
            else
            {
                if ( sNewPath.Len() > 0 )
                    sNewPath += cDelim;
                sNewPath += *(String*)pEntry->GetUserData();
            }
        }
        if ( sNewPath.Len() > 0 )
            sNewPath += cDelim;
        sNewPath += sWritable;
    }
    else
    {
        for ( USHORT i = 0; i < aPathLB.GetEntryCount(); ++i )
        {
            if ( sNewPath.Len() > 0 )
                sNewPath += cDelim;
            sNewPath += *(String*)aPathLB.GetEntryData(i);
        }
    }
    return sNewPath;
}

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

void SvxMultiPathDialog::SetPath( const String& rPath )
{
    sal_Unicode cDelim = pImpl->bIsClassPathMode ? CLASSPATH_DELIMITER : SVT_SEARCHPATH_DELIMITER;
    USHORT nPos, nCount = rPath.GetTokenCount( cDelim );

    for ( USHORT i = 0; i < nCount; ++i )
    {
        String sPath = rPath.GetToken( i, cDelim );
        String sSystemPath;
        sal_Bool bIsSystemPath =
            ::utl::LocalFileHelper::ConvertURLToSystemPath( sPath, sSystemPath );

        if ( pImpl->bIsRadioButtonMode )
        {
            String sEntry( '\t' );
            sEntry += bIsSystemPath ? sSystemPath : sPath;
            SvLBoxEntry* pEntry = aRadioLB.InsertEntry( sEntry );
            String* pURL = new String( sPath );
            pEntry->SetUserData( pURL );
        }
        else
        {
            if ( bIsSystemPath )
                nPos = aPathLB.InsertEntry( sSystemPath, LISTBOX_APPEND );
            else
                nPos = aPathLB.InsertEntry( sPath, LISTBOX_APPEND );
            aPathLB.SetEntryData( nPos, (void*)new String( sPath ) );
        }
    }

    if ( pImpl->bIsRadioButtonMode && nCount > 0 )
    {
        SvLBoxEntry* pEntry = aRadioLB.GetEntry( nCount - 1 );
        if ( pEntry )
        {
            aRadioLB.SetCheckButtonState( pEntry, SV_BUTTON_CHECKED );
            aRadioLB.HandleEntryChecked( pEntry );
        }
    }

    SelectHdl_Impl( NULL );
}

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

void SvxMultiPathDialog::SetClassPathMode()
{
    pImpl->bIsClassPathMode = TRUE;
    SetText( SVX_RES( RID_SVXSTR_ARCHIVE_TITLE ));
    aPathFL.SetText( SVX_RES( RID_SVXSTR_ARCHIVE_HEADLINE ) );
}

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

sal_Bool SvxMultiPathDialog::IsClassPathMode() const
{
    return pImpl->bIsClassPathMode;
}

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

void SvxMultiPathDialog::EnableRadioButtonMode()
{
    pImpl->bIsRadioButtonMode = true;

    aPathFL.Hide();
    aPathLB.Hide();

    aRadioLB.ShowTable();
    aRadioFT.Show();

    Point aNewPos = aAddBtn.GetPosPixel();
    long nDelta = aNewPos.Y() - aRadioLB.GetPosPixel().Y();
    aNewPos.Y() -= nDelta;
    aAddBtn.SetPosPixel( aNewPos );
    aNewPos = aDelBtn.GetPosPixel();
    aNewPos.Y() -= nDelta;
    aDelBtn.SetPosPixel( aNewPos );
}

<|endoftext|>