<commit_before>/*************************************************************************
 *
 *  $RCSfile: javacompskeleton.cxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: jsc $ $Date: 2005-08-23 08:30:10 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include "skeletonjava.hxx"

using namespace ::codemaker::java;

namespace skeletonmaker { namespace java {

void generatePackage(std::ostream & o, const rtl::OString & implname)
{
    short count=0;
    sal_Int32 index = implname.lastIndexOf('.');
    if (index != -1) {
        o << "package " << implname.copy(0, index) << ";\n\n";
    }
}

void generateImports(std::ostream & o,
         const std::hash_set< rtl::OString, rtl::OStringHash >& interfaces,
         const rtl::OString & propertyhelper,
         bool serviceobject, bool supportxcomponent)
{
    o << "import com.sun.star.uno.XComponentContext;\n";
    if (serviceobject) {
        o << "import com.sun.star.lib.uno.helper.Factory;\n";
        o << "import com.sun.star.lang.XSingleComponentFactory;\n";
        o << "import com.sun.star.registry.XRegistryKey;\n";
    }

    if  (!propertyhelper.equals("_")) {
        if (supportxcomponent)
            o << "import com.sun.star.lib.uno.helper.ComponentBase;\n";
        else
            o << "import com.sun.star.lib.uno.helper.WeakBase;\n";
    }
    if (propertyhelper.getLength() > 0) {
        if (propertyhelper.equals("_")) {
            o << "import com.sun.star.lib.uno.helper.PropertySet;\n";
            o << "import com.sun.star.beans.PropertyAttribute;\n";
        } else {
            o << "import com.sun.star.uno.Type;\n";
            o << "import com.sun.star.lib.uno.helper.PropertySetMixin;\n";
        }
    }

//     std::hash_set< rtl::OString, rtl::OStringHash >::const_iterator iter = interfaces.begin();
//     while (iter != interfaces.end()) {
//         o << "import " << ((*iter).getStr()) << ";\n";
//         iter++;
//     }
}

void generateCompFunctions(std::ostream & o, const rtl::OString & classname)
{
    o << "    public static XSingleComponentFactory __getComponentFactory("
      << "String sImplementationName ) {\n"
      << "        XSingleComponentFactory xFactory = null;\n\n"
      << "        if ( sImplementationName.equals( m_implementationName ) )\n"
      << "            xFactory = Factory.createComponentFactory("
      << classname << ".class, m_serviceNames);\n"
      << "        return xFactory;\n    }\n\n";

    o << "    public static boolean __writeRegistryServiceInfo("
      << "XRegistryKey xRegistryKey ) {\n"
      << "        return Factory.writeRegistryServiceInfo(m_implementationName,\n"
      << "                                                m_serviceNames,\n"
      << "                                                xRegistryKey);\n"
      << "    }\n\n";
}

void generateXServiceInfoBodies(std::ostream& o)
{
    o << "    /* com.sun.star.lang.XServiceInfo */\n";
    o << "    public java.lang.String getImplementationName() {\n"
      << "         return m_implementationName;\n    }\n\n";

    o << "    public boolean supportsService( java.lang.String sService ) {\n"
      << "        int len = m_serviceNames.length;\n\n"
      << "        for( int i=0; i < len; i++) {\n"
      << "            if (sService.equals(m_serviceNames[i]))\n"
      << "                return true;\n"
      << "        }\n        return false;\n    }\n\n";

    o << "    public java.lang.String[] getSupportedServiceNames() {\n"
      << "        return m_serviceNames;\n    }\n\n";
}

bool checkAttribute(rtl::OStringBuffer& attributeValue, sal_uInt16 attribute) {
    bool cast = false;
    sal_uInt16 attributes[9] = {
        /* com::sun::star::beans::PropertyValue::MAYBEVOID */ 1,
        /* com::sun::star::beans::PropertyValue::BOUND */ 2,
        /* com::sun::star::beans::PropertyValue::CONSTRAINED */ 4,
        /* com::sun::star::beans::PropertyValue::TRANSIENT */ 8,
        /* com::sun::star::beans::PropertyValue::READONLY */ 16,
        /* com::sun::star::beans::PropertyValue::MAYBEAMBIGIOUS */ 32,
        /* com::sun::star::beans::PropertyValue::MAYBEDEFAULT */ 64,
        /* com::sun::star::beans::PropertyValue::REMOVEABLE */ 128,
        /* com::sun::star::beans::PropertyValue::OPTIONAL */ 256 };

    for (sal_uInt16 i = 0; i < 9; i++) {
        if (attribute & attributes[i]) {
            if (attributeValue.getLength() > 0) {
                cast |= true;
                attributeValue.append("|");
            }
            switch (attributes[i]) {
            case 1:
                attributeValue.append("PropertyAttribute.MAYBEVOID");
                break;
            case 2:
                attributeValue.append("PropertyAttribute.BOUND");
                break;
            case 4:
                attributeValue.append("PropertyAttribute.CONSTRAINED");
                break;
            case 8:
                attributeValue.append("PropertyAttribute.TRANSIENT");
                break;
            case 16:
                attributeValue.append("PropertyAttribute.READONLY");
                break;
            case 32:
                attributeValue.append("PropertyAttribute.MAYBEAMBIGIOUS");
                break;
            case 64:
                attributeValue.append("PropertyAttribute.MAYBEDEFAULT");
                break;
            case 128:
                attributeValue.append("PropertyAttribute.REMOVEABLE");
                break;
            case 256:
                attributeValue.append("PropertyAttribute.OPTIONAL");
                break;
            }
        }
    }
    if (cast) {
        attributeValue.insert(0, '(');
        attributeValue.append(')');
    }

    return cast;
}

void registerProperties(std::ostream& o,
                        TypeManager const & manager,
                        const StringPairHashMap& properties,
                        const rtl::OString& indentation)
{
    if (!properties.empty()) {
        StringPairHashMap::const_iterator iter =
            properties.begin();
        bool cast = false;
        rtl::OStringBuffer attributeValue;
        while (iter != properties.end()) {
            if (iter->second.second > 0) {
                cast = checkAttribute(attributeValue, iter->second.second);
            } else {
                cast = true;
                attributeValue.append('0');
            }

            o << indentation << "registerProperty(\"" << iter->first
              << "\", \"m_" << iter->first << "\",\n"
              << indentation << "      ";
            if (cast)
                o << "(short)";

            o << attributeValue.makeStringAndClear() << ");\n";
            iter++;
        }
    }
}

void generateMethodBodies(std::ostream& o,
         ProgramOptions const & options,
         TypeManager const & manager,
         const std::hash_set< rtl::OString, rtl::OStringHash >& interfaces,
         const rtl::OString& indentation)
{
    std::hash_set< rtl::OString, rtl::OStringHash >::const_iterator iter =
        interfaces.begin();
    codemaker::GeneratedTypeSet generated;
    while (iter != interfaces.end()) {
        if ( (*iter).equals("com.sun.star.lang.XServiceInfo")) {
                generateXServiceInfoBodies(o);
        } else {
            typereg::Reader reader(manager.getTypeReader((*iter).replace('.','/')));
            printMethods(o, options, manager, reader, generated, "_",
                         indentation, true);
        }
        iter++;
    }
}

void generateClassDefinition(std::ostream& o,
         ProgramOptions const & options,
         TypeManager const & manager,
         const rtl::OString & classname,
         const std::hash_set< rtl::OString, rtl::OStringHash >& services,
         const std::hash_set< rtl::OString, rtl::OStringHash >& interfaces,
         const StringPairHashMap& properties,
         const rtl::OString& propertyhelper, bool supportxcomponent)
{
    o << "\n\npublic final class " << classname << " extends ";

    if (!interfaces.empty()) {
        if (propertyhelper.equals("_")) {
                o << "PropertySet\n";
        } else {
            if (supportxcomponent)
                o << "ComponentBase\n";
            else
                o << "WeakBase\n";
        }
        o << "    implements ";
        std::hash_set< rtl::OString, rtl::OStringHash >::const_iterator iter =
            interfaces.begin();
        while (iter != interfaces.end()) {
            o << (*iter);
            iter++;
            if (iter != interfaces.end())
                o << ",\n               ";
        }
    }
    o << "\n{\n";

    o << "    private final XComponentContext m_context;\n";

    // check property helper
    if (propertyhelper.getLength() > 1) {
        o << "    private final PropertySetMixin m_prophlp;";
    }

    o << "    private static final java.lang.String m_implementationName = "
      << classname << ".class.getName();\n";

    if (!services.empty()) {
        o << "    private static final java.lang.String[] m_serviceNames = {\n";
        std::hash_set< rtl::OString, rtl::OStringHash >::const_iterator iter =
            services.begin();
        while (iter != services.end()) {
            o << "        \"" << (*iter).replace('/','.') << "\"";
            iter++;
            if (iter != services.end())
                o << ",\n";
            else
                o << " };\n";
        }
    }
    o << "\n    public " << classname << "( XComponentContext context ) {\n"
      << "        m_context = context;\n";
    if (propertyhelper.equals("_")) {
        registerProperties(o, manager, properties, "        ");
    } else {
        if (propertyhelper.getLength() > 1) {
            o << "        m_prophlp = new PropertySetMixin(\n"
              << "            m_context, this, new Type(" << propertyhelper
              << ".class));\n";
        }
    }
    o << "    };\n\n";

    if (!services.empty())
        generateCompFunctions(o, classname);

    generateMethodBodies(o, options, manager, interfaces, "    ");

    if (!properties.empty()) {
        StringPairHashMap::const_iterator iter =
            properties.begin();
        while (iter != properties.end()) {
            o << "    protected ";
            printType(o, options, manager, iter->second.first.replace('.','/'),
                      false, false);
            o << " m_" << iter->first << ";\n";
            iter++;
        }
    }

    // end of class definition
    o << "}\n";
}

void generateSkeleton(ProgramOptions const & options,
                      TypeManager const & manager,
                      std::vector< rtl::OString > const & types,
                      rtl::OString const & delegate)
{
    std::hash_set< rtl::OString, rtl::OStringHash > interfaces;
    std::hash_set< rtl::OString, rtl::OStringHash > services;
    StringPairHashMap properties;
    bool attributes = false;
    bool serviceobject = false;
    bool supportxcomponent = false;

    std::vector< rtl::OString >::const_iterator iter = types.begin();
    while (iter != types.end()) {
        checkType(manager, *iter, interfaces, services, properties, attributes);
        iter++;
    }

    // check if service object or simple UNO object
    if (!services.empty())
        serviceobject = true;

    rtl::OString propertyhelper = checkPropertyHelper(manager, services);
    checkDefaultInterfaces(interfaces, services, propertyhelper);

    supportxcomponent = checkXComponentSupport(manager, interfaces);

    rtl::OString compFileName(createFileNameFromType(
                                  options.outputpath,
                                  options.implname.replace('.','/'),
                                  ".java"));

    rtl::OString tmpDir = getTempDir(compFileName);
    FileStream file;
    file.createTempFile(tmpDir);
    rtl::OString tmpFileName;

    if(!file.isValid())
    {
        rtl::OString message("cannot open ");
        message += compFileName + " for writing";
        throw CannotDumpException(message);
    } else {
        tmpFileName = file.getName();
    }
    file.close();
    std::ofstream oFile(tmpFileName.getStr(), std::ios_base::binary);

    try {
        generatePackage(oFile, options.implname);

        generateImports(oFile, interfaces, propertyhelper,
                        serviceobject, supportxcomponent);

        rtl::OString classname(options.implname);
        sal_Int32 index = 0;
        if ((index = classname.lastIndexOf('.')) > 0)
            classname = classname.copy(index+1);

        generateClassDefinition(oFile, options, manager, classname, services,
                                interfaces, properties, propertyhelper,
                                supportxcomponent);

        oFile.close();
        OSL_VERIFY(makeValidTypeFile(compFileName, tmpFileName, sal_False));
    } catch(CannotDumpException& e) {

        std::cout << "ERROR: " << e.m_message.getStr() << "\n";
        // remove existing type file if something goes wrong to ensure consistency
        if (fileExists(compFileName))
            removeTypeFile(compFileName);

        // remove tmp file if something goes wrong
        removeTypeFile(tmpFileName);
    }
}

} }

<commit_msg>#i52208# formatting<commit_after>/*************************************************************************
 *
 *  $RCSfile: javacompskeleton.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: jsc $ $Date: 2005-08-23 11:23:43 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include "skeletonjava.hxx"

using namespace ::codemaker::java;

namespace skeletonmaker { namespace java {

void generatePackage(std::ostream & o, const rtl::OString & implname)
{
    short count=0;
    sal_Int32 index = implname.lastIndexOf('.');
    if (index != -1) {
        o << "package " << implname.copy(0, index) << ";\n\n";
    }
}

void generateImports(std::ostream & o,
         const std::hash_set< rtl::OString, rtl::OStringHash >& interfaces,
         const rtl::OString & propertyhelper,
         bool serviceobject, bool supportxcomponent)
{
    o << "import com.sun.star.uno.XComponentContext;\n";
    if (serviceobject) {
        o << "import com.sun.star.lib.uno.helper.Factory;\n";
        o << "import com.sun.star.lang.XSingleComponentFactory;\n";
        o << "import com.sun.star.registry.XRegistryKey;\n";
    }

    if  (!propertyhelper.equals("_")) {
        if (supportxcomponent)
            o << "import com.sun.star.lib.uno.helper.ComponentBase;\n";
        else
            o << "import com.sun.star.lib.uno.helper.WeakBase;\n";
    }
    if (propertyhelper.getLength() > 0) {
        if (propertyhelper.equals("_")) {
            o << "import com.sun.star.lib.uno.helper.PropertySet;\n";
            o << "import com.sun.star.beans.PropertyAttribute;\n";
        } else {
            o << "import com.sun.star.uno.Type;\n";
            o << "import com.sun.star.lib.uno.helper.PropertySetMixin;\n";
        }
    }

//     std::hash_set< rtl::OString, rtl::OStringHash >::const_iterator iter = interfaces.begin();
//     while (iter != interfaces.end()) {
//         o << "import " << ((*iter).getStr()) << ";\n";
//         iter++;
//     }
}

void generateCompFunctions(std::ostream & o, const rtl::OString & classname)
{
    o << "    public static XSingleComponentFactory __getComponentFactory("
      << "String sImplementationName ) {\n"
      << "        XSingleComponentFactory xFactory = null;\n\n"
      << "        if ( sImplementationName.equals( m_implementationName ) )\n"
      << "            xFactory = Factory.createComponentFactory("
      << classname << ".class, m_serviceNames);\n"
      << "        return xFactory;\n    }\n\n";

    o << "    public static boolean __writeRegistryServiceInfo("
      << "XRegistryKey xRegistryKey ) {\n"
      << "        return Factory.writeRegistryServiceInfo(m_implementationName,\n"
      << "                                                m_serviceNames,\n"
      << "                                                xRegistryKey);\n"
      << "    }\n\n";
}

void generateXServiceInfoBodies(std::ostream& o)
{
    o << "    /* com.sun.star.lang.XServiceInfo */\n";
    o << "    public java.lang.String getImplementationName() {\n"
      << "         return m_implementationName;\n    }\n\n";

    o << "    public boolean supportsService( java.lang.String sService ) {\n"
      << "        int len = m_serviceNames.length;\n\n"
      << "        for( int i=0; i < len; i++) {\n"
      << "            if (sService.equals(m_serviceNames[i]))\n"
      << "                return true;\n"
      << "        }\n        return false;\n    }\n\n";

    o << "    public java.lang.String[] getSupportedServiceNames() {\n"
      << "        return m_serviceNames;\n    }\n\n";
}

bool checkAttribute(rtl::OStringBuffer& attributeValue, sal_uInt16 attribute) {
    bool cast = false;
    sal_uInt16 attributes[9] = {
        /* com::sun::star::beans::PropertyValue::MAYBEVOID */ 1,
        /* com::sun::star::beans::PropertyValue::BOUND */ 2,
        /* com::sun::star::beans::PropertyValue::CONSTRAINED */ 4,
        /* com::sun::star::beans::PropertyValue::TRANSIENT */ 8,
        /* com::sun::star::beans::PropertyValue::READONLY */ 16,
        /* com::sun::star::beans::PropertyValue::MAYBEAMBIGIOUS */ 32,
        /* com::sun::star::beans::PropertyValue::MAYBEDEFAULT */ 64,
        /* com::sun::star::beans::PropertyValue::REMOVEABLE */ 128,
        /* com::sun::star::beans::PropertyValue::OPTIONAL */ 256 };

    for (sal_uInt16 i = 0; i < 9; i++) {
        if (attribute & attributes[i]) {
            if (attributeValue.getLength() > 0) {
                cast |= true;
                attributeValue.append("|");
            }
            switch (attributes[i]) {
            case 1:
                attributeValue.append("PropertyAttribute.MAYBEVOID");
                break;
            case 2:
                attributeValue.append("PropertyAttribute.BOUND");
                break;
            case 4:
                attributeValue.append("PropertyAttribute.CONSTRAINED");
                break;
            case 8:
                attributeValue.append("PropertyAttribute.TRANSIENT");
                break;
            case 16:
                attributeValue.append("PropertyAttribute.READONLY");
                break;
            case 32:
                attributeValue.append("PropertyAttribute.MAYBEAMBIGIOUS");
                break;
            case 64:
                attributeValue.append("PropertyAttribute.MAYBEDEFAULT");
                break;
            case 128:
                attributeValue.append("PropertyAttribute.REMOVEABLE");
                break;
            case 256:
                attributeValue.append("PropertyAttribute.OPTIONAL");
                break;
            }
        }
    }
    if (cast) {
        attributeValue.insert(0, '(');
        attributeValue.append(')');
    }

    return cast;
}

void registerProperties(std::ostream& o,
                        TypeManager const & manager,
                        const StringPairHashMap& properties,
                        const rtl::OString& indentation)
{
    if (!properties.empty()) {
        StringPairHashMap::const_iterator iter =
            properties.begin();
        bool cast = false;
        rtl::OStringBuffer attributeValue;
        while (iter != properties.end()) {
            if (iter->second.second > 0) {
                cast = checkAttribute(attributeValue, iter->second.second);
            } else {
                cast = true;
                attributeValue.append('0');
            }

            o << indentation << "registerProperty(\"" << iter->first
              << "\", \"m_" << iter->first << "\",\n"
              << indentation << "      ";
            if (cast)
                o << "(short)";

            o << attributeValue.makeStringAndClear() << ");\n";
            iter++;
        }
    }
}

void generateMethodBodies(std::ostream& o,
         ProgramOptions const & options,
         TypeManager const & manager,
         const std::hash_set< rtl::OString, rtl::OStringHash >& interfaces,
         const rtl::OString& indentation)
{
    std::hash_set< rtl::OString, rtl::OStringHash >::const_iterator iter =
        interfaces.begin();
    codemaker::GeneratedTypeSet generated;
    while (iter != interfaces.end()) {
        if ( (*iter).equals("com.sun.star.lang.XServiceInfo")) {
                generateXServiceInfoBodies(o);
        } else {
            typereg::Reader reader(manager.getTypeReader((*iter).replace('.','/')));
            printMethods(o, options, manager, reader, generated, "_",
                         indentation, true);
        }
        iter++;
    }
}

void generateClassDefinition(std::ostream& o,
         ProgramOptions const & options,
         TypeManager const & manager,
         const rtl::OString & classname,
         const std::hash_set< rtl::OString, rtl::OStringHash >& services,
         const std::hash_set< rtl::OString, rtl::OStringHash >& interfaces,
         const StringPairHashMap& properties,
         const rtl::OString& propertyhelper, bool supportxcomponent)
{
    o << "\n\npublic final class " << classname << " extends ";

    if (!interfaces.empty()) {
        if (propertyhelper.equals("_")) {
                o << "PropertySet\n";
        } else {
            if (supportxcomponent)
                o << "ComponentBase\n";
            else
                o << "WeakBase\n";
        }
        o << "    implements ";
        std::hash_set< rtl::OString, rtl::OStringHash >::const_iterator iter =
            interfaces.begin();
        while (iter != interfaces.end()) {
            o << (*iter);
            iter++;
            if (iter != interfaces.end())
                o << ",\n               ";
        }
    }
    o << "\n{\n";

    o << "    private final XComponentContext m_context;\n";

    // check property helper
    if (propertyhelper.getLength() > 1) {
        o << "    private final PropertySetMixin m_prophlp;\n";
    }

    o << "    private static final java.lang.String m_implementationName = "
      << classname << ".class.getName();\n";

    if (!services.empty()) {
        o << "    private static final java.lang.String[] m_serviceNames = {\n";
        std::hash_set< rtl::OString, rtl::OStringHash >::const_iterator iter =
            services.begin();
        while (iter != services.end()) {
            o << "        \"" << (*iter).replace('/','.') << "\"";
            iter++;
            if (iter != services.end())
                o << ",\n";
            else
                o << " };\n";
        }
    }
    o << "\n    public " << classname << "( XComponentContext context ) {\n"
      << "        m_context = context;\n";
    if (propertyhelper.equals("_")) {
        registerProperties(o, manager, properties, "        ");
    } else {
        if (propertyhelper.getLength() > 1) {
            o << "        m_prophlp = new PropertySetMixin(\n"
              << "            m_context, this, new Type(" << propertyhelper
              << ".class));\n";
        }
    }
    o << "    };\n\n";

    if (!services.empty())
        generateCompFunctions(o, classname);

    generateMethodBodies(o, options, manager, interfaces, "    ");

    if (!properties.empty()) {
        StringPairHashMap::const_iterator iter =
            properties.begin();
        while (iter != properties.end()) {
            o << "    protected ";
            printType(o, options, manager, iter->second.first.replace('.','/'),
                      false, false);
            o << " m_" << iter->first << ";\n";
            iter++;
        }
    }

    // end of class definition
    o << "}\n";
}

void generateSkeleton(ProgramOptions const & options,
                      TypeManager const & manager,
                      std::vector< rtl::OString > const & types,
                      rtl::OString const & delegate)
{
    std::hash_set< rtl::OString, rtl::OStringHash > interfaces;
    std::hash_set< rtl::OString, rtl::OStringHash > services;
    StringPairHashMap properties;
    bool attributes = false;
    bool serviceobject = false;
    bool supportxcomponent = false;

    std::vector< rtl::OString >::const_iterator iter = types.begin();
    while (iter != types.end()) {
        checkType(manager, *iter, interfaces, services, properties, attributes);
        iter++;
    }

    // check if service object or simple UNO object
    if (!services.empty())
        serviceobject = true;

    rtl::OString propertyhelper = checkPropertyHelper(manager, services);
    checkDefaultInterfaces(interfaces, services, propertyhelper);

    supportxcomponent = checkXComponentSupport(manager, interfaces);

    rtl::OString compFileName(createFileNameFromType(
                                  options.outputpath,
                                  options.implname.replace('.','/'),
                                  ".java"));

    rtl::OString tmpDir = getTempDir(compFileName);
    FileStream file;
    file.createTempFile(tmpDir);
    rtl::OString tmpFileName;

    if(!file.isValid())
    {
        rtl::OString message("cannot open ");
        message += compFileName + " for writing";
        throw CannotDumpException(message);
    } else {
        tmpFileName = file.getName();
    }
    file.close();
    std::ofstream oFile(tmpFileName.getStr(), std::ios_base::binary);

    try {
        generatePackage(oFile, options.implname);

        generateImports(oFile, interfaces, propertyhelper,
                        serviceobject, supportxcomponent);

        rtl::OString classname(options.implname);
        sal_Int32 index = 0;
        if ((index = classname.lastIndexOf('.')) > 0)
            classname = classname.copy(index+1);

        generateClassDefinition(oFile, options, manager, classname, services,
                                interfaces, properties, propertyhelper,
                                supportxcomponent);

        oFile.close();
        OSL_VERIFY(makeValidTypeFile(compFileName, tmpFileName, sal_False));
    } catch(CannotDumpException& e) {

        std::cout << "ERROR: " << e.m_message.getStr() << "\n";
        // remove existing type file if something goes wrong to ensure consistency
        if (fileExists(compFileName))
            removeTypeFile(compFileName);

        // remove tmp file if something goes wrong
        removeTypeFile(tmpFileName);
    }
}

} }

<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */
#include "ProxyRequestContext.h"

#include <folly/Memory.h>

#include "mcrouter/config.h"
#include "mcrouter/McrouterClient.h"
#include "mcrouter/proxy.h"

namespace facebook { namespace memcache { namespace mcrouter {

ProxyRequestContext::ProxyRequestContext(
  proxy_t& pr,
  McMsgRef req,
  void (*enqReply)(ProxyRequestContext& preq),
  void* context,
  void (*reqComplete)(ProxyRequestContext& preq))
    : proxy_(pr),
      context_(context),
      enqueueReply_(enqReply),
      reqComplete_(reqComplete),
      logger_(&pr),
      additionalLogger_(&pr) {

  static const char* const kInternalGetPrefix = "__mcrouter__.";

  if (req->op == mc_op_get && !strncmp(req->key.str, kInternalGetPrefix,
                                       strlen(kInternalGetPrefix))) {
    /* HACK: for backwards compatibility, convert (get, "__mcrouter__.key")
       into (get-service-info, "key") */
    auto copy = MutableMcMsgRef(mc_msg_dup(req.get()));
    copy->op = mc_op_get_service_info;
    copy->key.str += strlen(kInternalGetPrefix);
    copy->key.len -= strlen(kInternalGetPrefix);
    origReq_ = std::move(copy);
  } else {
    origReq_ = std::move(req);
  }

  stat_incr_safe(proxy_.stats, proxy_request_num_outstanding_stat);
}

ProxyRequestContext::~ProxyRequestContext() {
  assert(replied_);
  if (reqComplete_) {
    reqComplete_(*this);
  }

  if (processing_) {
    --proxy_.numRequestsProcessing_;
    stat_decr(proxy_.stats, proxy_reqs_processing_stat, 1);
    proxy_.pump();
  }

  if (requester_) {
    requester_->decref();
  }

  stat_decr_safe(proxy_.stats, proxy_request_num_outstanding_stat);
}

uint64_t ProxyRequestContext::senderId() const {
  uint64_t id = 0;
  if (requester_) {
    id = requester_->clientId();
  }

  return id;
}

void ProxyRequestContext::sendReply(McReply newReply) {
  if (replied_) {
    return;
  }
  reply_ = std::move(newReply);
  replied_ = true;

  enqueueReply_(*this);

  stat_incr(proxy_.stats, request_replied_stat, 1);
  stat_incr(proxy_.stats, request_replied_count_stat, 1);
  if (mc_res_is_err(reply_->result())) {
    stat_incr(proxy_.stats, request_error_stat, 1);
    stat_incr(proxy_.stats, request_error_count_stat, 1);
  } else {
    stat_incr(proxy_.stats, request_success_stat, 1);
    stat_incr(proxy_.stats, request_success_count_stat, 1);
  }
}

}}}
<commit_msg>Fix embedded mcrouter mode<commit_after>/*
 *  Copyright (c) 2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */
#include "ProxyRequestContext.h"

#include <folly/Memory.h>

#include "mcrouter/config.h"
#include "mcrouter/McrouterClient.h"
#include "mcrouter/proxy.h"

namespace facebook { namespace memcache { namespace mcrouter {

ProxyRequestContext::ProxyRequestContext(
  proxy_t& pr,
  McMsgRef req,
  void (*enqReply)(ProxyRequestContext& preq),
  void* context,
  void (*reqComplete)(ProxyRequestContext& preq))
    : proxy_(pr),
      context_(context),
      enqueueReply_(enqReply),
      reqComplete_(reqComplete),
      logger_(&pr),
      additionalLogger_(&pr) {

  static const char* const kInternalGetPrefix = "__mcrouter__.";

  if (req->op == mc_op_get && !strncmp(req->key.str, kInternalGetPrefix,
                                       strlen(kInternalGetPrefix))) {
    /* HACK: for backwards compatibility, convert (get, "__mcrouter__.key")
       into (get-service-info, "key") */
    auto copy = MutableMcMsgRef(mc_msg_dup(req.get()));
    copy->op = mc_op_get_service_info;
    copy->key.str += strlen(kInternalGetPrefix);
    copy->key.len -= strlen(kInternalGetPrefix);
    origReq_ = std::move(copy);
  } else {
    origReq_ = std::move(req);
  }

  stat_incr_safe(proxy_.stats, proxy_request_num_outstanding_stat);
}

ProxyRequestContext::~ProxyRequestContext() {
  assert(replied_);
  if (reqComplete_) {
    reqComplete_(*this);
  }

  if (processing_) {
    --proxy_.numRequestsProcessing_;
    stat_decr(proxy_.stats, proxy_reqs_processing_stat, 1);
    proxy_.pump();
  }

  if (requester_) {
    requester_->decref();
  }

  stat_decr_safe(proxy_.stats, proxy_request_num_outstanding_stat);
}

uint64_t ProxyRequestContext::senderId() const {
  uint64_t id = 0;
  if (requester_) {
    id = requester_->clientId();
  }

  return id;
}

void ProxyRequestContext::sendReply(McReply newReply) {
  if (replied_) {
    return;
  }
  reply_ = std::move(newReply);
  replied_ = true;

  if (LIKELY(enqueueReply_ != nullptr)) {
    enqueueReply_(*this);
  }

  stat_incr(proxy_.stats, request_replied_stat, 1);
  stat_incr(proxy_.stats, request_replied_count_stat, 1);
  if (mc_res_is_err(reply_->result())) {
    stat_incr(proxy_.stats, request_error_stat, 1);
    stat_incr(proxy_.stats, request_error_count_stat, 1);
  } else {
    stat_incr(proxy_.stats, request_success_stat, 1);
    stat_incr(proxy_.stats, request_success_count_stat, 1);
  }
}

}}}
<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>

#include <vector>
#include <list>
#include <map>

#include <algorithm>

#include <iomanip>      // setw, set::precision, ...

using namespace std;

#define EXP

//______________________________________________________________________________
class EXP msrOptionsElement
{
  public:

    // creation from MusicXML
    // ------------------------------------------------------

  protected:

    msrOptionsElement (
      string optionsElementShortName,
      string optionsElementLongName,
      string optionsElementDescription);

    virtual ~msrOptionsElement();

  public:

    // set and get
    // ------------------------------------------------------

    string                getOptionsElementShortName () const
                              { return fOptionsElementShortName; }

    string                getOptionsElementLongName () const
                              { return fOptionsElementLongName; }

    string                getOptionsElementDescription () const
                              { return fOptionsElementDescription; }

    // services
    // ------------------------------------------------------

    string                operator() () const
                              { return fOptionsElementDescription; }

    // print
    // ------------------------------------------------------

    virtual void          print (ostream& os) const;

  protected:

    string                fOptionsElementShortName;
    string                fOptionsElementLongName;
    string                fOptionsElementDescription;
};
//typedef SMARTP<msrOptionsElement> S_msrOptionsElement;
typedef msrOptionsElement* S_msrOptionsElement;
EXP ostream& operator<< (ostream& os, const S_msrOptionsElement& elt);

msrOptionsElement::msrOptionsElement (
  string optionsElementShortName,
  string optionsElementLongName,
  string optionsElementDescription)
{
  fOptionsElementShortName   = optionsElementShortName;
  fOptionsElementLongName    = optionsElementLongName;
  fOptionsElementDescription = optionsElementDescription;
}

msrOptionsElement::~msrOptionsElement()
{}

ostream& operator<< (ostream& os, const S_msrOptionsElement& elt)
{
  elt->print (os);
  return os;
}

void msrOptionsElement::print (ostream& os) const
{
  os << "??? msrOptionsElement ???" << endl;
}

//______________________________________________________________________________
class EXP msrOptionsItem : public msrOptionsElement
{
  public:

    msrOptionsItem (
      string optionsItemShortName,
      string optionsItemLongName,
      string optionsItemDescription)
      : msrOptionsElement (
          optionsItemShortName,
          optionsItemLongName,
          optionsItemDescription)
      {
        fOptionsItemHasBeenSelected = false;
      }

    void                  setOptionsItemHasBeenSelected ()
                              { fOptionsItemHasBeenSelected = true; }

    bool                  getOptionsItemHasBeenSelected () const
                              { return fOptionsItemHasBeenSelected; }

    void                  print (ostream& os) const
      {
        const int fieldWidth = 19;

        os <<
          setw(fieldWidth) <<
          "fOptionsElementShortName" << " : " << fOptionsElementShortName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementLongName" << " : " << fOptionsElementLongName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementDescription" << " : " << fOptionsElementDescription <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsItemHasBeenSelected" << " : " << fOptionsItemHasBeenSelected <<
          endl;
      }

  protected:

    bool                  fOptionsItemHasBeenSelected;
};
typedef msrOptionsItem* S_msrOptionsItem;

ostream& operator<< (ostream& os, const msrOptionsItem& elt)
{
  elt.print (os);
  return os;
}

//______________________________________________________________________________
class EXP msrOptionsIntItem : public msrOptionsItem
{
  public:

    msrOptionsIntItem (
      string optionsItemShortName,
      string optionsItemLongName,
      string optionsItemDescription,
      int&   optionsIntItemVariable)
      : msrOptionsItem (
          optionsItemShortName,
          optionsItemLongName,
          optionsItemDescription),
        fOptionsIntItemVariable (optionsIntItemVariable)
      {}

    void                  print (ostream& os) const
      {
        const int fieldWidth = 19;

        os <<
          setw(fieldWidth) <<
          "fOptionsElementShortName" << " : " << fOptionsElementShortName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementLongName" << " : " << fOptionsElementLongName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementDescription" << " : " << fOptionsElementDescription <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsItemHasBeenSelected" << " : " << fOptionsItemHasBeenSelected <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsIntItemVariable" << " : " << fOptionsIntItemVariable <<
          endl;
      }

  private:

    int&                  fOptionsIntItemVariable;
};
typedef msrOptionsIntItem* S_msrOptionsIntItem;

ostream& operator<< (ostream& os, const msrOptionsIntItem& elt)
{
  elt.print (os);
  return os;
}

//______________________________________________________________________________
class EXP msrOptionsStringItem : public msrOptionsItem
{
  public:

    msrOptionsStringItem (
      string  optionsItemShortName,
      string  optionsItemLongName,
      string  optionsItemDescription,
      string& optionsStringItemVariable)
      : msrOptionsItem (
          optionsItemShortName,
          optionsItemLongName,
          optionsItemDescription),
        fOptionsStringItemVariable (optionsStringItemVariable)
      {}

    void                  print (ostream& os) const
      {
        const int fieldWidth = 19;

        os <<
          setw(fieldWidth) <<
          "fOptionsElementShortName" << " : " << fOptionsElementShortName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementLongName" << " : " << fOptionsElementLongName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementDescription" << " : " << fOptionsElementDescription <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsItemHasBeenSelected" << " : " << fOptionsItemHasBeenSelected <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsStringItemVariable" << " : " << fOptionsStringItemVariable <<
          endl;
      }

  private:

    string&                  fOptionsStringItemVariable;
};
typedef msrOptionsStringItem* S_msrOptionsStringItem;

ostream& operator<< (ostream& os, const msrOptionsStringItem& elt)
{
  elt.print (os);
  return os;
}

//_______________________________________________________________________________
class EXP msrOptionsSubGroup : public msrOptionsElement
{
  public:

    msrOptionsSubGroup (
      string optionsSubGroupShortName,
      string optionsSubGroupLongName,
      string optionsSubGroupDescription)
      : msrOptionsElement (
          optionsSubGroupShortName,
          optionsSubGroupLongName,
          optionsSubGroupDescription)
      {}

    void                  appendOptionsItem (
                            S_msrOptionsItem optionsItem)
      {
        fOptionsSubGroupItemsList.push_back (
          optionsItem);
      }

    void                  print (ostream& os) const
      {
        const int fieldWidth = 19;

        os <<
          setw(fieldWidth) <<
          "fOptionsElementShortName" << " : " << fOptionsElementShortName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementLongName" << " : " << fOptionsElementLongName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementDescription" << " : " << fOptionsElementDescription <<
          endl;

        for (
          list<S_msrOptionsItem>::const_iterator
            i = fOptionsSubGroupItemsList.begin();
          i != fOptionsSubGroupItemsList.end();
          i++) {
          // print the element
          os << (*i);
        } // for
      }

  private:

    list<S_msrOptionsItem>
                          fOptionsSubGroupItemsList;
};
typedef msrOptionsSubGroup* S_msrOptionsSubGroup;

ostream& operator<< (ostream& os, const msrOptionsSubGroup& elt)
{
  elt.print (os);
  return os;
}

//_______________________________________________________________________________
class EXP msrOptionsGroup : public msrOptionsElement
{
  public:

    msrOptionsGroup (
      string optionGroupShortName,
      string optionGroupLongName,
      string optionGroupDescription)
      : msrOptionsElement (
          optionGroupShortName,
          optionGroupLongName,
          optionGroupDescription)
      {}

    void                  appendOptionsSubGroup (
                            S_msrOptionsSubGroup optionsSubGroup)
      {
        fOptionsGroupSubGroupsList.push_back (
          optionsSubGroup);
      }

    void                  print (ostream& os) const
      {
        const int fieldWidth = 19;

        os <<
          setw(fieldWidth) <<
          "fOptionsElementShortName" << " : " << fOptionsElementShortName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementLongName" << " : " << fOptionsElementLongName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementDescription" << " : " << fOptionsElementDescription <<
          endl;

        for (
          list<S_msrOptionsSubGroup>::const_iterator
            i = fOptionsGroupSubGroupsList.begin();
          i != fOptionsGroupSubGroupsList.end();
          i++) {
          // print the element
          os << (*i);
        } // for
      }

  private:

    list<S_msrOptionsSubGroup>
                          fOptionsGroupSubGroupsList;
};
typedef msrOptionsGroup* S_msrOptionsGroup;

ostream& operator<< (ostream& os, const msrOptionsGroup& elt)
{
  elt.print (os);
  return os;
}

//______________________________________________________________________________
void optionError (string errorMessage)
{
  cerr <<
    endl <<
    endl <<
    "### ERROR in the options:" <<
    endl <<
    errorMessage <<
    endl <<
    endl;

  exit(99);
}

//_______________________________________________________________________________
// a private variable
map<string, string> pOptionShortNames;

void checkOptionUniqueness (
  string optionLongName, string optionShortName)
{
  if (optionShortName == optionLongName) {
    stringstream s;

    s <<
      "option long name '" << optionLongName << "'" <<
      " is also used as short name";

    optionError (s.str());
  }

  for (
    map<string, string>::iterator i = pOptionShortNames.begin();
    i != pOptionShortNames.end();
    i++) {

    // is optionLongName in the options names map?
    if ((*i).first == optionLongName) {
      stringstream s;

      s <<
        "option long name '" << optionLongName << "'" <<
        " is specified more that once";

      optionError (s.str());
    }

    // is optionShortName in the options names map?
    if ((*i).second == optionShortName) {
      if (optionShortName.size ()) {
        stringstream s;

        s <<
          "option short name '" << optionShortName << "'" <<
          " for option long name '" << optionLongName << "'" <<
          " is specified more that once";

        optionError (s.str());
      }
    }
  } // for

  // everything OK, register the option names
  pOptionShortNames [optionLongName] = optionShortName;
}

//_______________________________________________________________________________
void analyzeOptions (
  int            argc,
  char*          argv[])
{
  int   n = 0;

  S_msrOptionsGroup optionsGroup =
    new msrOptionsGroup (
    "hog", "helpOptionsGroup", " help for OptionsGroup");

  S_msrOptionsSubGroup optionsSubGroup =
    new msrOptionsSubGroup (
    "hosg", "helpOptionsSubGroup", " help for OptionsSubGroup");

  optionsGroup->
    appendOptionsSubGroup (optionsSubGroup);

  int intVariable;
  S_msrOptionsIntItem optionsItem1 =
    new msrOptionsIntItem (
      "is", "il", "intVariable", intVariable);
  optionsSubGroup->
    appendOptionsItem (optionsItem1);

  string stringVariable;
  S_msrOptionsStringItem optionsItem2 =
    new msrOptionsStringItem (
      "ss", "sl", "stringVariable", stringVariable);
  optionsSubGroup->
    appendOptionsItem (optionsItem2);

  cerr <<
    "optionsGroup:" << endl <<
    optionsGroup <<
    endl;

  while (true) {
    if (argv [n] == 0)
      break;

    string currentElement = string (argv [n]);

    // print current element
    cout <<
      n << ":" << currentElement <<
      endl;

    // handle current element
    if (currentElement [0] == '-') {
      // this is an option
      string elementTrailer =
        currentElement.substr (1, string::npos);

      /* JMI
      cout <<
        "elementTrailer '" << elementTrailer << "' is preceded by a dash" <<
        endl;
      */

      if (elementTrailer.size ()) {
        if (elementTrailer [0] == '-') {
          // it is a double-dashed option
          string currentDoubleDashedOption =
            elementTrailer.substr (1, string::npos);

          cout <<
            "'" << currentDoubleDashedOption << "' is a double-dashed option" <<
            endl;
        }
        else {
          // it is a single-dashed option
          string currentSingleDashedOption =
            elementTrailer; //.substr (1, string::npos);

          cout <<
            "'" << currentSingleDashedOption << "' is a single-dashed option" <<
            endl;
        }
      }

      else {
        cout <<
          "'-' is the minimal single-dashed option" <<
          endl;
      }
    }

    // next please
    n++;
  } // while
}

int main (int argc, char *argv[])
{
/*
  vector<msrOptionsItem> vec {
    msrOptionItem ("1short", "1long", "descr1"),
    msrOptionItem ("2short", "1long", "descr2")
  };

  int counter = 0;
  cout <<
    "The contents of 'vec' is:" <<
    endl << endl;
  for (msrOptionItem i : vec)
  {
    cout <<
      "Element " << counter << ":" <<
      endl <<
      i <<
      endl;
    counter++;
  }

struct option
{
  const char *name;
  // has_arg can't be an enum because some compilers complain about
  // type mismatches in all the code that assumes it is an int.
  int has_arg;
  int *flag;
  int val;
};
*/

/*
  vector<struct option> myLongOptions {
    option ("1short", no_argument, &vec [0].fOptionSelected, 1),
    option ("1long", no_argument, &vec [0].fOptionSelected, 1),

    option ("2short", required_argument, &vec [1].fOptionSelected, 1),
    option ("2long", required_argument, &vec [1].fOptionSelected, 1),

    option (0, 0, 0, 0) // option trailer
  };
*/

/*
  cout << "Which element should be printed? ";

  int n;
  cin >> n;

  cout << endl;

  if (n < vec.size ())
    cout <<
      "Element " << n << " constains:" <<
      endl <<
      endl <<
      vec [n] <<
      endl;
  else
    cout <<
      "Sorry, only elements from 0 to " << vec.size () - 1 << " exist" <<
      endl;
*/

  analyzeOptions (
    argc, argv);

}
<commit_msg>OptionsTest 4<commit_after>#include <iostream>
#include <sstream>

#include <vector>
#include <list>
#include <map>

#include <algorithm>

#include <iomanip>      // setw, set::precision, ...

using namespace std;

#define EXP

//______________________________________________________________________________
class EXP msrOptionsElement
{
  public:

    // creation from MusicXML
    // ------------------------------------------------------

  protected:

    msrOptionsElement (
      string optionsElementShortName,
      string optionsElementLongName,
      string optionsElementDescription);

    virtual ~msrOptionsElement();

  public:

    // set and get
    // ------------------------------------------------------

    string                getOptionsElementShortName () const
                              { return fOptionsElementShortName; }

    string                getOptionsElementLongName () const
                              { return fOptionsElementLongName; }

    string                getOptionsElementDescription () const
                              { return fOptionsElementDescription; }

    // services
    // ------------------------------------------------------

    string                operator() () const
                              { return fOptionsElementDescription; }

    // print
    // ------------------------------------------------------

    virtual void          print (ostream& os) const;

  protected:

    string                fOptionsElementShortName;
    string                fOptionsElementLongName;
    string                fOptionsElementDescription;
};
//typedef SMARTP<msrOptionsElement> S_msrOptionsElement;
typedef msrOptionsElement* S_msrOptionsElement;
EXP ostream& operator<< (ostream& os, const S_msrOptionsElement& elt);

msrOptionsElement::msrOptionsElement (
  string optionsElementShortName,
  string optionsElementLongName,
  string optionsElementDescription)
{
  fOptionsElementShortName   = optionsElementShortName;
  fOptionsElementLongName    = optionsElementLongName;
  fOptionsElementDescription = optionsElementDescription;
}

msrOptionsElement::~msrOptionsElement()
{}

ostream& operator<< (ostream& os, const S_msrOptionsElement& elt)
{
  elt->print (os);
  return os;
}

void msrOptionsElement::print (ostream& os) const
{
  os << "??? msrOptionsElement ???" << endl;
}

//______________________________________________________________________________
class EXP msrOptionsItem : public msrOptionsElement
{
  public:

    msrOptionsItem (
      string optionsItemShortName,
      string optionsItemLongName,
      string optionsItemDescription)
      : msrOptionsElement (
          optionsItemShortName,
          optionsItemLongName,
          optionsItemDescription)
      {
        fOptionsItemHasBeenSelected = false;
      }

    void                  setOptionsItemHasBeenSelected ()
                              { fOptionsItemHasBeenSelected = true; }

    bool                  getOptionsItemHasBeenSelected () const
                              { return fOptionsItemHasBeenSelected; }

    void                  print (ostream& os) const
      {
        const int fieldWidth = 19;

        os <<
          "OptionsItem ???:" <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementShortName" << " : " << fOptionsElementShortName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementLongName" << " : " << fOptionsElementLongName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementDescription" << " : " << fOptionsElementDescription <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsItemHasBeenSelected" << " : " << fOptionsItemHasBeenSelected <<
          endl;
      }

  protected:

    bool                  fOptionsItemHasBeenSelected;
};
typedef msrOptionsItem* S_msrOptionsItem;

ostream& operator<< (ostream& os, const msrOptionsItem& elt)
{
  os <<
    "OptionsItem ???:" <<
    endl;
  elt.print (os);
  return os;
}

//______________________________________________________________________________
class EXP msrOptionsIntItem : public msrOptionsItem
{
  public:

    msrOptionsIntItem (
      string optionsItemShortName,
      string optionsItemLongName,
      string optionsItemDescription,
      int&   optionsIntItemVariable)
      : msrOptionsItem (
          optionsItemShortName,
          optionsItemLongName,
          optionsItemDescription),
        fOptionsIntItemVariable (optionsIntItemVariable)
      {}

    void                  print (ostream& os) const
      {
        const int fieldWidth = 19;

        os <<
          "OptionsIntItem:" <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementShortName" << " : " << fOptionsElementShortName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementLongName" << " : " << fOptionsElementLongName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementDescription" << " : " << fOptionsElementDescription <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsItemHasBeenSelected" << " : " << fOptionsItemHasBeenSelected <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsIntItemVariable" << " : " << fOptionsIntItemVariable <<
          endl;
      }

  private:

    int&                  fOptionsIntItemVariable;
};
typedef msrOptionsIntItem* S_msrOptionsIntItem;

ostream& operator<< (ostream& os, const msrOptionsIntItem& elt)
{
  os <<
    "OptionsIntItem:" <<
    endl;
  elt.print (os);
  return os;
}

//______________________________________________________________________________
class EXP msrOptionsStringItem : public msrOptionsItem
{
  public:

    msrOptionsStringItem (
      string  optionsItemShortName,
      string  optionsItemLongName,
      string  optionsItemDescription,
      string& optionsStringItemVariable)
      : msrOptionsItem (
          optionsItemShortName,
          optionsItemLongName,
          optionsItemDescription),
        fOptionsStringItemVariable (optionsStringItemVariable)
      {}

    void                  print (ostream& os) const
      {
        const int fieldWidth = 19;

        os <<
          "OptionsStringItem:" <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementShortName" << " : " << fOptionsElementShortName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementLongName" << " : " << fOptionsElementLongName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementDescription" << " : " << fOptionsElementDescription <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsItemHasBeenSelected" << " : " << fOptionsItemHasBeenSelected <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsStringItemVariable" << " : " << fOptionsStringItemVariable <<
          endl;
      }

  private:

    string&                  fOptionsStringItemVariable;
};
typedef msrOptionsStringItem* S_msrOptionsStringItem;

ostream& operator<< (ostream& os, const msrOptionsStringItem& elt)
{
  os <<
    "OptionsStringItem:" <<
    endl;
  elt.print (os);
  return os;
}

//_______________________________________________________________________________
class EXP msrOptionsSubGroup : public msrOptionsElement
{
  public:

    msrOptionsSubGroup (
      string optionsSubGroupShortName,
      string optionsSubGroupLongName,
      string optionsSubGroupDescription)
      : msrOptionsElement (
          optionsSubGroupShortName,
          optionsSubGroupLongName,
          optionsSubGroupDescription)
      {}

    void                  appendOptionsItem (
                            S_msrOptionsItem optionsItem)
      {
        fOptionsSubGroupItemsList.push_back (
          optionsItem);
      }

    void                  print (ostream& os) const
      {
        const int fieldWidth = 19;

        os <<
          "OptionsSubGroup:" <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementShortName" << " : " << fOptionsElementShortName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementLongName" << " : " << fOptionsElementLongName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementDescription" << " : " << fOptionsElementDescription <<
          endl;

        for (
          list<S_msrOptionsItem>::const_iterator
            i = fOptionsSubGroupItemsList.begin();
          i != fOptionsSubGroupItemsList.end();
          i++) {
          // print the element
          os << (*i);
        } // for
      }

  private:

    list<S_msrOptionsItem>
                          fOptionsSubGroupItemsList;
};
typedef msrOptionsSubGroup* S_msrOptionsSubGroup;

ostream& operator<< (ostream& os, const msrOptionsSubGroup& elt)
{
  os <<
    "OptionsSubGroup:" <<
    endl;
  elt.print (os);
  return os;
}

//_______________________________________________________________________________
class EXP msrOptionsGroup : public msrOptionsElement
{
  public:

    msrOptionsGroup (
      string optionGroupShortName,
      string optionGroupLongName,
      string optionGroupDescription)
      : msrOptionsElement (
          optionGroupShortName,
          optionGroupLongName,
          optionGroupDescription)
      {}

    void                  appendOptionsSubGroup (
                            S_msrOptionsSubGroup optionsSubGroup)
      {
        fOptionsGroupSubGroupsList.push_back (
          optionsSubGroup);
      }

    void                  print (ostream& os) const
      {
        const int fieldWidth = 19;

        os <<
          "OptionsGroup:" <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementShortName" << " : " << fOptionsElementShortName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementLongName" << " : " << fOptionsElementLongName <<
          endl <<
          setw(fieldWidth) <<
          "fOptionsElementDescription" << " : " << fOptionsElementDescription <<
          endl;

        for (
          list<S_msrOptionsSubGroup>::const_iterator
            i = fOptionsGroupSubGroupsList.begin();
          i != fOptionsGroupSubGroupsList.end();
          i++) {
          // print the element
          os << (*i);
        } // for
      }

  private:

    list<S_msrOptionsSubGroup>
                          fOptionsGroupSubGroupsList;
};
typedef msrOptionsGroup* S_msrOptionsGroup;

ostream& operator<< (ostream& os, const msrOptionsGroup& elt)
{
  os <<
    "OptionsGroup:" <<
    endl;
  elt.print (os);
  return os;
}

//______________________________________________________________________________
void optionError (string errorMessage)
{
  cerr <<
    endl <<
    endl <<
    "### ERROR in the options:" <<
    endl <<
    errorMessage <<
    endl <<
    endl;

  exit(99);
}

//_______________________________________________________________________________
// a private variable
map<string, string> pOptionShortNames;

void checkOptionUniqueness (
  string optionLongName, string optionShortName)
{
  if (optionShortName == optionLongName) {
    stringstream s;

    s <<
      "option long name '" << optionLongName << "'" <<
      " is also used as short name";

    optionError (s.str());
  }

  for (
    map<string, string>::iterator i = pOptionShortNames.begin();
    i != pOptionShortNames.end();
    i++) {

    // is optionLongName in the options names map?
    if ((*i).first == optionLongName) {
      stringstream s;

      s <<
        "option long name '" << optionLongName << "'" <<
        " is specified more that once";

      optionError (s.str());
    }

    // is optionShortName in the options names map?
    if ((*i).second == optionShortName) {
      if (optionShortName.size ()) {
        stringstream s;

        s <<
          "option short name '" << optionShortName << "'" <<
          " for option long name '" << optionLongName << "'" <<
          " is specified more that once";

        optionError (s.str());
      }
    }
  } // for

  // everything OK, register the option names
  pOptionShortNames [optionLongName] = optionShortName;
}

//_______________________________________________________________________________
void analyzeOptions (
  int            argc,
  char*          argv[])
{
  int   n = 0;

  S_msrOptionsGroup optionsGroup =
    new msrOptionsGroup (
    "hog", "helpOptionsGroup", " help for OptionsGroup");

  S_msrOptionsSubGroup optionsSubGroup =
    new msrOptionsSubGroup (
    "hosg", "helpOptionsSubGroup", " help for OptionsSubGroup");

  optionsGroup->
    appendOptionsSubGroup (optionsSubGroup);

  int intVariable = -3;
  S_msrOptionsIntItem optionsItem1 =
    new msrOptionsIntItem (
      "is", "il", "intVariable", intVariable);
  optionsSubGroup->
    appendOptionsItem (optionsItem1);

  string stringVariable = "a string";
  S_msrOptionsStringItem optionsItem2 =
    new msrOptionsStringItem (
      "ss", "sl", "stringVariable", stringVariable);
  optionsSubGroup->
    appendOptionsItem (optionsItem2);

  cerr <<
    "optionsItem1:" << endl <<
    optionsItem1 <<
    endl;

  cerr <<
    "optionsGroup:" << endl <<
    optionsGroup <<
    endl;

  while (true) {
    if (argv [n] == 0)
      break;

    string currentElement = string (argv [n]);

    // print current element
    cout <<
      n << ":" << currentElement <<
      endl;

    // handle current element
    if (currentElement [0] == '-') {
      // this is an option
      string elementTrailer =
        currentElement.substr (1, string::npos);

      /* JMI
      cout <<
        "elementTrailer '" << elementTrailer << "' is preceded by a dash" <<
        endl;
      */

      if (elementTrailer.size ()) {
        if (elementTrailer [0] == '-') {
          // it is a double-dashed option
          string currentDoubleDashedOption =
            elementTrailer.substr (1, string::npos);

          cout <<
            "'" << currentDoubleDashedOption << "' is a double-dashed option" <<
            endl;
        }
        else {
          // it is a single-dashed option
          string currentSingleDashedOption =
            elementTrailer; //.substr (1, string::npos);

          cout <<
            "'" << currentSingleDashedOption << "' is a single-dashed option" <<
            endl;
        }
      }

      else {
        cout <<
          "'-' is the minimal single-dashed option" <<
          endl;
      }
    }

    // next please
    n++;
  } // while
}

int main (int argc, char *argv[])
{
/*
  vector<msrOptionsItem> vec {
    msrOptionItem ("1short", "1long", "descr1"),
    msrOptionItem ("2short", "1long", "descr2")
  };

  int counter = 0;
  cout <<
    "The contents of 'vec' is:" <<
    endl << endl;
  for (msrOptionItem i : vec)
  {
    cout <<
      "Element " << counter << ":" <<
      endl <<
      i <<
      endl;
    counter++;
  }

struct option
{
  const char *name;
  // has_arg can't be an enum because some compilers complain about
  // type mismatches in all the code that assumes it is an int.
  int has_arg;
  int *flag;
  int val;
};
*/

/*
  vector<struct option> myLongOptions {
    option ("1short", no_argument, &vec [0].fOptionSelected, 1),
    option ("1long", no_argument, &vec [0].fOptionSelected, 1),

    option ("2short", required_argument, &vec [1].fOptionSelected, 1),
    option ("2long", required_argument, &vec [1].fOptionSelected, 1),

    option (0, 0, 0, 0) // option trailer
  };
*/

/*
  cout << "Which element should be printed? ";

  int n;
  cin >> n;

  cout << endl;

  if (n < vec.size ())
    cout <<
      "Element " << n << " constains:" <<
      endl <<
      endl <<
      vec [n] <<
      endl;
  else
    cout <<
      "Sorry, only elements from 0 to " << vec.size () - 1 << " exist" <<
      endl;
*/

  analyzeOptions (
    argc, argv);

}
<|endoftext|>


<commit_before>/*
Copyright (C) 2018 Jakob Sinclair

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

This program 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 program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "game.hpp"
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include "entity.hpp"
#include "shader.hpp"
#include "input.hpp"
#include "graphics.hpp"
#include "rect2d.hpp"
#include "camera.hpp"
#include "sprite.hpp"
#include "cache.hpp"
#include "luascript.hpp"
#include "iomanager.hpp"

Game::Game()
{
	;
}

Game::~Game()
{
	;
}

bool Game::Init()
{
	//if (Res.CreateModel("nanosuit", "Model/nanosuit.obj") != nullptr)
	//	m_Model = static_cast<Model*>(Res.GetResource("nanosuit")->Data());

	m_EM.AddEntity<Entity>(std::make_unique<Entity>("Camera"));
	m_EM.GetEntity("Camera").AddComponent<Camera>(std::make_unique<Camera>(1280, 720));

	Res.LoadSample("sound.ogg")->Play();
	m_EM.GetSystem<Graphics>().RegisterComponent(std::type_index(typeid(Sprite)));

	m_EM.AddEntity<Entity>(std::make_unique<Entity>("Player"));
	auto &sprite = m_EM.GetEntity("Player").AddComponent<Sprite>(std::make_unique<Sprite>(Res.LoadTex("sprite.png"),
	                                        110, 200,
	                                        std::vector<uint32_t>({25, 29, 135, 229, 150, 29, 260, 229, 287, 29, 397, 229, 438, 29, 548, 229})));

	LuaScript script("player.lua");
	int posX = script.Get<int>("player.pos.X");
	int posY = script.Get<int>("player.pos.Y");

	sprite.SetImageSpeed(0.1f);
	sprite.SetPos(glm::vec3((float)posX, (float)posY, 0.0f));

	return true;
}

void Game::Update(double delta)
{
	/*
	float speed = 3.0f * (float)delta;
	float xoffset = m_Input.GetMousePos().x - m_LastX;
	float yoffset = m_LastY - m_Input.GetMousePos().y;
	m_LastX = m_Input.GetMousePos().x;
	m_LastY = m_Input.GetMousePos().y;

	float sensitivity = 0.05f;
	xoffset *= sensitivity;
	yoffset *= sensitivity;
	m_Yaw += xoffset;
	m_Pitch +=  yoffset;

	if (m_Pitch > 89.0f)
		m_Pitch = 89.0f;
	else if (m_Pitch < -89.0f)
		m_Pitch = -89.0f;

	glm::vec3 front;
	front.x = cos(glm::radians(m_Pitch)) * cos(glm::radians(m_Yaw));
	front.y = sin(glm::radians(m_Pitch));
	front.z = sin(glm::radians(m_Yaw)) * cos(glm::radians(m_Pitch));
	m_Front = glm::normalize(front);
	*/
	if (m_EM.GetSystem<Input>().GetKey(GLFW_KEY_ESCAPE))
		m_Quit = true;
	else if (m_EM.GetSystem<Input>().GetKey(GLFW_KEY_SPACE))
		Res.LoadSample("sound.ogg")->Play();
	/*if (m_Input.GetKey(GLFW_KEY_W))
		m_Pos += speed * m_Front;
	if (m_Input.GetKey(GLFW_KEY_S))
		m_Pos -= speed * m_Front;
	if (m_Input.GetKey(GLFW_KEY_A))
		m_Pos -= glm::normalize(glm::cross(m_Front, m_Up)) * speed;
	if (m_Input.GetKey(GLFW_KEY_D))
		m_Pos += glm::normalize(glm::cross(m_Front, m_Up)) * speed;
	m_EntityManager.GetCamera()->SetPos(m_Pos);
	m_EntityManager.GetCamera()->SetDir(m_Front);*/
}<commit_msg>Remove all 3D code from 2D demo<commit_after>/*
Copyright (C) 2018 Jakob Sinclair

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

This program 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 program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "game.hpp"
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include "entity.hpp"
#include "shader.hpp"
#include "input.hpp"
#include "graphics.hpp"
#include "rect2d.hpp"
#include "camera.hpp"
#include "sprite.hpp"
#include "cache.hpp"
#include "luascript.hpp"
#include "iomanager.hpp"

Game::Game()
{
	;
}

Game::~Game()
{
	;
}

bool Game::Init()
{
	m_EM.AddEntity<Entity>(std::make_unique<Entity>("Camera"));
	m_EM.GetEntity("Camera").AddComponent<Camera>(std::make_unique<Camera>(1280, 720));

	Res.LoadSample("sound.ogg")->Play();
	m_EM.GetSystem<Graphics>().RegisterComponent(std::type_index(typeid(Sprite)));

	m_EM.AddEntity<Entity>(std::make_unique<Entity>("Player"));
	auto &sprite = m_EM.GetEntity("Player").AddComponent<Sprite>(std::make_unique<Sprite>(Res.LoadTex("sprite.png"),
	                                        110, 200,
	                                        std::vector<uint32_t>({25, 29, 135, 229, 150, 29, 260, 229, 287, 29, 397, 229, 438, 29, 548, 229})));

	LuaScript script("player.lua");
	int posX = script.Get<int>("player.pos.X");
	int posY = script.Get<int>("player.pos.Y");

	sprite.SetImageSpeed(0.1f);
	sprite.SetPos(glm::vec3((float)posX, (float)posY, 0.0f));

	return true;
}

void Game::Update(double delta)
{
	if (m_EM.GetSystem<Input>().GetKey(GLFW_KEY_ESCAPE))
		m_Quit = true;
	else if (m_EM.GetSystem<Input>().GetKey(GLFW_KEY_SPACE))
		Res.LoadSample("sound.ogg")->Play();
}<|endoftext|>


<commit_before> /*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: aboutdialog.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: sj $ $Date: 2007-07-10 16:16:25 $
 *
 *  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 ABOUTDIALOG_HXX
#include "aboutdialog.hxx"
#endif
#ifndef OPTIMIZATIONSTATS_HXX
#include "optimizationstats.hxx"
#endif
#ifndef _FILEOPEN_DIALOG_HXX_
#include "fileopendialog.hxx"
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif

// ---------------
// - ABOUTDIALOG -
// ---------------

using namespace ::rtl;
using namespace ::com::sun::star::ui;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::script;
using namespace ::com::sun::star::container;

#define ABOUT_DIALOG_WIDTH  220
#define ABOUT_DIALOG_HEIGHT 221

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

rtl::OUString InsertFixedText( AboutDialog& rAboutDialog, const rtl::OUString& rControlName, const OUString& rLabel,
                                sal_Int32 nXPos, sal_Int32 nYPos, sal_Int32 nWidth, sal_Int32 nHeight, sal_Bool bMultiLine, sal_Int16 nTabIndex )
{
    OUString pNames[] = {
        TKGet( TK_Height ),
        TKGet( TK_Label ),
        TKGet( TK_MultiLine ),
        TKGet( TK_PositionX ),
        TKGet( TK_PositionY ),
        TKGet( TK_Step ),
        TKGet( TK_TabIndex ),
        TKGet( TK_Width ) };

    Any pValues[] = {
        Any( nHeight ),
        Any( rLabel ),
        Any( bMultiLine ),
        Any( nXPos ),
        Any( nYPos ),
        Any( (sal_Int16)0 ),
        Any( nTabIndex ),
        Any( nWidth ) };

    sal_Int32 nCount = sizeof( pNames ) / sizeof( OUString );

    Sequence< rtl::OUString >   aNames( pNames, nCount );
    Sequence< Any >             aValues( pValues, nCount );

    rAboutDialog.insertFixedText( rControlName, aNames, aValues );
    return rControlName;
}

rtl::OUString InsertSeparator( AboutDialog& rAboutDialog, const OUString& rControlName, sal_Int32 nOrientation,
                        sal_Int32 nPosX, sal_Int32 nPosY, sal_Int32 nWidth, sal_Int32 nHeight )
{
    OUString pNames[] = {
        TKGet( TK_Height ),
        TKGet( TK_Orientation ),
        TKGet( TK_PositionX ),
        TKGet( TK_PositionY ),
        TKGet( TK_Step ),
        TKGet( TK_Width ) };

    Any pValues[] = {
        Any( nHeight ),
        Any( nOrientation ),
        Any( nPosX ),
        Any( nPosY ),
        Any( sal_Int16( 0 ) ),
        Any( nWidth ) };

    sal_Int32 nCount = sizeof( pNames ) / sizeof( OUString );

    Sequence< rtl::OUString >   aNames( pNames, nCount );
    Sequence< Any >             aValues( pValues, nCount );

    rAboutDialog.insertControlModel( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.awt.UnoControlFixedLineModel" ) ),
        rControlName, aNames, aValues );
    return rControlName;
}

rtl::OUString InsertImage( AboutDialog& rAboutDialog, const OUString& rControlName, const OUString& rURL,
                        sal_Int32 nPosX, sal_Int32 nPosY, sal_Int32 nWidth, sal_Int32 nHeight )
{
    OUString pNames[] = {
        TKGet( TK_Border ),
        TKGet( TK_Height ),
        TKGet( TK_ImageURL ),
        TKGet( TK_PositionX ),
        TKGet( TK_PositionY ),
        TKGet( TK_ScaleImage ),
        TKGet( TK_Width ) };

    Any pValues[] = {
        Any( sal_Int16( 1 ) ),
        Any( nHeight ),
        Any( rURL ),
        Any( nPosX ),
        Any( nPosY ),
        Any( sal_True ),
        Any( nWidth ) };
    sal_Int32 nCount = sizeof( pNames ) / sizeof( OUString );

    Sequence< rtl::OUString >   aNames( pNames, nCount );
    Sequence< Any >             aValues( pValues, nCount );

    rAboutDialog.insertImage( rControlName, aNames, aValues );
    return rControlName;
}

rtl::OUString InsertButton( AboutDialog& rAboutDialog, const OUString& rControlName, Reference< XActionListener >& xActionListener,
    sal_Int32 nXPos, sal_Int32 nYPos, sal_Int32 nWidth, sal_Int32 nHeight, sal_Int16 nTabIndex, PPPOptimizerTokenEnum nResID )
{
    OUString pNames[] = {
        TKGet( TK_Enabled ),
        TKGet( TK_Height ),
        TKGet( TK_Label ),
        TKGet( TK_PositionX ),
        TKGet( TK_PositionY ),
        TKGet( TK_PushButtonType ),
        TKGet( TK_Step ),
        TKGet( TK_TabIndex ),
        TKGet( TK_Width ) };

    Any pValues[] = {
        Any( sal_True ),
        Any( nHeight ),
        Any( rAboutDialog.getString( nResID ) ),
        Any( nXPos ),
        Any( nYPos ),
        Any( static_cast< sal_Int16 >( PushButtonType_OK ) ),
        Any( (sal_Int16)0 ),
        Any( nTabIndex ),
        Any( nWidth ) };

    sal_Int32 nCount = sizeof( pNames ) / sizeof( OUString );

    Sequence< rtl::OUString >   aNames( pNames, nCount );
    Sequence< Any >             aValues( pValues, nCount );

    rAboutDialog.insertButton( rControlName, xActionListener, aNames, aValues );
    return rControlName;
}

void AboutDialog::InitDialog()
{
   // setting the dialog properties
    OUString pNames[] = {
        TKGet( TK_Closeable ),
        TKGet( TK_Height ),
        TKGet( TK_Moveable ),
        TKGet( TK_PositionX ),
        TKGet( TK_PositionY ),
        TKGet( TK_Title ),
        TKGet( TK_Width ) };

    Any pValues[] = {
        Any( sal_True ),
        Any( sal_Int32( ABOUT_DIALOG_HEIGHT ) ),
        Any( sal_True ),
        Any( sal_Int32( 113 ) ),
        Any( sal_Int32( 42 ) ),
        Any( getString( STR_ABOUT_VERSION ) ),
        Any( sal_Int32( ABOUT_DIALOG_WIDTH ) ) };

    sal_Int32 nCount = sizeof( pNames ) / sizeof( OUString );

    Sequence< rtl::OUString >   aNames( pNames, nCount );
    Sequence< Any >             aValues( pValues, nCount );

    rtl::OUString sBitmapPath( getPath( TK_BitmapPath ) );
    rtl::OUString sBitmap( rtl::OUString::createFromAscii( "/aboutlogo.png" ) );
    rtl::OUString sURL( sBitmapPath += sBitmap );

    mxDialogModelMultiPropertySet->setPropertyValues( aNames, aValues );

    int nWidth = (int) getMapsFromPixels( 387 );
//    int nHeight = (int) getMapsFromPixels( 95 );

    InsertImage( *this, rtl::OUString( rtl::OUString::createFromAscii( "aboutimage" ) ), sURL, 0, 0, ABOUT_DIALOG_WIDTH, 60 );
    InsertFixedText( *this, rtl::OUString( rtl::OUString::createFromAscii( "fixedtext" ) ), getString( STR_ABOUT_PRN ), 9, 66, ABOUT_DIALOG_WIDTH - 18, 127, sal_True, 0 );
    InsertSeparator( *this, rtl::OUString( rtl::OUString::createFromAscii( "separator" ) ), 0, 0, 196, ABOUT_DIALOG_WIDTH, 8 );
    InsertButton( *this, rtl::OUString( rtl::OUString::createFromAscii( "button" ) ), mxActionListener, ( nWidth / 2 ) - 25, 204, 50, 14, 1, STR_OK );
}

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

AboutDialog::AboutDialog( const Reference< XComponentContext > &rxMSF, Reference< XFrame >& rxFrame ) :
    UnoDialog( rxMSF, rxFrame ),
    ConfigurationAccess( rxMSF, NULL ),
    mxMSF( rxMSF ),
    mxFrame( rxFrame ),
    mxActionListener( new AboutActionListener( *this ) )
{
    Reference< XFrame > xFrame( mxController->getFrame() );
    Reference< XWindow > xContainerWindow( xFrame->getContainerWindow() );
    Reference< XWindowPeer > xWindowPeer( xContainerWindow, UNO_QUERY_THROW );
    createWindowPeer( xWindowPeer );

    InitDialog();
}

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

AboutDialog::~AboutDialog()
{
}

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

sal_Bool AboutDialog::execute()
{
    UnoDialog::execute();
    return mbStatus;
}

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

void AboutActionListener::actionPerformed( const ActionEvent& rEvent )
    throw ( com::sun::star::uno::RuntimeException )
{
    if ( rEvent.ActionCommand == rtl::OUString( rtl::OUString::createFromAscii( "button" ) ) )
    {
        mrAboutDialog.endExecute( sal_True );
    }
}
void AboutActionListener::disposing( const ::com::sun::star::lang::EventObject& /* Source */ )
    throw ( com::sun::star::uno::RuntimeException )
{
}
<commit_msg>fixed about image scaling<commit_after> /*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: aboutdialog.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: sj $ $Date: 2007-08-17 15:10:57 $
 *
 *  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 ABOUTDIALOG_HXX
#include "aboutdialog.hxx"
#endif
#ifndef OPTIMIZATIONSTATS_HXX
#include "optimizationstats.hxx"
#endif
#ifndef _FILEOPEN_DIALOG_HXX_
#include "fileopendialog.hxx"
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif

// ---------------
// - ABOUTDIALOG -
// ---------------

using namespace ::rtl;
using namespace ::com::sun::star::ui;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::script;
using namespace ::com::sun::star::container;

#define ABOUT_DIALOG_WIDTH  200
#define ABOUT_DIALOG_HEIGHT 221

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

rtl::OUString InsertFixedText( AboutDialog& rAboutDialog, const rtl::OUString& rControlName, const OUString& rLabel,
                                sal_Int32 nXPos, sal_Int32 nYPos, sal_Int32 nWidth, sal_Int32 nHeight, sal_Bool bMultiLine, sal_Int16 nTabIndex )
{
    OUString pNames[] = {
        TKGet( TK_Height ),
        TKGet( TK_Label ),
        TKGet( TK_MultiLine ),
        TKGet( TK_PositionX ),
        TKGet( TK_PositionY ),
        TKGet( TK_Step ),
        TKGet( TK_TabIndex ),
        TKGet( TK_Width ) };

    Any pValues[] = {
        Any( nHeight ),
        Any( rLabel ),
        Any( bMultiLine ),
        Any( nXPos ),
        Any( nYPos ),
        Any( (sal_Int16)0 ),
        Any( nTabIndex ),
        Any( nWidth ) };

    sal_Int32 nCount = sizeof( pNames ) / sizeof( OUString );

    Sequence< rtl::OUString >   aNames( pNames, nCount );
    Sequence< Any >             aValues( pValues, nCount );

    rAboutDialog.insertFixedText( rControlName, aNames, aValues );
    return rControlName;
}

rtl::OUString InsertSeparator( AboutDialog& rAboutDialog, const OUString& rControlName, sal_Int32 nOrientation,
                        sal_Int32 nPosX, sal_Int32 nPosY, sal_Int32 nWidth, sal_Int32 nHeight )
{
    OUString pNames[] = {
        TKGet( TK_Height ),
        TKGet( TK_Orientation ),
        TKGet( TK_PositionX ),
        TKGet( TK_PositionY ),
        TKGet( TK_Step ),
        TKGet( TK_Width ) };

    Any pValues[] = {
        Any( nHeight ),
        Any( nOrientation ),
        Any( nPosX ),
        Any( nPosY ),
        Any( sal_Int16( 0 ) ),
        Any( nWidth ) };

    sal_Int32 nCount = sizeof( pNames ) / sizeof( OUString );

    Sequence< rtl::OUString >   aNames( pNames, nCount );
    Sequence< Any >             aValues( pValues, nCount );

    rAboutDialog.insertControlModel( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.awt.UnoControlFixedLineModel" ) ),
        rControlName, aNames, aValues );
    return rControlName;
}

rtl::OUString InsertImage( AboutDialog& rAboutDialog, const OUString& rControlName, const OUString& rURL,
                        sal_Int32 nPosX, sal_Int32 nPosY, sal_Int32 nWidth, sal_Int32 nHeight )
{
    OUString pNames[] = {
        TKGet( TK_Border ),
        TKGet( TK_Height ),
        TKGet( TK_ImageURL ),
        TKGet( TK_PositionX ),
        TKGet( TK_PositionY ),
        TKGet( TK_ScaleImage ),
        TKGet( TK_Width ) };

    Any pValues[] = {
        Any( sal_Int16( 1 ) ),
        Any( nHeight ),
        Any( rURL ),
        Any( nPosX ),
        Any( nPosY ),
        Any( sal_False ),
        Any( nWidth ) };
    sal_Int32 nCount = sizeof( pNames ) / sizeof( OUString );

    Sequence< rtl::OUString >   aNames( pNames, nCount );
    Sequence< Any >             aValues( pValues, nCount );

    rAboutDialog.insertImage( rControlName, aNames, aValues );
    return rControlName;
}

rtl::OUString InsertButton( AboutDialog& rAboutDialog, const OUString& rControlName, Reference< XActionListener >& xActionListener,
    sal_Int32 nXPos, sal_Int32 nYPos, sal_Int32 nWidth, sal_Int32 nHeight, sal_Int16 nTabIndex, PPPOptimizerTokenEnum nResID )
{
    OUString pNames[] = {
        TKGet( TK_Enabled ),
        TKGet( TK_Height ),
        TKGet( TK_Label ),
        TKGet( TK_PositionX ),
        TKGet( TK_PositionY ),
        TKGet( TK_PushButtonType ),
        TKGet( TK_Step ),
        TKGet( TK_TabIndex ),
        TKGet( TK_Width ) };

    Any pValues[] = {
        Any( sal_True ),
        Any( nHeight ),
        Any( rAboutDialog.getString( nResID ) ),
        Any( nXPos ),
        Any( nYPos ),
        Any( static_cast< sal_Int16 >( PushButtonType_OK ) ),
        Any( (sal_Int16)0 ),
        Any( nTabIndex ),
        Any( nWidth ) };

    sal_Int32 nCount = sizeof( pNames ) / sizeof( OUString );

    Sequence< rtl::OUString >   aNames( pNames, nCount );
    Sequence< Any >             aValues( pValues, nCount );

    rAboutDialog.insertButton( rControlName, xActionListener, aNames, aValues );
    return rControlName;
}

void AboutDialog::InitDialog()
{
   // setting the dialog properties
    OUString pNames[] = {
        TKGet( TK_Closeable ),
        TKGet( TK_Height ),
        TKGet( TK_Moveable ),
        TKGet( TK_PositionX ),
        TKGet( TK_PositionY ),
        TKGet( TK_Title ),
        TKGet( TK_Width ) };

    Any pValues[] = {
        Any( sal_True ),
        Any( sal_Int32( ABOUT_DIALOG_HEIGHT ) ),
        Any( sal_True ),
        Any( sal_Int32( 113 ) ),
        Any( sal_Int32( 42 ) ),
        Any( getString( STR_ABOUT_VERSION ) ),
        Any( sal_Int32( ABOUT_DIALOG_WIDTH ) ) };

    sal_Int32 nCount = sizeof( pNames ) / sizeof( OUString );

    Sequence< rtl::OUString >   aNames( pNames, nCount );
    Sequence< Any >             aValues( pValues, nCount );

    rtl::OUString sBitmapPath( getPath( TK_BitmapPath ) );
    rtl::OUString sBitmap( rtl::OUString::createFromAscii( "/aboutlogo.png" ) );
    rtl::OUString sURL( sBitmapPath += sBitmap );

    mxDialogModelMultiPropertySet->setPropertyValues( aNames, aValues );
    sal_Int32 nWidth = getMapsFromPixels( 387 );
    if ( nWidth )
        mxDialogModelPropertySet->setPropertyValue( TKGet( TK_Width ), Any( nWidth ) );
    else
        nWidth = ABOUT_DIALOG_WIDTH;

//    int nHeight = (int) getMapsFromPixels( 95 );

    InsertImage( *this, rtl::OUString( rtl::OUString::createFromAscii( "aboutimage" ) ), sURL, 0, 0, nWidth, 60 );
    InsertFixedText( *this, rtl::OUString( rtl::OUString::createFromAscii( "fixedtext" ) ), getString( STR_ABOUT_PRN ), 9, 66, nWidth - 18, 127, sal_True, 0 );
    InsertSeparator( *this, rtl::OUString( rtl::OUString::createFromAscii( "separator" ) ), 0, 0, 196, nWidth, 8 );
    InsertButton( *this, rtl::OUString( rtl::OUString::createFromAscii( "button" ) ), mxActionListener, ( nWidth / 2 ) - 25, 204, 50, 14, 1, STR_OK );
}

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

AboutDialog::AboutDialog( const Reference< XComponentContext > &rxMSF, Reference< XFrame >& rxFrame ) :
    UnoDialog( rxMSF, rxFrame ),
    ConfigurationAccess( rxMSF, NULL ),
    mxMSF( rxMSF ),
    mxFrame( rxFrame ),
    mxActionListener( new AboutActionListener( *this ) )
{
    Reference< XFrame > xFrame( mxController->getFrame() );
    Reference< XWindow > xContainerWindow( xFrame->getContainerWindow() );
    Reference< XWindowPeer > xWindowPeer( xContainerWindow, UNO_QUERY_THROW );
    createWindowPeer( xWindowPeer );

    InitDialog();
}

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

AboutDialog::~AboutDialog()
{
}

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

sal_Bool AboutDialog::execute()
{
    UnoDialog::execute();
    return mbStatus;
}

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

void AboutActionListener::actionPerformed( const ActionEvent& rEvent )
    throw ( com::sun::star::uno::RuntimeException )
{
    if ( rEvent.ActionCommand == rtl::OUString( rtl::OUString::createFromAscii( "button" ) ) )
    {
        mrAboutDialog.endExecute( sal_True );
    }
}
void AboutActionListener::disposing( const ::com::sun::star::lang::EventObject& /* Source */ )
    throw ( com::sun::star::uno::RuntimeException )
{
}
<|endoftext|>