<commit_before>
#include <stdio.h>

#include <cppuhelper/factory.hxx>

#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/implbase2.hxx>

#include <com/sun/star/bridge/XUnoUrlResolver.hpp>

#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/loader/XImplementationLoader.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>

using namespace ::com::sun::star::bridge;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::loader;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::registry;

using namespace ::cppu;
using namespace ::rtl;

namespace dynamic_loader {

    class SingleServiceFactory : public WeakImplHelper2<XServiceInfo, XSingleServiceFactory> {
        Reference<XMultiServiceFactory> _xServiceManager;
        OUString _serviceName;
        OUString _link;
        OUString _resolver;

        Reference<XSingleServiceFactory> getRemoteFactory() throw(Exception, RuntimeException);

    public:

        SingleServiceFactory(const Reference<XMultiServiceFactory > & xServiceManager,
                             const OUString & serviceName,
                             const OUString & link,
                             const OUString & resolver)
            : _xServiceManager(xServiceManager),
              _serviceName(serviceName),
              _link(link),
              _resolver(resolver)
        {}

        // XSingleServiceFactory
        Reference<XInterface> SAL_CALL createInstance() throw(Exception, RuntimeException);
        Reference<XInterface> SAL_CALL createInstanceWithArguments(const Sequence<Any>& Arguments)
            throw(::com::sun::star::uno::Exception,
                  ::com::sun::star::uno::RuntimeException);

        // XServiceInfo
        OUString           SAL_CALL getImplementationName()                      throw(RuntimeException);
        sal_Bool           SAL_CALL supportsService(const OUString& ServiceName) throw(RuntimeException);
        Sequence<OUString> SAL_CALL getSupportedServiceNames(void)               throw(RuntimeException);
    };

    Reference<XSingleServiceFactory> SingleServiceFactory::getRemoteFactory() throw(Exception, RuntimeException) {
        Reference<XUnoUrlResolver> xResolver(_xServiceManager->createInstance(_resolver), UNO_QUERY);
        if(!xResolver.is()) {
            OUString message(RTL_CONSTASCII_USTRINGPARAM("dynamic_loader::singleServiceFactory.createInstance - couldn't create resolver: "));
            message += _resolver;

            throw Exception(message, Reference<XInterface>());
        }

        Reference<XInterface> remoteObject = xResolver->resolve(_link);
        if(!remoteObject.is()) {
            OUString message(RTL_CONSTASCII_USTRINGPARAM("dynamic_loader::singleServiceFactory.createInstance - couldn't resolve link: "));
            message += _link;

            throw Exception(message, Reference<XInterface>());
        }

        Reference<XSingleServiceFactory> remoteFactory(remoteObject, UNO_QUERY);
        if(!remoteFactory.is()) {
            OUString message(RTL_CONSTASCII_USTRINGPARAM("dynamic_loader::singleServiceFactory.createInstance - couldn't get XSingleServiceFactory from: "));
            message += _link;

            throw Exception(message, Reference<XInterface>());
        }

        return remoteFactory;
    }

    // XSingleServiceFactory
    Reference<XInterface> SAL_CALL SingleServiceFactory::createInstance() throw(Exception, RuntimeException) {
        OSL_TRACE("dynamic_loader::singleServiceFactory::createInstance");

        return getRemoteFactory()->createInstance();
    }

    Reference<XInterface> SAL_CALL SingleServiceFactory::createInstanceWithArguments(const Sequence<Any>& Arguments)
        throw(Exception, RuntimeException)
    {
        OSL_TRACE("dynamic_loader::singleServiceFactory::createInstanceWithArguments");

        return getRemoteFactory()->createInstanceWithArguments(Arguments);
    }

    // XServiceInfo
    OUString SAL_CALL SingleServiceFactory::getImplementationName() throw(RuntimeException) {
        return _link;
    }

    sal_Bool SAL_CALL SingleServiceFactory::supportsService(const OUString & ServiceName) throw(RuntimeException) {
        return _serviceName.equals(ServiceName);
    }

    Sequence<OUString> SAL_CALL SingleServiceFactory::getSupportedServiceNames(void) throw(RuntimeException) {
        return Sequence<OUString>(&_serviceName, 1);
    }

    class DynamicLoader : public WeakImplHelper2<XImplementationLoader, XServiceInfo> {
        Reference<XMultiServiceFactory>  _xSMgr;

    protected:
        DynamicLoader(const Reference<XMultiServiceFactory> & rXSMgr) throw(RuntimeException);
        ~DynamicLoader();

    public:
        static const OUString implname;
        static const OUString servname;

        static Reference<XInterface> SAL_CALL createInstance(const Reference<XMultiServiceFactory> & rSMgr) throw(Exception);
        static Sequence<OUString>    SAL_CALL getSupportedServiceNames_Static() throw();

        static void parseUrl(const OUString & url, OUString * serviceName, OUString * link, OUString * resolver) throw(RuntimeException);

        // XServiceInfo
        virtual OUString           SAL_CALL getImplementationName()                      throw(RuntimeException);
        virtual sal_Bool           SAL_CALL supportsService(const OUString& ServiceName) throw(RuntimeException);
        virtual Sequence<OUString> SAL_CALL getSupportedServiceNames()                   throw(RuntimeException);

        // XImplementationLoader
        virtual Reference<XInterface> SAL_CALL activate(const OUString & implementationName,
                                                        const OUString & implementationLoaderUrl,
                                                        const OUString& locationUrl,
                                                        const Reference<XRegistryKey>& xKey)       throw(CannotActivateFactoryException, RuntimeException);
        virtual sal_Bool              SAL_CALL writeRegistryInfo(const Reference<XRegistryKey>& xKey,
                                                                 const OUString& implementationLoaderUrl,
                                                                 const OUString& locationUrl)      throw(CannotRegisterImplementationException, RuntimeException);
    };

    const OUString DynamicLoader::implname = OUString::createFromAscii("com.sun.star.comp.stoc.DynamicLoader");
    const OUString DynamicLoader::servname = OUString::createFromAscii("com.sun.star.loader.Dynamic");

    Sequence<OUString> SAL_CALL DynamicLoader::getSupportedServiceNames_Static() throw() {
        return Sequence<OUString>(&servname, 1);
    }

    Reference<XInterface> SAL_CALL DynamicLoader::createInstance(const Reference<XMultiServiceFactory> & rSMgr) throw(Exception) {
        Reference<XInterface> xRet;

        try {
            XImplementationLoader *pXLoader = (XImplementationLoader *)new DynamicLoader(rSMgr);

            xRet = Reference<XInterface>::query(pXLoader);
        }
        catch(RuntimeException & runtimeException) {
            OString message = OUStringToOString(runtimeException.Message, RTL_TEXTENCODING_ASCII_US);
            osl_trace("dynamic loader - could not init cause of %s", message.getStr());
        }

        OSL_TRACE("DynamicLoader - createInstance: %d", xRet.is());

        return xRet;
    }

    DynamicLoader::DynamicLoader(const Reference<XMultiServiceFactory> & xSMgr) throw(RuntimeException)
        : _xSMgr(xSMgr)
    {
    }

    DynamicLoader::~DynamicLoader() throw() {
    }

    // XServiceInfo
    OUString SAL_CALL DynamicLoader::getImplementationName() throw(RuntimeException) {
        return implname;
    }

    sal_Bool SAL_CALL DynamicLoader::supportsService(const OUString & ServiceName) throw(RuntimeException)  {
        sal_Bool bSupport = sal_False;

        Sequence<OUString> aSNL = getSupportedServiceNames();
        const OUString * pArray = aSNL.getArray();
        for(sal_Int32 i = 0; i < aSNL.getLength() && !bSupport; ++ i)
            bSupport = pArray[i] == ServiceName;

        return bSupport;
    }

    Sequence<OUString> SAL_CALL DynamicLoader::getSupportedServiceNames() throw(RuntimeException) {
        return getSupportedServiceNames_Static();
    }

    void DynamicLoader::parseUrl(const OUString & locationUrl, OUString * serviceName, OUString * link, OUString * resolver) throw(RuntimeException) {
#ifdef DEBUG
        OString tmp = OUStringToOString(locationUrl, RTL_TEXTENCODING_ASCII_US);
        OSL_TRACE("DynamicLoader - locationUrl %s", tmp.getStr());
#endif

        // This is the default resolver
        *resolver = OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.UnoUrlResolver"));

        const OUString bSlash(OUString(RTL_CONSTASCII_USTRINGPARAM("\\")));
        const OUString tuedle(OUString(RTL_CONSTASCII_USTRINGPARAM("\"")));
        const OUString separator(OUString(RTL_CONSTASCII_USTRINGPARAM(",")));
        const OUString emptyString(OUString(RTL_CONSTASCII_USTRINGPARAM("")));
        const OUString equalSign(OUString(RTL_CONSTASCII_USTRINGPARAM("=")));

        sal_Int32 index = 0;
        sal_Bool  left = sal_True;
        sal_Bool  quote = sal_False;
        sal_Bool  inString = sal_False;

        const sal_Unicode * raw_url = locationUrl.getStr();
        OUString token;
        OUString attribute;

        while(index <= locationUrl.getLength()) {
            if(index >= locationUrl.getLength() || (raw_url[index] == separator.getStr()[0] && !quote && !inString)) { // a separator or end?
                OUString value;

                if(left)
                    attribute = token.trim();

                else
                    value = token.trim();

#ifdef DEBUG
                OString attribute_tmp = OUStringToOString(attribute, RTL_TEXTENCODING_ASCII_US);
                OSL_TRACE("DynamicLoader - attribute %s", attribute_tmp.getStr());
                OString value_tmp = OUStringToOString(value, RTL_TEXTENCODING_ASCII_US);
                OSL_TRACE("DynamicLoader - value %s", value_tmp.getStr());
#endif

                if(attribute.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("servicename"))))
                    *serviceName = value;

                else if(attribute.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("link"))))
                    *link = value;

                else if(attribute.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("resolver"))))
                    *resolver = value;

                else  {
                    OUString message(RTL_CONSTASCII_USTRINGPARAM("help called"));

                    if(!attribute.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("help")))) {
                        message = OUString(RTL_CONSTASCII_USTRINGPARAM("DynamicLoader - unknown attribute: "));
                        message += attribute;
                    }

                    fprintf(stdout, "DynamicLoader - help\n");
                    fprintf(stdout, "attributes:\n");
                    fprintf(stdout, "\tservicename:  service name of dynamic component\n");
                    fprintf(stdout, "\tlink:         link to a single service factory for dynamic component\n");
                    fprintf(stdout, "\tresolver:     the service which resolves the link\n");
                    fprintf(stdout, "\thelp:         this help\n");

                    throw RuntimeException(message, Reference<XInterface>());
                }

                left = sal_True; // reset state to be left
                token = emptyString;
            }
            else if(raw_url[index] == bSlash.getStr()[0] && !quote) // a back slash?
                quote = sal_True;

            else if(raw_url[index] == equalSign.getStr()[0] && !quote && !inString) { // equalSign (switch from left to right)?
                left = sal_False;

                attribute = token.trim();
                token = emptyString;
            }
            else if(raw_url[index] == tuedle.getStr()[0] && !quote) // begin or end of string?
                inString = !inString;

            else { // no special handling
                token += OUString(raw_url + index, 1);
                quote = sal_False;
            }

            ++ index;
        }

        // enshure, that attributes are set properly
        if(!(*serviceName).getLength())
            throw RuntimeException(OUString(RTL_CONSTASCII_USTRINGPARAM("dynamic_loader::DynamicLoader.parseUrl - missing or empty attribute: servicename")),
                                   Reference<XInterface>());

        if(!(*link).getLength())
            throw RuntimeException(OUString(RTL_CONSTASCII_USTRINGPARAM("dynamic_loader::DynamicLoader.parseUrl - missing or empty attribute: link")),
                                   Reference<XInterface>());

        if(!(*resolver).getLength())
            throw RuntimeException(OUString(RTL_CONSTASCII_USTRINGPARAM("dynamic_loader::DynamicLoader.parseUrl - missing or empty attribute: resolver")),
                                   Reference<XInterface>());
    }

    // XImplementationLoader
    sal_Bool SAL_CALL DynamicLoader::writeRegistryInfo(const Reference<XRegistryKey> & xKey,
                                                       const OUString & implementationLoaderUrl,
                                                       const OUString & locationUrl)
        throw(CannotRegisterImplementationException, RuntimeException)
    {
        OSL_TRACE("DynamicLoader::writeRegistryInfo");

        OUString serviceName;
        OUString link;
        OUString resolver;

        try {
            parseUrl(locationUrl, &serviceName, &link, &resolver);
        }
        catch(RuntimeException & runtimeException) {
            throw CannotRegisterImplementationException(runtimeException.Message, Reference<XInterface>());
        }

        // create the keys
        OUString keyName = OUString::createFromAscii("/");
        keyName += implementationLoaderUrl;
        keyName += OUString(RTL_CONSTASCII_USTRINGPARAM("_"));
        keyName += serviceName;
        keyName += OUString::createFromAscii("/UNO/SERVICES");

        Reference<XRegistryKey> xNewKey(xKey->createKey(keyName));
        xNewKey->createKey(serviceName);

        sal_Bool bSuccess = sal_True;

        return bSuccess;
    }

    Reference<XInterface> SAL_CALL DynamicLoader::activate(const OUString & rImplName,
                                                           const OUString & loaderUrl,
                                                           const OUString & locationUrl,
                                                           const Reference<XRegistryKey> & xKey)
        throw(CannotActivateFactoryException, RuntimeException)
    {
        OSL_TRACE("DynamicLoader::activate");

        OUString serviceName;
        OUString link;
        OUString resolver;

        parseUrl(locationUrl, &serviceName, &link, &resolver);

        XSingleServiceFactory * xFactory = (XSingleServiceFactory *)new SingleServiceFactory(_xSMgr,
                                                                                serviceName,
                                                                                link,
                                                                                resolver);

          Reference<XInterface> xReturn;

        if(xFactory)
            xReturn = Reference<XInterface>::query(xFactory);

        return xReturn;
    }
}

extern "C" {
    SAL_DLLEXPORT void SAL_CALL component_getImplementationEnvironment(const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv)   {
        *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
    }

    SAL_DLLEXPORT sal_Bool SAL_CALL component_writeInfo(XMultiServiceFactory * pServiceManager, XRegistryKey * pRegistryKey) {
        sal_Bool bRes = sal_False;

        if (pRegistryKey) {
            try {
                OUString x = OUString::createFromAscii("/");
                x += ::dynamic_loader::DynamicLoader::implname;
                x += OUString::createFromAscii("/UNO/SERVICES");

                Reference<XRegistryKey> xNewKey(pRegistryKey->createKey(x));

                const Sequence<OUString> rSNL = ::dynamic_loader::DynamicLoader::getSupportedServiceNames_Static();
                const OUString * pArray = rSNL.getConstArray();
                for (sal_Int32 nPos = rSNL.getLength(); nPos--;)
                    xNewKey->createKey(pArray[nPos]);

                bRes = sal_True;
            }
            catch (InvalidRegistryException &) {
                  OSL_ENSHURE( sal_False, "### InvalidRegistryException!" );
            }
        }

        return bRes;
    }

    SAL_DLLEXPORT void * SAL_CALL component_getFactory(const sal_Char * pImplName, XMultiServiceFactory * pServiceManager, XRegistryKey * pRegistryKey) {
        void * pRet = 0;

        if (pServiceManager && OUString::createFromAscii(pImplName).equals(::dynamic_loader::DynamicLoader::implname)) {
            Reference<XSingleServiceFactory> xFactory(createOneInstanceFactory(pServiceManager,
                                                                               ::dynamic_loader::DynamicLoader::implname,
                                                                               ::dynamic_loader::DynamicLoader::createInstance,
                                                                               ::dynamic_loader::DynamicLoader::getSupportedServiceNames_Static()));

            if (xFactory.is()) {
                xFactory->acquire();
                pRet = xFactory.get();
            }
        }
        else
            OSL_TRACE("DynamicLoader - warning - given wrong implName: %s", pImplName);

        return pRet;
    }
}
<commit_msg>#65293#: exception specification<commit_after>
#include <stdio.h>

#include <cppuhelper/factory.hxx>

#include <cppuhelper/implbase1.hxx>
#include <cppuhelper/implbase2.hxx>

#include <com/sun/star/bridge/XUnoUrlResolver.hpp>

#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/loader/XImplementationLoader.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>

using namespace ::com::sun::star::bridge;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::loader;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::registry;

using namespace ::cppu;
using namespace ::rtl;

namespace dynamic_loader {

    class SingleServiceFactory : public WeakImplHelper2<XServiceInfo, XSingleServiceFactory> {
        Reference<XMultiServiceFactory> _xServiceManager;
        OUString _serviceName;
        OUString _link;
        OUString _resolver;

        Reference<XSingleServiceFactory> getRemoteFactory() throw(Exception, RuntimeException);

    public:

        SingleServiceFactory(const Reference<XMultiServiceFactory > & xServiceManager,
                             const OUString & serviceName,
                             const OUString & link,
                             const OUString & resolver)
            : _xServiceManager(xServiceManager),
              _serviceName(serviceName),
              _link(link),
              _resolver(resolver)
        {}

        // XSingleServiceFactory
        Reference<XInterface> SAL_CALL createInstance() throw(Exception, RuntimeException);
        Reference<XInterface> SAL_CALL createInstanceWithArguments(const Sequence<Any>& Arguments)
            throw(::com::sun::star::uno::Exception,
                  ::com::sun::star::uno::RuntimeException);

        // XServiceInfo
        OUString           SAL_CALL getImplementationName()                      throw(RuntimeException);
        sal_Bool           SAL_CALL supportsService(const OUString& ServiceName) throw(RuntimeException);
        Sequence<OUString> SAL_CALL getSupportedServiceNames(void)               throw(RuntimeException);
    };

    Reference<XSingleServiceFactory> SingleServiceFactory::getRemoteFactory() throw(Exception, RuntimeException) {
        Reference<XUnoUrlResolver> xResolver(_xServiceManager->createInstance(_resolver), UNO_QUERY);
        if(!xResolver.is()) {
            OUString message(RTL_CONSTASCII_USTRINGPARAM("dynamic_loader::singleServiceFactory.createInstance - couldn't create resolver: "));
            message += _resolver;

            throw Exception(message, Reference<XInterface>());
        }

        Reference<XInterface> remoteObject = xResolver->resolve(_link);
        if(!remoteObject.is()) {
            OUString message(RTL_CONSTASCII_USTRINGPARAM("dynamic_loader::singleServiceFactory.createInstance - couldn't resolve link: "));
            message += _link;

            throw Exception(message, Reference<XInterface>());
        }

        Reference<XSingleServiceFactory> remoteFactory(remoteObject, UNO_QUERY);
        if(!remoteFactory.is()) {
            OUString message(RTL_CONSTASCII_USTRINGPARAM("dynamic_loader::singleServiceFactory.createInstance - couldn't get XSingleServiceFactory from: "));
            message += _link;

            throw Exception(message, Reference<XInterface>());
        }

        return remoteFactory;
    }

    // XSingleServiceFactory
    Reference<XInterface> SAL_CALL SingleServiceFactory::createInstance() throw(Exception, RuntimeException) {
        OSL_TRACE("dynamic_loader::singleServiceFactory::createInstance");

        return getRemoteFactory()->createInstance();
    }

    Reference<XInterface> SAL_CALL SingleServiceFactory::createInstanceWithArguments(const Sequence<Any>& Arguments)
        throw(Exception, RuntimeException)
    {
        OSL_TRACE("dynamic_loader::singleServiceFactory::createInstanceWithArguments");

        return getRemoteFactory()->createInstanceWithArguments(Arguments);
    }

    // XServiceInfo
    OUString SAL_CALL SingleServiceFactory::getImplementationName() throw(RuntimeException) {
        return _link;
    }

    sal_Bool SAL_CALL SingleServiceFactory::supportsService(const OUString & ServiceName) throw(RuntimeException) {
        return _serviceName.equals(ServiceName);
    }

    Sequence<OUString> SAL_CALL SingleServiceFactory::getSupportedServiceNames(void) throw(RuntimeException) {
        return Sequence<OUString>(&_serviceName, 1);
    }

    class DynamicLoader : public WeakImplHelper2<XImplementationLoader, XServiceInfo> {
        Reference<XMultiServiceFactory>  _xSMgr;

    protected:
        DynamicLoader(const Reference<XMultiServiceFactory> & rXSMgr) throw(RuntimeException);
        ~DynamicLoader() throw();

    public:
        static const OUString implname;
        static const OUString servname;

        static Reference<XInterface> SAL_CALL createInstance(const Reference<XMultiServiceFactory> & rSMgr) throw(Exception);
        static Sequence<OUString>    SAL_CALL getSupportedServiceNames_Static() throw();

        static void parseUrl(const OUString & url, OUString * serviceName, OUString * link, OUString * resolver) throw(RuntimeException);

        // XServiceInfo
        virtual OUString           SAL_CALL getImplementationName()                      throw(RuntimeException);
        virtual sal_Bool           SAL_CALL supportsService(const OUString& ServiceName) throw(RuntimeException);
        virtual Sequence<OUString> SAL_CALL getSupportedServiceNames()                   throw(RuntimeException);

        // XImplementationLoader
        virtual Reference<XInterface> SAL_CALL activate(const OUString & implementationName,
                                                        const OUString & implementationLoaderUrl,
                                                        const OUString& locationUrl,
                                                        const Reference<XRegistryKey>& xKey)       throw(CannotActivateFactoryException, RuntimeException);
        virtual sal_Bool              SAL_CALL writeRegistryInfo(const Reference<XRegistryKey>& xKey,
                                                                 const OUString& implementationLoaderUrl,
                                                                 const OUString& locationUrl)      throw(CannotRegisterImplementationException, RuntimeException);
    };

    const OUString DynamicLoader::implname = OUString::createFromAscii("com.sun.star.comp.stoc.DynamicLoader");
    const OUString DynamicLoader::servname = OUString::createFromAscii("com.sun.star.loader.Dynamic");

    Sequence<OUString> SAL_CALL DynamicLoader::getSupportedServiceNames_Static() throw() {
        return Sequence<OUString>(&servname, 1);
    }

    Reference<XInterface> SAL_CALL DynamicLoader::createInstance(const Reference<XMultiServiceFactory> & rSMgr) throw(Exception) {
        Reference<XInterface> xRet;

        try {
            XImplementationLoader *pXLoader = (XImplementationLoader *)new DynamicLoader(rSMgr);

            xRet = Reference<XInterface>::query(pXLoader);
        }
        catch(RuntimeException & runtimeException) {
            OString message = OUStringToOString(runtimeException.Message, RTL_TEXTENCODING_ASCII_US);
            osl_trace("dynamic loader - could not init cause of %s", message.getStr());
        }

        OSL_TRACE("DynamicLoader - createInstance: %d", xRet.is());

        return xRet;
    }

    DynamicLoader::DynamicLoader(const Reference<XMultiServiceFactory> & xSMgr) throw(RuntimeException)
        : _xSMgr(xSMgr)
    {
    }

    DynamicLoader::~DynamicLoader() throw() {
    }

    // XServiceInfo
    OUString SAL_CALL DynamicLoader::getImplementationName() throw(RuntimeException) {
        return implname;
    }

    sal_Bool SAL_CALL DynamicLoader::supportsService(const OUString & ServiceName) throw(RuntimeException)  {
        sal_Bool bSupport = sal_False;

        Sequence<OUString> aSNL = getSupportedServiceNames();
        const OUString * pArray = aSNL.getArray();
        for(sal_Int32 i = 0; i < aSNL.getLength() && !bSupport; ++ i)
            bSupport = pArray[i] == ServiceName;

        return bSupport;
    }

    Sequence<OUString> SAL_CALL DynamicLoader::getSupportedServiceNames() throw(RuntimeException) {
        return getSupportedServiceNames_Static();
    }

    void DynamicLoader::parseUrl(const OUString & locationUrl, OUString * serviceName, OUString * link, OUString * resolver) throw(RuntimeException) {
#ifdef DEBUG
        OString tmp = OUStringToOString(locationUrl, RTL_TEXTENCODING_ASCII_US);
        OSL_TRACE("DynamicLoader - locationUrl %s", tmp.getStr());
#endif

        // This is the default resolver
        *resolver = OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.UnoUrlResolver"));

        const OUString bSlash(OUString(RTL_CONSTASCII_USTRINGPARAM("\\")));
        const OUString tuedle(OUString(RTL_CONSTASCII_USTRINGPARAM("\"")));
        const OUString separator(OUString(RTL_CONSTASCII_USTRINGPARAM(",")));
        const OUString emptyString(OUString(RTL_CONSTASCII_USTRINGPARAM("")));
        const OUString equalSign(OUString(RTL_CONSTASCII_USTRINGPARAM("=")));

        sal_Int32 index = 0;
        sal_Bool  left = sal_True;
        sal_Bool  quote = sal_False;
        sal_Bool  inString = sal_False;

        const sal_Unicode * raw_url = locationUrl.getStr();
        OUString token;
        OUString attribute;

        while(index <= locationUrl.getLength()) {
            if(index >= locationUrl.getLength() || (raw_url[index] == separator.getStr()[0] && !quote && !inString)) { // a separator or end?
                OUString value;

                if(left)
                    attribute = token.trim();

                else
                    value = token.trim();

#ifdef DEBUG
                OString attribute_tmp = OUStringToOString(attribute, RTL_TEXTENCODING_ASCII_US);
                OSL_TRACE("DynamicLoader - attribute %s", attribute_tmp.getStr());
                OString value_tmp = OUStringToOString(value, RTL_TEXTENCODING_ASCII_US);
                OSL_TRACE("DynamicLoader - value %s", value_tmp.getStr());
#endif

                if(attribute.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("servicename"))))
                    *serviceName = value;

                else if(attribute.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("link"))))
                    *link = value;

                else if(attribute.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("resolver"))))
                    *resolver = value;

                else  {
                    OUString message(RTL_CONSTASCII_USTRINGPARAM("help called"));

                    if(!attribute.equals(OUString(RTL_CONSTASCII_USTRINGPARAM("help")))) {
                        message = OUString(RTL_CONSTASCII_USTRINGPARAM("DynamicLoader - unknown attribute: "));
                        message += attribute;
                    }

                    fprintf(stdout, "DynamicLoader - help\n");
                    fprintf(stdout, "attributes:\n");
                    fprintf(stdout, "\tservicename:  service name of dynamic component\n");
                    fprintf(stdout, "\tlink:         link to a single service factory for dynamic component\n");
                    fprintf(stdout, "\tresolver:     the service which resolves the link\n");
                    fprintf(stdout, "\thelp:         this help\n");

                    throw RuntimeException(message, Reference<XInterface>());
                }

                left = sal_True; // reset state to be left
                token = emptyString;
            }
            else if(raw_url[index] == bSlash.getStr()[0] && !quote) // a back slash?
                quote = sal_True;

            else if(raw_url[index] == equalSign.getStr()[0] && !quote && !inString) { // equalSign (switch from left to right)?
                left = sal_False;

                attribute = token.trim();
                token = emptyString;
            }
            else if(raw_url[index] == tuedle.getStr()[0] && !quote) // begin or end of string?
                inString = !inString;

            else { // no special handling
                token += OUString(raw_url + index, 1);
                quote = sal_False;
            }

            ++ index;
        }

        // enshure, that attributes are set properly
        if(!(*serviceName).getLength())
            throw RuntimeException(OUString(RTL_CONSTASCII_USTRINGPARAM("dynamic_loader::DynamicLoader.parseUrl - missing or empty attribute: servicename")),
                                   Reference<XInterface>());

        if(!(*link).getLength())
            throw RuntimeException(OUString(RTL_CONSTASCII_USTRINGPARAM("dynamic_loader::DynamicLoader.parseUrl - missing or empty attribute: link")),
                                   Reference<XInterface>());

        if(!(*resolver).getLength())
            throw RuntimeException(OUString(RTL_CONSTASCII_USTRINGPARAM("dynamic_loader::DynamicLoader.parseUrl - missing or empty attribute: resolver")),
                                   Reference<XInterface>());
    }

    // XImplementationLoader
    sal_Bool SAL_CALL DynamicLoader::writeRegistryInfo(const Reference<XRegistryKey> & xKey,
                                                       const OUString & implementationLoaderUrl,
                                                       const OUString & locationUrl)
        throw(CannotRegisterImplementationException, RuntimeException)
    {
        OSL_TRACE("DynamicLoader::writeRegistryInfo");

        OUString serviceName;
        OUString link;
        OUString resolver;

        try {
            parseUrl(locationUrl, &serviceName, &link, &resolver);
        }
        catch(RuntimeException & runtimeException) {
            throw CannotRegisterImplementationException(runtimeException.Message, Reference<XInterface>());
        }

        // create the keys
        OUString keyName = OUString::createFromAscii("/");
        keyName += implementationLoaderUrl;
        keyName += OUString(RTL_CONSTASCII_USTRINGPARAM("_"));
        keyName += serviceName;
        keyName += OUString::createFromAscii("/UNO/SERVICES");

        Reference<XRegistryKey> xNewKey(xKey->createKey(keyName));
        xNewKey->createKey(serviceName);

        sal_Bool bSuccess = sal_True;

        return bSuccess;
    }

    Reference<XInterface> SAL_CALL DynamicLoader::activate(const OUString & rImplName,
                                                           const OUString & loaderUrl,
                                                           const OUString & locationUrl,
                                                           const Reference<XRegistryKey> & xKey)
        throw(CannotActivateFactoryException, RuntimeException)
    {
        OSL_TRACE("DynamicLoader::activate");

        OUString serviceName;
        OUString link;
        OUString resolver;

        parseUrl(locationUrl, &serviceName, &link, &resolver);

        XSingleServiceFactory * xFactory = (XSingleServiceFactory *)new SingleServiceFactory(_xSMgr,
                                                                                serviceName,
                                                                                link,
                                                                                resolver);

          Reference<XInterface> xReturn;

        if(xFactory)
            xReturn = Reference<XInterface>::query(xFactory);

        return xReturn;
    }
}

extern "C" {
    SAL_DLLEXPORT void SAL_CALL component_getImplementationEnvironment(const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv)   {
        *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
    }

    SAL_DLLEXPORT sal_Bool SAL_CALL component_writeInfo(XMultiServiceFactory * pServiceManager, XRegistryKey * pRegistryKey) {
        sal_Bool bRes = sal_False;

        if (pRegistryKey) {
            try {
                OUString x = OUString::createFromAscii("/");
                x += ::dynamic_loader::DynamicLoader::implname;
                x += OUString::createFromAscii("/UNO/SERVICES");

                Reference<XRegistryKey> xNewKey(pRegistryKey->createKey(x));

                const Sequence<OUString> rSNL = ::dynamic_loader::DynamicLoader::getSupportedServiceNames_Static();
                const OUString * pArray = rSNL.getConstArray();
                for (sal_Int32 nPos = rSNL.getLength(); nPos--;)
                    xNewKey->createKey(pArray[nPos]);

                bRes = sal_True;
            }
            catch (InvalidRegistryException &) {
                  OSL_ENSHURE( sal_False, "### InvalidRegistryException!" );
            }
        }

        return bRes;
    }

    SAL_DLLEXPORT void * SAL_CALL component_getFactory(const sal_Char * pImplName, XMultiServiceFactory * pServiceManager, XRegistryKey * pRegistryKey) {
        void * pRet = 0;

        if (pServiceManager && OUString::createFromAscii(pImplName).equals(::dynamic_loader::DynamicLoader::implname)) {
            Reference<XSingleServiceFactory> xFactory(createOneInstanceFactory(pServiceManager,
                                                                               ::dynamic_loader::DynamicLoader::implname,
                                                                               ::dynamic_loader::DynamicLoader::createInstance,
                                                                               ::dynamic_loader::DynamicLoader::getSupportedServiceNames_Static()));

            if (xFactory.is()) {
                xFactory->acquire();
                pRet = xFactory.get();
            }
        }
        else
            OSL_TRACE("DynamicLoader - warning - given wrong implName: %s", pImplName);

        return pRet;
    }
}
<|endoftext|>


<commit_before>// Copyright 2014 BVLC and contributors.
// caffe.hpp is the header file that you need to include in your code. It wraps
// all the internal caffe header files into one for simpler inclusion.

#ifndef CAFFE_CAFFE_HPP_
#define CAFFE_CAFFE_HPP_

#include "caffe/common.hpp"
#include "caffe/blob.hpp"
#include "caffe/filler.hpp"
#include "caffe/layer.hpp"
#include "caffe/net.hpp"
#include "caffe/solver.hpp"
#include "caffe/util/io.hpp"
#include "caffe/vision_layers.hpp"

#include "caffe/proto/caffe.pb.h"

#endif  // CAFFE_CAFFE_HPP_
<commit_msg>add test for image io<commit_after>// Copyright 2014 BVLC and contributors.
// caffe.hpp is the header file that you need to include in your code. It wraps
// all the internal caffe header files into one for simpler inclusion.

#ifndef CAFFE_CAFFE_HPP_
#define CAFFE_CAFFE_HPP_

#include "caffe/common.hpp"
#include "caffe/blob.hpp"
#include "caffe/filler.hpp"
#include "caffe/layer.hpp"
#include "caffe/net.hpp"
#include "caffe/feedback_net.hpp"
#include "caffe/solver.hpp"
#include "caffe/util/io.hpp"
#include "caffe/vision_layers.hpp"

#include "caffe/proto/caffe.pb.h"

#endif  // CAFFE_CAFFE_HPP_
<|endoftext|>


<commit_before>//
// Created by arrow on 9/21/16.
//

#include "autoconf.h"
#include "config.h"

#include <boost/program_options.hpp>
#include <iostream>
#include <cstdlib>

namespace po = boost::program_options;

namespace rethinkmud
{
    namespace config
    {
        namespace
        {
            po::options_description get_command_line_options(std::string const &argv0)
            {
                std::string default_config_file = argv0 + ".cfg";

                po::options_description general{"General options"};
                general.add_options()
                    ("help,h", "show help message")
                    ("version,v", "show program version")
                    ("config,c", po::value<std::string>()->default_value(default_config_file), "configuration file");

                po::options_description options;
                return options.add(general);
            }
        }

        void load(int argc, char* argv[])
        {
            auto options = get_command_line_options(argv[0]);
            //auto config = get_config_options();
            //auto common = get_common_options();

            //options.add(common);
            //config.add(common);

            po::variables_map vm;

            try
            {
                po::store(po::parse_command_line(argc, argv, options), vm, true);
            }
            catch (po::error& e)
            {
                std::clog << "Error: " << e.what() << '\n';
                std::clog << "Error: Use '" << argv[0] << " --help' to get help about command line options\n";
                std::exit(1);
            }

            po::notify(vm);

            if (vm.count("help"))
            {
                std::cout << options << '\n';
                std::exit(0);
            }

            if (vm.count("version"))
            {
                std::cout << "RethinkMUD version " << RETHINKMUD_VERSION << '\n';
                std::exit(0);
            }

            std::cout << "Configuration file = " << vm["config"].as<std::string>() << '\n';

            //try
            //{
            //    po::store(po::parse_command_line(argc, argv, config), vm, true);
            //}
            //catch (po::error& e)
            //{
            //    std::clog << "Error: " << e.what() << '\n';
            //    std::exit(1);
            //}

        }
    }
}
<commit_msg>Configuration file parsing<commit_after>//
// Created by arrow on 9/21/16.
//

#include "autoconf.h"
#include "config.h"

#include <boost/program_options.hpp>
#include <iostream>
#include <fstream>
#include <cstdlib>

namespace po = boost::program_options;

namespace rethinkmud
{
    namespace config
    {
        namespace
        {
            auto get_command_line_options(std::string const &argv0)
            {
                std::string default_config_file = argv0 + ".cfg";

                po::options_description options{"General options"};
                options.add_options()
                    ("help,h", "show help message")
                    ("version,v", "show program version")
                    ("config,c", po::value<std::string>()->default_value(default_config_file), "configuration file");

                return options;
            }

            auto get_config_options()
            {
                po::options_description config;
                return config;
            }

            auto get_common_options()
            {
                po::options_description common{"Common options"};
                common.add_options()
                    ("port,p", po::value<int>()->default_value(4000), "main port number");

                return common;
            }
        }

        void load(int argc, char* argv[])
        {
            auto options = get_command_line_options(argv[0]);
            auto config = get_config_options();
            auto common = get_common_options();

            options.add(common);
            config.add(common);

            po::variables_map vm;

            try
            {
                po::store(po::parse_command_line(argc, argv, options), vm, true);
            }
            catch (po::error& e)
            {
                std::clog << "Error: " << e.what() << '\n';
                std::clog << "Error: Use '" << argv[0] << " --help' to get help about command line options\n";
                std::exit(1);
            }

            po::notify(vm);

            if (vm.count("help"))
            {
                std::cout << options << '\n';
                std::exit(0);
            }

            if (vm.count("version"))
            {
                std::cout << "RethinkMUD version " << RETHINKMUD_VERSION << '\n';
                std::exit(0);
            }

            std::cout << "Configuration file = " << vm["config"].as<std::string>() << '\n';

            std::ifstream config_file{vm["config"].as<std::string>()};
            if (config_file)
            {
                try
                {
                    po::store(po::parse_config_file(config_file, config), vm, true);
                }
                catch (po::error& e)
                {
                    std::clog << "Error: " << e.what() << '\n';
                    std::exit(1);
                }
            }

            std::cout << "Main port number = " << vm["port"].as<int>() << '\n';

            // TODO: Environment variables?

        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Resolves fdo#81084 fdo#81696 fdo#80874 fdo#81010 : sort causes crash<commit_after><|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) 2007 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <boost/signals.hpp>
# include <boost/bind.hpp>
# include <qapplication.h>
# include <qregexp.h>
# include <QEvent>
# include <QCloseEvent>
# include <QMdiSubWindow>
#include <iostream>
#endif

#include "MDIView.h"
#include "Command.h"
#include "Document.h"
#include "Application.h"
#include "MainWindow.h"
#include "ViewProviderDocumentObject.h"

using namespace Gui;

TYPESYSTEM_SOURCE_ABSTRACT(Gui::MDIView,Gui::BaseView);

MDIView::MDIView(Gui::Document* pcDocument,QWidget* parent, Qt::WindowFlags wflags)
  : QMainWindow(parent, wflags), BaseView(pcDocument),currentMode(Child), wstate(Qt::WindowNoState)
{
    setAttribute(Qt::WA_DeleteOnClose);

    if (pcDocument)
    {
      connectDelObject = pcDocument->signalDeletedObject.connect
        (boost::bind(&ActiveObjectList::objectDeleted, &ActiveObjects, _1));
      assert(connectDelObject.connected());
    }
}

MDIView::~MDIView()
{
    //This view might be the focus widget of the main window. In this case we must
    //clear the focus and e.g. set the focus directly to the main window, otherwise
    //the application crashes when accessing this deleted view.
    //This effect only occurs if this widget is not in Child mode, because otherwise
    //the focus stuff is done correctly.
    if (getMainWindow()) {
        QWidget* foc = getMainWindow()->focusWidget();
        if (foc) {
            QWidget* par = foc;
            while (par) {
                if (par == this) {
                    getMainWindow()->setFocus();
                    break;
                }
                par = par->parentWidget();
            }
        }
    }
    if (connectDelObject.connected())
      connectDelObject.disconnect();
}

void MDIView::deleteSelf()
{
    // When using QMdiArea make sure to remove the QMdiSubWindow
    // this view is associated with.
    //
    // #0001023: Crash when quitting after using Windows > Tile
    // Use deleteLater() instead of delete operator.
    QWidget* parent = this->parentWidget();
    if (qobject_cast<QMdiSubWindow*>(parent)) {
        // https://forum.freecadweb.org/viewtopic.php?f=22&t=23070
        parent->close();
    }
    else {
        this->close();
    }

    // detach from document
    if (_pcDocument)
        onClose();
    _pcDocument = 0;
}

void MDIView::setOverrideCursor(const QCursor& c)
{
    Q_UNUSED(c);
}

void  MDIView::restoreOverrideCursor()
{
}

void MDIView::onRelabel(Gui::Document *pDoc)
{
    if (!bIsPassive) {
        // Try to separate document name and view number if there is one
        QString cap = windowTitle();
        // Either with dirty flag ...
        QRegExp rx(QLatin1String("(\\s\\:\\s\\d+\\[\\*\\])$"));
        int pos = rx.lastIndexIn(cap);
        if (pos == -1) {
            // ... or not
            rx.setPattern(QLatin1String("(\\s\\:\\s\\d+)$"));
            pos = rx.lastIndexIn(cap);
        }
        if (pos != -1) {
            cap = QString::fromUtf8(pDoc->getDocument()->Label.getValue());
            cap += rx.cap();
            setWindowTitle(cap);
        }
        else {
            cap = QString::fromUtf8(pDoc->getDocument()->Label.getValue());
            cap = QString::fromLatin1("%1[*]").arg(cap);
            setWindowTitle(cap);
        }
    }
}

void MDIView::viewAll()
{
}

/// receive a message
bool MDIView::onMsg(const char* pMsg,const char** ppReturn)
{
    Q_UNUSED(pMsg);
    Q_UNUSED(ppReturn);
    return false;
}

bool MDIView::onHasMsg(const char* pMsg) const
{
    Q_UNUSED(pMsg);
    return false;
}

bool MDIView::canClose(void)
{
    if (!bIsPassive && getGuiDocument() && getGuiDocument()->isLastView()) {
        this->setFocus(); // raises the view to front
        return (getGuiDocument()->canClose());
    }

    return true;
}

void MDIView::closeEvent(QCloseEvent *e)
{
    if (canClose()) {
        e->accept();
        if (!bIsPassive) {
            // must be detached so that the last view can get asked
            Document* doc = this->getGuiDocument();
            if (doc && !doc->isLastView())
                doc->detachView(this);
        }

        // Note: When using QMdiArea we must not use removeWindow()
        // because otherwise the QMdiSubWindow will lose its parent
        // and thus the notification in QMdiSubWindow::closeEvent of
        // other mdi windows to get maximized if this window
        // is maximized will fail.
        // This odd behaviour is caused by the invocation of
        // d->mdiArea->removeSubWindow(parent) which we must let there
        // because otherwise other parts don't work as they should.
        QMainWindow::closeEvent(e);
    }
    else
        e->ignore();
}

void MDIView::windowStateChanged( MDIView* )
{
}

void MDIView::print(QPrinter* printer)
{
    Q_UNUSED(printer);
    std::cerr << "Printing not implemented for " << this->metaObject()->className() << std::endl;
}

void MDIView::print()
{
    std::cerr << "Printing not implemented for " << this->metaObject()->className() << std::endl;
}

void MDIView::printPdf()
{
    std::cerr << "Printing PDF not implemented for " << this->metaObject()->className() << std::endl;
}

void MDIView::printPreview()
{
    std::cerr << "Printing preview not implemented for " << this->metaObject()->className() << std::endl;
}

QSize MDIView::minimumSizeHint () const
{
    return QSize(400, 300);
}

void MDIView::changeEvent(QEvent *e)
{
    switch (e->type()) {
        case QEvent::ActivationChange:
            {
                // Forces this top-level window to be the active view of the main window
                if (isActiveWindow()) {
                    if (getMainWindow()->activeWindow() != this)
                        getMainWindow()->setActiveWindow(this);
                }
            }   break;
        case QEvent::WindowTitleChange:
        case QEvent::ModifiedChange:
            {
                // sets the appropriate tab of the tabbar
                getMainWindow()->tabChanged(this);
            }   break;
        default:
            {
                QMainWindow::changeEvent(e);
            }   break;
    }
}

#if defined(Q_WS_X11)
// To fix bug #0000345 move function declaration to here
extern void qt_x11_wait_for_window_manager( QWidget* w ); // defined in qwidget_x11.cpp
#endif

void MDIView::setCurrentViewMode(ViewMode mode)
{
    switch (mode) {
        // go to normal mode
        case Child:
            {
                if (this->currentMode == FullScreen) {
                    showNormal();
                    setWindowFlags(windowFlags() & ~Qt::Window);
                }
                else if (this->currentMode == TopLevel) {
                    this->wstate = windowState();
                    setWindowFlags( windowFlags() & ~Qt::Window );
                }

                if (this->currentMode != Child) {
                    this->currentMode = Child;
                    getMainWindow()->addWindow(this);
                    getMainWindow()->activateWindow();
                    update();
                }
            }   break;
        // go to top-level mode
        case TopLevel:
            {
                if (this->currentMode == Child) {
                    if (qobject_cast<QMdiSubWindow*>(this->parentWidget()))
                        getMainWindow()->removeWindow(this);
                    setWindowFlags(windowFlags() | Qt::Window);
                    setParent(0, Qt::Window | Qt::WindowTitleHint | Qt::WindowSystemMenuHint |
                                 Qt::WindowMinMaxButtonsHint);
                    if (this->wstate & Qt::WindowMaximized)
                        showMaximized();
                    else
                        showNormal();

#if defined(Q_WS_X11)
                    //extern void qt_x11_wait_for_window_manager( QWidget* w ); // defined in qwidget_x11.cpp
                    qt_x11_wait_for_window_manager(this);
#endif
                    activateWindow();
                }
                else if (this->currentMode == FullScreen) {
                    if (this->wstate & Qt::WindowMaximized)
                        showMaximized();
                    else
                        showNormal();
                }

                this->currentMode = TopLevel;
                update();
            }   break;
        // go to fullscreen mode
        case FullScreen:
            {
                if (this->currentMode == Child) {
                    if (qobject_cast<QMdiSubWindow*>(this->parentWidget()))
                        getMainWindow()->removeWindow(this);
                    setWindowFlags(windowFlags() | Qt::Window);
                    setParent(0, Qt::Window);
                    showFullScreen();
                }
                else if (this->currentMode == TopLevel) {
                    this->wstate = windowState();
                    showFullScreen();
                }

                this->currentMode = FullScreen;
                update();
            }   break;
    }
}

#include "moc_MDIView.cpp"
<commit_msg>MDIView: remove from parent before close<commit_after>/***************************************************************************
 *   Copyright (c) 2007 Werner Mayer <wmayer[at]users.sourceforge.net>     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   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 Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <boost/signals.hpp>
# include <boost/bind.hpp>
# include <qapplication.h>
# include <qregexp.h>
# include <QEvent>
# include <QCloseEvent>
# include <QMdiSubWindow>
#include <iostream>
#endif

#include "MDIView.h"
#include "Command.h"
#include "Document.h"
#include "Application.h"
#include "MainWindow.h"
#include "ViewProviderDocumentObject.h"

using namespace Gui;

TYPESYSTEM_SOURCE_ABSTRACT(Gui::MDIView,Gui::BaseView);

MDIView::MDIView(Gui::Document* pcDocument,QWidget* parent, Qt::WindowFlags wflags)
  : QMainWindow(parent, wflags), BaseView(pcDocument),currentMode(Child), wstate(Qt::WindowNoState)
{
    setAttribute(Qt::WA_DeleteOnClose);

    if (pcDocument)
    {
      connectDelObject = pcDocument->signalDeletedObject.connect
        (boost::bind(&ActiveObjectList::objectDeleted, &ActiveObjects, _1));
      assert(connectDelObject.connected());
    }
}

MDIView::~MDIView()
{
    //This view might be the focus widget of the main window. In this case we must
    //clear the focus and e.g. set the focus directly to the main window, otherwise
    //the application crashes when accessing this deleted view.
    //This effect only occurs if this widget is not in Child mode, because otherwise
    //the focus stuff is done correctly.
    if (getMainWindow()) {
        QWidget* foc = getMainWindow()->focusWidget();
        if (foc) {
            QWidget* par = foc;
            while (par) {
                if (par == this) {
                    getMainWindow()->setFocus();
                    break;
                }
                par = par->parentWidget();
            }
        }
    }
    if (connectDelObject.connected())
      connectDelObject.disconnect();
}

void MDIView::deleteSelf()
{
    // When using QMdiArea make sure to remove the QMdiSubWindow
    // this view is associated with.
    //
    // #0001023: Crash when quitting after using Windows > Tile
    // Use deleteLater() instead of delete operator.
    QWidget* parent = this->parentWidget();
    if (qobject_cast<QMdiSubWindow*>(parent)) {
        // https://forum.freecadweb.org/viewtopic.php?f=22&t=23070
#if QT_VERSION < 0x050000
        // With Qt5 this would lead to some annoying flickering
        getMainWindow()->removeWindow(this);
#endif
        parent->close();
    }
    else {
        this->close();
    }

    // detach from document
    if (_pcDocument)
        onClose();
    _pcDocument = 0;
}

void MDIView::setOverrideCursor(const QCursor& c)
{
    Q_UNUSED(c);
}

void  MDIView::restoreOverrideCursor()
{
}

void MDIView::onRelabel(Gui::Document *pDoc)
{
    if (!bIsPassive) {
        // Try to separate document name and view number if there is one
        QString cap = windowTitle();
        // Either with dirty flag ...
        QRegExp rx(QLatin1String("(\\s\\:\\s\\d+\\[\\*\\])$"));
        int pos = rx.lastIndexIn(cap);
        if (pos == -1) {
            // ... or not
            rx.setPattern(QLatin1String("(\\s\\:\\s\\d+)$"));
            pos = rx.lastIndexIn(cap);
        }
        if (pos != -1) {
            cap = QString::fromUtf8(pDoc->getDocument()->Label.getValue());
            cap += rx.cap();
            setWindowTitle(cap);
        }
        else {
            cap = QString::fromUtf8(pDoc->getDocument()->Label.getValue());
            cap = QString::fromLatin1("%1[*]").arg(cap);
            setWindowTitle(cap);
        }
    }
}

void MDIView::viewAll()
{
}

/// receive a message
bool MDIView::onMsg(const char* pMsg,const char** ppReturn)
{
    Q_UNUSED(pMsg);
    Q_UNUSED(ppReturn);
    return false;
}

bool MDIView::onHasMsg(const char* pMsg) const
{
    Q_UNUSED(pMsg);
    return false;
}

bool MDIView::canClose(void)
{
    if (!bIsPassive && getGuiDocument() && getGuiDocument()->isLastView()) {
        this->setFocus(); // raises the view to front
        return (getGuiDocument()->canClose());
    }

    return true;
}

void MDIView::closeEvent(QCloseEvent *e)
{
    if (canClose()) {
        e->accept();
        if (!bIsPassive) {
            // must be detached so that the last view can get asked
            Document* doc = this->getGuiDocument();
            if (doc && !doc->isLastView())
                doc->detachView(this);
        }

        // Note: When using QMdiArea we must not use removeWindow()
        // because otherwise the QMdiSubWindow will lose its parent
        // and thus the notification in QMdiSubWindow::closeEvent of
        // other mdi windows to get maximized if this window
        // is maximized will fail.
        // This odd behaviour is caused by the invocation of
        // d->mdiArea->removeSubWindow(parent) which we must let there
        // because otherwise other parts don't work as they should.
        QMainWindow::closeEvent(e);
    }
    else
        e->ignore();
}

void MDIView::windowStateChanged( MDIView* )
{
}

void MDIView::print(QPrinter* printer)
{
    Q_UNUSED(printer);
    std::cerr << "Printing not implemented for " << this->metaObject()->className() << std::endl;
}

void MDIView::print()
{
    std::cerr << "Printing not implemented for " << this->metaObject()->className() << std::endl;
}

void MDIView::printPdf()
{
    std::cerr << "Printing PDF not implemented for " << this->metaObject()->className() << std::endl;
}

void MDIView::printPreview()
{
    std::cerr << "Printing preview not implemented for " << this->metaObject()->className() << std::endl;
}

QSize MDIView::minimumSizeHint () const
{
    return QSize(400, 300);
}

void MDIView::changeEvent(QEvent *e)
{
    switch (e->type()) {
        case QEvent::ActivationChange:
            {
                // Forces this top-level window to be the active view of the main window
                if (isActiveWindow()) {
                    if (getMainWindow()->activeWindow() != this)
                        getMainWindow()->setActiveWindow(this);
                }
            }   break;
        case QEvent::WindowTitleChange:
        case QEvent::ModifiedChange:
            {
                // sets the appropriate tab of the tabbar
                getMainWindow()->tabChanged(this);
            }   break;
        default:
            {
                QMainWindow::changeEvent(e);
            }   break;
    }
}

#if defined(Q_WS_X11)
// To fix bug #0000345 move function declaration to here
extern void qt_x11_wait_for_window_manager( QWidget* w ); // defined in qwidget_x11.cpp
#endif

void MDIView::setCurrentViewMode(ViewMode mode)
{
    switch (mode) {
        // go to normal mode
        case Child:
            {
                if (this->currentMode == FullScreen) {
                    showNormal();
                    setWindowFlags(windowFlags() & ~Qt::Window);
                }
                else if (this->currentMode == TopLevel) {
                    this->wstate = windowState();
                    setWindowFlags( windowFlags() & ~Qt::Window );
                }

                if (this->currentMode != Child) {
                    this->currentMode = Child;
                    getMainWindow()->addWindow(this);
                    getMainWindow()->activateWindow();
                    update();
                }
            }   break;
        // go to top-level mode
        case TopLevel:
            {
                if (this->currentMode == Child) {
                    if (qobject_cast<QMdiSubWindow*>(this->parentWidget()))
                        getMainWindow()->removeWindow(this);
                    setWindowFlags(windowFlags() | Qt::Window);
                    setParent(0, Qt::Window | Qt::WindowTitleHint | Qt::WindowSystemMenuHint |
                                 Qt::WindowMinMaxButtonsHint);
                    if (this->wstate & Qt::WindowMaximized)
                        showMaximized();
                    else
                        showNormal();

#if defined(Q_WS_X11)
                    //extern void qt_x11_wait_for_window_manager( QWidget* w ); // defined in qwidget_x11.cpp
                    qt_x11_wait_for_window_manager(this);
#endif
                    activateWindow();
                }
                else if (this->currentMode == FullScreen) {
                    if (this->wstate & Qt::WindowMaximized)
                        showMaximized();
                    else
                        showNormal();
                }

                this->currentMode = TopLevel;
                update();
            }   break;
        // go to fullscreen mode
        case FullScreen:
            {
                if (this->currentMode == Child) {
                    if (qobject_cast<QMdiSubWindow*>(this->parentWidget()))
                        getMainWindow()->removeWindow(this);
                    setWindowFlags(windowFlags() | Qt::Window);
                    setParent(0, Qt::Window);
                    showFullScreen();
                }
                else if (this->currentMode == TopLevel) {
                    this->wstate = windowState();
                    showFullScreen();
                }

                this->currentMode = FullScreen;
                update();
            }   break;
    }
}

#include "moc_MDIView.cpp"
<|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: tpcalc.cxx,v $
 * $Revision: 1.17 $
 *
 * 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_sc.hxx"

#undef SC_DLLIMPLEMENTATION

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

#include <math.h>

#include "scitems.hxx"
#include <vcl/msgbox.hxx>

#include "global.hxx"
#include "globstr.hrc"
#include "uiitems.hxx"
#include "docsh.hxx"
#include "document.hxx"
#include "docoptio.hxx"
#include "scresid.hxx"
#include "sc.hrc"       // -> Slot-IDs
#include "optdlg.hrc"

#define _TPCALC_CXX
#include "tpcalc.hxx"
#undef _TPCALC_CXX

// STATIC DATA -----------------------------------------------------------

static USHORT pCalcOptRanges[] =
{
    SID_SCDOCOPTIONS,
    SID_SCDOCOPTIONS,
    0
};

//========================================================================

ScTpCalcOptions::ScTpCalcOptions( Window*           pParent,
                                  const SfxItemSet& rCoreAttrs )

    :   SfxTabPage      ( pParent,
                          ScResId( RID_SCPAGE_CALC ),
                          rCoreAttrs ),

        aGbZRefs        ( this, ScResId( GB_ZREFS ) ),
        aBtnIterate     ( this, ScResId( BTN_ITERATE ) ),
        aFtSteps        ( this, ScResId( FT_STEPS ) ),
        aEdSteps        ( this, ScResId( ED_STEPS ) ),
        aFtEps          ( this, ScResId( FT_EPS ) ),
        aEdEps          ( this, ScResId( ED_EPS ) ),
        aSeparatorFL    ( this, ScResId( FL_SEPARATOR ) ),
        aGbDate         ( this, ScResId( GB_DATE ) ),
        aBtnDateStd     ( this, ScResId( BTN_DATESTD ) ),
        aBtnDateSc10    ( this, ScResId( BTN_DATESC10 ) ),
        aBtnDate1904    ( this, ScResId( BTN_DATE1904 ) ),
        aHSeparatorFL   ( this, ScResId( FL_H_SEPARATOR ) ),
        aBtnCase        ( this, ScResId( BTN_CASE ) ),
        aBtnCalc        ( this, ScResId( BTN_CALC ) ),
        aBtnMatch       ( this, ScResId( BTN_MATCH ) ),
        aBtnRegex       ( this, ScResId( BTN_REGEX ) ),
        aBtnLookUp      ( this, ScResId( BTN_LOOKUP ) ),
        aFtPrec         ( this, ScResId( FT_PREC ) ),
        aEdPrec         ( this, ScResId( ED_PREC ) ),
        pOldOptions     ( new ScDocOptions(
                            ((const ScTpCalcItem&)rCoreAttrs.Get(
                                GetWhich( SID_SCDOCOPTIONS ))).
                                    GetDocOptions() ) ),
        pLocalOptions   ( new ScDocOptions ),
        nWhichCalc      ( GetWhich( SID_SCDOCOPTIONS ) )
{
    aSeparatorFL.SetStyle( aSeparatorFL.GetStyle() | WB_VERT );
    Init();
    FreeResource();
    SetExchangeSupport();
}

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

__EXPORT ScTpCalcOptions::~ScTpCalcOptions()
{
    delete pOldOptions;
    delete pLocalOptions;
}

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

void ScTpCalcOptions::Init()
{
    aBtnIterate .SetClickHdl( LINK( this, ScTpCalcOptions, CheckClickHdl ) );
    aBtnDateStd .SetClickHdl( LINK( this, ScTpCalcOptions, RadioClickHdl ) );
    aBtnDateSc10.SetClickHdl( LINK( this, ScTpCalcOptions, RadioClickHdl ) );
    aBtnDate1904.SetClickHdl( LINK( this, ScTpCalcOptions, RadioClickHdl ) );
}

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

USHORT* __EXPORT ScTpCalcOptions::GetRanges()
{
    return pCalcOptRanges;
}

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

SfxTabPage* __EXPORT ScTpCalcOptions::Create( Window* pParent, const SfxItemSet& rAttrSet )
{
    return ( new ScTpCalcOptions( pParent, rAttrSet ) );
}

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

void __EXPORT ScTpCalcOptions::Reset( const SfxItemSet& /* rCoreAttrs */ )
{
    USHORT  d,m,y;

    *pLocalOptions  = *pOldOptions;

    aBtnCase   .Check( !pLocalOptions->IsIgnoreCase() );
    aBtnCalc   .Check( pLocalOptions->IsCalcAsShown() );
    aBtnMatch  .Check( pLocalOptions->IsMatchWholeCell() );
    aBtnRegex  .Check( pLocalOptions->IsFormulaRegexEnabled() );
    aBtnLookUp .Check( pLocalOptions->IsLookUpColRowNames() );
    aBtnIterate.Check( pLocalOptions->IsIter() );
    aEdSteps   .SetValue( pLocalOptions->GetIterCount() );
    aEdPrec    .SetValue( pLocalOptions->GetStdPrecision() );
    aEdEps     .SetValue( pLocalOptions->GetIterEps(), 6 );

    pLocalOptions->GetDate( d, m, y );

    switch ( y )
    {
        case 1899:
            aBtnDateStd.Check();
            break;
        case 1900:
            aBtnDateSc10.Check();
            break;
        case 1904:
            aBtnDate1904.Check();
            break;
    }

    CheckClickHdl( &aBtnIterate );
}

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

BOOL __EXPORT ScTpCalcOptions::FillItemSet( SfxItemSet& rCoreAttrs )
{
    // alle weiteren Optionen werden in den Handlern aktualisiert
    pLocalOptions->SetIterCount( (USHORT)aEdSteps.GetValue() );
    pLocalOptions->SetStdPrecision( (USHORT)aEdPrec.GetValue() );
    pLocalOptions->SetIgnoreCase( !aBtnCase.IsChecked() );
    pLocalOptions->SetCalcAsShown( aBtnCalc.IsChecked() );
    pLocalOptions->SetMatchWholeCell( aBtnMatch.IsChecked() );
    pLocalOptions->SetFormulaRegexEnabled( aBtnRegex.IsChecked() );
    pLocalOptions->SetLookUpColRowNames( aBtnLookUp.IsChecked() );

    if ( *pLocalOptions != *pOldOptions )
    {
        rCoreAttrs.Put( ScTpCalcItem( nWhichCalc, *pLocalOptions ) );
        return TRUE;
    }
    else
        return FALSE;
}

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

int __EXPORT ScTpCalcOptions::DeactivatePage( SfxItemSet* pSetP )
{
    int nReturn = KEEP_PAGE;

    double fEps;
    if( aEdEps.GetValue( fEps ) && (fEps > 0.0) )
    {
        pLocalOptions->SetIterEps( fEps );
        nReturn = LEAVE_PAGE;
    }

    if ( nReturn == KEEP_PAGE )
    {
        ErrorBox( this,
                  WinBits( WB_OK | WB_DEF_OK ),
                  ScGlobal::GetRscString( STR_INVALID_EPS )
                ).Execute();

        aEdEps.GrabFocus();
    }
    else if ( pSetP )
        FillItemSet( *pSetP );

    return nReturn;
}

//-----------------------------------------------------------------------
// Handler:

IMPL_LINK( ScTpCalcOptions, RadioClickHdl, RadioButton*, pBtn )
{
    if ( pBtn == &aBtnDateStd )
    {
        pLocalOptions->SetDate( 30, 12, 1899 );
    }
    else if ( pBtn == &aBtnDateSc10 )
    {
        pLocalOptions->SetDate( 1, 1, 1900 );
    }
    else if ( pBtn == &aBtnDate1904 )
    {
        pLocalOptions->SetDate( 1, 1, 1904 );
    }

    return 0;
}

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

IMPL_LINK(  ScTpCalcOptions, CheckClickHdl, CheckBox*, pBtn )
{
    if ( pBtn->IsChecked() )
    {
        pLocalOptions->SetIter( TRUE );
        aFtSteps.Enable();  aEdSteps.Enable();
        aFtEps  .Enable();  aEdEps  .Enable();
    }
    else
    {
        pLocalOptions->SetIter( FALSE );
        aFtSteps.Disable(); aEdSteps.Disable();
        aFtEps  .Disable(); aEdEps  .Disable();
    }

    return 0;
}

<commit_msg>INTEGRATION: CWS aw033 (1.15.152); FILE MERGED 2008/05/14 15:24:34 aw 1.15.152.3: RESYNC: (1.16-1.17); FILE MERGED 2007/03/20 17:15:45 aw 1.15.152.2: RESYNC: (1.15-1.16); FILE MERGED 2007/01/22 15:20:34 aw 1.15.152.1: changes after resync<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: tpcalc.cxx,v $
 * $Revision: 1.18 $
 *
 * 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_sc.hxx"

#undef SC_DLLIMPLEMENTATION

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

#include "scitems.hxx"
#include <vcl/msgbox.hxx>

#include "global.hxx"
#include "globstr.hrc"
#include "uiitems.hxx"
#include "docsh.hxx"
#include "document.hxx"
#include "docoptio.hxx"
#include "scresid.hxx"
#include "sc.hrc"       // -> Slot-IDs
#include "optdlg.hrc"

#define _TPCALC_CXX
#include "tpcalc.hxx"
#undef _TPCALC_CXX

#include <math.h>

// STATIC DATA -----------------------------------------------------------

static USHORT pCalcOptRanges[] =
{
    SID_SCDOCOPTIONS,
    SID_SCDOCOPTIONS,
    0
};

//========================================================================

ScTpCalcOptions::ScTpCalcOptions( Window*           pParent,
                                  const SfxItemSet& rCoreAttrs )

    :   SfxTabPage      ( pParent,
                          ScResId( RID_SCPAGE_CALC ),
                          rCoreAttrs ),

        aGbZRefs        ( this, ScResId( GB_ZREFS ) ),
        aBtnIterate     ( this, ScResId( BTN_ITERATE ) ),
        aFtSteps        ( this, ScResId( FT_STEPS ) ),
        aEdSteps        ( this, ScResId( ED_STEPS ) ),
        aFtEps          ( this, ScResId( FT_EPS ) ),
        aEdEps          ( this, ScResId( ED_EPS ) ),
        aSeparatorFL    ( this, ScResId( FL_SEPARATOR ) ),
        aGbDate         ( this, ScResId( GB_DATE ) ),
        aBtnDateStd     ( this, ScResId( BTN_DATESTD ) ),
        aBtnDateSc10    ( this, ScResId( BTN_DATESC10 ) ),
        aBtnDate1904    ( this, ScResId( BTN_DATE1904 ) ),
        aHSeparatorFL   ( this, ScResId( FL_H_SEPARATOR ) ),
        aBtnCase        ( this, ScResId( BTN_CASE ) ),
        aBtnCalc        ( this, ScResId( BTN_CALC ) ),
        aBtnMatch       ( this, ScResId( BTN_MATCH ) ),
        aBtnRegex       ( this, ScResId( BTN_REGEX ) ),
        aBtnLookUp      ( this, ScResId( BTN_LOOKUP ) ),
        aFtPrec         ( this, ScResId( FT_PREC ) ),
        aEdPrec         ( this, ScResId( ED_PREC ) ),
        pOldOptions     ( new ScDocOptions(
                            ((const ScTpCalcItem&)rCoreAttrs.Get(
                                GetWhich( SID_SCDOCOPTIONS ))).
                                    GetDocOptions() ) ),
        pLocalOptions   ( new ScDocOptions ),
        nWhichCalc      ( GetWhich( SID_SCDOCOPTIONS ) )
{
    aSeparatorFL.SetStyle( aSeparatorFL.GetStyle() | WB_VERT );
    Init();
    FreeResource();
    SetExchangeSupport();
}

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

__EXPORT ScTpCalcOptions::~ScTpCalcOptions()
{
    delete pOldOptions;
    delete pLocalOptions;
}

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

void ScTpCalcOptions::Init()
{
    aBtnIterate .SetClickHdl( LINK( this, ScTpCalcOptions, CheckClickHdl ) );
    aBtnDateStd .SetClickHdl( LINK( this, ScTpCalcOptions, RadioClickHdl ) );
    aBtnDateSc10.SetClickHdl( LINK( this, ScTpCalcOptions, RadioClickHdl ) );
    aBtnDate1904.SetClickHdl( LINK( this, ScTpCalcOptions, RadioClickHdl ) );
}

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

USHORT* __EXPORT ScTpCalcOptions::GetRanges()
{
    return pCalcOptRanges;
}

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

SfxTabPage* __EXPORT ScTpCalcOptions::Create( Window* pParent, const SfxItemSet& rAttrSet )
{
    return ( new ScTpCalcOptions( pParent, rAttrSet ) );
}

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

void __EXPORT ScTpCalcOptions::Reset( const SfxItemSet& /* rCoreAttrs */ )
{
    USHORT  d,m,y;

    *pLocalOptions  = *pOldOptions;

    aBtnCase   .Check( !pLocalOptions->IsIgnoreCase() );
    aBtnCalc   .Check( pLocalOptions->IsCalcAsShown() );
    aBtnMatch  .Check( pLocalOptions->IsMatchWholeCell() );
    aBtnRegex  .Check( pLocalOptions->IsFormulaRegexEnabled() );
    aBtnLookUp .Check( pLocalOptions->IsLookUpColRowNames() );
    aBtnIterate.Check( pLocalOptions->IsIter() );
    aEdSteps   .SetValue( pLocalOptions->GetIterCount() );
    aEdPrec    .SetValue( pLocalOptions->GetStdPrecision() );
    aEdEps     .SetValue( pLocalOptions->GetIterEps(), 6 );

    pLocalOptions->GetDate( d, m, y );

    switch ( y )
    {
        case 1899:
            aBtnDateStd.Check();
            break;
        case 1900:
            aBtnDateSc10.Check();
            break;
        case 1904:
            aBtnDate1904.Check();
            break;
    }

    CheckClickHdl( &aBtnIterate );
}

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

BOOL __EXPORT ScTpCalcOptions::FillItemSet( SfxItemSet& rCoreAttrs )
{
    // alle weiteren Optionen werden in den Handlern aktualisiert
    pLocalOptions->SetIterCount( (USHORT)aEdSteps.GetValue() );
    pLocalOptions->SetStdPrecision( (USHORT)aEdPrec.GetValue() );
    pLocalOptions->SetIgnoreCase( !aBtnCase.IsChecked() );
    pLocalOptions->SetCalcAsShown( aBtnCalc.IsChecked() );
    pLocalOptions->SetMatchWholeCell( aBtnMatch.IsChecked() );
    pLocalOptions->SetFormulaRegexEnabled( aBtnRegex.IsChecked() );
    pLocalOptions->SetLookUpColRowNames( aBtnLookUp.IsChecked() );

    if ( *pLocalOptions != *pOldOptions )
    {
        rCoreAttrs.Put( ScTpCalcItem( nWhichCalc, *pLocalOptions ) );
        return TRUE;
    }
    else
        return FALSE;
}

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

int __EXPORT ScTpCalcOptions::DeactivatePage( SfxItemSet* pSetP )
{
    int nReturn = KEEP_PAGE;

    double fEps;
    if( aEdEps.GetValue( fEps ) && (fEps > 0.0) )
    {
        pLocalOptions->SetIterEps( fEps );
        nReturn = LEAVE_PAGE;
    }

    if ( nReturn == KEEP_PAGE )
    {
        ErrorBox( this,
                  WinBits( WB_OK | WB_DEF_OK ),
                  ScGlobal::GetRscString( STR_INVALID_EPS )
                ).Execute();

        aEdEps.GrabFocus();
    }
    else if ( pSetP )
        FillItemSet( *pSetP );

    return nReturn;
}

//-----------------------------------------------------------------------
// Handler:

IMPL_LINK( ScTpCalcOptions, RadioClickHdl, RadioButton*, pBtn )
{
    if ( pBtn == &aBtnDateStd )
    {
        pLocalOptions->SetDate( 30, 12, 1899 );
    }
    else if ( pBtn == &aBtnDateSc10 )
    {
        pLocalOptions->SetDate( 1, 1, 1900 );
    }
    else if ( pBtn == &aBtnDate1904 )
    {
        pLocalOptions->SetDate( 1, 1, 1904 );
    }

    return 0;
}

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

IMPL_LINK(  ScTpCalcOptions, CheckClickHdl, CheckBox*, pBtn )
{
    if ( pBtn->IsChecked() )
    {
        pLocalOptions->SetIter( TRUE );
        aFtSteps.Enable();  aEdSteps.Enable();
        aFtEps  .Enable();  aEdEps  .Enable();
    }
    else
    {
        pLocalOptions->SetIter( FALSE );
        aFtSteps.Disable(); aEdSteps.Disable();
        aFtEps  .Disable(); aEdEps  .Disable();
    }

    return 0;
}

<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef DBN_WATCHER_HPP
#define DBN_WATCHER_HPP

#include <fstream>

#include <sys/stat.h>

#include "stop_watch.hpp"
#include "rbm_traits.hpp"

namespace dll {

template<typename RBM>
struct default_watcher {
    stop_watch<std::chrono::seconds> watch;

    void training_begin(const RBM& rbm){
        std::cout << "RBM: Train with learning_rate=" << rbm.learning_rate;

        if(rbm_traits<RBM>::has_momentum()){
            std::cout << ", momentum=" << rbm.momentum;
        }

        if(rbm_traits<RBM>::decay() != decay_type::NONE){
            std::cout << ", weight_cost=" << rbm.weight_cost;
        }

        if(rbm_traits<RBM>::has_sparsity()){
            std::cout << ", sparsity_target=" << rbm.sparsity_target;
        }

        std::cout << std::endl;
    }

    void epoch_end(std::size_t epoch, double error, const RBM& rbm){
        printf("epoch %ld - Reconstruction error average: %.3f - Free energy: %.3f\n",
            epoch, error, rbm.free_energy());
    }

    void training_end(const RBM&){
        std::cout << "Training took " << watch.elapsed() << "s" << std::endl;
    }
};

template<typename RBM>
struct histogram_watcher {
    default_watcher<RBM> parent;

    void training_begin(const RBM& rbm){
        parent.training_begin(rbm);
    }

    void epoch_end(std::size_t epoch, double error, const RBM& rbm){
        parent.epoch_end(epoch, error, rbm);
    }

    void training_end(const RBM& rbm){
        parent.training_end(rbm);
    }

    void generate_hidden_images(size_t epoch, const RBM& rbm){
        mkdir("reports", 0777);

        auto folder = "reports/epoch_" + std::to_string(epoch);
        mkdir(folder.c_str(), 0777);

        for(size_t j = 0; j < RBM::num_hidden; ++j){
            auto path = folder + "/h_" + std::to_string(j) + ".dat";
            std::ofstream file(path, std::ios::out);

            if(!file){
                std::cout << "Could not open file " << path << std::endl;
            } else {
                size_t i = RBM::num_visible;
                while(i > 0){
                    --i;

                    auto value = rbm.w(i,j);
                    file << static_cast<size_t>(value > 0 ? static_cast<size_t>(value * 255.0) << 8 : static_cast<size_t>(-value * 255.0) << 16) << " ";
                }

                file << std::endl;
                file.close();
            }
        }
    }

    void generate_histograms(size_t epoch, const RBM& rbm){
        mkdir("reports", 0777);

        auto folder = "reports/epoch_" + std::to_string(epoch);
        mkdir(folder.c_str(), 0777);

        generate_histogram(folder + "/weights.dat", rbm.w);
        generate_histogram(folder + "/visibles.dat", rbm.a);
        generate_histogram(folder + "/hiddens.dat", rbm.b);
    }

    template<typename Container>
    void generate_histogram(const std::string& path, const Container& weights){
        std::ofstream file(path, std::ios::out);

        if(!file){
            std::cout << "Could not open file " << path << std::endl;
        } else {
            for(auto& weight : weights){
                file << weight << std::endl;
            }

            file << std::endl;
            file.close();
        }
    }
};

} //end of dbn namespace

#endif<commit_msg>Increase precision of reporting<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef DBN_WATCHER_HPP
#define DBN_WATCHER_HPP

#include <fstream>

#include <sys/stat.h>

#include "stop_watch.hpp"
#include "rbm_traits.hpp"

namespace dll {

template<typename RBM>
struct default_watcher {
    stop_watch<std::chrono::seconds> watch;

    void training_begin(const RBM& rbm){
        std::cout << "RBM: Train with learning_rate=" << rbm.learning_rate;

        if(rbm_traits<RBM>::has_momentum()){
            std::cout << ", momentum=" << rbm.momentum;
        }

        if(rbm_traits<RBM>::decay() != decay_type::NONE){
            std::cout << ", weight_cost=" << rbm.weight_cost;
        }

        if(rbm_traits<RBM>::has_sparsity()){
            std::cout << ", sparsity_target=" << rbm.sparsity_target;
        }

        std::cout << std::endl;
    }

    void epoch_end(std::size_t epoch, double error, const RBM& rbm){
        printf("epoch %ld - Reconstruction error average: %.5f - Free energy: %.3f\n",
            epoch, error, rbm.free_energy());
    }

    void training_end(const RBM&){
        std::cout << "Training took " << watch.elapsed() << "s" << std::endl;
    }
};

template<typename RBM>
struct histogram_watcher {
    default_watcher<RBM> parent;

    void training_begin(const RBM& rbm){
        parent.training_begin(rbm);
    }

    void epoch_end(std::size_t epoch, double error, const RBM& rbm){
        parent.epoch_end(epoch, error, rbm);
    }

    void training_end(const RBM& rbm){
        parent.training_end(rbm);
    }

    void generate_hidden_images(size_t epoch, const RBM& rbm){
        mkdir("reports", 0777);

        auto folder = "reports/epoch_" + std::to_string(epoch);
        mkdir(folder.c_str(), 0777);

        for(size_t j = 0; j < RBM::num_hidden; ++j){
            auto path = folder + "/h_" + std::to_string(j) + ".dat";
            std::ofstream file(path, std::ios::out);

            if(!file){
                std::cout << "Could not open file " << path << std::endl;
            } else {
                size_t i = RBM::num_visible;
                while(i > 0){
                    --i;

                    auto value = rbm.w(i,j);
                    file << static_cast<size_t>(value > 0 ? static_cast<size_t>(value * 255.0) << 8 : static_cast<size_t>(-value * 255.0) << 16) << " ";
                }

                file << std::endl;
                file.close();
            }
        }
    }

    void generate_histograms(size_t epoch, const RBM& rbm){
        mkdir("reports", 0777);

        auto folder = "reports/epoch_" + std::to_string(epoch);
        mkdir(folder.c_str(), 0777);

        generate_histogram(folder + "/weights.dat", rbm.w);
        generate_histogram(folder + "/visibles.dat", rbm.a);
        generate_histogram(folder + "/hiddens.dat", rbm.b);
    }

    template<typename Container>
    void generate_histogram(const std::string& path, const Container& weights){
        std::ofstream file(path, std::ios::out);

        if(!file){
            std::cout << "Could not open file " << path << std::endl;
        } else {
            for(auto& weight : weights){
                file << weight << std::endl;
            }

            file << std::endl;
            file.close();
        }
    }
};

} //end of dbn namespace

#endif<|endoftext|>