<commit_before>#pragma once

#include <ctime>
#include <functional>
#include <limits>
#include <locale>
#include <memory>
#include <sstream>
#include <vector>

#include <boost/assert.hpp>
#include <boost/config.hpp>
#include <boost/range.hpp>
#include <boost/version.hpp>
#include <boost/utility.hpp>

#include "blackhole/detail/stream/stream.hpp"

namespace blackhole {

namespace aux {

struct context_t {
    attachable_ostringstream& stream;
    std::string& str;
    std::tm tm;
};

inline void fill(std::string& str, int value, uint length, char filler = '0') {
    char buffer[std::numeric_limits<uint32_t>::digits10 + 2];
    uint digits = 0;
    do {
        buffer[digits] = (value % 10) + '0';
        value /= 10;
        digits++;
    } while (value);

    BOOST_ASSERT(length >= digits);
    const uint gap = length - digits;
    for (uint i = 0; i < gap; ++i) {
        str.push_back(filler);
    }

    for (uint i = 0; i < digits; ++i) {
        str.push_back(buffer[digits - 1 - i]);
    }
}

namespace visit {

template<char Format>
inline void localized(context_t& context) {
    typedef std::time_put<char> facet_type;
    typedef typename facet_type::iter_type iter_type;
    std::use_facet<facet_type>(context.stream.getloc())
            .put(iter_type(context.stream), context.stream, ' ', &context.tm, Format);
    context.stream.flush();
}

namespace year {

inline void full(context_t& context) {
    fill(context.str, context.tm.tm_year + 1900, 4);
}

inline void last_two_digits(context_t& context) {
    fill(context.str, context.tm.tm_year % 100, 2);
}

inline void first_two_digits(context_t& context) {
    fill(context.str, context.tm.tm_year / 100 + 19, 2);
}

} // namespace year

namespace month {

inline void numeric(context_t& context) {
    fill(context.str, context.tm.tm_mon + 1, 2);
}

} // namespace month

namespace day {

namespace year {

inline void numeric(context_t& context) {
    fill(context.str, context.tm.tm_yday + 1, 3);
}

} // namespace year

namespace month {

template<char Filler = '0'>
inline void numeric(context_t& context) {
    fill(context.str, context.tm.tm_mday, 2, Filler);
}

} // namespace month

} // namespace day

namespace hour {

inline void h24(context_t& context) {
    fill(context.str, context.tm.tm_hour, 2);
}

inline void h12(context_t& context) {
    const uint mod = context.tm.tm_hour % 12;
    fill(context.str, mod == 0 ? 12 : mod, 2);
}

} // namespace hour

namespace time {

namespace minute {

inline void normal(context_t& context) {
    fill(context.str, context.tm.tm_min, 2);
}

} // namespace minute

namespace second {

inline void normal(context_t& context) {
    fill(context.str, context.tm.tm_sec, 2);
}

} // namespace second

} // namespace time

inline void standard(context_t& context) {
    typedef std::time_put<char> facet_type;
    typedef typename facet_type::iter_type iter_type;
    auto locale = context.stream.getloc();
    std::use_facet<facet_type>(locale)
            .put(iter_type(context.stream), context.stream, ' ', &context.tm, 'a');
    context.stream.flush();
    context.str.push_back(' ');
    std::use_facet<facet_type>(locale)
            .put(iter_type(context.stream), context.stream, ' ', &context.tm, 'b');
    context.stream.flush();
    context.str.push_back(' ');
    day::month::numeric(context);
    context.str.push_back(' ');
    hour::h24(context);
    context.str.push_back(':');
    time::minute::normal(context);
    context.str.push_back(':');
    time::second::normal(context);
    context.str.push_back(' ');
    year::full(context);
}

} // namespace visit

struct literal_generator_t {
    std::string literal;

    void operator()(context_t& context) const {
        context.str.append(literal);
    }
};

namespace datetime {

typedef std::function<void(context_t&)> generator_action_t;

//!@note: copyable, movable.
class generator_t {
    std::vector<generator_action_t> actions;
public:
    generator_t(std::vector<generator_action_t>&& actions) :
        actions(std::move(actions))
    {}

    template<class Stream>
    void operator()(Stream& stream, const std::tm& tm) const {
        context_t context { stream, *stream.rdbuf()->storage(), tm };

        for (auto it = actions.begin(); it != actions.end(); ++it) {
            const generator_action_t& action = *it;
            action(context);
        }
    }
};

class generator_handler_t {
    typedef std::string::const_iterator iterator_type;

    std::vector<generator_action_t>& actions;
    std::string m_literal;
public:
    generator_handler_t(std::vector<generator_action_t>& actions) :
        actions(actions)
    {}

    virtual void partial_literal(iterator_type begin, iterator_type end) {
        m_literal.append(begin, end);
    }

    virtual void end_partial_literal() {
        if (!m_literal.empty()) {
            literal(boost::make_iterator_range(m_literal));
            m_literal.clear();
        }
    }

    virtual void literal(const std::string& lit) {
        actions.push_back(literal_generator_t { lit });
    }

    virtual void literal(const boost::iterator_range<iterator_type>& range) {
        actions.push_back(literal_generator_t { boost::copy_range<std::string>(range) });
    }

    virtual void placeholder(const boost::iterator_range<iterator_type>& range) {
        literal(range);
    }

    virtual void full_year() {
        end_partial_literal();
        actions.push_back(&visit::year::full);
    }

    virtual void short_year() {
        end_partial_literal();
        actions.push_back(&visit::year::last_two_digits);
    }

    virtual void short_year_first_two_digits() {
        end_partial_literal();
        actions.push_back(&visit::year::first_two_digits);
    }

    virtual void numeric_month() {
        end_partial_literal();
        actions.push_back(&visit::month::numeric);
    }

    virtual void abbreviate_month() {
        end_partial_literal();
        actions.push_back(&visit::localized<'b'>);
    }

    virtual void full_month() {
        end_partial_literal();
        actions.push_back(&visit::localized<'B'>);
    }

    virtual void year_day() {
        end_partial_literal();
        actions.push_back(&visit::day::year::numeric);
    }

    virtual void month_day(bool has_leading_zero = true) {
        end_partial_literal();
        if (has_leading_zero) {
            actions.push_back(&visit::day::month::numeric<'0'>);
        } else {
            actions.push_back(&visit::day::month::numeric<' '>);
        }
    }

    virtual void abbreviate_weekday() {
        end_partial_literal();
        actions.push_back(&visit::localized<'a'>);
    }

    virtual void full_weekday() {
        end_partial_literal();
        actions.push_back(&visit::localized<'A'>);
    }

    virtual void hours() {
        end_partial_literal();
        actions.push_back(&visit::hour::h24);
    }

    virtual void hours12() {
        end_partial_literal();
        actions.push_back(&visit::hour::h12);
    }

    virtual void minute() {
        end_partial_literal();
        actions.push_back(&visit::time::minute::normal);
    }

    virtual void second() {
        end_partial_literal();
        actions.push_back(&visit::time::second::normal);
    }

    virtual void standard_date_time() {
        end_partial_literal();
        actions.push_back(&visit::standard);
    }
};

namespace parser {

class through_t {
public:
    typedef std::string::const_iterator iterator_type;

    static iterator_type parse(iterator_type it, iterator_type end, generator_handler_t& handler) {
        BOOST_ASSERT(it != end && it + 1 != end);
        handler.placeholder(boost::make_iterator_range(it, it + 2));
        return it + 2;
    }
};

template<class Decorate = through_t>
class common {
public:
    typedef typename Decorate::iterator_type iterator_type;

    static iterator_type parse(iterator_type it, iterator_type end, generator_handler_t& handler) {
        BOOST_ASSERT(it != end && it + 1 != end);
        switch (*(it + 1)) {
        case 'c':
            break;
        default:
            return Decorate::parse(it, end, handler);
        }
        return it + 2;
    }
};

template<class Decorate>
class time {
public:
    typedef typename Decorate::iterator_type iterator_type;

    static iterator_type parse(iterator_type it, iterator_type end, generator_handler_t& handler) {
        BOOST_ASSERT(it != end && it + 1 != end);
        switch (*(it + 1)) {
        case 'H':
            handler.hours();
            break;
        case 'I':
            handler.hours12();
            break;
        case 'M':
            handler.minute();
            break;
        case 'S':
            handler.second();
            break;
        default:
            return Decorate::parse(it, end, handler);
        }

        return it + 2;
    }
};

template<class Decorate>
class date {
public:
    typedef typename Decorate::iterator_type iterator_type;

    static iterator_type parse(iterator_type it, iterator_type end, generator_handler_t& handler) {
        BOOST_ASSERT(it != end && it + 1 != end);
        switch (*(it + 1)) {
        //! =========== YEAR SECTION ===========
        case 'Y':
            handler.full_year();
            break;
        case 'y':
            handler.short_year();
            break;
        case 'C':
            handler.short_year_first_two_digits();
            break;
        //! =========== MONTH SECTION ===========
        case 'm':
            handler.numeric_month();
            break;
        case 'b':
        case 'h':
            handler.abbreviate_month();
            break;
        case 'B':
            handler.full_month();
            break;
        //! =========== DAY SECTION ===========
        case 'j':
            handler.year_day();
            break;
        case 'd':
            handler.month_day();
            break;
        case 'e':
            handler.month_day(false);
            break;
        case 'a':
            handler.abbreviate_weekday();
            break;
        case 'A':
            handler.full_weekday();
            break;
        //! =========== OTHER SECTION ===========
        case 'c':
            handler.standard_date_time();
            break;
        default:
            return Decorate::parse(it, end, handler);
        }

        return it + 2;
    }
};

} // namespace parser

template<class Decorate>
class parser_t {
    typedef typename Decorate::iterator_type iterator_type;

public:
    static void parse(const std::string& format, generator_handler_t& handler) {
        iterator_type it = format.begin();
        iterator_type end = format.end();

        while (it != end) {
            iterator_type p = std::find(it, end, '%');
            handler.partial_literal(it, p);

            if (std::distance(p, end) >= 2) {
                it = Decorate::parse(p, end, handler);
            } else {
                if (p != end) {
                    handler.partial_literal(p, end);
                }
                break;
            }
        }

        handler.end_partial_literal();
    }
};

class generator_factory_t {
public:
    static generator_t make(const std::string& pattern) {
        std::vector<generator_action_t> actions;
        generator_handler_t handler(actions);
        parser_t<parser::date<parser::time<parser::common<parser::through_t>>>>::parse(pattern, handler);
        return generator_t(std::move(actions));
    }
};

} // namespace datetime

} // namespace aux

} // namespace blackhole
<commit_msg>[Datetime generator] Hour visitor function now placed in `time` namespace.<commit_after>#pragma once

#include <ctime>
#include <functional>
#include <limits>
#include <locale>
#include <memory>
#include <sstream>
#include <vector>

#include <boost/assert.hpp>
#include <boost/config.hpp>
#include <boost/range.hpp>
#include <boost/version.hpp>
#include <boost/utility.hpp>

#include "blackhole/detail/stream/stream.hpp"

namespace blackhole {

namespace aux {

struct context_t {
    attachable_ostringstream& stream;
    std::string& str;
    std::tm tm;
};

inline void fill(std::string& str, int value, uint length, char filler = '0') {
    char buffer[std::numeric_limits<uint32_t>::digits10 + 2];
    uint digits = 0;
    do {
        buffer[digits] = (value % 10) + '0';
        value /= 10;
        digits++;
    } while (value);

    BOOST_ASSERT(length >= digits);
    const uint gap = length - digits;
    for (uint i = 0; i < gap; ++i) {
        str.push_back(filler);
    }

    for (uint i = 0; i < digits; ++i) {
        str.push_back(buffer[digits - 1 - i]);
    }
}

namespace visit {

template<char Format>
inline void localized(context_t& context) {
    typedef std::time_put<char> facet_type;
    typedef typename facet_type::iter_type iter_type;
    std::use_facet<facet_type>(context.stream.getloc())
            .put(iter_type(context.stream), context.stream, ' ', &context.tm, Format);
    context.stream.flush();
}

namespace year {

inline void full(context_t& context) {
    fill(context.str, context.tm.tm_year + 1900, 4);
}

inline void last_two_digits(context_t& context) {
    fill(context.str, context.tm.tm_year % 100, 2);
}

inline void first_two_digits(context_t& context) {
    fill(context.str, context.tm.tm_year / 100 + 19, 2);
}

} // namespace year

namespace month {

inline void numeric(context_t& context) {
    fill(context.str, context.tm.tm_mon + 1, 2);
}

} // namespace month

namespace day {

namespace year {

inline void numeric(context_t& context) {
    fill(context.str, context.tm.tm_yday + 1, 3);
}

} // namespace year

namespace month {

template<char Filler = '0'>
inline void numeric(context_t& context) {
    fill(context.str, context.tm.tm_mday, 2, Filler);
}

} // namespace month

} // namespace day

namespace time {

namespace hour {

inline void h24(context_t& context) {
    fill(context.str, context.tm.tm_hour, 2);
}

inline void h12(context_t& context) {
    const uint mod = context.tm.tm_hour % 12;
    fill(context.str, mod == 0 ? 12 : mod, 2);
}

} // namespace hour

namespace minute {

inline void normal(context_t& context) {
    fill(context.str, context.tm.tm_min, 2);
}

} // namespace minute

namespace second {

inline void normal(context_t& context) {
    fill(context.str, context.tm.tm_sec, 2);
}

} // namespace second

} // namespace time

inline void standard(context_t& context) {
    typedef std::time_put<char> facet_type;
    typedef typename facet_type::iter_type iter_type;
    auto locale = context.stream.getloc();
    std::use_facet<facet_type>(locale)
            .put(iter_type(context.stream), context.stream, ' ', &context.tm, 'a');
    context.stream.flush();
    context.str.push_back(' ');
    std::use_facet<facet_type>(locale)
            .put(iter_type(context.stream), context.stream, ' ', &context.tm, 'b');
    context.stream.flush();
    context.str.push_back(' ');
    day::month::numeric(context);
    context.str.push_back(' ');
    time::hour::h24(context);
    context.str.push_back(':');
    time::minute::normal(context);
    context.str.push_back(':');
    time::second::normal(context);
    context.str.push_back(' ');
    year::full(context);
}

} // namespace visit

struct literal_generator_t {
    std::string literal;

    void operator()(context_t& context) const {
        context.str.append(literal);
    }
};

namespace datetime {

typedef std::function<void(context_t&)> generator_action_t;

//!@note: copyable, movable.
class generator_t {
    std::vector<generator_action_t> actions;
public:
    generator_t(std::vector<generator_action_t>&& actions) :
        actions(std::move(actions))
    {}

    template<class Stream>
    void operator()(Stream& stream, const std::tm& tm) const {
        context_t context { stream, *stream.rdbuf()->storage(), tm };

        for (auto it = actions.begin(); it != actions.end(); ++it) {
            const generator_action_t& action = *it;
            action(context);
        }
    }
};

class generator_handler_t {
    typedef std::string::const_iterator iterator_type;

    std::vector<generator_action_t>& actions;
    std::string m_literal;
public:
    generator_handler_t(std::vector<generator_action_t>& actions) :
        actions(actions)
    {}

    virtual void partial_literal(iterator_type begin, iterator_type end) {
        m_literal.append(begin, end);
    }

    virtual void end_partial_literal() {
        if (!m_literal.empty()) {
            literal(boost::make_iterator_range(m_literal));
            m_literal.clear();
        }
    }

    virtual void literal(const std::string& lit) {
        actions.push_back(literal_generator_t { lit });
    }

    virtual void literal(const boost::iterator_range<iterator_type>& range) {
        actions.push_back(literal_generator_t { boost::copy_range<std::string>(range) });
    }

    virtual void placeholder(const boost::iterator_range<iterator_type>& range) {
        literal(range);
    }

    virtual void full_year() {
        end_partial_literal();
        actions.push_back(&visit::year::full);
    }

    virtual void short_year() {
        end_partial_literal();
        actions.push_back(&visit::year::last_two_digits);
    }

    virtual void short_year_first_two_digits() {
        end_partial_literal();
        actions.push_back(&visit::year::first_two_digits);
    }

    virtual void numeric_month() {
        end_partial_literal();
        actions.push_back(&visit::month::numeric);
    }

    virtual void abbreviate_month() {
        end_partial_literal();
        actions.push_back(&visit::localized<'b'>);
    }

    virtual void full_month() {
        end_partial_literal();
        actions.push_back(&visit::localized<'B'>);
    }

    virtual void year_day() {
        end_partial_literal();
        actions.push_back(&visit::day::year::numeric);
    }

    virtual void month_day(bool has_leading_zero = true) {
        end_partial_literal();
        if (has_leading_zero) {
            actions.push_back(&visit::day::month::numeric<'0'>);
        } else {
            actions.push_back(&visit::day::month::numeric<' '>);
        }
    }

    virtual void abbreviate_weekday() {
        end_partial_literal();
        actions.push_back(&visit::localized<'a'>);
    }

    virtual void full_weekday() {
        end_partial_literal();
        actions.push_back(&visit::localized<'A'>);
    }

    virtual void hours() {
        end_partial_literal();
        actions.push_back(&visit::time::hour::h24);
    }

    virtual void hours12() {
        end_partial_literal();
        actions.push_back(&visit::time::hour::h12);
    }

    virtual void minute() {
        end_partial_literal();
        actions.push_back(&visit::time::minute::normal);
    }

    virtual void second() {
        end_partial_literal();
        actions.push_back(&visit::time::second::normal);
    }

    virtual void standard_date_time() {
        end_partial_literal();
        actions.push_back(&visit::standard);
    }
};

namespace parser {

class through_t {
public:
    typedef std::string::const_iterator iterator_type;

    static iterator_type parse(iterator_type it, iterator_type end, generator_handler_t& handler) {
        BOOST_ASSERT(it != end && it + 1 != end);
        handler.placeholder(boost::make_iterator_range(it, it + 2));
        return it + 2;
    }
};

template<class Decorate = through_t>
class common {
public:
    typedef typename Decorate::iterator_type iterator_type;

    static iterator_type parse(iterator_type it, iterator_type end, generator_handler_t& handler) {
        BOOST_ASSERT(it != end && it + 1 != end);
        switch (*(it + 1)) {
        case 'c':
            break;
        default:
            return Decorate::parse(it, end, handler);
        }
        return it + 2;
    }
};

template<class Decorate>
class time {
public:
    typedef typename Decorate::iterator_type iterator_type;

    static iterator_type parse(iterator_type it, iterator_type end, generator_handler_t& handler) {
        BOOST_ASSERT(it != end && it + 1 != end);
        switch (*(it + 1)) {
        case 'H':
            handler.hours();
            break;
        case 'I':
            handler.hours12();
            break;
        case 'M':
            handler.minute();
            break;
        case 'S':
            handler.second();
            break;
        default:
            return Decorate::parse(it, end, handler);
        }

        return it + 2;
    }
};

template<class Decorate>
class date {
public:
    typedef typename Decorate::iterator_type iterator_type;

    static iterator_type parse(iterator_type it, iterator_type end, generator_handler_t& handler) {
        BOOST_ASSERT(it != end && it + 1 != end);
        switch (*(it + 1)) {
        //! =========== YEAR SECTION ===========
        case 'Y':
            handler.full_year();
            break;
        case 'y':
            handler.short_year();
            break;
        case 'C':
            handler.short_year_first_two_digits();
            break;
        //! =========== MONTH SECTION ===========
        case 'm':
            handler.numeric_month();
            break;
        case 'b':
        case 'h':
            handler.abbreviate_month();
            break;
        case 'B':
            handler.full_month();
            break;
        //! =========== DAY SECTION ===========
        case 'j':
            handler.year_day();
            break;
        case 'd':
            handler.month_day();
            break;
        case 'e':
            handler.month_day(false);
            break;
        case 'a':
            handler.abbreviate_weekday();
            break;
        case 'A':
            handler.full_weekday();
            break;
        //! =========== OTHER SECTION ===========
        case 'c':
            handler.standard_date_time();
            break;
        default:
            return Decorate::parse(it, end, handler);
        }

        return it + 2;
    }
};

} // namespace parser

template<class Decorate>
class parser_t {
    typedef typename Decorate::iterator_type iterator_type;

public:
    static void parse(const std::string& format, generator_handler_t& handler) {
        iterator_type it = format.begin();
        iterator_type end = format.end();

        while (it != end) {
            iterator_type p = std::find(it, end, '%');
            handler.partial_literal(it, p);

            if (std::distance(p, end) >= 2) {
                it = Decorate::parse(p, end, handler);
            } else {
                if (p != end) {
                    handler.partial_literal(p, end);
                }
                break;
            }
        }

        handler.end_partial_literal();
    }
};

class generator_factory_t {
public:
    static generator_t make(const std::string& pattern) {
        std::vector<generator_action_t> actions;
        generator_handler_t handler(actions);
        parser_t<parser::date<parser::time<parser::common<parser::through_t>>>>::parse(pattern, handler);
        return generator_t(std::move(actions));
    }
};

} // namespace datetime

} // namespace aux

} // namespace blackhole
<|endoftext|>


<commit_before>#include "gtest/gtest.h"

#include <Syncs/GameAgent.h>
#include <Syncs/Interface.h>
#include <Tasks/BasicTask.h>

using namespace Hearthstonepp;

TEST(BasicCard, EX1_066)
{
    GameAgent agent(
        Player(new Account("Player 1", ""), new Deck("", CardClass::WARRIOR)),
        Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE)));
    agent.GetPlayer1().totalMana = agent.GetPlayer1().existMana = 10;
    agent.GetPlayer2().totalMana = agent.GetPlayer2().existMana = 10;

    agent.Process(agent.GetPlayer1(),
                  BasicTask::DrawTask(
                      Cards::GetInstance()->FindCardByName("Fiery War Axe")));
    EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(1));

    agent.Process(agent.GetPlayer2(),
                  BasicTask::DrawTask(Cards::GetInstance()->FindCardByName(
                      "Acidic Swamp Ooze")));
    EXPECT_EQ(agent.GetPlayer2().hand.size(), static_cast<size_t>(1));

    agent.Process(agent.GetPlayer1(),
                  BasicTask::PlayCardTask(agent.GetPlayer1(), 0));
    EXPECT_EQ(agent.GetPlayer1().hero->weapon != nullptr, true);

    //agent.Process(agent.GetPlayer2(),
    //              BasicTask::PlayCardTask(agent.GetPlayer2(), 0, 0));
    //EXPECT_EQ(agent.GetPlayer1().hero->weapon != nullptr, false);
}<commit_msg>[ci skip] Uncomment EX1_066 card test<commit_after>#include "gtest/gtest.h"

#include <Syncs/GameAgent.h>
#include <Syncs/Interface.h>
#include <Tasks/BasicTask.h>

using namespace Hearthstonepp;

TEST(BasicCard, EX1_066)
{
    GameAgent agent(
        Player(new Account("Player 1", ""), new Deck("", CardClass::WARRIOR)),
        Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE)));
    agent.GetPlayer1().totalMana = agent.GetPlayer1().existMana = 10;
    agent.GetPlayer2().totalMana = agent.GetPlayer2().existMana = 10;

    agent.Process(agent.GetPlayer1(),
                  BasicTask::DrawTask(
                      Cards::GetInstance()->FindCardByName("Fiery War Axe")));
    EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(1));

    agent.Process(agent.GetPlayer2(),
                  BasicTask::DrawTask(Cards::GetInstance()->FindCardByName(
                      "Acidic Swamp Ooze")));
    EXPECT_EQ(agent.GetPlayer2().hand.size(), static_cast<size_t>(1));

    agent.Process(agent.GetPlayer1(),
                  BasicTask::PlayCardTask(agent.GetPlayer1(), 0));
    EXPECT_EQ(agent.GetPlayer1().hero->weapon != nullptr, true);

    agent.Process(agent.GetPlayer2(),
                  BasicTask::PlayCardTask(agent.GetPlayer2(), 0, 0));
    EXPECT_EQ(agent.GetPlayer1().hero->weapon != nullptr, false);
}<|endoftext|>


<commit_before>#include "collinswordtomemo.h"
#include <QFileInfo>
#include <assert.h>
#include "shanbay.hxx"

QString EnExampleToEnJieshi::highlightWord(const QString &sentence, const QString &word)
{
    //    if (cs == Qt::CaseInsensitive) {
    //    }
    QString tempSentence = sentence;
    if (tempSentence.contains(word))
        tempSentence = tempSentence.replace(word,""+word+"");
    if (word.size() > 0) {
        QString bigWord = word.at(0).toUpper() + word.mid(1);
        if (tempSentence.contains(bigWord))
            tempSentence = tempSentence.replace(bigWord,""+bigWord+"");
    }
    //            QString tempSentence = collinsInfo.sentences;
    //            if (tempSentence.contains(word))
    //                tempSentence = tempSentence.replace(word,""+word+"");
    //            if (word.size() > 0) {
    //                QString bigWord = word.at(0).toUpper() + word.mid(1);
    //                if (tempSentence.contains(bigWord))
    //                    tempSentence = tempSentence.replace(bigWord,""+bigWord+"");
    //            }
    return tempSentence;
}

QString EnExampleToEnJieshi::clozeWord(const QString &sentence, const QString &word)
{
    QString tempSentence = sentence;
    QString cloze; // "[____]"
    int size = word.size();
    cloze = "[";
    for (int i = 0; i < size; ++i) {
        cloze += "_";
    }
    cloze += ']';
    // replace word with [___]
    if (tempSentence.contains(word))
        tempSentence = tempSentence.replace(word,""+cloze+"");
    if (size > 0) {
        QString bigWord = word.at(0).toUpper() + word.mid(1);
        if (tempSentence.contains(bigWord))
            tempSentence = tempSentence.replace(bigWord,""+cloze+"");
    }
    return tempSentence;
}

QString EnExampleToEnJieshi::pronToHtml(const QString &pron)
{
    const ushort * utf16 = pron.utf16();
    QString utf16pron;
    for (int j = 0; j < pron.size(); ++j){
        ushort ch = *(utf16+j);
        QString temp = "&#";
        temp += QString::number(ch);
        temp += ";";
        utf16pron += temp;
    }
    return utf16pron;
}

QString EnExampleToEnJieshi::multiSpace(int count)
{
    QString space = " ";

    if (count < 0) return space;
    QString temp;
    for (int i = 0 ; i < count; ++i) {
        temp += space;
    }
    return temp;
}

MemoUnit EnExampleToEnJieshi::covertToMemoUnit(const CollinsInfo &collinsInfo)
{

    MemoUnit unit;

    QString br = "
";
    QString word = collinsInfo.word;
    QStringList enzhlist;
    QMap<QString,QString> exampleEnZh = collinsInfo.example; //<en,zh> pair
    for (QMap<QString,QString>::iterator kv = exampleEnZh.begin(); kv != exampleEnZh.end(); ++kv) {
        QString en = kv.key();
        QString zh = kv.value();
        QString enzh = highlightWord(en,word) + multiSpace(10) + zh;
        enzhlist.append(enzh);
    }
    QString example = enzhlist.join(br);
    QStringList enList = exampleEnZh.keys();
    QString exampleEn = enList.join(br);
    QString highlightExampleEn = highlightWord(exampleEn,word);

    QString highlightSentence = clozeWord(collinsInfo.sentences, word);
    QString question = highlightSentence;

    ShanbayWordInfo wordInfo = Shanbay::instance()->getWordInfo(word);

    QString utf16pron = pronToHtml(wordInfo.pron);
    qDebug() << utf16pron;
    QString pron = " [ " +utf16pron + " ] ";

    // TODO: copy mp3 from zip
#if 0
    QFileInfo fileInfo(outFile);
    QString mp3path = fileInfo.baseName()+"_files/Elements";

    Util::downloadFile(wordInfo.audio, mp3path); // down mp3
#endif
//    QTextCodec *gbk = QTextCodec::codecForName("GB18030");
//    QTextCodec *utf8 = QTextCodec::codecForName("UTF-8");
//    QString g2u = gbk->toUnicode(gbk->fromUnicode(wordInfo.pron));
//    qDebug()<< wordInfo.pron<<"    GBK -> UTF-8     " << g2u<<endl;
//    QString cn = wordInfo.cn;
//    QStringList cnList = cn.split("\n");

    QString answer;

//    QString answer_pron = answer_head +pron+ br;
//    answer.append(answer_pron + "\r\n");
//    foreach (QString onecn, cnList) {
//        QString oneAnswer = answer_head + onecn + br;
//        answer.append(oneAnswer + "\r\n");
//    }
#if 0
    answer = highlightSentence+br       //  If you describe something as immoderate, you disapprove of it because it is too extreme.
            +collinsInfo.cn+br          // 极端的;不合理的
            +collinsInfo.st+br          // ADJ-GRADED	能被表示程度的副词或介词词组修饰的形容词
            +pron+br                    // [immoderate]
            +collinsInfo.grammer+br     // 【搭配模式】：usu ADJ n【语用信息】：disapproval【语域标签】：FORMAL 正式
            +collinsInfo.explain+br     // in BRIT, also use 英国英语亦用 characterise
            +collinsInfo.usagenote;     // Usage Note :In British English, a person's weight is normally measured in stones and pounds.
                                        //A stone is equivalent to 14 pounds, or 6.35 kilograms...
#else

    answer = highlightWord(word,word) + "  "
            + pron + multiSpace(80)
            + collinsInfo.cn + br + br
            + example;
#endif
    unit.setQuestion(Question(question));
    unit.setAnswer(Answer(answer));

    //            QString pron;
//            ShanbayWordInfo wordInfo = Shanbay::instance()->getWordInfo(word);

//            QString utf16pron = pronToHtml(wordInfo.pron);
//            qDebug() << utf16pron;
//            QString pron = " [ " +utf16pron + " ] ";

//            // TODO: copy mp3 from zip

//            QFileInfo fileInfo(outFile);
//            QString mp3path = fileInfo.baseName()+"_files/Elements";
//            Util::downloadFile(wordInfo.audio, mp3path); // down mp3
//            QString name = wordInfo.word;
//            QString audio = wordInfo.audio;
//            int audioIndex = audio.lastIndexOf("/");
//            audio = audio.mid(audioIndex + 1);
//            QString url = "[SecondaryStorage]\\"+ audio;
//            qDebug() << "mp3name"<<url;
    Sound sound;
    QString audio = wordInfo.audio;
    int audioIndex = audio.lastIndexOf("/");
    audio = audio.mid(audioIndex + 1);
    QString url = "[SecondaryStorage]\\"+ audio;

    sound.setUrl(url);
    sound.setName(word);
    sound.setText(pron);
    QUrl sourceUrl = wordInfo.audio;
    QFileInfo fileinfo("./shanbaymp3/" + audio );
    if (fileinfo.exists()) {
        sourceUrl = QUrl::fromLocalFile("./shanbaymp3/" + audio );
    }
    sound.setSource(sourceUrl);
    unit.setSound(sound);
    return unit;
}

CollinsWordToMemo::CollinsWordToMemo(CovertStrategy *strategy) : covertStrategy_(strategy)
{
    assert(covertStrategy_);
}

void CollinsWordToMemo::addWord(const QString &word)
{
    wordList_.append(word);
}

void CollinsWordToMemo::addWordList(const QStringList &list)
{
    wordList_.append(list);
}

void CollinsWordToMemo::setCovertStrategy(CovertStrategy *strategy)
{
    covertStrategy_ = strategy;
}

QSharedPointer<MemoCollection> CollinsWordToMemo::makeCollection()
{
    QSharedPointer<MemoCollection> collection(new MemoCollection);
    Q_FOREACH(const QString& word, wordList_) {
        QList<CollinsInfo> infoList = COLLINS->zhCollins(word);
        Q_FOREACH(const CollinsInfo& info, infoList) {
            MemoUnit unit = covertStrategy_->covertToMemoUnit(info);
            collection->addMemoUnit(unit);
        }
    }
    return collection;
}

<commit_msg>remove name of sound<commit_after>#include "collinswordtomemo.h"
#include <QFileInfo>
#include <assert.h>
#include "shanbay.hxx"

QString EnExampleToEnJieshi::highlightWord(const QString &sentence, const QString &word)
{
    //    if (cs == Qt::CaseInsensitive) {
    //    }
    QString tempSentence = sentence;
    if (tempSentence.contains(word))
        tempSentence = tempSentence.replace(word,""+word+"");
    if (word.size() > 0) {
        QString bigWord = word.at(0).toUpper() + word.mid(1);
        if (tempSentence.contains(bigWord))
            tempSentence = tempSentence.replace(bigWord,""+bigWord+"");
    }
    //            QString tempSentence = collinsInfo.sentences;
    //            if (tempSentence.contains(word))
    //                tempSentence = tempSentence.replace(word,""+word+"");
    //            if (word.size() > 0) {
    //                QString bigWord = word.at(0).toUpper() + word.mid(1);
    //                if (tempSentence.contains(bigWord))
    //                    tempSentence = tempSentence.replace(bigWord,""+bigWord+"");
    //            }
    return tempSentence;
}

QString EnExampleToEnJieshi::clozeWord(const QString &sentence, const QString &word)
{
    QString tempSentence = sentence;
    QString cloze; // "[____]"
    int size = word.size();
    cloze = "[";
    for (int i = 0; i < size; ++i) {
        cloze += "_";
    }
    cloze += ']';
    // replace word with [___]
    if (tempSentence.contains(word))
        tempSentence = tempSentence.replace(word,""+cloze+"");
    if (size > 0) {
        QString bigWord = word.at(0).toUpper() + word.mid(1);
        if (tempSentence.contains(bigWord))
            tempSentence = tempSentence.replace(bigWord,""+cloze+"");
    }
    return tempSentence;
}

QString EnExampleToEnJieshi::pronToHtml(const QString &pron)
{
    const ushort * utf16 = pron.utf16();
    QString utf16pron;
    for (int j = 0; j < pron.size(); ++j){
        ushort ch = *(utf16+j);
        QString temp = "&#";
        temp += QString::number(ch);
        temp += ";";
        utf16pron += temp;
    }
    return utf16pron;
}

QString EnExampleToEnJieshi::multiSpace(int count)
{
    QString space = " ";

    if (count < 0) return space;
    QString temp;
    for (int i = 0 ; i < count; ++i) {
        temp += space;
    }
    return temp;
}

MemoUnit EnExampleToEnJieshi::covertToMemoUnit(const CollinsInfo &collinsInfo)
{

    MemoUnit unit;

    QString br = "
";
    QString word = collinsInfo.word;
    QStringList enzhlist;
    QMap<QString,QString> exampleEnZh = collinsInfo.example; //<en,zh> pair
    for (QMap<QString,QString>::iterator kv = exampleEnZh.begin(); kv != exampleEnZh.end(); ++kv) {
        QString en = kv.key();
        QString zh = kv.value();
        QString enzh = highlightWord(en,word) + multiSpace(10) + zh;
        enzhlist.append(enzh);
    }
    QString example = enzhlist.join(br);
    QStringList enList = exampleEnZh.keys();
    QString exampleEn = enList.join(br);
    QString highlightExampleEn = highlightWord(exampleEn,word);

    QString highlightSentence = clozeWord(collinsInfo.sentences, word);
    QString question = highlightSentence;

    ShanbayWordInfo wordInfo = Shanbay::instance()->getWordInfo(word);

    QString utf16pron = pronToHtml(wordInfo.pron);
    qDebug() << utf16pron;
    QString pron = " [ " +utf16pron + " ] ";

    // TODO: copy mp3 from zip
#if 0
    QFileInfo fileInfo(outFile);
    QString mp3path = fileInfo.baseName()+"_files/Elements";

    Util::downloadFile(wordInfo.audio, mp3path); // down mp3
#endif
//    QTextCodec *gbk = QTextCodec::codecForName("GB18030");
//    QTextCodec *utf8 = QTextCodec::codecForName("UTF-8");
//    QString g2u = gbk->toUnicode(gbk->fromUnicode(wordInfo.pron));
//    qDebug()<< wordInfo.pron<<"    GBK -> UTF-8     " << g2u<<endl;
//    QString cn = wordInfo.cn;
//    QStringList cnList = cn.split("\n");

    QString answer;

//    QString answer_pron = answer_head +pron+ br;
//    answer.append(answer_pron + "\r\n");
//    foreach (QString onecn, cnList) {
//        QString oneAnswer = answer_head + onecn + br;
//        answer.append(oneAnswer + "\r\n");
//    }
#if 0
    answer = highlightSentence+br       //  If you describe something as immoderate, you disapprove of it because it is too extreme.
            +collinsInfo.cn+br          // 极端的;不合理的
            +collinsInfo.st+br          // ADJ-GRADED	能被表示程度的副词或介词词组修饰的形容词
            +pron+br                    // [immoderate]
            +collinsInfo.grammer+br     // 【搭配模式】：usu ADJ n【语用信息】：disapproval【语域标签】：FORMAL 正式
            +collinsInfo.explain+br     // in BRIT, also use 英国英语亦用 characterise
            +collinsInfo.usagenote;     // Usage Note :In British English, a person's weight is normally measured in stones and pounds.
                                        //A stone is equivalent to 14 pounds, or 6.35 kilograms...
#else

    answer = highlightWord(word,word) + "  "
            + pron + multiSpace(80)
            + collinsInfo.cn + br + br
            + example;
#endif
    unit.setQuestion(Question(question));
    unit.setAnswer(Answer(answer));

    //            QString pron;
//            ShanbayWordInfo wordInfo = Shanbay::instance()->getWordInfo(word);

//            QString utf16pron = pronToHtml(wordInfo.pron);
//            qDebug() << utf16pron;
//            QString pron = " [ " +utf16pron + " ] ";

//            // TODO: copy mp3 from zip

//            QFileInfo fileInfo(outFile);
//            QString mp3path = fileInfo.baseName()+"_files/Elements";
//            Util::downloadFile(wordInfo.audio, mp3path); // down mp3
//            QString name = wordInfo.word;
//            QString audio = wordInfo.audio;
//            int audioIndex = audio.lastIndexOf("/");
//            audio = audio.mid(audioIndex + 1);
//            QString url = "[SecondaryStorage]\\"+ audio;
//            qDebug() << "mp3name"<<url;
    Sound sound;
    QString audio = wordInfo.audio;
    int audioIndex = audio.lastIndexOf("/");
    audio = audio.mid(audioIndex + 1);
    QString url = "[SecondaryStorage]\\"+ audio;

    sound.setUrl(url);
    sound.setName("");
    sound.setText(pron);
    QUrl sourceUrl = wordInfo.audio;
    QFileInfo fileinfo("./shanbaymp3/" + audio );
    if (fileinfo.exists()) {
        sourceUrl = QUrl::fromLocalFile("./shanbaymp3/" + audio );
    }
    sound.setSource(sourceUrl);
    unit.setSound(sound);
    return unit;
}

CollinsWordToMemo::CollinsWordToMemo(CovertStrategy *strategy) : covertStrategy_(strategy)
{
    assert(covertStrategy_);
}

void CollinsWordToMemo::addWord(const QString &word)
{
    wordList_.append(word);
}

void CollinsWordToMemo::addWordList(const QStringList &list)
{
    wordList_.append(list);
}

void CollinsWordToMemo::setCovertStrategy(CovertStrategy *strategy)
{
    covertStrategy_ = strategy;
}

QSharedPointer<MemoCollection> CollinsWordToMemo::makeCollection()
{
    QSharedPointer<MemoCollection> collection(new MemoCollection);
    Q_FOREACH(const QString& word, wordList_) {
        QList<CollinsInfo> infoList = COLLINS->zhCollins(word);
        Q_FOREACH(const CollinsInfo& info, infoList) {
            MemoUnit unit = covertStrategy_->covertToMemoUnit(info);
            collection->addMemoUnit(unit);
        }
    }
    return collection;
}

<|endoftext|>


<commit_before>/* bzflag
* Copyright (c) 1993 - 2007 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

// interface header
#include "StandardTankAvatar.h"
#include "BZDBCache.h"
#include "SceneRenderer.h"
#include "TextureManager.h"
#include "Team.h"
#include "OpenGLMaterial.h"

StandardTankAvatar::StandardTankAvatar ( int playerID, const float pos[3], const float forward[3] )
{
  tankNode = new TankSceneNode(pos,forward);
  IDLNode = new TankIDLSceneNode(tankNode);

  const float sphereRad = (1.5f * BZDBCache::tankRadius);
  if (RENDERER.useQuality() >= _HIGH_QUALITY) {
    pausedSphere = new SphereLodSceneNode(pos, sphereRad);
  } else {
    pausedSphere = new SphereBspSceneNode(pos, sphereRad);
  }
  pausedSphere->setColor(0.0f, 0.0f, 0.0f, 0.5f);
  lastVisualTeam = NoTeam;
  tankTexture = -1;
}

StandardTankAvatar::~StandardTankAvatar ( void )
{
  if (IDLNode)
    delete(IDLNode);

  if (tankNode)
    delete(tankNode);
}

void StandardTankAvatar::move ( const float pos[3], const float forward[3] )
{
  tankNode->move(pos,forward);
}

void StandardTankAvatar::moveIDL ( const float plane[4] )
{
  IDLNode->move(plane);
}

void StandardTankAvatar::movePause ( const float pos[3], float rad )
{
  pausedSphere->move(pos,rad);
}

void StandardTankAvatar::setTurnOffsets ( const float left, const float right )
{
  tankNode->addTreadOffsets(left,right);
}

void StandardTankAvatar::setScale ( const float scale[3])
{
  tankNode->setDimensions(scale);
}

void StandardTankAvatar::setScale ( teAvatarScaleModes mode )
{
  switch (mode)
  {
    case eNormal:
      tankNode->setNormal();
      break;
    case eFat:
      tankNode->setObese();
      break;
    case eTiny:
      tankNode->setTiny();
      break;
    case eThin:
      tankNode->setNarrow();
      break;
    case eThief:
      tankNode->setThief();
      break;
  }
}

void StandardTankAvatar::explode ( void )
{
  tankNode->rebuildExplosion();
}

void StandardTankAvatar::setVisualTeam (TeamColor visualTeam, const float color[4] )
{
  // only do all this junk when the effective team color actually changes
  if (visualTeam == lastVisualTeam)
    return;
  lastVisualTeam = visualTeam;

  static const GLfloat	tankSpecular[3] = { 0.1f, 0.1f, 0.1f };
  static GLfloat	tankEmissive[3] = { 0.0f, 0.0f, 0.0f };
  static float		tankShininess = 20.0f;
  static GLfloat	rabbitEmissive[3] = { 0.0f, 0.0f, 0.0f };
  static float		rabbitShininess = 100.0f;

  GLfloat *emissive;
  GLfloat shininess;

  if (visualTeam == RabbitTeam) {
    emissive = rabbitEmissive;
    shininess = rabbitShininess;
  } else {
    emissive = tankEmissive;
    shininess = tankShininess;
  }

  TextureManager &tm = TextureManager::instance();
  std::string texName;
  texName = Team::getImagePrefix(visualTeam);

  texName += BZDB.get("tankTexture");

  // now after we did all that, see if they have a user texture
  tankTexture = tm.getTextureID(texName.c_str(),false);

  tankNode->setMaterial(OpenGLMaterial(tankSpecular, emissive, shininess));
  tankNode->setTexture(tankTexture);

  int jumpJetsTexture = tm.getTextureID("jumpjets", false);
  tankNode->setJumpJetsTexture(jumpJetsTexture);

  tankNode->setColor(color);

  // reset the clipping plane
  tankNode->setClipPlane(NULL);

  tankNode->setJumpJets(0.0f);
}

void StandardTankAvatar::setColor ( const float color[4] )
{
  tankNode->setColor(color);
}

void StandardTankAvatar::setVisualMode ( bool inCockpit, bool showTreads )
{
  // setup the visibility properties
  if (inCockpit && !showTreads)
    tankNode->setOnlyShadows(true);
  else
    tankNode->setOnlyShadows(false);

  tankNode->setInTheCockpit(inCockpit);
}

void StandardTankAvatar::setAnimationValues ( float explodeParam, float jumpParam )
{
  tankNode->setExplodeFraction(explodeParam);
  tankNode->setJumpJets(jumpParam);
}

void StandardTankAvatar::setClipingPlane (  const float plane[4] )
{
  tankNode->setClipPlane(plane);
}

std::vector<SceneNode*> StandardTankAvatar::getSceneNodes ( void )
{
  std::vector<SceneNode*> l;
  l.push_back(tankNode);
  return l;
}

std::vector<SceneNode*> StandardTankAvatar::getIDLSceneNodes ( void )
{
  std::vector<SceneNode*> l;
  l.push_back(IDLNode);
  return l;
}

std::vector<SceneNode*> StandardTankAvatar::getPauseSceneNodes ( void )
{
  std::vector<SceneNode*> l;
  l.push_back(pausedSphere);
  return l;
}

void StandardTankAvatar::renderRadar ( void )
{
  tankNode->renderRadar();
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>delete the paused sphere when the avatar is done.<commit_after>/* bzflag
* Copyright (c) 1993 - 2007 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

// interface header
#include "StandardTankAvatar.h"
#include "BZDBCache.h"
#include "SceneRenderer.h"
#include "TextureManager.h"
#include "Team.h"
#include "OpenGLMaterial.h"

StandardTankAvatar::StandardTankAvatar ( int playerID, const float pos[3], const float forward[3] )
{
  tankNode = new TankSceneNode(pos,forward);
  IDLNode = new TankIDLSceneNode(tankNode);

  const float sphereRad = (1.5f * BZDBCache::tankRadius);
  if (RENDERER.useQuality() >= _HIGH_QUALITY) {
    pausedSphere = new SphereLodSceneNode(pos, sphereRad);
  } else {
    pausedSphere = new SphereBspSceneNode(pos, sphereRad);
  }
  pausedSphere->setColor(0.0f, 0.0f, 0.0f, 0.5f);
  lastVisualTeam = NoTeam;
  tankTexture = -1;
}

StandardTankAvatar::~StandardTankAvatar ( void )
{
  if (IDLNode)
    delete(IDLNode);

  if (tankNode)
    delete(tankNode);

  if (pausedSphere)
    delete(pausedSphere);
}

void StandardTankAvatar::move ( const float pos[3], const float forward[3] )
{
  tankNode->move(pos,forward);
}

void StandardTankAvatar::moveIDL ( const float plane[4] )
{
  IDLNode->move(plane);
}

void StandardTankAvatar::movePause ( const float pos[3], float rad )
{
  pausedSphere->move(pos,rad);
}

void StandardTankAvatar::setTurnOffsets ( const float left, const float right )
{
  tankNode->addTreadOffsets(left,right);
}

void StandardTankAvatar::setScale ( const float scale[3])
{
  tankNode->setDimensions(scale);
}

void StandardTankAvatar::setScale ( teAvatarScaleModes mode )
{
  switch (mode)
  {
    case eNormal:
      tankNode->setNormal();
      break;
    case eFat:
      tankNode->setObese();
      break;
    case eTiny:
      tankNode->setTiny();
      break;
    case eThin:
      tankNode->setNarrow();
      break;
    case eThief:
      tankNode->setThief();
      break;
  }
}

void StandardTankAvatar::explode ( void )
{
  tankNode->rebuildExplosion();
}

void StandardTankAvatar::setVisualTeam (TeamColor visualTeam, const float color[4] )
{
  // only do all this junk when the effective team color actually changes
  if (visualTeam == lastVisualTeam)
    return;
  lastVisualTeam = visualTeam;

  static const GLfloat	tankSpecular[3] = { 0.1f, 0.1f, 0.1f };
  static GLfloat	tankEmissive[3] = { 0.0f, 0.0f, 0.0f };
  static float		tankShininess = 20.0f;
  static GLfloat	rabbitEmissive[3] = { 0.0f, 0.0f, 0.0f };
  static float		rabbitShininess = 100.0f;

  GLfloat *emissive;
  GLfloat shininess;

  if (visualTeam == RabbitTeam) {
    emissive = rabbitEmissive;
    shininess = rabbitShininess;
  } else {
    emissive = tankEmissive;
    shininess = tankShininess;
  }

  TextureManager &tm = TextureManager::instance();
  std::string texName;
  texName = Team::getImagePrefix(visualTeam);

  texName += BZDB.get("tankTexture");

  // now after we did all that, see if they have a user texture
  tankTexture = tm.getTextureID(texName.c_str(),false);

  tankNode->setMaterial(OpenGLMaterial(tankSpecular, emissive, shininess));
  tankNode->setTexture(tankTexture);

  int jumpJetsTexture = tm.getTextureID("jumpjets", false);
  tankNode->setJumpJetsTexture(jumpJetsTexture);

  tankNode->setColor(color);

  // reset the clipping plane
  tankNode->setClipPlane(NULL);

  tankNode->setJumpJets(0.0f);
}

void StandardTankAvatar::setColor ( const float color[4] )
{
  tankNode->setColor(color);
}

void StandardTankAvatar::setVisualMode ( bool inCockpit, bool showTreads )
{
  // setup the visibility properties
  if (inCockpit && !showTreads)
    tankNode->setOnlyShadows(true);
  else
    tankNode->setOnlyShadows(false);

  tankNode->setInTheCockpit(inCockpit);
}

void StandardTankAvatar::setAnimationValues ( float explodeParam, float jumpParam )
{
  tankNode->setExplodeFraction(explodeParam);
  tankNode->setJumpJets(jumpParam);
}

void StandardTankAvatar::setClipingPlane (  const float plane[4] )
{
  tankNode->setClipPlane(plane);
}

std::vector<SceneNode*> StandardTankAvatar::getSceneNodes ( void )
{
  std::vector<SceneNode*> l;
  l.push_back(tankNode);
  return l;
}

std::vector<SceneNode*> StandardTankAvatar::getIDLSceneNodes ( void )
{
  std::vector<SceneNode*> l;
  l.push_back(IDLNode);
  return l;
}

std::vector<SceneNode*> StandardTankAvatar::getPauseSceneNodes ( void )
{
  std::vector<SceneNode*> l;
  l.push_back(pausedSphere);
  return l;
}

void StandardTankAvatar::renderRadar ( void )
{
  tankNode->renderRadar();
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// Provide BZFS with a list server connection

/* class header */
#include "ListServerConnection.h"

/* system implementation headers */
#include <string.h>
#include <string>
#include <math.h>
#include <errno.h>

/* common implementation headers */
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "Protocol.h"

extern Address serverAddress;
extern PingPacket getTeamCounts();

ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle)
{
  // parse url
  std::string protocol, hostname, pathname;
  int port = 80;
  bool useDefault = false;

  // use default if it can't be parsed
  if (!BzfNetwork::parseURL(listServerURL, protocol, hostname, port, pathname))
    useDefault = true;

  // use default if wrong protocol or invalid port
  if ((protocol != "http") || (port < 1) || (port > 65535))
    useDefault = true;

  // use default if bad address
  Address address = Address::getHostAddress(hostname);
  if (address.isAny())
    useDefault = true;

  // parse default list server URL if we need to; assume default works
  if (useDefault) {
    BzfNetwork::parseURL(DefaultListServerURL, protocol, hostname, port, pathname);
    DEBUG1("Provided list server URL (%s) is invalid.  Using default of %s.\n", listServerURL.c_str(), DefaultListServerURL);
  }

  // add to list
  this->address	   = address;
  this->port	   = port;
  this->pathname   = pathname;
  this->hostname   = hostname;
  this->linkSocket = NotConnected;

  this->publicizeAddress     = publicizedAddress;
  this->publicizeDescription = publicizedTitle;
  this->publicizeServer	     = true;  //if this c'tor is called, it's safe to publicize

  // schedule initial ADD message
  queueMessage(ListServerLink::ADD);
}

ListServerLink::ListServerLink()
{
  // does not create a usable link, so checks should be placed
  // in  all public member functions to ensure that nothing tries
  // to happen if publicizeServer is false
  this->linkSocket = NotConnected;
  this->publicizeServer = false;
}

ListServerLink::~ListServerLink()
{
  // now tell the list server that we're going away.  this can
  // take some time but we don't want to wait too long.  we do
  // our own multiplexing loop and wait for a maximum of 3 seconds
  // total.

  // if we aren't supposed to be publicizing, skip the whole thing
  // and don't waste 3 seconds.
  if (!publicizeServer)
    return;

  queueMessage(ListServerLink::REMOVE);
  TimeKeeper start = TimeKeeper::getCurrent();
  do {
    // compute timeout
    float waitTime = 3.0f - (TimeKeeper::getCurrent() - start);
    if (waitTime <= 0.0f)
      break;
    if (!isConnected()) //queueMessage should have connected us
      break;
    // check for list server socket connection
    int fdMax = -1;
    fd_set write_set;
    fd_set read_set;
    FD_ZERO(&write_set);
    FD_ZERO(&read_set);
    if (phase == ListServerLink::CONNECTING)
      _FD_SET(linkSocket, &write_set);
    else
      _FD_SET(linkSocket, &read_set);
    fdMax = linkSocket;

    // wait for socket to connect or timeout
    struct timeval timeout;
    timeout.tv_sec = long(floorf(waitTime));
    timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime)));
    int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set,
			0, &timeout);
    if (nfound == 0)
      // Time has gone, close and go
      break;
    // check for connection to list server
    if (FD_ISSET(linkSocket, &write_set))
      sendQueuedMessages();
    else if (FD_ISSET(linkSocket, &read_set))
      read();
  } while (true);

  // stop list server communication
  closeLink();
}

void ListServerLink::closeLink()
{
  if (isConnected()) {
    close(linkSocket);
    DEBUG4("Closing List Server\n");
    linkSocket = NotConnected;
  }
}

void ListServerLink::read()
{
  if (isConnected()) {
    char    buf[256];
    recv(linkSocket, buf, sizeof(buf), 0);
    closeLink();
    if (nextMessageType != ListServerLink::NONE)
      // There was a pending request arrived after we write:
      // we should redo all the stuff
      openLink();
  }
}

void ListServerLink::openLink()
{
  // start opening connection if not already doing so
  if (!isConnected()) {
    linkSocket = socket(AF_INET, SOCK_STREAM, 0);
    DEBUG4("Opening List Server\n");
    if (!isConnected()) {
      return;
    }

    // set to non-blocking for connect
    if (BzfNetwork::setNonBlocking(linkSocket) < 0) {
      closeLink();
      return;
    }

    // Make our connection come from our serverAddress in case we have
    // multiple/masked IPs so the list server can verify us.
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr = serverAddress;

    // assign the address to the socket
    if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
      closeLink();
      return;
    }

    // connect.  this should fail with EINPROGRESS but check for
    // success just in case.
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port   = htons(port);
    addr.sin_addr   = address;
    if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
#if defined(_WIN32)
#undef EINPROGRESS
#define EINPROGRESS EWOULDBLOCK
#endif
      if (getErrno() != EINPROGRESS) {
	nerror("connecting to list server");
	// try to lookup dns name again in case it moved
	this->address = Address::getHostAddress(this->hostname);
	closeLink();
      } else {
	phase = CONNECTING;
      }
    } else {
      // shouldn't arrive here. Just in case, clean
      closeLink();
    }
  }
}

void ListServerLink::queueMessage(MessageType type)
{
  // ignore if the server is not public
  if (!publicizeServer) return;

  // Open network connection only if closed
  if (!isConnected()) openLink();

  // record next message to send.
  nextMessageType = type;
}

void ListServerLink::sendQueuedMessages()
{
  if (!isConnected())
    return;

  if (nextMessageType == ListServerLink::ADD) {
    DEBUG3("Queuing ADD message to list server\n");
    addMe(getTeamCounts(), publicizeAddress, TextUtils::url_encode(publicizeDescription));
    lastAddTime = TimeKeeper::getCurrent();
  } else if (nextMessageType == ListServerLink::REMOVE) {
    DEBUG3("Queuing REMOVE message to list server\n");
    removeMe(publicizeAddress);
  }
}

void ListServerLink::addMe(PingPacket pingInfo,
			   std::string publicizedAddress,
			   std::string publicizedTitle)
{
  std::string msg;

  // encode ping reply as ascii hex digits plus NULL
  char gameInfo[PingPacketHexPackedSize + 1];
  pingInfo.packHex(gameInfo);

  // TODO loop through and send any player tokens that need approval
  // TODO loop through groups we are interested and request those too
  // TODO we probably should convert to a POST instead. List server now allows either
  // send ADD message (must send blank line)
  msg = TextUtils::format("GET %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s&title=%s HTTP/1.1\r\n"
    "Host: %s\r\nCache-Control: no-cache\r\n\r\n",
    pathname.c_str(), publicizedAddress.c_str(),
    getServerVersion(), gameInfo,
    getAppVersion(),
    publicizedTitle.c_str(),
    hostname.c_str());
  // TODO need to listen for user info replies and setup callsign for isAllowedToEnter()
  sendMessage(msg);
}

void ListServerLink::removeMe(std::string publicizedAddress)
{
  std::string msg;
  // send REMOVE (must send blank line)
  msg = TextUtils::format("GET %s?action=REMOVE&nameport=%s HTTP/1.1\r\n"
    "Host: %s\r\nCache-Control: no-cache\r\n\r\n",
    pathname.c_str(),
    publicizedAddress.c_str(),
    hostname.c_str());
  sendMessage(msg);
}

void ListServerLink::sendMessage(std::string message)
{
  const int bufsize = 4096;
  char msg[bufsize];
  strncpy(msg, message.c_str(), bufsize);
  msg[bufsize - 1] = 0;
  if (strlen(msg) > 0) {
    DEBUG3("%s\n", msg);
    if (send(linkSocket, msg, strlen(msg), 0) == -1) {
      perror("List server send failed");
      DEBUG3("Unable to send to the list server!\n");
      closeLink();
    } else {
      nextMessageType = ListServerLink::NONE;
      phase	   = ListServerLink::WRITTEN;
    }
  } else {
    closeLink();
  }
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>comments on next steps for authentication<commit_after>/* bzflag
 * Copyright (c) 1993 - 2004 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// Provide BZFS with a list server connection

/* class header */
#include "ListServerConnection.h"

/* system implementation headers */
#include <string.h>
#include <string>
#include <math.h>
#include <errno.h>

/* common implementation headers */
#include "bzfio.h"
#include "version.h"
#include "TextUtils.h"
#include "Protocol.h"

extern Address serverAddress;
extern PingPacket getTeamCounts();

ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle)
{
  // parse url
  std::string protocol, hostname, pathname;
  int port = 80;
  bool useDefault = false;

  // use default if it can't be parsed
  if (!BzfNetwork::parseURL(listServerURL, protocol, hostname, port, pathname))
    useDefault = true;

  // use default if wrong protocol or invalid port
  if ((protocol != "http") || (port < 1) || (port > 65535))
    useDefault = true;

  // use default if bad address
  Address address = Address::getHostAddress(hostname);
  if (address.isAny())
    useDefault = true;

  // parse default list server URL if we need to; assume default works
  if (useDefault) {
    BzfNetwork::parseURL(DefaultListServerURL, protocol, hostname, port, pathname);
    DEBUG1("Provided list server URL (%s) is invalid.  Using default of %s.\n", listServerURL.c_str(), DefaultListServerURL);
  }

  // add to list
  this->address	   = address;
  this->port	   = port;
  this->pathname   = pathname;
  this->hostname   = hostname;
  this->linkSocket = NotConnected;

  this->publicizeAddress     = publicizedAddress;
  this->publicizeDescription = publicizedTitle;
  this->publicizeServer	     = true;  //if this c'tor is called, it's safe to publicize

  // schedule initial ADD message
  queueMessage(ListServerLink::ADD);
}

ListServerLink::ListServerLink()
{
  // does not create a usable link, so checks should be placed
  // in  all public member functions to ensure that nothing tries
  // to happen if publicizeServer is false
  this->linkSocket = NotConnected;
  this->publicizeServer = false;
}

ListServerLink::~ListServerLink()
{
  // now tell the list server that we're going away.  this can
  // take some time but we don't want to wait too long.  we do
  // our own multiplexing loop and wait for a maximum of 3 seconds
  // total.

  // if we aren't supposed to be publicizing, skip the whole thing
  // and don't waste 3 seconds.
  if (!publicizeServer)
    return;

  queueMessage(ListServerLink::REMOVE);
  TimeKeeper start = TimeKeeper::getCurrent();
  do {
    // compute timeout
    float waitTime = 3.0f - (TimeKeeper::getCurrent() - start);
    if (waitTime <= 0.0f)
      break;
    if (!isConnected()) //queueMessage should have connected us
      break;
    // check for list server socket connection
    int fdMax = -1;
    fd_set write_set;
    fd_set read_set;
    FD_ZERO(&write_set);
    FD_ZERO(&read_set);
    if (phase == ListServerLink::CONNECTING)
      _FD_SET(linkSocket, &write_set);
    else
      _FD_SET(linkSocket, &read_set);
    fdMax = linkSocket;

    // wait for socket to connect or timeout
    struct timeval timeout;
    timeout.tv_sec = long(floorf(waitTime));
    timeout.tv_usec = long(1.0e+6f * (waitTime - floorf(waitTime)));
    int nfound = select(fdMax + 1, (fd_set*)&read_set, (fd_set*)&write_set,
			0, &timeout);
    if (nfound == 0)
      // Time has gone, close and go
      break;
    // check for connection to list server
    if (FD_ISSET(linkSocket, &write_set))
      sendQueuedMessages();
    else if (FD_ISSET(linkSocket, &read_set))
      read();
  } while (true);

  // stop list server communication
  closeLink();
}

void ListServerLink::closeLink()
{
  if (isConnected()) {
    close(linkSocket);
    DEBUG4("Closing List Server\n");
    linkSocket = NotConnected;
  }
}

void ListServerLink::read()
{
  if (isConnected()) {
    char    buf[256];
    recv(linkSocket, buf, sizeof(buf), 0);
    closeLink();
    if (nextMessageType != ListServerLink::NONE)
      // There was a pending request arrived after we write:
      // we should redo all the stuff
      openLink();
  }
}

void ListServerLink::openLink()
{
  // start opening connection if not already doing so
  if (!isConnected()) {
    linkSocket = socket(AF_INET, SOCK_STREAM, 0);
    DEBUG4("Opening List Server\n");
    if (!isConnected()) {
      return;
    }

    // set to non-blocking for connect
    if (BzfNetwork::setNonBlocking(linkSocket) < 0) {
      closeLink();
      return;
    }

    // Make our connection come from our serverAddress in case we have
    // multiple/masked IPs so the list server can verify us.
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr = serverAddress;

    // assign the address to the socket
    if (bind(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
      closeLink();
      return;
    }

    // connect.  this should fail with EINPROGRESS but check for
    // success just in case.
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port   = htons(port);
    addr.sin_addr   = address;
    if (connect(linkSocket, (CNCTType*)&addr, sizeof(addr)) < 0) {
#if defined(_WIN32)
#undef EINPROGRESS
#define EINPROGRESS EWOULDBLOCK
#endif
      if (getErrno() != EINPROGRESS) {
	nerror("connecting to list server");
	// try to lookup dns name again in case it moved
	this->address = Address::getHostAddress(this->hostname);
	closeLink();
      } else {
	phase = CONNECTING;
      }
    } else {
      // shouldn't arrive here. Just in case, clean
      closeLink();
    }
  }
}

void ListServerLink::queueMessage(MessageType type)
{
  // ignore if the server is not public
  if (!publicizeServer) return;

  // Open network connection only if closed
  if (!isConnected()) openLink();

  // record next message to send.
  nextMessageType = type;
}

void ListServerLink::sendQueuedMessages()
{
  if (!isConnected())
    return;

  if (nextMessageType == ListServerLink::ADD) {
    DEBUG3("Queuing ADD message to list server\n");
    addMe(getTeamCounts(), publicizeAddress, TextUtils::url_encode(publicizeDescription));
    lastAddTime = TimeKeeper::getCurrent();
  } else if (nextMessageType == ListServerLink::REMOVE) {
    DEBUG3("Queuing REMOVE message to list server\n");
    removeMe(publicizeAddress);
  }
}

void ListServerLink::addMe(PingPacket pingInfo,
			   std::string publicizedAddress,
			   std::string publicizedTitle)
{
  std::string msg;

  // encode ping reply as ascii hex digits plus NULL
  char gameInfo[PingPacketHexPackedSize + 1];
  pingInfo.packHex(gameInfo);

  // TODO loop through and send any player tokens that need approval
  // confirm=callsign0%3D1%3A123123123%0D%0Acallsign1%3D1%3A123123123%0D%0A
  // TODO loop through groups we are interested and request those too
  // TODO we probably should convert to a POST instead. List server now allows either
  // send ADD message (must send blank line)
  msg = TextUtils::format("GET %s?action=ADD&nameport=%s&version=%s&gameinfo=%s&build=%s&title=%s HTTP/1.1\r\n"
    "Host: %s\r\nCache-Control: no-cache\r\n\r\n",
    pathname.c_str(), publicizedAddress.c_str(),
    getServerVersion(), gameInfo,
    getAppVersion(),
    publicizedTitle.c_str(),
    hostname.c_str());
  // TODO need to listen for user info replies and setup callsign for isAllowedToEnter()
  sendMessage(msg);
}

void ListServerLink::removeMe(std::string publicizedAddress)
{
  std::string msg;
  // send REMOVE (must send blank line)
  msg = TextUtils::format("GET %s?action=REMOVE&nameport=%s HTTP/1.1\r\n"
    "Host: %s\r\nCache-Control: no-cache\r\n\r\n",
    pathname.c_str(),
    publicizedAddress.c_str(),
    hostname.c_str());
  sendMessage(msg);
}

void ListServerLink::sendMessage(std::string message)
{
  const int bufsize = 4096;
  char msg[bufsize];
  strncpy(msg, message.c_str(), bufsize);
  msg[bufsize - 1] = 0;
  if (strlen(msg) > 0) {
    DEBUG3("%s\n", msg);
    if (send(linkSocket, msg, strlen(msg), 0) == -1) {
      perror("List server send failed");
      DEBUG3("Unable to send to the list server!\n");
      closeLink();
    } else {
      nextMessageType = ListServerLink::NONE;
      phase	   = ListServerLink::WRITTEN;
    }
  } else {
    closeLink();
  }
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * 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: dp_script.cxx,v $
 * $Revision: 1.13 $
 *
 * 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_desktop.hxx"

#include "dp_script.hrc"
#include "dp_lib_container.h"
#include "dp_backend.h"
#include "dp_ucb.h"
#include "rtl/uri.hxx"
#include "ucbhelper/content.hxx"
#include "cppuhelper/exc_hlp.hxx"
#include "cppuhelper/implbase1.hxx"
#include "comphelper/servicedecl.hxx"
#include "svtools/inettype.hxx"
#include "com/sun/star/util/XUpdatable.hpp"
#include "com/sun/star/script/XLibraryContainer.hpp"
#include <memory>

using namespace ::dp_misc;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using ::rtl::OUString;
namespace css = ::com::sun::star;

namespace dp_registry {
namespace backend {
namespace script {
namespace {

typedef ::cppu::ImplInheritanceHelper1<
    ::dp_registry::backend::PackageRegistryBackend, util::XUpdatable > t_helper;

//==============================================================================
class BackendImpl : public t_helper
{
    class PackageImpl : public ::dp_registry::backend::Package
    {
        BackendImpl * getMyBackend() const {
            return static_cast<BackendImpl *>(m_myBackend.get());
        }

        const OUString m_scriptURL;
        const OUString m_dialogURL;
        OUString m_dialogName;

        // Package
        virtual beans::Optional< beans::Ambiguous<sal_Bool> > isRegistered_(
            ::osl::ResettableMutexGuard & guard,
            ::rtl::Reference<AbortChannel> const & abortChannel,
            Reference<XCommandEnvironment> const & xCmdEnv );
        virtual void processPackage_(
            ::osl::ResettableMutexGuard & guard,
            bool registerPackage,
            ::rtl::Reference<AbortChannel> const & abortChannel,
            Reference<XCommandEnvironment> const & xCmdEnv );

    public:
        PackageImpl(
            ::rtl::Reference<BackendImpl> const & myBackend,
            OUString const & url,
            Reference<XCommandEnvironment> const &xCmdEnv,
            OUString const & scriptURL, OUString const & dialogURL );
    };
    friend class PackageImpl;

    // PackageRegistryBackend
    virtual Reference<deployment::XPackage> bindPackage_(
        OUString const & url, OUString const & mediaType,
        Reference<XCommandEnvironment> const & xCmdEnv );

    Reference<css::script::XLibraryContainer> m_xScriptLibs;
    Reference<css::script::XLibraryContainer> m_xDialogLibs;
    ::std::auto_ptr<LibraryContainer> m_basic_script_libs;
    ::std::auto_ptr<LibraryContainer> m_dialog_libs;

    const Reference<deployment::XPackageTypeInfo> m_xBasicLibTypeInfo;
    const Reference<deployment::XPackageTypeInfo> m_xDialogLibTypeInfo;
    Sequence< Reference<deployment::XPackageTypeInfo> > m_typeInfos;

public:
    BackendImpl( Sequence<Any> const & args,
                 Reference<XComponentContext> const & xComponentContext );

    // XUpdatable
    virtual void SAL_CALL update() throw (RuntimeException);

    // XPackageRegistry
    virtual Sequence< Reference<deployment::XPackageTypeInfo> > SAL_CALL
    getSupportedPackageTypes() throw (RuntimeException);
};

//______________________________________________________________________________
BackendImpl::PackageImpl::PackageImpl(
    ::rtl::Reference<BackendImpl> const & myBackend,
    OUString const & url,
    Reference<XCommandEnvironment> const &xCmdEnv,
    OUString const & scriptURL, OUString const & dialogURL )
    : Package( myBackend.get(), url,
               OUString(), OUString(), // will be late-initialized
               scriptURL.getLength() > 0 ? myBackend->m_xBasicLibTypeInfo
                                         : myBackend->m_xDialogLibTypeInfo ),
      m_scriptURL( scriptURL ),
      m_dialogURL( dialogURL )
{
    // name, displayName:
    if (dialogURL.getLength() > 0) {
        m_dialogName = LibraryContainer::get_libname(
            dialogURL, xCmdEnv, myBackend->getComponentContext() );
    }
    if (scriptURL.getLength() > 0) {
        m_name = LibraryContainer::get_libname(
            scriptURL, xCmdEnv, myBackend->getComponentContext() );
    }
    else
        m_name = m_dialogName;
    m_displayName = m_name;
}

//______________________________________________________________________________
BackendImpl::BackendImpl(
    Sequence<Any> const & args,
    Reference<XComponentContext> const & xComponentContext )
    : t_helper( args, xComponentContext ),
      m_xBasicLibTypeInfo( new Package::TypeInfo(
                               OUSTR("application/"
                                     "vnd.sun.star.basic-library"),
                               OUString() /* no file filter */,
                               getResourceString(RID_STR_BASIC_LIB),
                               RID_IMG_SCRIPTLIB, RID_IMG_SCRIPTLIB_HC ) ),
      m_xDialogLibTypeInfo( new Package::TypeInfo(
                                OUSTR("application/"
                                      "vnd.sun.star.dialog-library"),
                                OUString() /* no file filter */,
                                getResourceString(RID_STR_DIALOG_LIB),
                                RID_IMG_DIALOGLIB, RID_IMG_DIALOGLIB_HC ) ),
      m_typeInfos( 2 )
{
    m_typeInfos[ 0 ] = m_xBasicLibTypeInfo;
    m_typeInfos[ 1 ] = m_xDialogLibTypeInfo;

    OSL_ASSERT( ! transientMode() );
    if (office_is_running())
    {
        m_xScriptLibs.set(
            xComponentContext->getServiceManager()->createInstanceWithContext(
                OUSTR("com.sun.star.script.ApplicationScriptLibraryContainer"),
                xComponentContext ), UNO_QUERY_THROW );
        m_xDialogLibs.set(
            xComponentContext->getServiceManager()->createInstanceWithContext(
                OUSTR("com.sun.star.script.ApplicationDialogLibraryContainer"),
                xComponentContext ), UNO_QUERY_THROW );
    }
    else
    {
        OUString basic_path(
            m_eContext == CONTEXT_USER
            ? OUSTR("vnd.sun.star.expand:${$BRAND_BASE_DIR/program/"
                    SAL_CONFIGFILE("bootstrap")
                    ":UserInstallation}/user/basic")
            : OUSTR("vnd.sun.star.expand:${$BRAND_BASE_DIR/program/"
                    SAL_CONFIGFILE("bootstrap")
                    ":BaseInstallation}/share/basic") );
        m_basic_script_libs.reset(
            new LibraryContainer(
                makeURL( basic_path, OUSTR("script.xlc") ),
                getMutex(),
                xComponentContext ) );
        m_dialog_libs.reset(
            new LibraryContainer(
                makeURL( basic_path, OUSTR("dialog.xlc") ),
                getMutex(),
                xComponentContext ) );
    }
}

// XUpdatable
//______________________________________________________________________________
void BackendImpl::update() throw (RuntimeException)
{
    const Reference<XCommandEnvironment> xCmdEnv;
    if (m_basic_script_libs.get() != 0) {
        try {
            m_basic_script_libs->init(xCmdEnv);
            m_basic_script_libs->flush(xCmdEnv);
        }
        catch (RuntimeException &) {
            throw;
        }
        catch (Exception & exc) {
            (void) exc;
            OSL_ENSURE( 0, ::rtl::OUStringToOString(
                            exc.Message, RTL_TEXTENCODING_UTF8 ).getStr() );
        }
    }
    if (m_dialog_libs.get() != 0) {
        try {
            m_dialog_libs->init(xCmdEnv);
            m_dialog_libs->flush(xCmdEnv);
        }
        catch (RuntimeException &) {
            throw;
        }
        catch (Exception & exc) {
            (void) exc;
            OSL_ENSURE( 0, ::rtl::OUStringToOString(
                            exc.Message, RTL_TEXTENCODING_UTF8 ).getStr() );
        }
    }
}

// XPackageRegistry
//______________________________________________________________________________
Sequence< Reference<deployment::XPackageTypeInfo> >
BackendImpl::getSupportedPackageTypes() throw (RuntimeException)
{
    return m_typeInfos;
}

// PackageRegistryBackend
//______________________________________________________________________________
Reference<deployment::XPackage> BackendImpl::bindPackage_(
    OUString const & url, OUString const & mediaType_,
    Reference<XCommandEnvironment> const & xCmdEnv )
{
    OUString mediaType( mediaType_ );
    if (mediaType.getLength() == 0)
    {
        // detect media-type:
        ::ucbhelper::Content ucbContent;
        if (create_ucb_content( &ucbContent, url, xCmdEnv ) &&
            ucbContent.isFolder())
        {
            // probe for script.xlb:
            if (create_ucb_content(
                    0, makeURL( url, OUSTR("script.xlb") ),
                    xCmdEnv, false /* no throw */ ))
                mediaType = OUSTR("application/vnd.sun.star.basic-library");
            // probe for dialog.xlb:
            else if (create_ucb_content(
                         0, makeURL( url, OUSTR("dialog.xlb") ),
                         xCmdEnv, false /* no throw */ ))
                mediaType = OUSTR("application/vnd.sun.star.dialog-library");
        }
        if (mediaType.getLength() == 0)
            throw lang::IllegalArgumentException(
                StrCannotDetectMediaType::get() + url,
                static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );
    }

    String type, subType;
    INetContentTypeParameterList params;
    if (INetContentTypes::parse( mediaType, type, subType, &params ))
    {
        if (type.EqualsIgnoreCaseAscii("application"))
        {
            if (subType.EqualsIgnoreCaseAscii("vnd.sun.star.basic-library"))
            {
                OUString dialogURL( makeURL( url, OUSTR("dialog.xlb") ) );
                if (! create_ucb_content(
                        0, dialogURL, xCmdEnv, false /* no throw */ )) {
                    dialogURL = OUString();
                }
                return new PackageImpl( this, url, xCmdEnv,
                                        makeURL( url, OUSTR("script.xlb") ),
                                        dialogURL );
            }
            else if (subType.EqualsIgnoreCaseAscii(
                         "vnd.sun.star.dialog-library")) {
                return new PackageImpl( this, url, xCmdEnv,
                                        OUString() /* no script lib */,
                                        makeURL( url, OUSTR("dialog.xlb") ) );
            }
        }
    }
    throw lang::IllegalArgumentException(
        StrUnsupportedMediaType::get() + mediaType,
        static_cast<OWeakObject *>(this),
        static_cast<sal_Int16>(-1) );
}

//##############################################################################

// Package
//______________________________________________________________________________
beans::Optional< beans::Ambiguous<sal_Bool> >
BackendImpl::PackageImpl::isRegistered_(
    ::osl::ResettableMutexGuard &,
    ::rtl::Reference<AbortChannel> const &,
    Reference<XCommandEnvironment> const & xCmdEnv )
{
    BackendImpl * that = getMyBackend();
    bool reg = false;
    if (m_scriptURL.getLength() > 0) {
        if (that->m_xScriptLibs.is())
            reg = that->m_xScriptLibs->hasByName( m_name );
        else
            reg = that->m_basic_script_libs->has( m_name, xCmdEnv );
    }
    else {
        if (that->m_xDialogLibs.is())
            reg = that->m_xDialogLibs->hasByName( m_dialogName );
        else
            reg = that->m_dialog_libs->has( m_dialogName, xCmdEnv );
    }
    return beans::Optional< beans::Ambiguous<sal_Bool> >(
        true /* IsPresent */,
        beans::Ambiguous<sal_Bool>( reg, false /* IsAmbiguous */ ) );
}

//______________________________________________________________________________
void BackendImpl::PackageImpl::processPackage_(
    ::osl::ResettableMutexGuard &,
    bool doRegisterPackage,
    ::rtl::Reference<AbortChannel> const &,
    Reference<XCommandEnvironment> const & xCmdEnv )
{
    BackendImpl * that = getMyBackend();
    if (doRegisterPackage)
    {
        if (m_scriptURL.getLength() > 0) {
            if (that->m_xScriptLibs.is())
                that->m_xScriptLibs->createLibraryLink(
                    m_name, m_scriptURL, false /* ! read-only */ );
            else
                that->m_basic_script_libs->insert(
                    m_name, m_scriptURL, xCmdEnv );
        }
        if (m_dialogURL.getLength() > 0) {
            if (that->m_xDialogLibs.is())
                that->m_xDialogLibs->createLibraryLink(
                    m_dialogName, m_dialogURL, false /* ! read-only */ );
            else
                that->m_dialog_libs->insert(
                    m_dialogName, m_dialogURL, xCmdEnv );
        }
    }
    else // revokePackage()
    {
        try {
            if (m_scriptURL.getLength() > 0) {
                if (that->m_xScriptLibs.is())
                    that->m_xScriptLibs->removeLibrary( m_name );
                else
                    that->m_basic_script_libs->remove(
                        m_name, m_scriptURL, xCmdEnv );
            }
            if (m_dialogURL.getLength() > 0) {
                if (that->m_xDialogLibs.is())
                    that->m_xDialogLibs->removeLibrary( m_dialogName );
                else
                    that->m_dialog_libs->remove(
                        m_dialogName, m_dialogURL, xCmdEnv );
            }
        }
        catch (lang::WrappedTargetException & exc) {
            // unwrap WrappedTargetException:
            ::cppu::throwException( exc.TargetException );
        }
    }
}

} // anon namespace

namespace sdecl = comphelper::service_decl;
sdecl::class_<BackendImpl, sdecl::with_args<true> > serviceBI;
extern sdecl::ServiceDecl const serviceDecl(
    serviceBI,
    "com.sun.star.comp.deployment.script.PackageRegistryBackend",
    BACKEND_SERVICE_NAME );

} // namespace script
} // namespace backend
} // namespace dp_registry

<commit_msg>INTEGRATION: CWS jl100_DEV300 (1.11.114); FILE MERGED 2008/05/13 15:08:21 jl 1.11.114.1: #156271# The package::getMyBackend functions now throw a DisposedException<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: dp_script.cxx,v $
 * $Revision: 1.14 $
 *
 * 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_desktop.hxx"

#include "dp_script.hrc"
#include "dp_lib_container.h"
#include "dp_backend.h"
#include "dp_ucb.h"
#include "rtl/uri.hxx"
#include "ucbhelper/content.hxx"
#include "cppuhelper/exc_hlp.hxx"
#include "cppuhelper/implbase1.hxx"
#include "comphelper/servicedecl.hxx"
#include "svtools/inettype.hxx"
#include "com/sun/star/util/XUpdatable.hpp"
#include "com/sun/star/script/XLibraryContainer.hpp"
#include <memory>

using namespace ::dp_misc;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ucb;
using ::rtl::OUString;
namespace css = ::com::sun::star;

namespace dp_registry {
namespace backend {
namespace script {
namespace {

typedef ::cppu::ImplInheritanceHelper1<
    ::dp_registry::backend::PackageRegistryBackend, util::XUpdatable > t_helper;

//==============================================================================
class BackendImpl : public t_helper
{
    class PackageImpl : public ::dp_registry::backend::Package
    {
        BackendImpl * getMyBackend() const;

        const OUString m_scriptURL;
        const OUString m_dialogURL;
        OUString m_dialogName;

        // Package
        virtual beans::Optional< beans::Ambiguous<sal_Bool> > isRegistered_(
            ::osl::ResettableMutexGuard & guard,
            ::rtl::Reference<AbortChannel> const & abortChannel,
            Reference<XCommandEnvironment> const & xCmdEnv );
        virtual void processPackage_(
            ::osl::ResettableMutexGuard & guard,
            bool registerPackage,
            ::rtl::Reference<AbortChannel> const & abortChannel,
            Reference<XCommandEnvironment> const & xCmdEnv );

    public:
        PackageImpl(
            ::rtl::Reference<BackendImpl> const & myBackend,
            OUString const & url,
            Reference<XCommandEnvironment> const &xCmdEnv,
            OUString const & scriptURL, OUString const & dialogURL );
    };
    friend class PackageImpl;

    // PackageRegistryBackend
    virtual Reference<deployment::XPackage> bindPackage_(
        OUString const & url, OUString const & mediaType,
        Reference<XCommandEnvironment> const & xCmdEnv );

    Reference<css::script::XLibraryContainer> m_xScriptLibs;
    Reference<css::script::XLibraryContainer> m_xDialogLibs;
    ::std::auto_ptr<LibraryContainer> m_basic_script_libs;
    ::std::auto_ptr<LibraryContainer> m_dialog_libs;

    const Reference<deployment::XPackageTypeInfo> m_xBasicLibTypeInfo;
    const Reference<deployment::XPackageTypeInfo> m_xDialogLibTypeInfo;
    Sequence< Reference<deployment::XPackageTypeInfo> > m_typeInfos;

public:
    BackendImpl( Sequence<Any> const & args,
                 Reference<XComponentContext> const & xComponentContext );

    // XUpdatable
    virtual void SAL_CALL update() throw (RuntimeException);

    // XPackageRegistry
    virtual Sequence< Reference<deployment::XPackageTypeInfo> > SAL_CALL
    getSupportedPackageTypes() throw (RuntimeException);
};

//______________________________________________________________________________
BackendImpl::PackageImpl::PackageImpl(
    ::rtl::Reference<BackendImpl> const & myBackend,
    OUString const & url,
    Reference<XCommandEnvironment> const &xCmdEnv,
    OUString const & scriptURL, OUString const & dialogURL )
    : Package( myBackend.get(), url,
               OUString(), OUString(), // will be late-initialized
               scriptURL.getLength() > 0 ? myBackend->m_xBasicLibTypeInfo
                                         : myBackend->m_xDialogLibTypeInfo ),
      m_scriptURL( scriptURL ),
      m_dialogURL( dialogURL )
{
    // name, displayName:
    if (dialogURL.getLength() > 0) {
        m_dialogName = LibraryContainer::get_libname(
            dialogURL, xCmdEnv, myBackend->getComponentContext() );
    }
    if (scriptURL.getLength() > 0) {
        m_name = LibraryContainer::get_libname(
            scriptURL, xCmdEnv, myBackend->getComponentContext() );
    }
    else
        m_name = m_dialogName;
    m_displayName = m_name;
}

//______________________________________________________________________________
BackendImpl::BackendImpl(
    Sequence<Any> const & args,
    Reference<XComponentContext> const & xComponentContext )
    : t_helper( args, xComponentContext ),
      m_xBasicLibTypeInfo( new Package::TypeInfo(
                               OUSTR("application/"
                                     "vnd.sun.star.basic-library"),
                               OUString() /* no file filter */,
                               getResourceString(RID_STR_BASIC_LIB),
                               RID_IMG_SCRIPTLIB, RID_IMG_SCRIPTLIB_HC ) ),
      m_xDialogLibTypeInfo( new Package::TypeInfo(
                                OUSTR("application/"
                                      "vnd.sun.star.dialog-library"),
                                OUString() /* no file filter */,
                                getResourceString(RID_STR_DIALOG_LIB),
                                RID_IMG_DIALOGLIB, RID_IMG_DIALOGLIB_HC ) ),
      m_typeInfos( 2 )
{
    m_typeInfos[ 0 ] = m_xBasicLibTypeInfo;
    m_typeInfos[ 1 ] = m_xDialogLibTypeInfo;

    OSL_ASSERT( ! transientMode() );
    if (office_is_running())
    {
        m_xScriptLibs.set(
            xComponentContext->getServiceManager()->createInstanceWithContext(
                OUSTR("com.sun.star.script.ApplicationScriptLibraryContainer"),
                xComponentContext ), UNO_QUERY_THROW );
        m_xDialogLibs.set(
            xComponentContext->getServiceManager()->createInstanceWithContext(
                OUSTR("com.sun.star.script.ApplicationDialogLibraryContainer"),
                xComponentContext ), UNO_QUERY_THROW );
    }
    else
    {
        OUString basic_path(
            m_eContext == CONTEXT_USER
            ? OUSTR("vnd.sun.star.expand:${$BRAND_BASE_DIR/program/"
                    SAL_CONFIGFILE("bootstrap")
                    ":UserInstallation}/user/basic")
            : OUSTR("vnd.sun.star.expand:${$BRAND_BASE_DIR/program/"
                    SAL_CONFIGFILE("bootstrap")
                    ":BaseInstallation}/share/basic") );
        m_basic_script_libs.reset(
            new LibraryContainer(
                makeURL( basic_path, OUSTR("script.xlc") ),
                getMutex(),
                xComponentContext ) );
        m_dialog_libs.reset(
            new LibraryContainer(
                makeURL( basic_path, OUSTR("dialog.xlc") ),
                getMutex(),
                xComponentContext ) );
    }
}

// XUpdatable
//______________________________________________________________________________
void BackendImpl::update() throw (RuntimeException)
{
    const Reference<XCommandEnvironment> xCmdEnv;
    if (m_basic_script_libs.get() != 0) {
        try {
            m_basic_script_libs->init(xCmdEnv);
            m_basic_script_libs->flush(xCmdEnv);
        }
        catch (RuntimeException &) {
            throw;
        }
        catch (Exception & exc) {
            (void) exc;
            OSL_ENSURE( 0, ::rtl::OUStringToOString(
                            exc.Message, RTL_TEXTENCODING_UTF8 ).getStr() );
        }
    }
    if (m_dialog_libs.get() != 0) {
        try {
            m_dialog_libs->init(xCmdEnv);
            m_dialog_libs->flush(xCmdEnv);
        }
        catch (RuntimeException &) {
            throw;
        }
        catch (Exception & exc) {
            (void) exc;
            OSL_ENSURE( 0, ::rtl::OUStringToOString(
                            exc.Message, RTL_TEXTENCODING_UTF8 ).getStr() );
        }
    }
}

// XPackageRegistry
//______________________________________________________________________________
Sequence< Reference<deployment::XPackageTypeInfo> >
BackendImpl::getSupportedPackageTypes() throw (RuntimeException)
{
    return m_typeInfos;
}

// PackageRegistryBackend
//______________________________________________________________________________
Reference<deployment::XPackage> BackendImpl::bindPackage_(
    OUString const & url, OUString const & mediaType_,
    Reference<XCommandEnvironment> const & xCmdEnv )
{
    OUString mediaType( mediaType_ );
    if (mediaType.getLength() == 0)
    {
        // detect media-type:
        ::ucbhelper::Content ucbContent;
        if (create_ucb_content( &ucbContent, url, xCmdEnv ) &&
            ucbContent.isFolder())
        {
            // probe for script.xlb:
            if (create_ucb_content(
                    0, makeURL( url, OUSTR("script.xlb") ),
                    xCmdEnv, false /* no throw */ ))
                mediaType = OUSTR("application/vnd.sun.star.basic-library");
            // probe for dialog.xlb:
            else if (create_ucb_content(
                         0, makeURL( url, OUSTR("dialog.xlb") ),
                         xCmdEnv, false /* no throw */ ))
                mediaType = OUSTR("application/vnd.sun.star.dialog-library");
        }
        if (mediaType.getLength() == 0)
            throw lang::IllegalArgumentException(
                StrCannotDetectMediaType::get() + url,
                static_cast<OWeakObject *>(this), static_cast<sal_Int16>(-1) );
    }

    String type, subType;
    INetContentTypeParameterList params;
    if (INetContentTypes::parse( mediaType, type, subType, &params ))
    {
        if (type.EqualsIgnoreCaseAscii("application"))
        {
            if (subType.EqualsIgnoreCaseAscii("vnd.sun.star.basic-library"))
            {
                OUString dialogURL( makeURL( url, OUSTR("dialog.xlb") ) );
                if (! create_ucb_content(
                        0, dialogURL, xCmdEnv, false /* no throw */ )) {
                    dialogURL = OUString();
                }
                return new PackageImpl( this, url, xCmdEnv,
                                        makeURL( url, OUSTR("script.xlb") ),
                                        dialogURL );
            }
            else if (subType.EqualsIgnoreCaseAscii(
                         "vnd.sun.star.dialog-library")) {
                return new PackageImpl( this, url, xCmdEnv,
                                        OUString() /* no script lib */,
                                        makeURL( url, OUSTR("dialog.xlb") ) );
            }
        }
    }
    throw lang::IllegalArgumentException(
        StrUnsupportedMediaType::get() + mediaType,
        static_cast<OWeakObject *>(this),
        static_cast<sal_Int16>(-1) );
}

//##############################################################################

// Package
BackendImpl * BackendImpl::PackageImpl::getMyBackend() const
{
    BackendImpl * pBackend = static_cast<BackendImpl *>(m_myBackend.get());
    if (NULL == pBackend)
    {
        //May throw a DisposedException
        check();
        //We should never get here...
        throw RuntimeException(
            OUSTR("Failed to get the BackendImpl"),
            static_cast<OWeakObject*>(const_cast<PackageImpl *>(this)));
    }
    return pBackend;
}
//______________________________________________________________________________
beans::Optional< beans::Ambiguous<sal_Bool> >
BackendImpl::PackageImpl::isRegistered_(
    ::osl::ResettableMutexGuard &,
    ::rtl::Reference<AbortChannel> const &,
    Reference<XCommandEnvironment> const & xCmdEnv )
{
    BackendImpl * that = getMyBackend();
    bool reg = false;
    if (m_scriptURL.getLength() > 0) {
        if (that->m_xScriptLibs.is())
            reg = that->m_xScriptLibs->hasByName( m_name );
        else
            reg = that->m_basic_script_libs->has( m_name, xCmdEnv );
    }
    else {
        if (that->m_xDialogLibs.is())
            reg = that->m_xDialogLibs->hasByName( m_dialogName );
        else
            reg = that->m_dialog_libs->has( m_dialogName, xCmdEnv );
    }
    return beans::Optional< beans::Ambiguous<sal_Bool> >(
        true /* IsPresent */,
        beans::Ambiguous<sal_Bool>( reg, false /* IsAmbiguous */ ) );
}

//______________________________________________________________________________
void BackendImpl::PackageImpl::processPackage_(
    ::osl::ResettableMutexGuard &,
    bool doRegisterPackage,
    ::rtl::Reference<AbortChannel> const &,
    Reference<XCommandEnvironment> const & xCmdEnv )
{
    BackendImpl * that = getMyBackend();
    if (doRegisterPackage)
    {
        if (m_scriptURL.getLength() > 0) {
            if (that->m_xScriptLibs.is())
                that->m_xScriptLibs->createLibraryLink(
                    m_name, m_scriptURL, false /* ! read-only */ );
            else
                that->m_basic_script_libs->insert(
                    m_name, m_scriptURL, xCmdEnv );
        }
        if (m_dialogURL.getLength() > 0) {
            if (that->m_xDialogLibs.is())
                that->m_xDialogLibs->createLibraryLink(
                    m_dialogName, m_dialogURL, false /* ! read-only */ );
            else
                that->m_dialog_libs->insert(
                    m_dialogName, m_dialogURL, xCmdEnv );
        }
    }
    else // revokePackage()
    {
        try {
            if (m_scriptURL.getLength() > 0) {
                if (that->m_xScriptLibs.is())
                    that->m_xScriptLibs->removeLibrary( m_name );
                else
                    that->m_basic_script_libs->remove(
                        m_name, m_scriptURL, xCmdEnv );
            }
            if (m_dialogURL.getLength() > 0) {
                if (that->m_xDialogLibs.is())
                    that->m_xDialogLibs->removeLibrary( m_dialogName );
                else
                    that->m_dialog_libs->remove(
                        m_dialogName, m_dialogURL, xCmdEnv );
            }
        }
        catch (lang::WrappedTargetException & exc) {
            // unwrap WrappedTargetException:
            ::cppu::throwException( exc.TargetException );
        }
    }
}

} // anon namespace

namespace sdecl = comphelper::service_decl;
sdecl::class_<BackendImpl, sdecl::with_args<true> > serviceBI;
extern sdecl::ServiceDecl const serviceDecl(
    serviceBI,
    "com.sun.star.comp.deployment.script.PackageRegistryBackend",
    BACKEND_SERVICE_NAME );

} // namespace script
} // namespace backend
} // namespace dp_registry

<|endoftext|>