<commit_before>//
// Created by alex on 09/07/2015.
//

#include <stddef.h>
#include <assert.h>
#include <string.h>
#include "lzlib.h"
#include <vector>
#include <stdio.h>

#define CHUNK 16384

/* report a zlib or i/o error */
void zerr(int ret)
{
    fputs("zpipe: ", stderr);
    switch (ret) {
        case Z_ERRNO:
            if (ferror(stdin))
                fputs("error reading stdin\n", stderr);
            if (ferror(stdout))
                fputs("error writing stdout\n", stderr);
            break;
        case Z_STREAM_ERROR:
            fputs("invalid compression level\n", stderr);
            break;
        case Z_DATA_ERROR:
            fputs("invalid or incomplete deflate data\n", stderr);
            break;
        case Z_MEM_ERROR:
            fputs("out of memory\n", stderr);
            break;
        case Z_VERSION_ERROR:
            fputs("zlib version mismatch!\n", stderr);
        default:break;
    }
}

void static compress(void) {

}

/* Decompress data */
static int _decompress(char *data, int data_size, std::vector<unsigned char> &buff) {
    int ret;
    unsigned have;
    z_stream strm;
    unsigned char in[CHUNK];
    unsigned char out[CHUNK];

    /* allocate inflate state */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.avail_in = 0;
    strm.next_in = Z_NULL;

    ret = inflateInit(&strm);
    if (ret != Z_OK)
        return ret;

    /* decompress until deflate stream ends or end of file */
    size_t remain = CHUNK;
    uInt chunk_size = 0;

    do {
        chunk_size = remain > data_size ? (size_t) data_size : remain;

        memcpy(in, data, chunk_size);
        strm.avail_in = chunk_size;

        data += chunk_size;
        data_size -= chunk_size;

        if (strm.avail_in == 0)
            break;
        strm.next_in = in;
        /* run inflate() on input until output buffer not full */
        do {
            strm.avail_out = CHUNK;
            strm.next_out = out;

            ret = inflate(&strm, Z_NO_FLUSH);
            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */

            switch (ret) {
                case Z_NEED_DICT:
                    ret = Z_DATA_ERROR;     /* and fall through */
                case Z_DATA_ERROR:
                case Z_MEM_ERROR:
                    (void)inflateEnd(&strm);
                    return ret;
                default:break;
            }
            have = CHUNK - strm.avail_out;
            if (have > 0) {
                buff.insert(buff.end(), out, out + have);
            }
        } while (strm.avail_out == 0);

        /* done when inflate() says it's done */
    } while (ret != Z_STREAM_END);

    buff.push_back('\0'); // end of stream

    /* clean up and return */
    (void)inflateEnd(&strm);
    return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}

void static decompress(void) {
    std::vector<unsigned char> buff;
    lua_Object obj = lua_getparam(1);

    if (!lua_isstring(obj)) {
        lua_error((char *) "decompress: string required!");
    }
    int data_size = lua_strlen(obj);
    char *data = lua_getstring(obj);

    int ret = _decompress(data, data_size, buff);
    if (ret != Z_OK) zerr(ret);

    lua_pushstring((char *) buff.data());
}

static struct luaL_reg lzlib[] = {
    {(char *) "zlib_compress", compress},
    {(char *) "zlib_decompress", decompress}
};

LUA_LIBRARY void lua_lzlibopen(lua_State *L) {
    lua_state = L;
    luaL_openlib(lzlib, (sizeof(lzlib) / sizeof(lzlib[0])));
}<commit_msg>implemented function decompress.<commit_after>//
// Created by alex on 09/07/2015.
//

#include <stddef.h>
#include <assert.h>
#include <string.h>
#include "lzlib.h"
#include <vector>
#include <stdio.h>

#define CHUNK 16384

/* report a zlib or i/o error */
void zerr(int ret) {
    fputs("zpipe: ", stderr);
    switch (ret) {
        case Z_ERRNO:
            if (ferror(stdin))
                fputs("error reading stdin\n", stderr);
            if (ferror(stdout))
                fputs("error writing stdout\n", stderr);
            break;
        case Z_STREAM_ERROR:
            fputs("invalid compression level\n", stderr);
            break;
        case Z_DATA_ERROR:
            fputs("invalid or incomplete deflate data\n", stderr);
            break;
        case Z_MEM_ERROR:
            fputs("out of memory\n", stderr);
            break;
        case Z_VERSION_ERROR:
            fputs("zlib version mismatch!\n", stderr);
        default:break;
    }
}

int _compress(char *data, std::vector<unsigned char> &buff, int level) {
    int ret, flush;
    unsigned have;
    z_stream strm;
    unsigned char in[CHUNK];
    unsigned char out[CHUNK];

    /* allocate deflate state */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;

    ret = deflateInit(&strm, level);
    if (ret != Z_OK)
        return ret;

    /* compress until end of file */
    size_t remain = CHUNK;
    uInt chunk_size = 0;
    int data_size  = strlen(data);

    do {
        chunk_size = remain > data_size ? (size_t) data_size : remain;
        memcpy(in, data, chunk_size);
        strm.avail_in = chunk_size;
        data += chunk_size;

        flush = data[0] == '\0' ? Z_FINISH : Z_NO_FLUSH;

        data_size -= chunk_size;
        strm.next_in = in;

        /* run deflate() on input until output buffer not full, finish
           compression if all of source has been read in */
        do {
            strm.avail_out = CHUNK;
            strm.next_out = out;

            ret = deflate(&strm, flush);    /* no bad return value */
            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
            have = CHUNK - strm.avail_out;

            if (have > 0) {
                buff.insert(buff.end(), out, out + have);
            }
        } while (strm.avail_out == 0);
        assert(strm.avail_in == 0);     /* all input will be used */

    /* done when last data in file processed */
    } while (flush != Z_FINISH);
    assert(ret == Z_STREAM_END);        /* stream will be complete */

    /* clean up and return */
    (void)deflateEnd(&strm);
    return Z_OK;
}

void static compress(void) {
    char *data = luaL_check_string(1);
    if (!data[strlen(data)] == '\0') {
        lua_error((char *) "compress(eof): invalid string!");
    }
    lua_Object level_Object = lua_getparam(1);
    int level = lua_isnumber(level_Object) ? (int) lua_getnumber(level_Object) : Z_DEFAULT_COMPRESSION;
    std::vector<unsigned char> buff;

    _compress(data, buff, level);
    lua_pushlstring((char *) buff.data(), (long) buff.size());

}

/* Decompress data */
static int _decompress(char *data, int data_size, std::vector<unsigned char> &buff) {
    int ret;
    unsigned have;
    z_stream strm;
    unsigned char in[CHUNK];
    unsigned char out[CHUNK];

    /* allocate inflate state */
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;
    strm.avail_in = 0;
    strm.next_in = Z_NULL;

    ret = inflateInit(&strm);
    if (ret != Z_OK)
        return ret;

    /* decompress until deflate stream ends or end of file */
    size_t remain = CHUNK;
    uInt chunk_size = 0;

    do {
        chunk_size = remain > data_size ? (size_t) data_size : remain;

        memcpy(in, data, chunk_size);
        strm.avail_in = chunk_size;

        data += chunk_size;
        data_size -= chunk_size;

        if (strm.avail_in == 0)
            break;
        strm.next_in = in;
        /* run inflate() on input until output buffer not full */
        do {
            strm.avail_out = CHUNK;
            strm.next_out = out;

            ret = inflate(&strm, Z_NO_FLUSH);
            assert(ret != Z_STREAM_ERROR);  /* state not clobbered */

            switch (ret) {
                case Z_NEED_DICT:
                    ret = Z_DATA_ERROR;     /* and fall through */
                case Z_DATA_ERROR:
                case Z_MEM_ERROR:
                    (void)inflateEnd(&strm);
                    return ret;
                default:break;
            }
            have = CHUNK - strm.avail_out;
            if (have > 0) {
                buff.insert(buff.end(), out, out + have);
            }
        } while (strm.avail_out == 0);

        /* done when inflate() says it's done */
    } while (ret != Z_STREAM_END);

    buff.push_back('\0'); // end of stream

    /* clean up and return */
    (void)inflateEnd(&strm);
    return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}

void static decompress(void) {
    std::vector<unsigned char> buff;
    lua_Object obj = lua_getparam(1);

    if (!lua_isstring(obj)) {
        lua_error((char *) "decompress: string required!");
    }
    int data_size = lua_strlen(obj);
    char *data = lua_getstring(obj);

    int ret = _decompress(data, data_size, buff);
    if (ret != Z_OK) zerr(ret);

    lua_pushstring((char *) buff.data());
}

static struct luaL_reg lzlib[] = {
    {(char *) "zlib_compress", compress},
    {(char *) "zlib_decompress", decompress}
};

LUA_LIBRARY void lua_lzlibopen(lua_State *L) {
    lua_state = L;
    luaL_openlib(lzlib, (sizeof(lzlib) / sizeof(lzlib[0])));
}<|endoftext|>


<commit_before>#include "utility.hpp"

#include <sse/runners/sophos/sophos_client_runner.hpp>
#include <sse/runners/sophos/sophos_server_runner.hpp>
#include <sse/schemes/sophos/sophos_client.hpp>
#include <sse/schemes/sophos/sophos_server.hpp>
#include <sse/schemes/utils/utils.hpp>

#include <sse/crypto/utils.hpp>

#include <grpc++/impl/codegen/service_type.h>
#include <grpc++/server_builder.h>

#include <condition_variable>
#include <gtest/gtest.h>

#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <thread>

namespace sse {
namespace sophos {

class SophosImpl
{
public:
    explicit SophosImpl(std::string path);
};

namespace test {

#define SSE_SOPHOS_TEST_DIR "test_sophos_runners"

constexpr auto sophos_test_dir = SSE_SOPHOS_TEST_DIR;
constexpr auto server_db_path  = SSE_SOPHOS_TEST_DIR "/server.db";
constexpr auto client_db_path  = SSE_SOPHOS_TEST_DIR "/client.db";

TEST(sophos_runner, insertion_search)
{
    sse::test::cleanup_directory(sophos_test_dir);

    grpc::ServerBuilder            builder;
    std::unique_ptr<grpc::Service> service;

    auto server = build_sophos_server(builder, server_db_path, false, service);

    // Get the in-process channel
    std::shared_ptr<grpc::Channel> channel
        = server->InProcessChannel(grpc::ChannelArguments());
    // Create the client
    std::unique_ptr<SophosClientRunner> client(
        new SophosClientRunner(channel, client_db_path));

    const std::map<std::string, std::list<uint64_t>> test_db
        = {{"kw_1", {0, 1}}, {"kw_2", {0}}, {"kw_3", {0}}};

    sse::test::insert_database(client, test_db);
    sse::test::test_search_correctness(client, test_db);

    server->Shutdown()
}

} // namespace test
} // namespace sophos
} // namespace sse
<commit_msg>Fix a stupid typo<commit_after>#include "utility.hpp"

#include <sse/runners/sophos/sophos_client_runner.hpp>
#include <sse/runners/sophos/sophos_server_runner.hpp>
#include <sse/schemes/sophos/sophos_client.hpp>
#include <sse/schemes/sophos/sophos_server.hpp>
#include <sse/schemes/utils/utils.hpp>

#include <sse/crypto/utils.hpp>

#include <grpc++/impl/codegen/service_type.h>
#include <grpc++/server_builder.h>

#include <condition_variable>
#include <gtest/gtest.h>

#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <thread>

namespace sse {
namespace sophos {

class SophosImpl
{
public:
    explicit SophosImpl(std::string path);
};

namespace test {

#define SSE_SOPHOS_TEST_DIR "test_sophos_runners"

constexpr auto sophos_test_dir = SSE_SOPHOS_TEST_DIR;
constexpr auto server_db_path  = SSE_SOPHOS_TEST_DIR "/server.db";
constexpr auto client_db_path  = SSE_SOPHOS_TEST_DIR "/client.db";

TEST(sophos_runner, insertion_search)
{
    sse::test::cleanup_directory(sophos_test_dir);

    grpc::ServerBuilder            builder;
    std::unique_ptr<grpc::Service> service;

    auto server = build_sophos_server(builder, server_db_path, false, service);

    // Get the in-process channel
    std::shared_ptr<grpc::Channel> channel
        = server->InProcessChannel(grpc::ChannelArguments());
    // Create the client
    std::unique_ptr<SophosClientRunner> client(
        new SophosClientRunner(channel, client_db_path));

    const std::map<std::string, std::list<uint64_t>> test_db
        = {{"kw_1", {0, 1}}, {"kw_2", {0}}, {"kw_3", {0}}};

    sse::test::insert_database(client, test_db);
    sse::test::test_search_correctness(client, test_db);

    server->Shutdown();
}

} // namespace test
} // namespace sophos
} // namespace sse
<|endoftext|>


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

#ifndef FORMS_SOURCE_COMPONENT_RTATTRIBUTEHANDLER_HXX
#define FORMS_SOURCE_COMPONENT_RTATTRIBUTEHANDLER_HXX

#ifndef FORMS_SOURCE_RICHTEXT_RTATTRIBUTES_HXX
#include "rtattributes.hxx"
#endif

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif

#ifndef _SVX_SVXENUM_HXX
#include <svx/svxenum.hxx>
#endif
#ifndef _SVX_FRMDIR_HXX
#include <svx/frmdir.hxx>
#endif

class SfxItemSet;
class SfxPoolItem;
class SfxItemPool;
//........................................................................
namespace frm
{
//........................................................................

    //====================================================================
    //= ReferenceBase
    //====================================================================
    class ReferenceBase : public ::rtl::IReference
    {
    protected:
        oslInterlockedCount m_refCount;

    public:
        // IReference
        virtual oslInterlockedCount SAL_CALL acquire();
        virtual oslInterlockedCount SAL_CALL release();

    protected:
        virtual ~ReferenceBase();
    };

    //====================================================================
    //= IAttributeHandler
    //====================================================================
    class IAttributeHandler : public ::rtl::IReference
    {
    public:
        virtual     AttributeId     getAttributeId( ) const = 0;
        virtual     AttributeState  getState( const SfxItemSet& _rAttribs ) const = 0;
        virtual     void            executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const = 0;
    };

    //====================================================================
    //= AttributeHandler
    //====================================================================
    class AttributeHandler  :public ReferenceBase
                            ,public IAttributeHandler
    {
    private:
        AttributeId     m_nAttribute;
        WhichId         m_nWhich;

    protected:
        AttributeId getAttribute() const { return m_nAttribute; }
        WhichId     getWhich() const     { return m_nWhich;     }

    public:
        AttributeHandler( AttributeId _nAttributeId, WhichId _nWhichId );

        // IAttributeHandler
        virtual     AttributeId     getAttributeId( ) const;
        virtual     AttributeState  getState( const SfxItemSet& _rAttribs ) const;
        virtual     void            executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const = 0;

    protected:
        /// helper method calling implGetCheckState
        AttributeCheckState getCheckState( const SfxItemSet& _rAttribs ) const;

        /// helper method putting an item into a set, respecting a script type
        void        putItemForScript( SfxItemSet& _rAttribs, const SfxPoolItem& _rItem, ScriptType _nForScriptType ) const;

        // pseudo-abstract
        virtual     AttributeCheckState  implGetCheckState( const SfxPoolItem& _rItem ) const;

        // disambiguate IReference
        virtual oslInterlockedCount SAL_CALL acquire();
        virtual oslInterlockedCount SAL_CALL release();

    protected:
        virtual ~AttributeHandler();
    };

    //====================================================================
    //= AttributeHandlerFactory
    //====================================================================
    class AttributeHandlerFactory
    {
    public:
        static ::rtl::Reference< IAttributeHandler > getHandlerFor( AttributeId _nAttributeId, const SfxItemPool& _rEditEnginePool );

    private:
        AttributeHandlerFactory();                                              // never implemented
        AttributeHandlerFactory( const AttributeHandlerFactory& );              // never implemented
        AttributeHandlerFactory& operator=( const AttributeHandlerFactory& );   // never implemented
        ~AttributeHandlerFactory();                                             // never implemented
    };

    //====================================================================
    //= ParaAlignmentHandler
    //====================================================================
    class ParaAlignmentHandler : public AttributeHandler
    {
    private:
        SvxAdjust   m_eAdjust;

    public:
        ParaAlignmentHandler( AttributeId _nAttributeId );

    public:
        virtual     AttributeCheckState implGetCheckState( const SfxPoolItem& _rItem ) const;
        virtual     void                executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const;
    };

    //====================================================================
    //= LineSpacingHandler
    //====================================================================
    class LineSpacingHandler : public AttributeHandler
    {
    private:
        USHORT  m_nLineSpace;

    public:
        LineSpacingHandler( AttributeId _nAttributeId );

    public:
        virtual     AttributeCheckState implGetCheckState( const SfxPoolItem& _rItem ) const;
        virtual     void                executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const;
    };

    //====================================================================
    //= EscapementHandler
    //====================================================================
    class EscapementHandler : public AttributeHandler
    {
    private:
        SvxEscapement   m_eEscapement;

    public:
        EscapementHandler( AttributeId _nAttributeId );

    public:
        virtual     AttributeCheckState implGetCheckState( const SfxPoolItem& _rItem ) const;
        virtual     void                executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const;
    };

    //====================================================================
    //= SlotHandler
    //====================================================================
    class SlotHandler : public AttributeHandler
    {
    private:
        bool    m_bScriptDependent;

    public:
        SlotHandler( AttributeId _nAttributeId, WhichId _nWhichId );

    public:
        virtual     AttributeState  getState( const SfxItemSet& _rAttribs ) const;
        virtual     void            executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const;
    };

    //====================================================================
    //= BooleanHandler
    //====================================================================
    class BooleanHandler : public AttributeHandler
    {
    public:
        BooleanHandler( AttributeId _nAttributeId, WhichId _nWhichId );

    public:
        virtual     AttributeCheckState implGetCheckState( const SfxPoolItem& _rItem ) const;
        virtual     void                executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const;
    };

    //====================================================================
    //= FontSizeHandler
    //====================================================================
    class FontSizeHandler : public AttributeHandler
    {
    public:
        FontSizeHandler( AttributeId _nAttributeId, WhichId _nWhichId );

    public:
        virtual     AttributeState  getState( const SfxItemSet& _rAttribs ) const;
        virtual     void            executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const;
    };

    //====================================================================
    //= ParagraphDirectionHandler
    //====================================================================
    class ParagraphDirectionHandler : public AttributeHandler
    {
    private:
        SvxFrameDirection   m_eParagraphDirection;
        SvxAdjust           m_eDefaultAdjustment;
        SvxAdjust           m_eOppositeDefaultAdjustment;

    public:
        ParagraphDirectionHandler( AttributeId _nAttributeId );

    public:
        virtual     AttributeCheckState implGetCheckState( const SfxPoolItem& _rItem ) const;
        virtual     void                executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const;
    };

//........................................................................
} // namespace frm
//........................................................................

#endif // FORMS_SOURCE_COMPONENT_RTATTRIBUTEHANDLER_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.3.244); FILE MERGED 2008/04/01 15:16:40 thb 1.3.244.3: #i85898# Stripping all external header guards 2008/04/01 12:30:31 thb 1.3.244.2: #i85898# Stripping all external header guards 2008/03/31 13:11:42 rt 1.3.244.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: rtattributehandler.hxx,v $
 * $Revision: 1.4 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef FORMS_SOURCE_COMPONENT_RTATTRIBUTEHANDLER_HXX
#define FORMS_SOURCE_COMPONENT_RTATTRIBUTEHANDLER_HXX

#include "rtattributes.hxx"
#include <rtl/ref.hxx>
#include <svx/svxenum.hxx>
#include <svx/frmdir.hxx>

class SfxItemSet;
class SfxPoolItem;
class SfxItemPool;
//........................................................................
namespace frm
{
//........................................................................

    //====================================================================
    //= ReferenceBase
    //====================================================================
    class ReferenceBase : public ::rtl::IReference
    {
    protected:
        oslInterlockedCount m_refCount;

    public:
        // IReference
        virtual oslInterlockedCount SAL_CALL acquire();
        virtual oslInterlockedCount SAL_CALL release();

    protected:
        virtual ~ReferenceBase();
    };

    //====================================================================
    //= IAttributeHandler
    //====================================================================
    class IAttributeHandler : public ::rtl::IReference
    {
    public:
        virtual     AttributeId     getAttributeId( ) const = 0;
        virtual     AttributeState  getState( const SfxItemSet& _rAttribs ) const = 0;
        virtual     void            executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const = 0;
    };

    //====================================================================
    //= AttributeHandler
    //====================================================================
    class AttributeHandler  :public ReferenceBase
                            ,public IAttributeHandler
    {
    private:
        AttributeId     m_nAttribute;
        WhichId         m_nWhich;

    protected:
        AttributeId getAttribute() const { return m_nAttribute; }
        WhichId     getWhich() const     { return m_nWhich;     }

    public:
        AttributeHandler( AttributeId _nAttributeId, WhichId _nWhichId );

        // IAttributeHandler
        virtual     AttributeId     getAttributeId( ) const;
        virtual     AttributeState  getState( const SfxItemSet& _rAttribs ) const;
        virtual     void            executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const = 0;

    protected:
        /// helper method calling implGetCheckState
        AttributeCheckState getCheckState( const SfxItemSet& _rAttribs ) const;

        /// helper method putting an item into a set, respecting a script type
        void        putItemForScript( SfxItemSet& _rAttribs, const SfxPoolItem& _rItem, ScriptType _nForScriptType ) const;

        // pseudo-abstract
        virtual     AttributeCheckState  implGetCheckState( const SfxPoolItem& _rItem ) const;

        // disambiguate IReference
        virtual oslInterlockedCount SAL_CALL acquire();
        virtual oslInterlockedCount SAL_CALL release();

    protected:
        virtual ~AttributeHandler();
    };

    //====================================================================
    //= AttributeHandlerFactory
    //====================================================================
    class AttributeHandlerFactory
    {
    public:
        static ::rtl::Reference< IAttributeHandler > getHandlerFor( AttributeId _nAttributeId, const SfxItemPool& _rEditEnginePool );

    private:
        AttributeHandlerFactory();                                              // never implemented
        AttributeHandlerFactory( const AttributeHandlerFactory& );              // never implemented
        AttributeHandlerFactory& operator=( const AttributeHandlerFactory& );   // never implemented
        ~AttributeHandlerFactory();                                             // never implemented
    };

    //====================================================================
    //= ParaAlignmentHandler
    //====================================================================
    class ParaAlignmentHandler : public AttributeHandler
    {
    private:
        SvxAdjust   m_eAdjust;

    public:
        ParaAlignmentHandler( AttributeId _nAttributeId );

    public:
        virtual     AttributeCheckState implGetCheckState( const SfxPoolItem& _rItem ) const;
        virtual     void                executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const;
    };

    //====================================================================
    //= LineSpacingHandler
    //====================================================================
    class LineSpacingHandler : public AttributeHandler
    {
    private:
        USHORT  m_nLineSpace;

    public:
        LineSpacingHandler( AttributeId _nAttributeId );

    public:
        virtual     AttributeCheckState implGetCheckState( const SfxPoolItem& _rItem ) const;
        virtual     void                executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const;
    };

    //====================================================================
    //= EscapementHandler
    //====================================================================
    class EscapementHandler : public AttributeHandler
    {
    private:
        SvxEscapement   m_eEscapement;

    public:
        EscapementHandler( AttributeId _nAttributeId );

    public:
        virtual     AttributeCheckState implGetCheckState( const SfxPoolItem& _rItem ) const;
        virtual     void                executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const;
    };

    //====================================================================
    //= SlotHandler
    //====================================================================
    class SlotHandler : public AttributeHandler
    {
    private:
        bool    m_bScriptDependent;

    public:
        SlotHandler( AttributeId _nAttributeId, WhichId _nWhichId );

    public:
        virtual     AttributeState  getState( const SfxItemSet& _rAttribs ) const;
        virtual     void            executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const;
    };

    //====================================================================
    //= BooleanHandler
    //====================================================================
    class BooleanHandler : public AttributeHandler
    {
    public:
        BooleanHandler( AttributeId _nAttributeId, WhichId _nWhichId );

    public:
        virtual     AttributeCheckState implGetCheckState( const SfxPoolItem& _rItem ) const;
        virtual     void                executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const;
    };

    //====================================================================
    //= FontSizeHandler
    //====================================================================
    class FontSizeHandler : public AttributeHandler
    {
    public:
        FontSizeHandler( AttributeId _nAttributeId, WhichId _nWhichId );

    public:
        virtual     AttributeState  getState( const SfxItemSet& _rAttribs ) const;
        virtual     void            executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const;
    };

    //====================================================================
    //= ParagraphDirectionHandler
    //====================================================================
    class ParagraphDirectionHandler : public AttributeHandler
    {
    private:
        SvxFrameDirection   m_eParagraphDirection;
        SvxAdjust           m_eDefaultAdjustment;
        SvxAdjust           m_eOppositeDefaultAdjustment;

    public:
        ParagraphDirectionHandler( AttributeId _nAttributeId );

    public:
        virtual     AttributeCheckState implGetCheckState( const SfxPoolItem& _rItem ) const;
        virtual     void                executeAttribute( const SfxItemSet& _rCurrentAttribs, SfxItemSet& _rNewAttribs, const SfxPoolItem* _pAdditionalArg, ScriptType _nForScriptType ) const;
    };

//........................................................................
} // namespace frm
//........................................................................

#endif // FORMS_SOURCE_COMPONENT_RTATTRIBUTEHANDLER_HXX

<|endoftext|>


<commit_before>
#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_
#define __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_

// own includes
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif

#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XDISPATCHRECORDER_HPP_
#include <com/sun/star/frame/XDispatchRecorder.hpp>
#endif

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

#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp
#endif

#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HDL_
#include <com/sun/star/uno/RuntimeException.hdl>
#endif

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

namespace framework{

class DispatchRecorder
    : private ThreadHelpBase
    , public  css::lang::XTypeProvider
    , public  css::lang::XServiceInfo
    , public  css::frame::XDispatchRecorder
    , public  ::cppu::OWeakObject
{
    // private member
    private:
        css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR        ;
        ::rtl::OUStringBuffer                                  m_aScriptBuffer;
        ::rtl::OUString                                        m_sScript      ;
        sal_Int32                                              m_nRecordingID ;

    // public interface
    public:
        DispatchRecorder( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR );
        ~DispatchRecorder();

        // XInterface, XTypeProvider, XServiceInfo
        DECLARE_XINTERFACE
        DECLARE_XTYPEPROVIDER
        DECLARE_XSERVICEINFO

        // XDispatchRecorder
        virtual void SAL_CALL            startRecording         ( const css::uno::Reference< css::frame::XFrame >& xFrame ) throw( css::uno::RuntimeException );
        virtual void SAL_CALL            recordDispatch         ( const css::util::URL& aURL, const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException );
        virtual void SAL_CALL            recordDispatchAsComment( const css::util::URL& aURL, const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException );
        virtual void SAL_CALL            endRecording           () throw( css::uno::RuntimeException );
        virtual ::rtl::OUString SAL_CALL getRecordedMacro       () throw( css::uno::RuntimeException );

    // private functions
    private:
        void SAL_CALL implts_recordMacro( const css::util::URL& aURL,
                                          const css::uno::Sequence< css::beans::PropertyValue >& lArguments,
                                                sal_Bool bAsComment );
}; // class DispatcRecorder

} // namespace framework

#endif // define __FRAMEWORK...
<commit_msg>#65293# corrected typo<commit_after>
#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_
#define __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_

// own includes
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif

#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XDISPATCHRECORDER_HPP_
#include <com/sun/star/frame/XDispatchRecorder.hpp>
#endif

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

#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HDL_
#include <com/sun/star/uno/RuntimeException.hdl>
#endif

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

namespace framework{

class DispatchRecorder
    : private ThreadHelpBase
    , public  css::lang::XTypeProvider
    , public  css::lang::XServiceInfo
    , public  css::frame::XDispatchRecorder
    , public  ::cppu::OWeakObject
{
    // private member
    private:
        css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR        ;
        ::rtl::OUStringBuffer                                  m_aScriptBuffer;
        ::rtl::OUString                                        m_sScript      ;
        sal_Int32                                              m_nRecordingID ;

    // public interface
    public:
        DispatchRecorder( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR );
        ~DispatchRecorder();

        // XInterface, XTypeProvider, XServiceInfo
        DECLARE_XINTERFACE
        DECLARE_XTYPEPROVIDER
        DECLARE_XSERVICEINFO

        // XDispatchRecorder
        virtual void SAL_CALL            startRecording         ( const css::uno::Reference< css::frame::XFrame >& xFrame ) throw( css::uno::RuntimeException );
        virtual void SAL_CALL            recordDispatch         ( const css::util::URL& aURL, const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException );
        virtual void SAL_CALL            recordDispatchAsComment( const css::util::URL& aURL, const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException );
        virtual void SAL_CALL            endRecording           () throw( css::uno::RuntimeException );
        virtual ::rtl::OUString SAL_CALL getRecordedMacro       () throw( css::uno::RuntimeException );

    // private functions
    private:
        void SAL_CALL implts_recordMacro( const css::util::URL& aURL,
                                          const css::uno::Sequence< css::beans::PropertyValue >& lArguments,
                                                sal_Bool bAsComment );
}; // class DispatcRecorder

} // namespace framework

#endif // define __FRAMEWORK...
<|endoftext|>


<commit_before>
#include "odrive_main.h"

Controller::Controller(Config_t& config) :
    config_(config)
{
    update_filter_gains();
}

void Controller::reset() {
    pos_setpoint_ = 0.0f;
    vel_setpoint_ = 0.0f;
    vel_integrator_current_ = 0.0f;
    current_setpoint_ = 0.0f;
}

void Controller::set_error(Error_t error) {
    error_ |= error;
    axis_->error_ |= Axis::ERROR_CONTROLLER_FAILED;
}

//--------------------------------
// Command Handling
//--------------------------------

void Controller::set_pos_setpoint(float pos_setpoint, float vel_feed_forward, float current_feed_forward) {
    pos_setpoint_ = pos_setpoint;
    vel_setpoint_ = vel_feed_forward;
    current_setpoint_ = current_feed_forward;
    config_.control_mode = CTRL_MODE_POSITION_CONTROL;
#ifdef DEBUG_PRINT
    printf("POSITION_CONTROL %6.0f %3.3f %3.3f\n", pos_setpoint, vel_setpoint_, current_setpoint_);
#endif
}

void Controller::set_vel_setpoint(float vel_setpoint, float current_feed_forward) {
    vel_setpoint_ = vel_setpoint;
    current_setpoint_ = current_feed_forward;
    config_.control_mode = CTRL_MODE_VELOCITY_CONTROL;
#ifdef DEBUG_PRINT
    printf("VELOCITY_CONTROL %3.3f %3.3f\n", vel_setpoint_, motor->current_setpoint_);
#endif
}

void Controller::set_current_setpoint(float current_setpoint) {
    current_setpoint_ = current_setpoint;
    config_.control_mode = CTRL_MODE_CURRENT_CONTROL;
#ifdef DEBUG_PRINT
    printf("CURRENT_CONTROL %3.3f\n", current_setpoint_);
#endif
}

void Controller::move_to_pos(float goal_point) {
    axis_->trap_.planTrapezoidal(goal_point, pos_setpoint_, vel_setpoint_,
                                 axis_->trap_.config_.vel_limit,
                                 axis_->trap_.config_.accel_limit,
                                 axis_->trap_.config_.decel_limit);
    traj_start_loop_count_ = axis_->loop_counter_;
    config_.control_mode = CTRL_MODE_TRAJECTORY_CONTROL;
}

void Controller::start_anticogging_calibration() {
    // Ensure the cogging map was correctly allocated earlier and that the motor is capable of calibrating
    if (anticogging_.cogging_map != NULL && axis_->error_ == Axis::ERROR_NONE) {
        anticogging_.calib_anticogging = true;
    }
}

/*
 * This anti-cogging implementation iterates through each encoder position,
 * waits for zero velocity & position error,
 * then samples the current required to maintain that position.
 *
 * This holding current is added as a feedforward term in the control loop.
 */
bool Controller::anticogging_calibration(float pos_estimate, float vel_estimate) {
    if (anticogging_.calib_anticogging && anticogging_.cogging_map != NULL) {
        float pos_err = anticogging_.index - pos_estimate;
        if (fabsf(pos_err) <= anticogging_.calib_pos_threshold &&
            fabsf(vel_estimate) < anticogging_.calib_vel_threshold) {
            anticogging_.cogging_map[anticogging_.index++] = vel_integrator_current_;
        }
        if (anticogging_.index < axis_->encoder_.config_.cpr) { // TODO: remove the dependency on encoder CPR
            set_pos_setpoint(anticogging_.index, 0.0f, 0.0f);
            return false;
        } else {
            anticogging_.index = 0;
            set_pos_setpoint(0.0f, 0.0f, 0.0f);  // Send the motor home
            anticogging_.use_anticogging = true;  // We're good to go, enable anti-cogging
            anticogging_.calib_anticogging = false;
            return true;
        }
    }
    return false;
}

void Controller::update_filter_gains() {
    input_filter_kp_ = 2.0f * config_.input_filter_bandwidth;  // basic conversion to discrete time
    input_filter_ki_ = 0.25f * (input_filter_kp_ * input_filter_kp_); // Critically damped

    // Check that we don't get problems with discrete time approximation
    if (!(current_meas_period * input_filter_kp_ < 1.0f)) {
        set_error(ERROR_UNSTABLE_GAIN);
    }
}

bool Controller::update(float pos_estimate, float vel_estimate, float* current_setpoint_output) {
    // Only runs if anticogging_.calib_anticogging is true; non-blocking
    anticogging_calibration(pos_estimate, vel_estimate);
    float anticogging_pos = pos_estimate;

    // Update inputs
    switch (config_.input_mode) {
        case INPUT_MODE_INACTIVE: {
            // do nothing
        } break;
        case INPUT_MODE_PASSTHROUGH: {
            pos_setpoint_ = input_pos_;
            vel_setpoint_ = input_vel_;
            current_setpoint_ = input_current_;
        } break;
        case INPUT_MODE_VEL_RAMP: {
            float max_step_size = current_meas_period * config_.vel_ramp_rate;
            float full_step = input_vel_ - vel_setpoint_;
            float step;
            if (fabsf(full_step) > max_step_size) {
                step = std::copysignf(max_step_size, full_step);
            } else {
                step = full_step;
            }
            vel_setpoint_ += step;
            current_setpoint_ = step / current_meas_period * config_.inertia;
        } break;
        case INPUT_MODE_POS_FILTER: {
            // 2nd order pos tracking filter
            pos_setpoint_ += current_meas_period * vel_setpoint_; // Integrate vel
            float delta_pos = input_pos_ - pos_setpoint_; // Pos error
            pos_setpoint_ += current_meas_period * input_filter_kp_ * delta_pos; // Kp
            float accel = input_filter_ki_ * delta_pos; // Ki
            vel_setpoint_ += current_meas_period * accel; // delta vel
            current_setpoint_ = accel * config_.inertia; // Accel
        } break;
        // case INPUT_MODE_MIX_CHANNELS: {
        //     // NOT YET IMPLEMENTED
        // } break;
        default: {
            set_error(ERROR_INVALID_INPUT_MODE);
            return false;
        }
    }

    // Trajectory control
    if (config_.control_mode == CTRL_MODE_TRAJECTORY_CONTROL) {
        // Note: uint32_t loop count delta is OK across overflow
        // Beware of negative deltas, as they will not be well behaved due to uint!
        float t = (axis_->loop_counter_ - traj_start_loop_count_) * current_meas_period;
        if (t > axis_->trap_.Tf_) {
            // Drop into position control mode when done to avoid problems on loop counter delta overflow
            config_.control_mode = CTRL_MODE_POSITION_CONTROL;
            // pos_setpoint already set by trajectory
            vel_setpoint_ = 0.0f;
            current_setpoint_ = 0.0f;
        } else {
            TrapezoidalTrajectory::Step_t traj_step = axis_->trap_.eval(t);
            pos_setpoint_ = traj_step.Y;
            vel_setpoint_ = traj_step.Yd;
            current_setpoint_ = traj_step.Ydd * config_.inertia;
        }
        anticogging_pos = pos_setpoint_; // FF the position setpoint instead of the pos_estimate
    }

    // Position control
    // TODO Decide if we want to use encoder or pll position here
    float vel_des = vel_setpoint_;
    if (config_.control_mode >= CTRL_MODE_POSITION_CONTROL) {
        float pos_err;
        if (config_.setpoints_in_cpr) {
            // TODO this breaks the semantics that estimates come in on the arguments.
            // It's probably better to call a get_estimate that will arbitrate (enc vs sensorless) instead.
            float cpr = (float)(axis_->encoder_.config_.cpr);
            // Keep pos setpoint from drifting
            pos_setpoint_ = fmodf_pos(pos_setpoint_, cpr);
            // Circular delta
            pos_err = pos_setpoint_ - axis_->encoder_.pos_cpr_;
            pos_err = wrap_pm(pos_err, 0.5f * cpr);
        } else {
            pos_err = pos_setpoint_ - pos_estimate;
        }
        vel_des += config_.pos_gain * pos_err;
    }

    // Velocity limiting
    float vel_lim = config_.vel_limit;
    if (vel_des > vel_lim) vel_des = vel_lim;
    if (vel_des < -vel_lim) vel_des = -vel_lim;

    // Check for overspeed fault (done in this module (controller) for cohesion with vel_lim)
    if (config_.vel_limit_tolerance > 0.0f) { // 0.0f to disable
        if (fabsf(vel_estimate) > config_.vel_limit_tolerance * vel_lim) {
            set_error(ERROR_OVERSPEED);
            return false;
        }
    }

    // Velocity control
    float Iq = current_setpoint_;

    // Anti-cogging is enabled after calibration
    // We get the current position and apply a current feed-forward
    // ensuring that we handle negative encoder positions properly (-1 == motor->encoder.encoder_cpr - 1)
    if (anticogging_.use_anticogging) {
        Iq += anticogging_.cogging_map[mod(static_cast<int>(anticogging_pos), axis_->encoder_.config_.cpr)];
    }

    float v_err = vel_des - vel_estimate;
    if (config_.control_mode >= CTRL_MODE_VELOCITY_CONTROL) {
        Iq += config_.vel_gain * v_err;
    }

    // Velocity integral action before limiting
    Iq += vel_integrator_current_;

    // Current limiting
    float Ilim = std::min(axis_->motor_.config_.current_lim, axis_->motor_.current_control_.max_allowed_current);
    bool limited = false;
    if (Iq > Ilim) {
        limited = true;
        Iq = Ilim;
    }
    if (Iq < -Ilim) {
        limited = true;
        Iq = -Ilim;
    }

    // Velocity integrator (behaviour dependent on limiting)
    if (config_.control_mode < CTRL_MODE_VELOCITY_CONTROL) {
        // reset integral if not in use
        vel_integrator_current_ = 0.0f;
    } else {
        if (limited) {
            // TODO make decayfactor configurable
            vel_integrator_current_ *= 0.99f;
        } else {
            vel_integrator_current_ += (config_.vel_integrator_gain * current_meas_period) * v_err;
        }
    }

    if (current_setpoint_output) *current_setpoint_output = Iq;
    return true;
}
<commit_msg>mass simulation style 2nd order filter works great<commit_after>
#include "odrive_main.h"

Controller::Controller(Config_t& config) :
    config_(config)
{
    update_filter_gains();
}

void Controller::reset() {
    pos_setpoint_ = 0.0f;
    vel_setpoint_ = 0.0f;
    vel_integrator_current_ = 0.0f;
    current_setpoint_ = 0.0f;
}

void Controller::set_error(Error_t error) {
    error_ |= error;
    axis_->error_ |= Axis::ERROR_CONTROLLER_FAILED;
}

//--------------------------------
// Command Handling
//--------------------------------

void Controller::set_pos_setpoint(float pos_setpoint, float vel_feed_forward, float current_feed_forward) {
    pos_setpoint_ = pos_setpoint;
    vel_setpoint_ = vel_feed_forward;
    current_setpoint_ = current_feed_forward;
    config_.control_mode = CTRL_MODE_POSITION_CONTROL;
#ifdef DEBUG_PRINT
    printf("POSITION_CONTROL %6.0f %3.3f %3.3f\n", pos_setpoint, vel_setpoint_, current_setpoint_);
#endif
}

void Controller::set_vel_setpoint(float vel_setpoint, float current_feed_forward) {
    vel_setpoint_ = vel_setpoint;
    current_setpoint_ = current_feed_forward;
    config_.control_mode = CTRL_MODE_VELOCITY_CONTROL;
#ifdef DEBUG_PRINT
    printf("VELOCITY_CONTROL %3.3f %3.3f\n", vel_setpoint_, motor->current_setpoint_);
#endif
}

void Controller::set_current_setpoint(float current_setpoint) {
    current_setpoint_ = current_setpoint;
    config_.control_mode = CTRL_MODE_CURRENT_CONTROL;
#ifdef DEBUG_PRINT
    printf("CURRENT_CONTROL %3.3f\n", current_setpoint_);
#endif
}

void Controller::move_to_pos(float goal_point) {
    axis_->trap_.planTrapezoidal(goal_point, pos_setpoint_, vel_setpoint_,
                                 axis_->trap_.config_.vel_limit,
                                 axis_->trap_.config_.accel_limit,
                                 axis_->trap_.config_.decel_limit);
    traj_start_loop_count_ = axis_->loop_counter_;
    config_.control_mode = CTRL_MODE_TRAJECTORY_CONTROL;
}

void Controller::start_anticogging_calibration() {
    // Ensure the cogging map was correctly allocated earlier and that the motor is capable of calibrating
    if (anticogging_.cogging_map != NULL && axis_->error_ == Axis::ERROR_NONE) {
        anticogging_.calib_anticogging = true;
    }
}

/*
 * This anti-cogging implementation iterates through each encoder position,
 * waits for zero velocity & position error,
 * then samples the current required to maintain that position.
 *
 * This holding current is added as a feedforward term in the control loop.
 */
bool Controller::anticogging_calibration(float pos_estimate, float vel_estimate) {
    if (anticogging_.calib_anticogging && anticogging_.cogging_map != NULL) {
        float pos_err = anticogging_.index - pos_estimate;
        if (fabsf(pos_err) <= anticogging_.calib_pos_threshold &&
            fabsf(vel_estimate) < anticogging_.calib_vel_threshold) {
            anticogging_.cogging_map[anticogging_.index++] = vel_integrator_current_;
        }
        if (anticogging_.index < axis_->encoder_.config_.cpr) { // TODO: remove the dependency on encoder CPR
            set_pos_setpoint(anticogging_.index, 0.0f, 0.0f);
            return false;
        } else {
            anticogging_.index = 0;
            set_pos_setpoint(0.0f, 0.0f, 0.0f);  // Send the motor home
            anticogging_.use_anticogging = true;  // We're good to go, enable anti-cogging
            anticogging_.calib_anticogging = false;
            return true;
        }
    }
    return false;
}

void Controller::update_filter_gains() {
    input_filter_ki_ = 2.0f * config_.input_filter_bandwidth;  // basic conversion to discrete time
    input_filter_kp_ = 0.25f * (input_filter_ki_ * input_filter_ki_); // Critically damped
}

bool Controller::update(float pos_estimate, float vel_estimate, float* current_setpoint_output) {
    // Only runs if anticogging_.calib_anticogging is true; non-blocking
    anticogging_calibration(pos_estimate, vel_estimate);
    float anticogging_pos = pos_estimate;

    // Update inputs
    switch (config_.input_mode) {
        case INPUT_MODE_INACTIVE: {
            // do nothing
        } break;
        case INPUT_MODE_PASSTHROUGH: {
            pos_setpoint_ = input_pos_;
            vel_setpoint_ = input_vel_;
            current_setpoint_ = input_current_;
        } break;
        case INPUT_MODE_VEL_RAMP: {
            float max_step_size = current_meas_period * config_.vel_ramp_rate;
            float full_step = input_vel_ - vel_setpoint_;
            float step;
            if (fabsf(full_step) > max_step_size) {
                step = std::copysignf(max_step_size, full_step);
            } else {
                step = full_step;
            }
            vel_setpoint_ += step;
            current_setpoint_ = step / current_meas_period * config_.inertia;
        } break;
        case INPUT_MODE_POS_FILTER: {
            // 2nd order pos tracking filter
            pos_setpoint_ += current_meas_period * vel_setpoint_; // Delta pos
            float delta_pos = input_pos_ - pos_setpoint_; // Pos error
            float delta_vel = input_vel_ - vel_setpoint_; // Vel error
            float accel = input_filter_kp_*delta_pos + input_filter_ki_*delta_vel; // Feedback
            vel_setpoint_ += current_meas_period * accel; // delta vel
            current_setpoint_ = accel * config_.inertia; // Accel
        } break;
        // case INPUT_MODE_MIX_CHANNELS: {
        //     // NOT YET IMPLEMENTED
        // } break;
        default: {
            set_error(ERROR_INVALID_INPUT_MODE);
            return false;
        }
    }

    // Trajectory control
    if (config_.control_mode == CTRL_MODE_TRAJECTORY_CONTROL) {
        // Note: uint32_t loop count delta is OK across overflow
        // Beware of negative deltas, as they will not be well behaved due to uint!
        float t = (axis_->loop_counter_ - traj_start_loop_count_) * current_meas_period;
        if (t > axis_->trap_.Tf_) {
            // Drop into position control mode when done to avoid problems on loop counter delta overflow
            config_.control_mode = CTRL_MODE_POSITION_CONTROL;
            // pos_setpoint already set by trajectory
            vel_setpoint_ = 0.0f;
            current_setpoint_ = 0.0f;
        } else {
            TrapezoidalTrajectory::Step_t traj_step = axis_->trap_.eval(t);
            pos_setpoint_ = traj_step.Y;
            vel_setpoint_ = traj_step.Yd;
            current_setpoint_ = traj_step.Ydd * config_.inertia;
        }
        anticogging_pos = pos_setpoint_; // FF the position setpoint instead of the pos_estimate
    }

    // Position control
    // TODO Decide if we want to use encoder or pll position here
    float vel_des = vel_setpoint_;
    if (config_.control_mode >= CTRL_MODE_POSITION_CONTROL) {
        float pos_err;
        if (config_.setpoints_in_cpr) {
            // TODO this breaks the semantics that estimates come in on the arguments.
            // It's probably better to call a get_estimate that will arbitrate (enc vs sensorless) instead.
            float cpr = (float)(axis_->encoder_.config_.cpr);
            // Keep pos setpoint from drifting
            pos_setpoint_ = fmodf_pos(pos_setpoint_, cpr);
            // Circular delta
            pos_err = pos_setpoint_ - axis_->encoder_.pos_cpr_;
            pos_err = wrap_pm(pos_err, 0.5f * cpr);
        } else {
            pos_err = pos_setpoint_ - pos_estimate;
        }
        vel_des += config_.pos_gain * pos_err;
    }

    // Velocity limiting
    float vel_lim = config_.vel_limit;
    if (vel_des > vel_lim) vel_des = vel_lim;
    if (vel_des < -vel_lim) vel_des = -vel_lim;

    // Check for overspeed fault (done in this module (controller) for cohesion with vel_lim)
    if (config_.vel_limit_tolerance > 0.0f) { // 0.0f to disable
        if (fabsf(vel_estimate) > config_.vel_limit_tolerance * vel_lim) {
            set_error(ERROR_OVERSPEED);
            return false;
        }
    }

    // Velocity control
    float Iq = current_setpoint_;

    // Anti-cogging is enabled after calibration
    // We get the current position and apply a current feed-forward
    // ensuring that we handle negative encoder positions properly (-1 == motor->encoder.encoder_cpr - 1)
    if (anticogging_.use_anticogging) {
        Iq += anticogging_.cogging_map[mod(static_cast<int>(anticogging_pos), axis_->encoder_.config_.cpr)];
    }

    float v_err = vel_des - vel_estimate;
    if (config_.control_mode >= CTRL_MODE_VELOCITY_CONTROL) {
        Iq += config_.vel_gain * v_err;
    }

    // Velocity integral action before limiting
    Iq += vel_integrator_current_;

    // Current limiting
    float Ilim = std::min(axis_->motor_.config_.current_lim, axis_->motor_.current_control_.max_allowed_current);
    bool limited = false;
    if (Iq > Ilim) {
        limited = true;
        Iq = Ilim;
    }
    if (Iq < -Ilim) {
        limited = true;
        Iq = -Ilim;
    }

    // Velocity integrator (behaviour dependent on limiting)
    if (config_.control_mode < CTRL_MODE_VELOCITY_CONTROL) {
        // reset integral if not in use
        vel_integrator_current_ = 0.0f;
    } else {
        if (limited) {
            // TODO make decayfactor configurable
            vel_integrator_current_ *= 0.99f;
        } else {
            vel_integrator_current_ += (config_.vel_integrator_gain * current_meas_period) * v_err;
        }
    }

    if (current_setpoint_output) *current_setpoint_output = Iq;
    return true;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: HStorageMap.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-21 16:40:13 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the License); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Ocke Janssen
 *
 *
 ************************************************************************/
#include "hsqldb/HStorageMap.hxx"

#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
//........................................................................
namespace connectivity
{
//........................................................................
    namespace hsqldb
    {
    //........................................................................
        using namespace ::com::sun::star::uno;
        using namespace ::com::sun::star::lang;
        using namespace ::com::sun::star::embed;
        using namespace ::com::sun::star::io;

#define ThrowException(env, type, msg) { \
    env->ThrowNew(env->FindClass(type), msg); }

        StreamHelper::StreamHelper(const Reference< XStream>& _xStream)
            : m_xStream(_xStream)
        {
        }
        // -----------------------------------------------------------------------------
        StreamHelper::~StreamHelper()
        {
            try
            {
                if ( m_xInputStream.is() )
                {
                    m_xInputStream->closeInput();
                    m_xInputStream = NULL;
                }
                if ( m_xOutputStream.is() )
                {
                    m_xOutputStream->closeOutput();
                    try
                    {
                        ::comphelper::disposeComponent(m_xOutputStream);
                    }
                    catch(const Exception& e)
                    {
                        e;
                        OSL_ENSURE(0,"Could not dispose OutputStream");
                    }
                    m_xOutputStream = NULL;
                }
                m_xStream = NULL;
                m_xSeek = NULL;
            }
            catch(Exception& )
            {
                OSL_ENSURE(0,"Exception catched!");
            }
        }
        // -----------------------------------------------------------------------------
        Reference< XInputStream> StreamHelper::getInputStream()
        {
            if ( !m_xInputStream.is() )
                m_xInputStream = m_xStream->getInputStream();
            return m_xInputStream;
        }
        // -----------------------------------------------------------------------------
        Reference< XOutputStream> StreamHelper::getOutputStream()
        {
            if ( !m_xOutputStream.is() )
                m_xOutputStream = m_xStream->getOutputStream();
            return m_xOutputStream;
        }
        // -----------------------------------------------------------------------------
        Reference< XStream> StreamHelper::getStream()
        {
            return m_xStream;
        }
        // -----------------------------------------------------------------------------
        Reference< XSeekable> StreamHelper::getSeek()
        {
            if ( !m_xSeek.is() )
                m_xSeek.set(m_xStream,UNO_QUERY);
            return m_xSeek;
        }
        // -----------------------------------------------------------------------------
        TStorages& lcl_getStorageMap()
        {
            static TStorages s_aMap;
            return s_aMap;
        }
        // -----------------------------------------------------------------------------
        ::rtl::OUString lcl_getNextCount()
        {
            static sal_Int32 s_nCount = 0;
            return ::rtl::OUString::valueOf(s_nCount++);
        }
        // -----------------------------------------------------------------------------
        ::rtl::OUString StorageContainer::removeURLPrefix(const ::rtl::OUString& _sURL)
        {
            ::rtl::OUString sRet = _sURL;
#if defined(WIN) || defined(WNT)
            sal_Int32 nIndex = sRet.lastIndexOf('\\');
#else
            sal_Int32 nIndex = sRet.lastIndexOf('/');
#endif
            if ( nIndex != -1 )
            {
                sRet = _sURL.copy(nIndex+1);
            }
            return sRet;

        }
        /*****************************************************************************/
        /* convert jstring to rtl_uString */

        ::rtl::OUString StorageContainer::jstring2ustring(JNIEnv * env, jstring jstr)
        {
            const char *    cstr;
            rtl_uString *   ustr    = NULL;
            cstr    = env->GetStringUTFChars(jstr, NULL);
            if (JNI_FALSE != env->ExceptionCheck())
            {
                env->ExceptionClear();
                OSL_ENSURE(0,"ExceptionClear");
            }
            rtl_uString_newFromAscii(&ustr, cstr);
            env->ReleaseStringUTFChars(jstr, cstr);
            if (JNI_FALSE != env->ExceptionCheck())
            {
                env->ExceptionClear();
                OSL_ENSURE(0,"ExceptionClear");
            }
            return ustr ? ::rtl::OUString(ustr,SAL_NO_ACQUIRE) : ::rtl::OUString();
        }

        // -----------------------------------------------------------------------------
        ::rtl::OUString StorageContainer::registerStorage(const Reference< XStorage>& _xStorage,const ::rtl::OUString& _sURL)
        {
            OSL_ENSURE(_xStorage.is(),"Storage is NULL!");
            TStorages& rMap = lcl_getStorageMap();
            // check if the storage is already in our map
            TStorages::iterator aFind = ::std::find_if(rMap.begin(),rMap.end(),
                                        ::std::compose1(
                                            ::std::bind2nd(::std::equal_to<Reference<XStorage> >(),_xStorage)
                                            ,::std::compose1(::std::select1st<TStorages::mapped_type>(),::std::select2nd<TStorages::value_type>()))
                    );
            if ( aFind == rMap.end() )
            {
                aFind = rMap.insert(TStorages::value_type(lcl_getNextCount(),TStorages::mapped_type(_xStorage,TStreamMap()))).first;
            }

            return aFind->first;
        }
        // -----------------------------------------------------------------------------
        Reference< XStorage> StorageContainer::getRegisteredStorage(const ::rtl::OUString& _sKey)
        {
            Reference< XStorage> xReturn;
            TStorages& rMap = lcl_getStorageMap();
            TStorages::iterator aFind = rMap.find(_sKey);
            OSL_ENSURE(aFind != rMap.end(),"Storage could not be found in list!");
            if ( aFind != rMap.end() )
                xReturn = aFind->second.first;

            return xReturn;
        }
        // -----------------------------------------------------------------------------
        void StorageContainer::revokeStorage(const ::rtl::OUString& _sKey)
        {
            TStorages& rMap = lcl_getStorageMap();
            rMap.erase(_sKey);
        }
        // -----------------------------------------------------------------------------
        TStreamMap::mapped_type StorageContainer::registerStream(JNIEnv * env,jstring name, jstring key,sal_Int32 _nMode)
        {
            TStreamMap::mapped_type pHelper;
            TStorages& rMap = lcl_getStorageMap();
            ::rtl::OUString sKey = jstring2ustring(env,key);
            TStorages::iterator aFind = rMap.find(sKey);
            OSL_ENSURE(aFind != rMap.end(),"Storage could not be found in list!");
            if ( aFind != rMap.end() )
            {
                Reference< XStorage> xStorage = StorageContainer::getRegisteredStorage(sKey);
                OSL_ENSURE(xStorage.is(),"No Storage available!");
                if ( xStorage.is() )
                {
                    ::rtl::OUString sName = removeURLPrefix(jstring2ustring(env,name));
                    TStreamMap::iterator aStreamFind = aFind->second.second.find(sName);
                    OSL_ENSURE( aStreamFind == aFind->second.second.end(),"A Stream was already registered for this object!");
                    if ( aStreamFind != aFind->second.second.end() )
                    {
                        pHelper = aStreamFind->second;
                    }
                    else
                    {
                        try
                        {
                            pHelper.reset(new StreamHelper(xStorage->openStreamElement(sName,_nMode)));
                            aFind->second.second.insert(TStreamMap::value_type(sName,pHelper));
                        }
                        catch(Exception& e)
                        {
                            OSL_ENSURE(0,"Exception catched!");
                            if (JNI_FALSE != env->ExceptionCheck())
                                env->ExceptionClear();
                            ::rtl::OString cstr( ::rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_JAVA_UTF8 ) );
                            OSL_TRACE( __FILE__": forwarding Exception: %s", cstr.getStr() );
                            ThrowException( env,
                                            "java/io/IOException",
                                            cstr.getStr());
                        }
                    }
                }
            }
            return pHelper;
        }
        // -----------------------------------------------------------------------------
        void StorageContainer::revokeStream( JNIEnv * env,jstring name, jstring key)
        {
            TStorages& rMap = lcl_getStorageMap();
            TStorages::iterator aFind = rMap.find(jstring2ustring(env,key));
            OSL_ENSURE(aFind != rMap.end(),"Storage could not be found in list!");
            if ( aFind != rMap.end() )
                aFind->second.second.erase(removeURLPrefix(jstring2ustring(env,name)));
        }
        // -----------------------------------------------------------------------------
        TStreamMap::mapped_type StorageContainer::getRegisteredStream( JNIEnv * env,jstring name, jstring key)
        {
            TStreamMap::mapped_type  pRet;
            TStorages& rMap = lcl_getStorageMap();
            TStorages::iterator aFind = rMap.find(jstring2ustring(env,key));
            OSL_ENSURE(aFind != rMap.end(),"Storage could not be found in list!");
            if ( aFind != rMap.end() )
            {
                TStreamMap::iterator aStreamFind = aFind->second.second.find(removeURLPrefix(jstring2ustring(env,name)));
                if ( aStreamFind != aFind->second.second.end() )
                    pRet = aStreamFind->second;
            }

            return pRet;
        }
        // -----------------------------------------------------------------------------
    //........................................................................
    }   // namespace hsqldb
    //........................................................................
//........................................................................
}
// namespace connectivity
//........................................................................

<commit_msg>INTEGRATION: CWS hsqldb2 (1.2.20); FILE MERGED 2005/01/28 12:21:54 oj 1.2.20.3: #i39922# new interfaces in hsqldb and some debug info 2005/01/25 08:42:51 oj 1.2.20.2: #i39922# correct stream handling 2005/01/19 07:03:28 oj 1.2.20.1: #i39922# remove db from stream name<commit_after>/*************************************************************************
 *
 *  $RCSfile: HStorageMap.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2005-02-16 15:51:25 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the License); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Ocke Janssen
 *
 *
 ************************************************************************/
#include "hsqldb/HStorageMap.hxx"

#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COM_SUN_STAR_EMBED_XTRANSACTIONBROADCASTER_HPP_
#include <com/sun/star/embed/XTransactionBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XTRANSACTEDOBJECT_HPP_
#include <com/sun/star/embed/XTransactedObject.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif

//........................................................................
namespace connectivity
{
//........................................................................
    namespace hsqldb
    {
    //........................................................................
        using namespace ::com::sun::star::uno;
        using namespace ::com::sun::star::lang;
        using namespace ::com::sun::star::embed;
        using namespace ::com::sun::star::io;

#define ThrowException(env, type, msg) { \
    env->ThrowNew(env->FindClass(type), msg); }

        StreamHelper::StreamHelper(const Reference< XStream>& _xStream)
            : m_xStream(_xStream)
        {
        }
        // -----------------------------------------------------------------------------
        StreamHelper::~StreamHelper()
        {
            try
            {
                m_xStream = NULL;
                m_xSeek = NULL;
                if ( m_xInputStream.is() )
                {
                    m_xInputStream->closeInput();
                    m_xInputStream = NULL;
                }
                if ( m_xOutputStream.is() )
                {
                    m_xOutputStream->closeOutput();
                    try
                    {
                        ::comphelper::disposeComponent(m_xOutputStream);
                    }
                    catch(DisposedException&)
                    {
                    }
                    catch(const Exception& e)
                    {
                        e;
                        OSL_ENSURE(0,"Could not dispose OutputStream");
                    }
                    m_xOutputStream = NULL;
                }
            }
            catch(Exception& )
            {
                OSL_ENSURE(0,"Exception catched!");
            }
        }
        // -----------------------------------------------------------------------------
        Reference< XInputStream> StreamHelper::getInputStream()
        {
            if ( !m_xInputStream.is() )
                m_xInputStream = m_xStream->getInputStream();
            return m_xInputStream;
        }
        // -----------------------------------------------------------------------------
        Reference< XOutputStream> StreamHelper::getOutputStream()
        {
            if ( !m_xOutputStream.is() )
                m_xOutputStream = m_xStream->getOutputStream();
            return m_xOutputStream;
        }
        // -----------------------------------------------------------------------------
        Reference< XStream> StreamHelper::getStream()
        {
            return m_xStream;
        }
        // -----------------------------------------------------------------------------
        Reference< XSeekable> StreamHelper::getSeek()
        {
            if ( !m_xSeek.is() )
                m_xSeek.set(m_xStream,UNO_QUERY);
            return m_xSeek;
        }
        // -----------------------------------------------------------------------------
        TStorages& lcl_getStorageMap()
        {
            static TStorages s_aMap;
            return s_aMap;
        }
        // -----------------------------------------------------------------------------
        ::rtl::OUString lcl_getNextCount()
        {
            static sal_Int32 s_nCount = 0;
            return ::rtl::OUString::valueOf(s_nCount++);
        }
        // -----------------------------------------------------------------------------
        ::rtl::OUString StorageContainer::removeURLPrefix(const ::rtl::OUString& _sURL,const ::rtl::OUString& _sFileURL)
        {
            return _sURL.copy(_sFileURL.getLength()+1);
        }
        // -----------------------------------------------------------------------------
        ::rtl::OUString StorageContainer::removeOldURLPrefix(const ::rtl::OUString& _sURL)
        {
            ::rtl::OUString sRet = _sURL;
#if defined(WIN) || defined(WNT)
            sal_Int32 nIndex = sRet.lastIndexOf('\\');
#else
            sal_Int32 nIndex = sRet.lastIndexOf('/');
#endif
            if ( nIndex != -1 )
            {
                sRet = _sURL.copy(nIndex+1);
            }
            return sRet;

        }
        /*****************************************************************************/
        /* convert jstring to rtl_uString */

        ::rtl::OUString StorageContainer::jstring2ustring(JNIEnv * env, jstring jstr)
        {
            const char *    cstr;
            rtl_uString *   ustr    = NULL;
            cstr    = env->GetStringUTFChars(jstr, NULL);
            if (JNI_FALSE != env->ExceptionCheck())
            {
                env->ExceptionClear();
                OSL_ENSURE(0,"ExceptionClear");
            }
            rtl_uString_newFromAscii(&ustr, cstr);
            env->ReleaseStringUTFChars(jstr, cstr);
            if (JNI_FALSE != env->ExceptionCheck())
            {
                env->ExceptionClear();
                OSL_ENSURE(0,"ExceptionClear");
            }
            return ustr ? ::rtl::OUString(ustr,SAL_NO_ACQUIRE) : ::rtl::OUString();
        }

        // -----------------------------------------------------------------------------
        ::rtl::OUString StorageContainer::registerStorage(const Reference< XStorage>& _xStorage,const ::rtl::OUString& _sURL)
        {
            OSL_ENSURE(_xStorage.is(),"Storage is NULL!");
            TStorages& rMap = lcl_getStorageMap();
            // check if the storage is already in our map
            TStorages::iterator aFind = ::std::find_if(rMap.begin(),rMap.end(),
                                        ::std::compose1(
                                            ::std::bind2nd(::std::equal_to<Reference<XStorage> >(),_xStorage)
                                            ,::std::compose1(::std::select1st<TStorageURLPair>(),::std::compose1(::std::select1st<TStorages::mapped_type>(),::std::select2nd<TStorages::value_type>())))
                    );
            if ( aFind == rMap.end() )
            {
                aFind = rMap.insert(TStorages::value_type(lcl_getNextCount(),TStorages::mapped_type(TStorageURLPair(_xStorage,_sURL),TStreamMap()))).first;
            }

            return aFind->first;
        }
        // -----------------------------------------------------------------------------
        TStorages::mapped_type StorageContainer::getRegisteredStorage(const ::rtl::OUString& _sKey)
        {
            TStorages::mapped_type aRet;
            TStorages& rMap = lcl_getStorageMap();
            TStorages::iterator aFind = rMap.find(_sKey);
            OSL_ENSURE(aFind != rMap.end(),"Storage could not be found in list!");
            if ( aFind != rMap.end() )
                aRet = aFind->second;

            return aRet;
        }
        // -----------------------------------------------------------------------------
        ::rtl::OUString StorageContainer::getRegisteredKey(const Reference< XStorage>& _xStorage)
        {
            ::rtl::OUString sKey;
            OSL_ENSURE(_xStorage.is(),"Storage is NULL!");
            TStorages& rMap = lcl_getStorageMap();
            // check if the storage is already in our map
            TStorages::iterator aFind = ::std::find_if(rMap.begin(),rMap.end(),
                                        ::std::compose1(
                                            ::std::bind2nd(::std::equal_to<Reference<XStorage> >(),_xStorage)
                                            ,::std::compose1(::std::select1st<TStorageURLPair>(),::std::compose1(::std::select1st<TStorages::mapped_type>(),::std::select2nd<TStorages::value_type>())))
                    );
            if ( aFind != rMap.end() )
                sKey = aFind->first;
            return sKey;
        }
        // -----------------------------------------------------------------------------
        void StorageContainer::revokeStorage(const ::rtl::OUString& _sKey,const Reference<XTransactionListener>& _xListener)
        {
            TStorages& rMap = lcl_getStorageMap();
            TStorages::iterator aFind = rMap.find(_sKey);
            if ( aFind != rMap.end() )
            {
                try
                {
                    if ( _xListener.is() )
                    {
                        Reference<XTransactionBroadcaster> xBroad(aFind->second.first.first,UNO_QUERY);
                        if ( xBroad.is() )
                            xBroad->removeTransactionListener(_xListener);
                        Reference<XTransactedObject> xTrans(aFind->second.first.first,UNO_QUERY);
                        if ( xTrans.is() )
                            xTrans->commit();
                    }
                }
                catch(Exception&)
                {
                }
                rMap.erase(aFind);
            }
        }
        // -----------------------------------------------------------------------------
        TStreamMap::mapped_type StorageContainer::registerStream(JNIEnv * env,jstring name, jstring key,sal_Int32 _nMode)
        {
            TStreamMap::mapped_type pHelper;
            TStorages& rMap = lcl_getStorageMap();
            ::rtl::OUString sKey = jstring2ustring(env,key);
            TStorages::iterator aFind = rMap.find(sKey);
            OSL_ENSURE(aFind != rMap.end(),"Storage could not be found in list!");
            if ( aFind != rMap.end() )
            {
                TStorages::mapped_type aStoragePair = StorageContainer::getRegisteredStorage(sKey);
                OSL_ENSURE(aStoragePair.first.first.is(),"No Storage available!");
                if ( aStoragePair.first.first.is() )
                {
                    ::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);
                    ::rtl::OUString sName = removeURLPrefix(sOrgName,aStoragePair.first.second);
                    TStreamMap::iterator aStreamFind = aFind->second.second.find(sName);
                    OSL_ENSURE( aStreamFind == aFind->second.second.end(),"A Stream was already registered for this object!");
                    if ( aStreamFind != aFind->second.second.end() )
                    {
                        pHelper = aStreamFind->second;
                    }
                    else
                    {
                        try
                        {
                            try
                            {
                                pHelper.reset(new StreamHelper(aStoragePair.first.first->openStreamElement(sName,_nMode)));
                            }
                            catch(Exception& )
                            {
                                ::rtl::OUString sName = removeOldURLPrefix(sOrgName);
                                pHelper.reset(new StreamHelper(aStoragePair.first.first->openStreamElement(sName,_nMode)));
                            }
                            aFind->second.second.insert(TStreamMap::value_type(sName,pHelper));
                        }
                        catch(Exception& e)
                        {
                            OSL_ENSURE(0,"Exception catched!");
                            if (JNI_FALSE != env->ExceptionCheck())
                                env->ExceptionClear();
                            ::rtl::OString cstr( ::rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_JAVA_UTF8 ) );
                            OSL_TRACE( __FILE__": forwarding Exception: %s", cstr.getStr() );
                            ThrowException( env,
                                            "java/io/IOException",
                                            cstr.getStr());
                        }
                    }
                }
            }
            return pHelper;
        }
        // -----------------------------------------------------------------------------
        void StorageContainer::revokeStream( JNIEnv * env,jstring name, jstring key)
        {
            TStorages& rMap = lcl_getStorageMap();
            TStorages::iterator aFind = rMap.find(jstring2ustring(env,key));
            OSL_ENSURE(aFind != rMap.end(),"Storage could not be found in list!");
            if ( aFind != rMap.end() )
                aFind->second.second.erase(removeURLPrefix(jstring2ustring(env,name),aFind->second.first.second));
        }
        // -----------------------------------------------------------------------------
        TStreamMap::mapped_type StorageContainer::getRegisteredStream( JNIEnv * env,jstring name, jstring key)
        {
            TStreamMap::mapped_type  pRet;
            TStorages& rMap = lcl_getStorageMap();
            TStorages::iterator aFind = rMap.find(jstring2ustring(env,key));
            OSL_ENSURE(aFind != rMap.end(),"Storage could not be found in list!");
            if ( aFind != rMap.end() )
            {
                TStreamMap::iterator aStreamFind = aFind->second.second.find(removeURLPrefix(jstring2ustring(env,name),aFind->second.first.second));
                if ( aStreamFind != aFind->second.second.end() )
                    pRet = aStreamFind->second;
            }

            return pRet;
        }
        // -----------------------------------------------------------------------------
    //........................................................................
    }   // namespace hsqldb
    //........................................................................
//........................................................................
}
// namespace connectivity
//........................................................................
#if OSL_DEBUG_LEVEL > 1
TDebugStreamMap& getStreams()
{
    static TDebugStreamMap streams;
    return streams;
}
#endif
<|endoftext|>