<commit_before>/*************************************************************************
 *
 *  $RCSfile: XmlFilterAdaptor.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: aidan $ $Date: 2002-05-21 09:50:05 $
 *
 *  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): Martin Gallwey (gallwey@sun.com)
 *                  Aidan Butler (aidan.butler@sun.com)
 *
 *
 ************************************************************************/
#include <iostream.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#ifndef _XMLFILTERADAPTOR_HXX
#include "XmlFilterAdaptor.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_INPUTSOURCE_HPP_
#include <com/sun/star/xml/sax/InputSource.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif

#ifndef _COM_SUN_STAR_XML_XIMPORTFILTER_HPP_
#include <com/sun/star/xml/XImportFilter.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_XEXPORTFILTER_HPP_
#include <com/sun/star/xml/XExportFilter.hpp>
#endif

using rtl::OUString;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::Reference;
using com::sun::star::uno::Any;
using com::sun::star::uno::UNO_QUERY;
using com::sun::star::uno::XInterface;
using com::sun::star::uno::Exception;
using com::sun::star::uno::RuntimeException;
using com::sun::star::lang::XMultiServiceFactory;
using com::sun::star::io::XActiveDataSource;
using com::sun::star::io::XOutputStream;
using com::sun::star::beans::PropertyValue;
using com::sun::star::document::XExporter;
using com::sun::star::document::XFilter;

using com::sun::star::io::XInputStream;
using com::sun::star::document::XImporter;
using com::sun::star::xml::sax::InputSource;
using com::sun::star::xml::sax::XDocumentHandler;
using com::sun::star::xml::sax::XParser;
//using com::sun::star::frame::XConfigManager;

sal_Bool SAL_CALL XmlFilterAdaptor::importImpl( const Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )
    throw (RuntimeException)
{

        OUString udConvertClass=msUserData[0];
        OUString udImport =msUserData[2];

    OUString sXMLImportService (  udImport  );
    const OUString sSaxParser ( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Parser") );

    Reference < XParser > xSaxParser( mxMSF->createInstance( sSaxParser ), UNO_QUERY );
    Reference < XDocumentHandler > xHandler( mxMSF->createInstance( sXMLImportService ), UNO_QUERY );
    Reference < XImporter > xImporter( xHandler, UNO_QUERY );
    xImporter->setTargetDocument ( mxDoc );

    // Creating a ConverterBridge instance
    //fprintf(stderr, "now creating the xConverter instance \n");
    Reference< XInterface > xConvBridge;

    xConvBridge = mxMSF->createInstance( udConvertClass );
    try{
      if(! xConvBridge.is()){
        fprintf (stderr, "XMLReader::Read: %s service missing\n",udConvertClass );
        return sal_False;
      }
    }
    catch( Exception& e)
      {
        fprintf (stderr, "XMLReader::Read: %s Unable to create service instance\n" );
        return sal_False;
     }
    //fprintf(stderr, "now creating the ConverterBridge instance\n");

    Reference< com::sun::star::xml::XImportFilter > xConverter;
    try {
      xConverter = Reference< com::sun::star::xml::XImportFilter > ( xConvBridge, UNO_QUERY );
    }
    catch( Exception& e)
      {
        fprintf(stderr, "Fell into the catch block!: %s\n",::rtl::OUStringToOString(
                                         e.Message, RTL_TEXTENCODING_ASCII_US).getStr() );
        fprintf(stderr, "Casting failure!\n");
      }

    //fprintf(stderr, "Created ConverterBridge instance\n");
     sal_Bool xconv_ret =xConverter->importer(aDescriptor,xHandler,msUserData);
     return sal_True;
}

sal_Bool SAL_CALL XmlFilterAdaptor::exportImpl( const Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )
    throw (RuntimeException)
{

    OUString udConvertClass=msUserData[0];
    OUString udExport =msUserData[3];

        // Set up converter bridge.
    //
    //fprintf(stderr, "going to create converterbridge!\n");
    Reference< XInterface > xConvBridge;

    xConvBridge = mxMSF->createInstance(
                        udConvertClass );
    if(! xConvBridge.is()){
      fprintf (stderr, "XMLReader::Read: %s service missing\n",::rtl::OUStringToOString(
                  msUserData[0], RTL_TEXTENCODING_ASCII_US).getStr() );
      return sal_False;
    }

        //fprintf(stderr, "now creating the xConverter instance\n");

    Reference< com::sun::star::xml::XExportFilter > xConverter;

    try {
      xConverter = Reference< com::sun::star::xml::XExportFilter > ( xConvBridge, UNO_QUERY );
    }
    catch( Exception& e){
      fprintf(stderr, "Fell into the catch block!: %s\n",::rtl::OUStringToOString(
                                           e.Message, RTL_TEXTENCODING_ASCII_US).getStr() );
      fprintf(stderr, "Casting failure!\n");
    }

    //fprintf(stderr, "created converterbridge\n");

    sal_Bool xconv_ret=xConverter->exporter(aDescriptor,msUserData);

    OUString sXMLExportService (  udExport  );
    Sequence < Any > aAnys ( 1 );
    aAnys[0] <<= xConverter;
    Reference < XExporter > xExporter( mxMSF->createInstanceWithArguments (
                       sXMLExportService, aAnys ), UNO_QUERY );
    Reference < XFilter > xFilter( xExporter, UNO_QUERY );
    xExporter->setSourceDocument ( mxDoc );
    xFilter->filter ( aDescriptor );
    return(sal_True);
}

sal_Bool SAL_CALL XmlFilterAdaptor::filter( const Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )
  throw (RuntimeException)
{
    return meType == FILTER_EXPORT ? exportImpl ( aDescriptor ) : importImpl ( aDescriptor );
}
void SAL_CALL XmlFilterAdaptor::cancel(  )
    throw (RuntimeException)
{
}
// XExporter
void SAL_CALL XmlFilterAdaptor::setSourceDocument( const Reference< ::com::sun::star::lang::XComponent >& xDoc )
    throw (::com::sun::star::lang::IllegalArgumentException, RuntimeException)
{
    meType = FILTER_EXPORT;
    mxDoc = xDoc;
}

// XImporter
void SAL_CALL XmlFilterAdaptor::setTargetDocument( const Reference< ::com::sun::star::lang::XComponent >& xDoc )
    throw (::com::sun::star::lang::IllegalArgumentException, RuntimeException)
{
    meType = FILTER_IMPORT;
    mxDoc = xDoc;
}
// XInitialization
void SAL_CALL XmlFilterAdaptor::initialize( const Sequence< Any >& aArguments )
    throw (Exception, RuntimeException)
{
    Sequence < PropertyValue > aAnySeq;
    sal_Int32 nLength = aArguments.getLength();
    sal_Int32 newLength;
    if ( nLength && ( aArguments[0] >>= aAnySeq ) )
    {
        const PropertyValue * pValue = aAnySeq.getConstArray();
        nLength = aAnySeq.getLength();
        for ( sal_Int32 i = 0 ; i < nLength; i++)
        {

            if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "Type" ) ) )
            {
                 pValue[i].Value >>= msFilterName;

            }
            else if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "UserData" ) ) )
            {

                pValue[i].Value >>= msUserData;

            }

        }
    }
}
OUString XmlFilterAdaptor_getImplementationName ()
    throw (RuntimeException)
{
    return OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.XmlFilterAdaptor" ) );
}
#define SERVICE_NAME1 "com.sun.star.document.ExportFilter"
#define SERVICE_NAME2 "com.sun.star.document.ImportFilter"
sal_Bool SAL_CALL XmlFilterAdaptor_supportsService( const OUString& ServiceName )
    throw (RuntimeException)
{
    return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME1 ) ) ||
           ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME2 ) );
}
Sequence< OUString > SAL_CALL XmlFilterAdaptor_getSupportedServiceNames(  )
    throw (RuntimeException)
{
    Sequence < OUString > aRet(2);
    OUString* pArray = aRet.getArray();
    pArray[0] =  OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME1 ) );
    pArray[1] =  OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME2 ) );
    return aRet;
}
#undef SERVICE_NAME1
#undef SERVICE_NAME2

Reference< XInterface > SAL_CALL XmlFilterAdaptor_createInstance( const Reference< XMultiServiceFactory > & rSMgr)
    throw( Exception )
{
    return (cppu::OWeakObject*) new XmlFilterAdaptor( rSMgr );
}

// XServiceInfo
OUString SAL_CALL XmlFilterAdaptor::getImplementationName(  )
    throw (RuntimeException)
{
    return XmlFilterAdaptor_getImplementationName();
}
sal_Bool SAL_CALL XmlFilterAdaptor::supportsService( const OUString& rServiceName )
    throw (RuntimeException)
{
    return XmlFilterAdaptor_supportsService( rServiceName );
}
Sequence< OUString > SAL_CALL XmlFilterAdaptor::getSupportedServiceNames(  )
    throw (RuntimeException)
{
    return XmlFilterAdaptor_getSupportedServiceNames();
}
<commit_msg>*** empty log message ***<commit_after>/*************************************************************************
 *
 *  $RCSfile: XmlFilterAdaptor.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: aidan $ $Date: 2002-07-02 12:11:35 $
 *
 *  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): Martin Gallwey (gallwey@sun.com)
 *                  Aidan Butler (aidan.butler@sun.com)
 *
 *
 ************************************************************************/
#include <iostream.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#ifndef _XMLFILTERADAPTOR_HXX
#include "XmlFilterAdaptor.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_IO_XACTIVEDATASOURCE_HPP_
#include <com/sun/star/io/XActiveDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_INPUTSOURCE_HPP_
#include <com/sun/star/xml/sax/InputSource.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_
#include <com/sun/star/xml/sax/XParser.hpp>
#endif

#ifndef _COM_SUN_STAR_XML_XIMPORTFILTER_HPP_
#include <com/sun/star/xml/XImportFilter.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_XEXPORTFILTER_HPP_
#include <com/sun/star/xml/XExportFilter.hpp>
#endif

using rtl::OUString;
using com::sun::star::uno::Sequence;
using com::sun::star::uno::Reference;
using com::sun::star::uno::Any;
using com::sun::star::uno::UNO_QUERY;
using com::sun::star::uno::XInterface;
using com::sun::star::uno::Exception;
using com::sun::star::uno::RuntimeException;
using com::sun::star::lang::XMultiServiceFactory;
using com::sun::star::io::XActiveDataSource;
using com::sun::star::io::XOutputStream;
using com::sun::star::beans::PropertyValue;
using com::sun::star::document::XExporter;
using com::sun::star::document::XFilter;

using com::sun::star::io::XInputStream;
using com::sun::star::document::XImporter;
using com::sun::star::xml::sax::InputSource;
using com::sun::star::xml::sax::XDocumentHandler;
using com::sun::star::xml::sax::XParser;
//using com::sun::star::frame::XConfigManager;

sal_Bool SAL_CALL XmlFilterAdaptor::importImpl( const Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )
    throw (RuntimeException)
{

        OUString udConvertClass=msUserData[0];
        OUString udImport =msUserData[2];

    OUString sXMLImportService (  udImport  );
    const OUString sSaxParser ( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.xml.sax.Parser") );

    Reference < XParser > xSaxParser( mxMSF->createInstance( sSaxParser ), UNO_QUERY );
    Reference < XDocumentHandler > xHandler( mxMSF->createInstance( sXMLImportService ), UNO_QUERY );
    Reference < XImporter > xImporter( xHandler, UNO_QUERY );
    xImporter->setTargetDocument ( mxDoc );

    Reference< XInterface > xConvBridge;

    xConvBridge = mxMSF->createInstance( udConvertClass );
    try{
      if(! xConvBridge.is()){
        //fprintf (stderr, "XMLReader::Read: %s service missing\n",udConvertClass );
        return sal_False;
      }
    }
    catch( Exception& e)
      {
        //fprintf (stderr, "XMLReader::Read: %s Unable to create service instance\n" );
        return sal_False;
     }

    Reference< com::sun::star::xml::XImportFilter > xConverter;
    try {
      xConverter = Reference< com::sun::star::xml::XImportFilter > ( xConvBridge, UNO_QUERY );
    }
    catch( Exception& e)
      {
        //fprintf(stderr, "Fell into the catch block!: %s\n",::rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US).getStr() );
        //fprintf(stderr, "Casting failure!\n");
      }

     sal_Bool xconv_ret =xConverter->importer(aDescriptor,xHandler,msUserData);
     return sal_True;
}

sal_Bool SAL_CALL XmlFilterAdaptor::exportImpl( const Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )
    throw (RuntimeException)
{

    OUString udConvertClass=msUserData[0];
    OUString udExport =msUserData[3];

        // Set up converter bridge.
    //

    Reference< XInterface > xConvBridge;

    xConvBridge = mxMSF->createInstance(
                        udConvertClass );
    if(! xConvBridge.is()){
      //fprintf (stderr, "XMLReader::Read: %s service missing\n",::rtl::OUStringToOString(
      //                msUserData[0], RTL_TEXTENCODING_ASCII_US).getStr() );
      return sal_False;
    }

    Reference< com::sun::star::xml::XExportFilter > xConverter;

    try {
      xConverter = Reference< com::sun::star::xml::XExportFilter > ( xConvBridge, UNO_QUERY );
    }
    catch( Exception& e){
      //fprintf(stderr, "Fell into the catch block!: %s\n",::rtl::OUStringToOString(
      //                                   e.Message, RTL_TEXTENCODING_ASCII_US).getStr() );

    }

    sal_Bool xconv_ret=xConverter->exporter(aDescriptor,msUserData);

    OUString sXMLExportService (  udExport  );
    Sequence < Any > aAnys ( 1 );
    aAnys[0] <<= xConverter;
    Reference < XExporter > xExporter( mxMSF->createInstanceWithArguments (
                       sXMLExportService, aAnys ), UNO_QUERY );
    Reference < XFilter > xFilter( xExporter, UNO_QUERY );
    xExporter->setSourceDocument ( mxDoc );
    xFilter->filter ( aDescriptor );
    return(sal_True);
}

sal_Bool SAL_CALL XmlFilterAdaptor::filter( const Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )
  throw (RuntimeException)
{
    return meType == FILTER_EXPORT ? exportImpl ( aDescriptor ) : importImpl ( aDescriptor );
}
void SAL_CALL XmlFilterAdaptor::cancel(  )
    throw (RuntimeException)
{
}
// XExporter
void SAL_CALL XmlFilterAdaptor::setSourceDocument( const Reference< ::com::sun::star::lang::XComponent >& xDoc )
    throw (::com::sun::star::lang::IllegalArgumentException, RuntimeException)
{
    meType = FILTER_EXPORT;
    mxDoc = xDoc;
}

// XImporter
void SAL_CALL XmlFilterAdaptor::setTargetDocument( const Reference< ::com::sun::star::lang::XComponent >& xDoc )
    throw (::com::sun::star::lang::IllegalArgumentException, RuntimeException)
{
    meType = FILTER_IMPORT;
    mxDoc = xDoc;
}
// XInitialization
void SAL_CALL XmlFilterAdaptor::initialize( const Sequence< Any >& aArguments )
    throw (Exception, RuntimeException)
{
    Sequence < PropertyValue > aAnySeq;
    sal_Int32 nLength = aArguments.getLength();
    sal_Int32 newLength;
    if ( nLength && ( aArguments[0] >>= aAnySeq ) )
    {
        const PropertyValue * pValue = aAnySeq.getConstArray();
        nLength = aAnySeq.getLength();
        for ( sal_Int32 i = 0 ; i < nLength; i++)
        {

            if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "Type" ) ) )
            {
                 pValue[i].Value >>= msFilterName;

            }
            else if ( pValue[i].Name.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "UserData" ) ) )
            {

                pValue[i].Value >>= msUserData;

            }

        }
    }
}
OUString XmlFilterAdaptor_getImplementationName ()
    throw (RuntimeException)
{
    return OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.XmlFilterAdaptor" ) );
}
#define SERVICE_NAME1 "com.sun.star.document.ExportFilter"
#define SERVICE_NAME2 "com.sun.star.document.ImportFilter"
sal_Bool SAL_CALL XmlFilterAdaptor_supportsService( const OUString& ServiceName )
    throw (RuntimeException)
{
    return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME1 ) ) ||
           ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME2 ) );
}
Sequence< OUString > SAL_CALL XmlFilterAdaptor_getSupportedServiceNames(  )
    throw (RuntimeException)
{
    Sequence < OUString > aRet(2);
    OUString* pArray = aRet.getArray();
    pArray[0] =  OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME1 ) );
    pArray[1] =  OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME2 ) );
    return aRet;
}
#undef SERVICE_NAME1
#undef SERVICE_NAME2

Reference< XInterface > SAL_CALL XmlFilterAdaptor_createInstance( const Reference< XMultiServiceFactory > & rSMgr)
    throw( Exception )
{
    return (cppu::OWeakObject*) new XmlFilterAdaptor( rSMgr );
}

// XServiceInfo
OUString SAL_CALL XmlFilterAdaptor::getImplementationName(  )
    throw (RuntimeException)
{
    return XmlFilterAdaptor_getImplementationName();
}
sal_Bool SAL_CALL XmlFilterAdaptor::supportsService( const OUString& rServiceName )
    throw (RuntimeException)
{
    return XmlFilterAdaptor_supportsService( rServiceName );
}
Sequence< OUString > SAL_CALL XmlFilterAdaptor::getSupportedServiceNames(  )
    throw (RuntimeException)
{
    return XmlFilterAdaptor_getSupportedServiceNames();
}
<|endoftext|>


<commit_before>#include <utils_export_client_library_python.h>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <websocketserver.h>
#include <employees.h>
#include <QtCore> // TODO remove

void UtilsExportClientLibraryPython::exportLib(){
    std::string idt = "    ";

    QCoreApplication::applicationVersion().toStdString();

    struct PyIL {
        std::string mLine;
        PyIL *mParent = NULL;
        std::vector<PyIL *> vLines;

        PyIL(){
            mParent = NULL;
            mLine = "";
        }

        PyIL(PyIL *parent, const std::string &line){
            mParent = parent;
            mLine = line;
        }
        PyIL &add(const std::string &line){
            vLines.push_back(new PyIL(this,line));
            return *this;
        }
        PyIL &sub(const std::string &line){
            PyIL *p = new PyIL(this,line);
            vLines.push_back(p);
            return *p;
        }
        PyIL &end(){
            return *mParent;
        }

        void print(std::string intent = ""){
            if(mParent != NULL){
                std::cout << intent << mLine << std::endl;
                intent += "    ";
            }
            for(int i = 0; i < vLines.size(); i++){
                vLines[i]->print(intent);
            }
        }
    };

    PyIL root = PyIL()
    .add("# -*- coding: utf-8 -*-")
    .add("### This file was automatically generated by fhq-server");

    root.add("### Version: " + QCoreApplication::applicationVersion().toStdString());
    root.add("### Date: some");
    root.add("");
    // imports
    root.add("import json");
    root.add("import functools");
    root.add("import websocket");
    root.add("import time");
    root.add("import Queue");
    root.add("import select");
    root.add("from threading import Thread");
    root.add("")

    .sub("class FHQCliRecvThread(Thread):")
        .add("__ws = None;")
        .add("__sendCommandQueue = Queue.Queue();")
        .add("__cmd_results = {};")
        .add("do_run = True;")
        .add("__url = None;")
        .add("__messageId = 0;")
        .add("")
        .sub("def __init__(self, url):")
            .add("Thread.__init__(self)")
            .add("self.__url = url;")
            .end()
        .add("")
        .sub("def run(self):")
            .add("print('[FHQCliThread] Connecting to ' + self.__url)")
            .sub("try:")
                .add("self.__ws = websocket.create_connection(self.__url)")
                .end()
            .sub("except:")
                .add("print('Failed connect to '' + self.__url)")
                .add("self.__ws = None")
                .add("return")
                .end()
            .add("# self.__ws.setblocking(0)")
            .add("print('[FHQCliThread] Connected');")
            .sub("while(self.do_run):")
                .sub("while not self.__sendCommandQueue.empty():")
                    .add("requestJson = self.__sendCommandQueue.get();")
                    .add("requestText = json.dumps(requestJson);")
                    .add("# print('requestText: ' + requestText);")
                    .add("self.__ws.send(requestText)")
                    .end()
                .add("ready = select.select([self.__ws], [], [], 0.1)")
                .sub("if ready[0]:")
                    .add("responseText =  self.__ws.recv()")
                    .add("responseJson = json.loads(responseText)")
                    .add("cmd_m = responseJson['m'];")
                    .add("self.__cmd_results[cmd_m] = json.loads(responseText);")
                    .add("# print(responseText)")
                    .end()
                .add("time.sleep(0.5)")
                .end()
            .add("print('[FHQCliThread] Stopping...');")
            .add("self.__ws.close()")
            .add("self.__ws = None")
            .add("print('[FHQCliThread] Stopped');")
            .end()
        .add("")
        .sub("def addToSendQueue(self, requestJson):")
            .add("self.__sendCommandQueue.put(requestJson);")
            .add("return requestJson['m'];")
            .end()
        .add("")
        .sub("def generateBaseCommand(self, cmd):")
            .add("self.__messageId = self.__messageId + 1;")
            .add("requestJson = {};")
            .add("msgId = 'm' + str(self.__messageId);")
            .add("requestJson['m'] = msgId;")
            .add("requestJson['cmd'] = cmd;")
            .add("return requestJson;")
            .end()
        .add("")
        .sub("def hasCmdResult(self, cmd_m):")
            .add("return cmd_m in self.__cmd_results;")
            .end()
        .add("")
        .sub("def getCmdResult(self, cmd_m):")
            .add("return self.__cmd_results[cmd_m]")
            .end()
        .add("")
        .sub("def removeCmdResult(self, cmd_m):")
            .add("self.__cmd_results.pop(cmd_m, None)")
            .end()
        .add("")
        .sub("def hasConnection(self):")
            .add("return self.__ws != None")
            .end()
        .end()
    .add("")
    .sub("class FHQCli:")
        .add("# __ws = None;")
        .add("__url = 'ws://localhost:1234/';")
        .add("__recvThread = None")
        .sub("def __init__(self, url):")
            .add("self.__url = url")
            .add("self.connect();")
            .end()
        .add("")
        .sub("def __enter__(self):")
            .add("return self")
            .end()
        .add("")
        .sub("def __exit__(self, exc_type, exc_value, traceback):")
            .add("self.__recvThread.do_run = False;")
            .end()
        .add("")
        .sub("def close(self):")
            .add("self.__recvThread.do_run = False;")
            .end()
        .add("")
        .sub("def setUrl(self, url):")
            .add("self.__url = url;")
            .end()
        .add("")
        .sub("def getUrl(self):")
            .add("return self.__url;")
            .end()
        .add("")
        .sub("def connect(self):")
            .add("self.__recvThread = FHQCliRecvThread(self.__url)")
            .add("self.__recvThread.start()")
            .add("# self.__recvThread.join()")
            .add("# print('FHQCli: Thread started');")
            .add("return True;")
            .end()
        .add("")
        .sub("def __looper(self, cmd_m):")
            .add("max_time = 5*10; # 5 seconds")
            .add("counter_time = 0;")
            .add("cmd_result = {};")
            .sub("while True:")
                .add("counter_time = counter_time + 1;")
                .sub("if self.__recvThread.hasCmdResult(cmd_m):")
                    .add("cmd_result = self.__recvThread.getCmdResult(cmd_m);")
                    .add("self.__recvThread.removeCmdResult(cmd_m);")
                    .add("break;")
                    .end()
                .sub("if counter_time > max_time:")
                    .add("cmd_result = None")
                    .add("break;")
                    .end()
                .add("time.sleep(0.2)")
                .end()
            .add("return cmd_result;")
            .end()
        .add("")
        .sub("def login(self, email, password):")
            .add("if not self.__recvThread.hasConnection(): return None")
            .add("requestJson = self.__recvThread.generateBaseCommand('login')")
            .add("requestJson['email'] = email;")
            .add("requestJson['password'] = password;")
            .add("cmd_m = self.__recvThread.addToSendQueue(requestJson);")
            .add("return self.__looper(cmd_m);")
            .end()
        .add("")
        .sub("def admin_user_create(self, email, nick, password, role, university):")
            .add("if not self.__recvThread.hasConnection(): return None")
            .add("requestJson = self.__recvThread.generateBaseCommand('user_create')")
            .add("requestJson['email'] = email;")
            .add("requestJson['nick'] = nick;")
            .add("requestJson['role'] = role;")
            .add("requestJson['password'] = password;")
            .add("requestJson['university'] = university;")
            .add("cmd_m = self.__recvThread.addToSendQueue(requestJson);")
            .add("return self.__looper(cmd_m);")
            .end()
        .add("")
        .sub("def scoreboard(self):")
            .add("if not self.__recvThread.hasConnection(): return None")
            .add("requestJson = self.__recvThread.generateBaseCommand('scoreboard')")
            .add("requestJson['page'] = 0;")
            .add("requestJson['onpage'] = 10;")
            .add("cmd_m = self.__recvThread.addToSendQueue(requestJson);")
            .add("return self.__looper(cmd_m);")
            .end()
        .end()
    .end()
     ;

    root.print();
    return;
}
<commit_msg>fixed #99<commit_after>#include <utils_export_client_library_python.h>

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <websocketserver.h>
#include <employees.h>
#include <QtCore> // TODO remove

#include <memory>

class PyCodeLine{

    PyCodeLine *m_pParent;
    std::string m_sLine;
    std::vector<PyCodeLine *> m_vLines;
public:

    PyCodeLine(){
        m_pParent = NULL;
        m_sLine = "";
    }

    PyCodeLine(PyCodeLine *parent, const std::string &sLine){
        m_pParent = parent;
        m_sLine = sLine;
    }

    ~PyCodeLine(){
        if(m_pParent == NULL){
            std::cout << "destruct root \n";
        }else{
            std::cout << "destruct something else [" << m_sLine << "]\n";
        }
    }

    PyCodeLine *addLine(const std::string &sLine){
        PyCodeLine *pPyCodeLine = new PyCodeLine(this,sLine);
        m_vLines.push_back(pPyCodeLine);
        return pPyCodeLine;
    }

    PyCodeLine *getParent(){
        return m_pParent;
    }

    std::string getLine(){
        return m_sLine;
    }

    PyCodeLine *findRoot(){
        if(m_pParent == NULL){
            return this;
        }
        return m_pParent->findRoot();
    }

    void print(std::string intent = ""){
        if(m_pParent != NULL){
            std::cout << intent << m_sLine << std::endl;
            intent += "    ";
        }
        for(int i = 0; i < m_vLines.size(); i++){
            m_vLines[i]->print(intent);
        }
    }
};

class PyCodeBuilder {

private:
    PyCodeLine *m_pCurr = NULL;

public:
    PyCodeBuilder(){
        m_pCurr = new PyCodeLine();
    }

    ~PyCodeBuilder(){
        // std::cout << "destruct something else [" << m_pCurr->getLine() << "]\n";
    }

    PyCodeBuilder &add(const std::string &sLine){
        m_pCurr->addLine(sLine);
        return *this;
    }
    PyCodeBuilder &sub(const std::string &sLine){
        m_pCurr = m_pCurr->addLine(sLine);
        return *this;
    }
    PyCodeBuilder &end(){
        PyCodeLine *p = m_pCurr->getParent();
        if(p != NULL){
            m_pCurr = p;
        }else{
            std::cout << "Wrong called end function" << std::endl;
        }
        return *this;
    }

    void print(){
        PyCodeLine *pRoot = m_pCurr->findRoot();
        pRoot->print();
    };
};

void UtilsExportClientLibraryPython::exportLib(){

    PyCodeBuilder builder;
    builder
    .add("# -*- coding: utf-8 -*-")
    .add("### This file was automatically generated by fhq-server")
    .add("### Version: " + QCoreApplication::applicationVersion().toStdString())
    .add("### Date: some")
    .add("")
    .add("import json")
    .add("import functools")
    .add("import websocket")
    .add("import time")
    .add("import Queue")
    .add("import select")
    .add("from threading import Thread")
    .add("")
    .sub("class FHQCliRecvThread(Thread):")
        .add("__ws = None;")
        .add("__sendCommandQueue = Queue.Queue();")
        .add("__cmd_results = {};")
        .add("do_run = True;")
        .add("__url = None;")
        .add("__messageId = 0;")
        .add("")
        .sub("def __init__(self, url):")
            .add("Thread.__init__(self)")
            .add("self.__url = url;")
            .end()
        .add("")
        .sub("def run(self):")
            .add("print('[FHQCliThread] Connecting to ' + self.__url)")
            .sub("try:")
                .add("self.__ws = websocket.create_connection(self.__url)")
                .end()
            .sub("except:")
                .add("print('Failed connect to ' + self.__url)")
                .add("self.__ws = None")
                .add("return")
                .end()
            .add("# self.__ws.setblocking(0)")
            .add("print('[FHQCliThread] Connected');")
            .sub("while(self.do_run):")
                .sub("while not self.__sendCommandQueue.empty():")
                    .add("requestJson = self.__sendCommandQueue.get();")
                    .add("requestText = json.dumps(requestJson);")
                    .add("# print('requestText: ' + requestText);")
                    .add("self.__ws.send(requestText)")
                    .end()
                .add("ready = select.select([self.__ws], [], [], 0.1)")
                .sub("if ready[0]:")
                    .add("responseText =  self.__ws.recv()")
                    .add("responseJson = json.loads(responseText)")
                    .add("cmd_m = responseJson['m'];")
                    .add("self.__cmd_results[cmd_m] = json.loads(responseText);")
                    .add("# print(responseText)")
                    .end()
                .add("time.sleep(0.5)")
                .end()
            .add("print('[FHQCliThread] Stopping...');")
            .add("self.__ws.close()")
            .add("self.__ws = None")
            .add("print('[FHQCliThread] Stopped');")
            .end()
        .add("")
        .sub("def addToSendQueue(self, requestJson):")
            .add("self.__sendCommandQueue.put(requestJson);")
            .add("return requestJson['m'];")
            .end()
        .add("")
        .sub("def generateBaseCommand(self, cmd):")
            .add("self.__messageId = self.__messageId + 1;")
            .add("requestJson = {};")
            .add("msgId = 'm' + str(self.__messageId);")
            .add("requestJson['m'] = msgId;")
            .add("requestJson['cmd'] = cmd;")
            .add("return requestJson;")
            .end()
        .add("")
        .sub("def hasCmdResult(self, cmd_m):")
            .add("return cmd_m in self.__cmd_results;")
            .end()
        .add("")
        .sub("def getCmdResult(self, cmd_m):")
            .add("return self.__cmd_results[cmd_m]")
            .end()
        .add("")
        .sub("def removeCmdResult(self, cmd_m):")
            .add("self.__cmd_results.pop(cmd_m, None)")
            .end()
        .add("")
        .sub("def hasConnection(self):")
            .add("return self.__ws != None")
            .end()
        .end()
    .add("")
    .sub("class FHQCli:")
        .add("# __ws = None;")
        .add("__url = 'ws://localhost:1234/';")
        .add("__recvThread = None")
        .sub("def __init__(self, url):")
            .add("self.__url = url")
            .add("self.connect();")
            .end()
        .add("")
        .sub("def __enter__(self):")
            .add("return self")
            .end()
        .add("")
        .sub("def __exit__(self, exc_type, exc_value, traceback):")
            .add("self.__recvThread.do_run = False;")
            .end()
        .add("")
        .sub("def close(self):")
            .add("self.__recvThread.do_run = False;")
            .end()
        .add("")
        .sub("def setUrl(self, url):")
            .add("self.__url = url;")
            .end()
        .add("")
        .sub("def getUrl(self):")
            .add("return self.__url;")
            .end()
        .add("")
        .sub("def connect(self):")
            .add("self.__recvThread = FHQCliRecvThread(self.__url)")
            .add("self.__recvThread.start()")
            .add("# self.__recvThread.join()")
            .add("# print('FHQCli: Thread started');")
            .add("return True;")
            .end()
        .add("")
        .sub("def __looper(self, cmd_m):")
            .add("max_time = 5*10; # 5 seconds")
            .add("counter_time = 0;")
            .add("cmd_result = {};")
            .sub("while True:")
                .add("counter_time = counter_time + 1;")
                .sub("if self.__recvThread.hasCmdResult(cmd_m):")
                    .add("cmd_result = self.__recvThread.getCmdResult(cmd_m);")
                    .add("self.__recvThread.removeCmdResult(cmd_m);")
                    .add("break;")
                    .end()
                .sub("if counter_time > max_time:")
                    .add("cmd_result = None")
                    .add("break;")
                    .end()
                .add("time.sleep(0.2)")
                .end()
            .add("return cmd_result;")
            .end()
        .add("");

    std::map<std::string, CmdHandlerBase*>::iterator it = g_pCmdHandlers->begin();
    for (; it!=g_pCmdHandlers->end(); ++it){
        std::string sCmd = it->first;
        CmdHandlerBase* pCmdHandlerBase = it->second;
        builder
        .add("# Access unauthorized " + std::string(pCmdHandlerBase->access().accessUnauthorized() ? "yes" : "no"))
        .add("# Acess user " + std::string(pCmdHandlerBase->access().accessUser() ? "yes" : "no"))
        .add("# Access admin " + std::string(pCmdHandlerBase->access().accessAdmin() ? "yes" : "no"));

        std::vector<CmdInputDef> vVin = pCmdHandlerBase->inputs();
        for(int i = 0; i < vVin.size(); i++){
            CmdInputDef inDef = vVin[i];
            std::string nameIn = std::string(inDef.getName());
            builder.add("# " + nameIn + " - " + inDef.getType() + ", " + inDef.getRestrict() + " (" + inDef.getDescription() + ")" );
        }

        builder
        .sub("def " + sCmd + "(self, req):")
            .add("if not self.__recvThread.hasConnection(): return None")
            .add("requestJson = self.__recvThread.generateBaseCommand('" + sCmd + "')");

        for(int i = 0; i < vVin.size(); i++){
            std::string nameIn = std::string(vVin[i].getName());
            builder
            .sub("if req['" + nameIn + "'] != None: ")
                .add("requestJson['" + nameIn + "'] = req['" + nameIn + "']")
                .end();
        }

        builder
            .add("cmd_m = self.__recvThread.addToSendQueue(requestJson);")
            .add("return self.__looper(cmd_m);")
            .end()
        .add("");
    }
    builder.end();
    builder.print();

    // pycode

        /*.sub("def login(self, email, password):")
            .add("if not self.__recvThread.hasConnection(): return None")
            .add("requestJson = self.__recvThread.generateBaseCommand('login')")
            .add("requestJson['email'] = email;")
            .add("requestJson['password'] = password;")
            .add("cmd_m = self.__recvThread.addToSendQueue(requestJson);")
            .add("return self.__looper(cmd_m);")
            .end()
        .add("")
        .sub("def admin_user_create(self, email, nick, password, role, university):")
            .add("if not self.__recvThread.hasConnection(): return None")
            .add("requestJson = self.__recvThread.generateBaseCommand('user_create')")
            .add("requestJson['email'] = email;")
            .add("requestJson['nick'] = nick;")
            .add("requestJson['role'] = role;")
            .add("requestJson['password'] = password;")
            .add("requestJson['university'] = university;")
            .add("cmd_m = self.__recvThread.addToSendQueue(requestJson);")
            .add("return self.__looper(cmd_m);")
            .end()
        .add("")
        .sub("def scoreboard(self):")
            .add("if not self.__recvThread.hasConnection(): return None")
            .add("requestJson = self.__recvThread.generateBaseCommand('scoreboard')")
            .add("requestJson['page'] = 0;")
            .add("requestJson['onpage'] = 10;")
            .add("cmd_m = self.__recvThread.addToSendQueue(requestJson);")
            .add("return self.__looper(cmd_m);")
            .end()
        .end()
    .end()*/
     ;

    return;
}
<|endoftext|>


<commit_before>//===-- DYLDRendezvous.cpp --------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// C Includes
// C++ Includes
// Other libraries and framework includes
#include "lldb/Core/ArchSpec.h"
#include "lldb/Core/Error.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/Module.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/Symbol.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"

#include "DYLDRendezvous.h"

using namespace lldb;
using namespace lldb_private;

/// Locates the address of the rendezvous structure.  Returns the address on
/// success and LLDB_INVALID_ADDRESS on failure.
static addr_t
ResolveRendezvousAddress(Process *process)
{
    Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
    addr_t info_location;
    addr_t info_addr;
    Error error;

    // Try to get it from our process.  This might be a remote process and might
    // grab it via some remote-specific mechanism.
    info_location = process->GetImageInfoAddress();
    if (log)
        log->Printf ("%s info_location = 0x%" PRIx64, __FUNCTION__, info_location);

    // If the process fails to return an address, fall back to seeing if the local object file can help us find it.
    if (info_location == LLDB_INVALID_ADDRESS)
    {
        Target *target = process ? &process->GetTarget() : nullptr;
        if (target)
        {
            ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
            Address addr = obj_file->GetImageInfoAddress(target);

            if (addr.IsValid())
            {
                info_location = addr.GetLoadAddress(target);
                if (log)
                    log->Printf ("%s resolved via direct object file approach to 0x%" PRIx64, __FUNCTION__, info_location);
            }
            else
            {
                if (log)
                    log->Printf ("%s FAILED - direct object file approach did not yield a valid address", __FUNCTION__);
            }
        }
    }

    if (info_location == LLDB_INVALID_ADDRESS)
    {
        if (log)
            log->Printf ("%s FAILED - invalid info address", __FUNCTION__);
        return LLDB_INVALID_ADDRESS;
    }

    info_addr = process->ReadPointerFromMemory(info_location, error);
    if (error.Fail())
    {
        if (log)
            log->Printf ("%s FAILED - could not read from the info location: %s", __FUNCTION__, error.AsCString ());
        return LLDB_INVALID_ADDRESS;
    }

    if (info_addr == 0)
    {
        if (log)
            log->Printf ("%s FAILED - the rendezvous address contained at 0x%" PRIx64 " returned a null value", __FUNCTION__, info_location);
        return LLDB_INVALID_ADDRESS;
    }

    return info_addr;
}

DYLDRendezvous::DYLDRendezvous(Process *process)
    : m_process(process),
      m_rendezvous_addr(LLDB_INVALID_ADDRESS),
      m_current(),
      m_previous(),
      m_soentries(),
      m_added_soentries(),
      m_removed_soentries()
{
    Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));

    m_thread_info.valid = false;

    // Cache a copy of the executable path
    if (m_process)
    {
        Module *exe_mod = m_process->GetTarget().GetExecutableModulePointer();
        if (exe_mod)
        {
            exe_mod->GetFileSpec().GetPath(m_exe_path, PATH_MAX);
            if (log)
                log->Printf ("DYLDRendezvous::%s exe module executable path set: '%s'", __FUNCTION__, m_exe_path);
        }
        else
        {
            if (log)
                log->Printf ("DYLDRendezvous::%s cannot cache exe module path: null executable module pointer", __FUNCTION__);
        }
    }
}

bool
DYLDRendezvous::Resolve()
{
    Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));

    const size_t word_size = 4;
    Rendezvous info;
    size_t address_size;
    size_t padding;
    addr_t info_addr;
    addr_t cursor;

    address_size = m_process->GetAddressByteSize();
    padding = address_size - word_size;
    if (log)
        log->Printf ("DYLDRendezvous::%s address size: %zu, padding %zu", __FUNCTION__, address_size, padding);

    if (m_rendezvous_addr == LLDB_INVALID_ADDRESS)
        cursor = info_addr = ResolveRendezvousAddress(m_process);
    else
        cursor = info_addr = m_rendezvous_addr;
    if (log)
        log->Printf ("DYLDRendezvous::%s cursor = 0x%" PRIx64, __FUNCTION__, cursor);

    if (cursor == LLDB_INVALID_ADDRESS)
        return false;

    if (!(cursor = ReadWord(cursor, &info.version, word_size)))
        return false;

    if (!(cursor = ReadPointer(cursor + padding, &info.map_addr)))
        return false;

    if (!(cursor = ReadPointer(cursor, &info.brk)))
        return false;

    if (!(cursor = ReadWord(cursor, &info.state, word_size)))
        return false;

    if (!(cursor = ReadPointer(cursor + padding, &info.ldbase)))
        return false;

    // The rendezvous was successfully read.  Update our internal state.
    m_rendezvous_addr = info_addr;
    m_previous = m_current;
    m_current = info;

    return UpdateSOEntries();
}

bool
DYLDRendezvous::IsValid()
{
    return m_rendezvous_addr != LLDB_INVALID_ADDRESS;
}

bool
DYLDRendezvous::UpdateSOEntries()
{
    SOEntry entry;

    if (m_current.map_addr == 0)
        return false;

    // When the previous and current states are consistent this is the first
    // time we have been asked to update.  Just take a snapshot of the currently
    // loaded modules.
    if (m_previous.state == eConsistent && m_current.state == eConsistent)
        return TakeSnapshot(m_soentries);

    // If we are about to add or remove a shared object clear out the current
    // state and take a snapshot of the currently loaded images.
    if (m_current.state == eAdd || m_current.state == eDelete)
    {
        assert(m_previous.state == eConsistent);
        m_soentries.clear();
        m_added_soentries.clear();
        m_removed_soentries.clear();
        return TakeSnapshot(m_soentries);
    }
    assert(m_current.state == eConsistent);

    // Otherwise check the previous state to determine what to expect and update
    // accordingly.
    if (m_previous.state == eAdd)
        return UpdateSOEntriesForAddition();
    else if (m_previous.state == eDelete)
        return UpdateSOEntriesForDeletion();

    return false;
}

bool
DYLDRendezvous::UpdateSOEntriesForAddition()
{
    SOEntry entry;
    iterator pos;

    assert(m_previous.state == eAdd);

    if (m_current.map_addr == 0)
        return false;

    for (addr_t cursor = m_current.map_addr; cursor != 0; cursor = entry.next)
    {
        if (!ReadSOEntryFromMemory(cursor, entry))
            return false;

        // Only add shared libraries and not the executable.
        // On Linux this is indicated by an empty path in the entry.
        // On FreeBSD it is the name of the executable.
        if (entry.path.empty() || ::strcmp(entry.path.c_str(), m_exe_path) == 0)
            continue;

        pos = std::find(m_soentries.begin(), m_soentries.end(), entry);
        if (pos == m_soentries.end())
        {
            m_soentries.push_back(entry);
            m_added_soentries.push_back(entry);
        }
    }

    return true;
}

bool
DYLDRendezvous::UpdateSOEntriesForDeletion()
{
    SOEntryList entry_list;
    iterator pos;

    assert(m_previous.state == eDelete);

    if (!TakeSnapshot(entry_list))
        return false;

    for (iterator I = begin(); I != end(); ++I)
    {
        pos = std::find(entry_list.begin(), entry_list.end(), *I);
        if (pos == entry_list.end())
            m_removed_soentries.push_back(*I);
    }

    m_soentries = entry_list;
    return true;
}

bool
DYLDRendezvous::TakeSnapshot(SOEntryList &entry_list)
{
    SOEntry entry;

    if (m_current.map_addr == 0)
        return false;

    for (addr_t cursor = m_current.map_addr; cursor != 0; cursor = entry.next)
    {
        if (!ReadSOEntryFromMemory(cursor, entry))
            return false;

        // Only add shared libraries and not the executable.
        // On Linux this is indicated by an empty path in the entry.
        // On FreeBSD it is the name of the executable.
        if (entry.path.empty() || ::strcmp(entry.path.c_str(), m_exe_path) == 0)
            continue;

        entry_list.push_back(entry);
    }

    return true;
}

addr_t
DYLDRendezvous::ReadWord(addr_t addr, uint64_t *dst, size_t size)
{
    Error error;

    *dst = m_process->ReadUnsignedIntegerFromMemory(addr, size, 0, error);
    if (error.Fail())
        return 0;

    return addr + size;
}

addr_t
DYLDRendezvous::ReadPointer(addr_t addr, addr_t *dst)
{
    Error error;

    *dst = m_process->ReadPointerFromMemory(addr, error);
    if (error.Fail())
        return 0;

    return addr + m_process->GetAddressByteSize();
}

std::string
DYLDRendezvous::ReadStringFromMemory(addr_t addr)
{
    std::string str;
    Error error;
    size_t size;
    char c;

    if (addr == LLDB_INVALID_ADDRESS)
        return std::string();

    for (;;) {
        size = m_process->DoReadMemory(addr, &c, 1, error);
        if (size != 1 || error.Fail())
            return std::string();
        if (c == 0)
            break;
        else {
            str.push_back(c);
            addr++;
        }
    }

    return str;
}

bool
DYLDRendezvous::ReadSOEntryFromMemory(lldb::addr_t addr, SOEntry &entry)
{
    entry.clear();

    entry.link_addr = addr;

    if (!(addr = ReadPointer(addr, &entry.base_addr)))
        return false;

    // mips adds an extra load offset field to the link map struct on
    // FreeBSD and NetBSD (need to validate other OSes).
    // http://svnweb.freebsd.org/base/head/sys/sys/link_elf.h?revision=217153&view=markup#l57
    const ArchSpec &arch = m_process->GetTarget().GetArchitecture();
    if (arch.GetCore() == ArchSpec::eCore_mips64)
    {
        assert (arch.GetTriple().getOS() == llvm::Triple::FreeBSD ||
                arch.GetTriple().getOS() == llvm::Triple::NetBSD);
        addr_t mips_l_offs;
        if (!(addr = ReadPointer(addr, &mips_l_offs)))
            return false;
        if (mips_l_offs != 0 && mips_l_offs != entry.base_addr)
            return false;
    }

    if (!(addr = ReadPointer(addr, &entry.path_addr)))
        return false;

    if (!(addr = ReadPointer(addr, &entry.dyn_addr)))
        return false;

    if (!(addr = ReadPointer(addr, &entry.next)))
        return false;

    if (!(addr = ReadPointer(addr, &entry.prev)))
        return false;

    entry.path = ReadStringFromMemory(entry.path_addr);

    return true;
}

bool
DYLDRendezvous::FindMetadata(const char *name, PThreadField field, uint32_t& value)
{
    Target& target = m_process->GetTarget();

    SymbolContextList list;
    if (!target.GetImages().FindSymbolsWithNameAndType (ConstString(name), eSymbolTypeAny, list))
        return false;

    Address address = list[0].symbol->GetAddress();
    addr_t addr = address.GetLoadAddress (&target);
    if (addr == LLDB_INVALID_ADDRESS)
        return false;

    Error error;
    value = (uint32_t)m_process->ReadUnsignedIntegerFromMemory(addr + field*sizeof(uint32_t), sizeof(uint32_t), 0, error);
    if (error.Fail())
        return false;

    if (field == eSize)
        value /= 8; // convert bits to bytes

    return true;
}

const DYLDRendezvous::ThreadInfo&
DYLDRendezvous::GetThreadInfo()
{
    if (!m_thread_info.valid)
    {
        bool ok = true;

        ok &= FindMetadata ("_thread_db_pthread_dtvp", eOffset, m_thread_info.dtv_offset);
        ok &= FindMetadata ("_thread_db_dtv_dtv", eSize, m_thread_info.dtv_slot_size);
        ok &= FindMetadata ("_thread_db_link_map_l_tls_modid", eOffset, m_thread_info.modid_offset);
        ok &= FindMetadata ("_thread_db_dtv_t_pointer_val", eOffset, m_thread_info.tls_offset);

        if (ok)
            m_thread_info.valid = true;
    }

    return m_thread_info;
}

void
DYLDRendezvous::DumpToLog(Log *log) const
{
    int state = GetState();

    if (!log)
        return;

    log->PutCString("DYLDRendezvous:");
    log->Printf("   Address: %" PRIx64, GetRendezvousAddress());
    log->Printf("   Version: %" PRIu64, GetVersion());
    log->Printf("   Link   : %" PRIx64, GetLinkMapAddress());
    log->Printf("   Break  : %" PRIx64, GetBreakAddress());
    log->Printf("   LDBase : %" PRIx64, GetLDBase());
    log->Printf("   State  : %s",
                (state == eConsistent) ? "consistent" :
                (state == eAdd)        ? "add"        :
                (state == eDelete)     ? "delete"     : "unknown");

    iterator I = begin();
    iterator E = end();

    if (I != E)
        log->PutCString("DYLDRendezvous SOEntries:");

    for (int i = 1; I != E; ++I, ++i)
    {
        log->Printf("\n   SOEntry [%d] %s", i, I->path.c_str());
        log->Printf("      Base : %" PRIx64, I->base_addr);
        log->Printf("      Path : %" PRIx64, I->path_addr);
        log->Printf("      Dyn  : %" PRIx64, I->dyn_addr);
        log->Printf("      Next : %" PRIx64, I->next);
        log->Printf("      Prev : %" PRIx64, I->prev);
    }
}
<commit_msg>Use the process' ReadCStringFromMemory from DYLDRendezvous::ReadStringFromMemory.<commit_after>//===-- DYLDRendezvous.cpp --------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// C Includes
// C++ Includes
// Other libraries and framework includes
#include "lldb/Core/ArchSpec.h"
#include "lldb/Core/Error.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/Module.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/Symbol.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"

#include "DYLDRendezvous.h"

using namespace lldb;
using namespace lldb_private;

/// Locates the address of the rendezvous structure.  Returns the address on
/// success and LLDB_INVALID_ADDRESS on failure.
static addr_t
ResolveRendezvousAddress(Process *process)
{
    Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));
    addr_t info_location;
    addr_t info_addr;
    Error error;

    // Try to get it from our process.  This might be a remote process and might
    // grab it via some remote-specific mechanism.
    info_location = process->GetImageInfoAddress();
    if (log)
        log->Printf ("%s info_location = 0x%" PRIx64, __FUNCTION__, info_location);

    // If the process fails to return an address, fall back to seeing if the local object file can help us find it.
    if (info_location == LLDB_INVALID_ADDRESS)
    {
        Target *target = process ? &process->GetTarget() : nullptr;
        if (target)
        {
            ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
            Address addr = obj_file->GetImageInfoAddress(target);

            if (addr.IsValid())
            {
                info_location = addr.GetLoadAddress(target);
                if (log)
                    log->Printf ("%s resolved via direct object file approach to 0x%" PRIx64, __FUNCTION__, info_location);
            }
            else
            {
                if (log)
                    log->Printf ("%s FAILED - direct object file approach did not yield a valid address", __FUNCTION__);
            }
        }
    }

    if (info_location == LLDB_INVALID_ADDRESS)
    {
        if (log)
            log->Printf ("%s FAILED - invalid info address", __FUNCTION__);
        return LLDB_INVALID_ADDRESS;
    }

    info_addr = process->ReadPointerFromMemory(info_location, error);
    if (error.Fail())
    {
        if (log)
            log->Printf ("%s FAILED - could not read from the info location: %s", __FUNCTION__, error.AsCString ());
        return LLDB_INVALID_ADDRESS;
    }

    if (info_addr == 0)
    {
        if (log)
            log->Printf ("%s FAILED - the rendezvous address contained at 0x%" PRIx64 " returned a null value", __FUNCTION__, info_location);
        return LLDB_INVALID_ADDRESS;
    }

    return info_addr;
}

DYLDRendezvous::DYLDRendezvous(Process *process)
    : m_process(process),
      m_rendezvous_addr(LLDB_INVALID_ADDRESS),
      m_current(),
      m_previous(),
      m_soentries(),
      m_added_soentries(),
      m_removed_soentries()
{
    Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));

    m_thread_info.valid = false;

    // Cache a copy of the executable path
    if (m_process)
    {
        Module *exe_mod = m_process->GetTarget().GetExecutableModulePointer();
        if (exe_mod)
        {
            exe_mod->GetFileSpec().GetPath(m_exe_path, PATH_MAX);
            if (log)
                log->Printf ("DYLDRendezvous::%s exe module executable path set: '%s'", __FUNCTION__, m_exe_path);
        }
        else
        {
            if (log)
                log->Printf ("DYLDRendezvous::%s cannot cache exe module path: null executable module pointer", __FUNCTION__);
        }
    }
}

bool
DYLDRendezvous::Resolve()
{
    Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER));

    const size_t word_size = 4;
    Rendezvous info;
    size_t address_size;
    size_t padding;
    addr_t info_addr;
    addr_t cursor;

    address_size = m_process->GetAddressByteSize();
    padding = address_size - word_size;
    if (log)
        log->Printf ("DYLDRendezvous::%s address size: %zu, padding %zu", __FUNCTION__, address_size, padding);

    if (m_rendezvous_addr == LLDB_INVALID_ADDRESS)
        cursor = info_addr = ResolveRendezvousAddress(m_process);
    else
        cursor = info_addr = m_rendezvous_addr;
    if (log)
        log->Printf ("DYLDRendezvous::%s cursor = 0x%" PRIx64, __FUNCTION__, cursor);

    if (cursor == LLDB_INVALID_ADDRESS)
        return false;

    if (!(cursor = ReadWord(cursor, &info.version, word_size)))
        return false;

    if (!(cursor = ReadPointer(cursor + padding, &info.map_addr)))
        return false;

    if (!(cursor = ReadPointer(cursor, &info.brk)))
        return false;

    if (!(cursor = ReadWord(cursor, &info.state, word_size)))
        return false;

    if (!(cursor = ReadPointer(cursor + padding, &info.ldbase)))
        return false;

    // The rendezvous was successfully read.  Update our internal state.
    m_rendezvous_addr = info_addr;
    m_previous = m_current;
    m_current = info;

    return UpdateSOEntries();
}

bool
DYLDRendezvous::IsValid()
{
    return m_rendezvous_addr != LLDB_INVALID_ADDRESS;
}

bool
DYLDRendezvous::UpdateSOEntries()
{
    SOEntry entry;

    if (m_current.map_addr == 0)
        return false;

    // When the previous and current states are consistent this is the first
    // time we have been asked to update.  Just take a snapshot of the currently
    // loaded modules.
    if (m_previous.state == eConsistent && m_current.state == eConsistent)
        return TakeSnapshot(m_soentries);

    // If we are about to add or remove a shared object clear out the current
    // state and take a snapshot of the currently loaded images.
    if (m_current.state == eAdd || m_current.state == eDelete)
    {
        assert(m_previous.state == eConsistent);
        m_soentries.clear();
        m_added_soentries.clear();
        m_removed_soentries.clear();
        return TakeSnapshot(m_soentries);
    }
    assert(m_current.state == eConsistent);

    // Otherwise check the previous state to determine what to expect and update
    // accordingly.
    if (m_previous.state == eAdd)
        return UpdateSOEntriesForAddition();
    else if (m_previous.state == eDelete)
        return UpdateSOEntriesForDeletion();

    return false;
}

bool
DYLDRendezvous::UpdateSOEntriesForAddition()
{
    SOEntry entry;
    iterator pos;

    assert(m_previous.state == eAdd);

    if (m_current.map_addr == 0)
        return false;

    for (addr_t cursor = m_current.map_addr; cursor != 0; cursor = entry.next)
    {
        if (!ReadSOEntryFromMemory(cursor, entry))
            return false;

        // Only add shared libraries and not the executable.
        // On Linux this is indicated by an empty path in the entry.
        // On FreeBSD it is the name of the executable.
        if (entry.path.empty() || ::strcmp(entry.path.c_str(), m_exe_path) == 0)
            continue;

        pos = std::find(m_soentries.begin(), m_soentries.end(), entry);
        if (pos == m_soentries.end())
        {
            m_soentries.push_back(entry);
            m_added_soentries.push_back(entry);
        }
    }

    return true;
}

bool
DYLDRendezvous::UpdateSOEntriesForDeletion()
{
    SOEntryList entry_list;
    iterator pos;

    assert(m_previous.state == eDelete);

    if (!TakeSnapshot(entry_list))
        return false;

    for (iterator I = begin(); I != end(); ++I)
    {
        pos = std::find(entry_list.begin(), entry_list.end(), *I);
        if (pos == entry_list.end())
            m_removed_soentries.push_back(*I);
    }

    m_soentries = entry_list;
    return true;
}

bool
DYLDRendezvous::TakeSnapshot(SOEntryList &entry_list)
{
    SOEntry entry;

    if (m_current.map_addr == 0)
        return false;

    for (addr_t cursor = m_current.map_addr; cursor != 0; cursor = entry.next)
    {
        if (!ReadSOEntryFromMemory(cursor, entry))
            return false;

        // Only add shared libraries and not the executable.
        // On Linux this is indicated by an empty path in the entry.
        // On FreeBSD it is the name of the executable.
        if (entry.path.empty() || ::strcmp(entry.path.c_str(), m_exe_path) == 0)
            continue;

        entry_list.push_back(entry);
    }

    return true;
}

addr_t
DYLDRendezvous::ReadWord(addr_t addr, uint64_t *dst, size_t size)
{
    Error error;

    *dst = m_process->ReadUnsignedIntegerFromMemory(addr, size, 0, error);
    if (error.Fail())
        return 0;

    return addr + size;
}

addr_t
DYLDRendezvous::ReadPointer(addr_t addr, addr_t *dst)
{
    Error error;

    *dst = m_process->ReadPointerFromMemory(addr, error);
    if (error.Fail())
        return 0;

    return addr + m_process->GetAddressByteSize();
}

std::string
DYLDRendezvous::ReadStringFromMemory(addr_t addr)
{
    std::string str;
    Error error;

    if (addr == LLDB_INVALID_ADDRESS)
        return std::string();

    m_process->ReadCStringFromMemory(addr, str, error);

    return str;
}

bool
DYLDRendezvous::ReadSOEntryFromMemory(lldb::addr_t addr, SOEntry &entry)
{
    entry.clear();

    entry.link_addr = addr;

    if (!(addr = ReadPointer(addr, &entry.base_addr)))
        return false;

    // mips adds an extra load offset field to the link map struct on
    // FreeBSD and NetBSD (need to validate other OSes).
    // http://svnweb.freebsd.org/base/head/sys/sys/link_elf.h?revision=217153&view=markup#l57
    const ArchSpec &arch = m_process->GetTarget().GetArchitecture();
    if (arch.GetCore() == ArchSpec::eCore_mips64)
    {
        assert (arch.GetTriple().getOS() == llvm::Triple::FreeBSD ||
                arch.GetTriple().getOS() == llvm::Triple::NetBSD);
        addr_t mips_l_offs;
        if (!(addr = ReadPointer(addr, &mips_l_offs)))
            return false;
        if (mips_l_offs != 0 && mips_l_offs != entry.base_addr)
            return false;
    }

    if (!(addr = ReadPointer(addr, &entry.path_addr)))
        return false;

    if (!(addr = ReadPointer(addr, &entry.dyn_addr)))
        return false;

    if (!(addr = ReadPointer(addr, &entry.next)))
        return false;

    if (!(addr = ReadPointer(addr, &entry.prev)))
        return false;

    entry.path = ReadStringFromMemory(entry.path_addr);

    return true;
}

bool
DYLDRendezvous::FindMetadata(const char *name, PThreadField field, uint32_t& value)
{
    Target& target = m_process->GetTarget();

    SymbolContextList list;
    if (!target.GetImages().FindSymbolsWithNameAndType (ConstString(name), eSymbolTypeAny, list))
        return false;

    Address address = list[0].symbol->GetAddress();
    addr_t addr = address.GetLoadAddress (&target);
    if (addr == LLDB_INVALID_ADDRESS)
        return false;

    Error error;
    value = (uint32_t)m_process->ReadUnsignedIntegerFromMemory(addr + field*sizeof(uint32_t), sizeof(uint32_t), 0, error);
    if (error.Fail())
        return false;

    if (field == eSize)
        value /= 8; // convert bits to bytes

    return true;
}

const DYLDRendezvous::ThreadInfo&
DYLDRendezvous::GetThreadInfo()
{
    if (!m_thread_info.valid)
    {
        bool ok = true;

        ok &= FindMetadata ("_thread_db_pthread_dtvp", eOffset, m_thread_info.dtv_offset);
        ok &= FindMetadata ("_thread_db_dtv_dtv", eSize, m_thread_info.dtv_slot_size);
        ok &= FindMetadata ("_thread_db_link_map_l_tls_modid", eOffset, m_thread_info.modid_offset);
        ok &= FindMetadata ("_thread_db_dtv_t_pointer_val", eOffset, m_thread_info.tls_offset);

        if (ok)
            m_thread_info.valid = true;
    }

    return m_thread_info;
}

void
DYLDRendezvous::DumpToLog(Log *log) const
{
    int state = GetState();

    if (!log)
        return;

    log->PutCString("DYLDRendezvous:");
    log->Printf("   Address: %" PRIx64, GetRendezvousAddress());
    log->Printf("   Version: %" PRIu64, GetVersion());
    log->Printf("   Link   : %" PRIx64, GetLinkMapAddress());
    log->Printf("   Break  : %" PRIx64, GetBreakAddress());
    log->Printf("   LDBase : %" PRIx64, GetLDBase());
    log->Printf("   State  : %s",
                (state == eConsistent) ? "consistent" :
                (state == eAdd)        ? "add"        :
                (state == eDelete)     ? "delete"     : "unknown");

    iterator I = begin();
    iterator E = end();

    if (I != E)
        log->PutCString("DYLDRendezvous SOEntries:");

    for (int i = 1; I != E; ++I, ++i)
    {
        log->Printf("\n   SOEntry [%d] %s", i, I->path.c_str());
        log->Printf("      Base : %" PRIx64, I->base_addr);
        log->Printf("      Path : %" PRIx64, I->path_addr);
        log->Printf("      Dyn  : %" PRIx64, I->dyn_addr);
        log->Printf("      Next : %" PRIx64, I->next);
        log->Printf("      Prev : %" PRIx64, I->prev);
    }
}
<|endoftext|>


<commit_before>#include "minimap.h"

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

#include "asdf_multiplat/main/asdf_multiplat.h"
#include "asdf_multiplat/data/gl_vertex_spec.h"
#include "asdf_multiplat/data/gl_state.h"

#include "ui/hex_map.h"

using namespace std;
using namespace glm;

namespace asdf
{
namespace hexmap
{
namespace ui
{
    gl_vertex_spec_<vertex_attrib::position2_t
                  , vertex_attrib::color_t> minimap_vertex_t::vertex_spec;

    minimap_t::minimap_t(ui::hex_map_t& _rendered_map)
    : rendered_map(_rendered_map)
    , map_data(_rendered_map.map_data)
    , render_target(1024, 1024)
    {
        render_target.texture.name = "minimap";
        render_target.init();
    }

    void minimap_t::rebuild()
    {
        scoped_render_target_t scoped(this->render_target);  //MSVC is making me put a this->  why?

        glClearColor(0,0,0,0);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // use glBlendFuncSeparate to allow the minimap FBO to have a transparent background
        // instead of black
        //glEnable(GL_BLEND);
        //glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

        //snapshot the camera
        auto& camera = rendered_map.camera;
        auto prev_camera = camera;

        //set camera such that the entire map will fit within the fbo when rendered
        auto grid_size = map_data.hex_grid.size_units();
        auto grid_size_d2 = grid_size / 2.0f;
        auto grid_bbox = map_data.hex_grid.bounding_box_units();

        camera.position = vec3(grid_bbox.lower + grid_size_d2, 0.0f);
        camera.viewport = viewport_for_size_aspect(grid_size, 1.0f);

        //render just the terrain (and grid outline for now)
        using flags_e = hex_map_t::render_flags_e;
        uint32_t flags = flags_e::terrain | flags_e::grid_outline;
        rendered_map.render(flags_e(flags));

        camera = prev_camera;
    }

    void minimap_t::render()
    {
        //render texture to quad
        auto const& quad = app.renderer->quad;
        auto& shader = app.renderer->screen_shader;

        GL_State->bind(shader);

        float minimap_scale_px = 400.0f;

        shader->world_matrix = scale(translate(mat4(), vec3(0, 0, 0)), vec3(minimap_scale_px));
        shader->view_matrix = mat4();

        float halfwidth = app.surface_width / 2.0f;
        float halfheight = app.surface_height / 2.0f;
        // float const& halfwidth = texture.halfwidth;
        // float const& halfheight = texture.halfheight;

        //project such that each unit is one pixel
        shader->projection_matrix = ortho<float>(-halfwidth, halfwidth,
                            -halfheight, halfheight,
                            -1000, 1000);

        shader->update_wvp_uniform();

        glBindTexture(GL_TEXTURE_2D, render_target.texture.texture_id);
        quad.render();

        //TODO: render box-outline representing current viewport
        //      ie: how much of the map is on screen based on zoom/pan
    }
}
}
}<commit_msg>minor change<commit_after>#include "minimap.h"

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>

#include "asdf_multiplat/main/asdf_multiplat.h"
#include "asdf_multiplat/data/gl_vertex_spec.h"
#include "asdf_multiplat/data/gl_state.h"

#include "ui/hex_map.h"

using namespace std;
using namespace glm;

namespace asdf
{
namespace hexmap
{
namespace ui
{
    gl_vertex_spec_<vertex_attrib::position2_t
                  , vertex_attrib::color_t> minimap_vertex_t::vertex_spec;

    minimap_t::minimap_t(ui::hex_map_t& _rendered_map)
    : rendered_map(_rendered_map)
    , map_data(_rendered_map.map_data)
    , render_target(1024, 1024)
    {
        render_target.texture.name = "minimap";
        render_target.init();
    }

    void minimap_t::rebuild()
    {
        scoped_render_target_t scoped(this->render_target);  //MSVC is making me put a this->  why?

        glClearColor(0,0,0,0);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // use glBlendFuncSeparate to allow the minimap FBO to have a transparent background
        // instead of black
        //glEnable(GL_BLEND);
        //glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

        //snapshot the camera
        auto& camera = rendered_map.camera;
        auto prev_camera = camera;

        //set camera such that the entire map will fit within the fbo when rendered
        auto grid_size = map_data.hex_grid.size_units();
        auto grid_size_d2 = grid_size / 2.0f;
        auto grid_bbox = map_data.hex_grid.bounding_box_units();

        camera.position = vec3(grid_bbox.lower + grid_size_d2, 0.0f);
        camera.viewport = viewport_for_size_aspect(grid_size, 1.0f);

        //render just the terrain (and grid outline for now)
        using flags_e = hex_map_t::render_flags_e;
        uint32_t flags = flags_e::terrain | flags_e::grid_outline;
        rendered_map.render(flags_e(flags));

        camera = prev_camera;
    }

    void minimap_t::render()
    {
        //render texture to quad
        auto const& quad = app.renderer->quad;
        auto& shader = app.renderer->screen_shader;

        GL_State->bind(shader);

        float minimap_scale_px = 400.0f;

        shader->world_matrix = scale(translate(mat4(), vec3(0, 0, 0)), vec3(minimap_scale_px));
        shader->view_matrix = mat4();

        float halfwidth = app.render_target_size().x / 2.0f;
        float halfheight = app.render_target_size().y / 2.0f;
        // float const& halfwidth = texture.halfwidth;
        // float const& halfheight = texture.halfheight;

        //project such that each unit is one pixel
        shader->projection_matrix = ortho<float>(-halfwidth, halfwidth,
                            -halfheight, halfheight,
                            -1000, 1000);

        shader->update_wvp_uniform();

        glBindTexture(GL_TEXTURE_2D, render_target.texture.texture_id);
        quad.render();

        //TODO: render box-outline representing current viewport
        //      ie: how much of the map is on screen based on zoom/pan
    }
}
}
}<|endoftext|>


<commit_before>/**
 * (c) 2019 by Mega Limited, Wellsford, New Zealand
 *
 * This file is part of the MEGA SDK - Client Access Engine.
 *
 * Applications using the MEGA API must present a valid application key
 * and comply with the the rules set forth in the Terms of Service.
 *
 * The MEGA SDK 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.
 *
 * @copyright Simplified (2-clause) BSD License.
 *
 * You should have received a copy of the license along with this
 * program.
 */

#include "utils.h"

#include <random>

#include <mega/megaapp.h>
#include <mega.h>

#include "constants.h"
#include "DefaultedFileSystemAccess.h"
#include "FsNode.h"

namespace mt {

namespace {

std::mt19937 gRandomGenerator{1};

} // anonymous

mega::handle nextFsId()
{
    static mega::handle fsId{0};
    return fsId++;
}

std::shared_ptr<mega::MegaClient> makeClient(mega::MegaApp& app, mega::FileSystemAccess& fsaccess)
{
    struct HttpIo : mega::HttpIO
    {
        void addevents(mega::Waiter*, int) override {}
        void post(struct mega::HttpReq*, const char* = NULL, unsigned = 0) override {}
        void cancel(mega::HttpReq*) override {}
        m_off_t postpos(void*) override { return {}; }
        bool doio(void) override { return {}; }
        void setuseragent(std::string*) override {}
    };

    auto httpio = new HttpIo;

    auto deleter = [httpio](mega::MegaClient* client)
    {
        delete client;
        delete httpio;
    };

    std::shared_ptr<mega::MegaClient> client{new mega::MegaClient{
            &app, nullptr, httpio, &fsaccess, nullptr, nullptr, "XXX", "unit_test", 0
        }, deleter};

    return client;
}

mega::Node& makeNode(mega::MegaClient& client, const mega::nodetype_t type, const mega::handle handle, mega::Node* const parent)
{
    assert(client.nodes.find(handle) == client.nodes.end());
    mega::node_vector dp;
    const auto ph = parent ? parent->nodehandle : mega::UNDEF;
    auto n = new mega::Node{&client, &dp, handle, ph, type, -1, mega::UNDEF, nullptr, 0}; // owned by the client
    n->setkey(reinterpret_cast<const mega::byte*>(std::string((type == mega::FILENODE) ? mega::FILENODEKEYLENGTH : mega::FOLDERNODEKEYLENGTH, 'X').c_str()));
    return *n;
}

#ifdef ENABLE_SYNC
std::unique_ptr<mega::Sync> makeSync(mega::MegaClient& client, const std::string& localname)
{
    mega::FSACCESS_CLASS fsaccess;
    std::string localdebris = gLocalDebris;
    auto& n = makeNode(client, mega::FOLDERNODE, std::hash<std::string>{}(localname));
    auto localdebrisLP = ::mega::LocalPath::fromPath(localdebris, fsaccess);
    mega::SyncConfig config{127, localname, localname, n.nodehandle, std::string(), 0};
    auto sync = new mega::Sync{&client, config,
                               nullptr, &localdebrisLP, &n, false, 0, nullptr);
    sync->state = mega::SYNC_CANCELED; // to avoid the assertion in Sync::~Sync()
    return std::unique_ptr<mega::Sync>{sync};
}

std::unique_ptr<mega::LocalNode> makeLocalNode(mega::Sync& sync, mega::LocalNode& parent,
                                               mega::nodetype_t type, const std::string& name,
                                               const mega::FileFingerprint& ffp)
{
    std::string tmpname = name;
    mega::FSACCESS_CLASS fsaccess;
    auto l = std::unique_ptr<mega::LocalNode>{new mega::LocalNode};
    auto path = parent.getLocalPath();
    path.appendWithSeparator(::mega::LocalPath::fromPath(tmpname, fsaccess), true, fsaccess.localseparator);
    l->init(&sync, type, &parent, path, sync.client->fsaccess->fsShortname(path));
    l->setfsid(nextFsId(), sync.client->fsidnode);
    static_cast<mega::FileFingerprint&>(*l) = ffp;
    return l;
}
#endif

void collectAllFsNodes(std::map<mega::LocalPath, const mt::FsNode*>& nodes, const mt::FsNode& node)
{
    const auto path = node.getPath();
    assert(nodes.find(path) == nodes.end());
    nodes[path] = &node;
    if (node.getType() == mega::FOLDERNODE)
    {
        for (const auto child : node.getChildren())
        {
            collectAllFsNodes(nodes, *child);
        }
    }
}

std::uint16_t nextRandomInt()
{
    std::uniform_int_distribution<std::uint16_t> dist{0, std::numeric_limits<std::uint16_t>::max()};
    return dist(gRandomGenerator);
}

mega::byte nextRandomByte()
{
    std::uniform_int_distribution<unsigned short> dist{0, std::numeric_limits<mega::byte>::max()};
    return static_cast<mega::byte>(dist(gRandomGenerator));
}

} // mt
<commit_msg>Fix syntax error.<commit_after>/**
 * (c) 2019 by Mega Limited, Wellsford, New Zealand
 *
 * This file is part of the MEGA SDK - Client Access Engine.
 *
 * Applications using the MEGA API must present a valid application key
 * and comply with the the rules set forth in the Terms of Service.
 *
 * The MEGA SDK 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.
 *
 * @copyright Simplified (2-clause) BSD License.
 *
 * You should have received a copy of the license along with this
 * program.
 */

#include "utils.h"

#include <random>

#include <mega/megaapp.h>
#include <mega.h>

#include "constants.h"
#include "DefaultedFileSystemAccess.h"
#include "FsNode.h"

namespace mt {

namespace {

std::mt19937 gRandomGenerator{1};

} // anonymous

mega::handle nextFsId()
{
    static mega::handle fsId{0};
    return fsId++;
}

std::shared_ptr<mega::MegaClient> makeClient(mega::MegaApp& app, mega::FileSystemAccess& fsaccess)
{
    struct HttpIo : mega::HttpIO
    {
        void addevents(mega::Waiter*, int) override {}
        void post(struct mega::HttpReq*, const char* = NULL, unsigned = 0) override {}
        void cancel(mega::HttpReq*) override {}
        m_off_t postpos(void*) override { return {}; }
        bool doio(void) override { return {}; }
        void setuseragent(std::string*) override {}
    };

    auto httpio = new HttpIo;

    auto deleter = [httpio](mega::MegaClient* client)
    {
        delete client;
        delete httpio;
    };

    std::shared_ptr<mega::MegaClient> client{new mega::MegaClient{
            &app, nullptr, httpio, &fsaccess, nullptr, nullptr, "XXX", "unit_test", 0
        }, deleter};

    return client;
}

mega::Node& makeNode(mega::MegaClient& client, const mega::nodetype_t type, const mega::handle handle, mega::Node* const parent)
{
    assert(client.nodes.find(handle) == client.nodes.end());
    mega::node_vector dp;
    const auto ph = parent ? parent->nodehandle : mega::UNDEF;
    auto n = new mega::Node{&client, &dp, handle, ph, type, -1, mega::UNDEF, nullptr, 0}; // owned by the client
    n->setkey(reinterpret_cast<const mega::byte*>(std::string((type == mega::FILENODE) ? mega::FILENODEKEYLENGTH : mega::FOLDERNODEKEYLENGTH, 'X').c_str()));
    return *n;
}

#ifdef ENABLE_SYNC
std::unique_ptr<mega::Sync> makeSync(mega::MegaClient& client, const std::string& localname)
{
    mega::FSACCESS_CLASS fsaccess;
    std::string localdebris = gLocalDebris;
    auto& n = makeNode(client, mega::FOLDERNODE, std::hash<std::string>{}(localname));
    auto localdebrisLP = ::mega::LocalPath::fromPath(localdebris, fsaccess);
    mega::SyncConfig config{127, localname, localname, n.nodehandle, std::string(), 0};
    auto sync = new mega::Sync{&client, config, nullptr, &localdebrisLP, &n, false, 0, nullptr};
    sync->state = mega::SYNC_CANCELED; // to avoid the assertion in Sync::~Sync()
    return std::unique_ptr<mega::Sync>{sync};
}

std::unique_ptr<mega::LocalNode> makeLocalNode(mega::Sync& sync, mega::LocalNode& parent,
                                               mega::nodetype_t type, const std::string& name,
                                               const mega::FileFingerprint& ffp)
{
    std::string tmpname = name;
    mega::FSACCESS_CLASS fsaccess;
    auto l = std::unique_ptr<mega::LocalNode>{new mega::LocalNode};
    auto path = parent.getLocalPath();
    path.appendWithSeparator(::mega::LocalPath::fromPath(tmpname, fsaccess), true, fsaccess.localseparator);
    l->init(&sync, type, &parent, path, sync.client->fsaccess->fsShortname(path));
    l->setfsid(nextFsId(), sync.client->fsidnode);
    static_cast<mega::FileFingerprint&>(*l) = ffp;
    return l;
}
#endif

void collectAllFsNodes(std::map<mega::LocalPath, const mt::FsNode*>& nodes, const mt::FsNode& node)
{
    const auto path = node.getPath();
    assert(nodes.find(path) == nodes.end());
    nodes[path] = &node;
    if (node.getType() == mega::FOLDERNODE)
    {
        for (const auto child : node.getChildren())
        {
            collectAllFsNodes(nodes, *child);
        }
    }
}

std::uint16_t nextRandomInt()
{
    std::uniform_int_distribution<std::uint16_t> dist{0, std::numeric_limits<std::uint16_t>::max()};
    return dist(gRandomGenerator);
}

mega::byte nextRandomByte()
{
    std::uniform_int_distribution<unsigned short> dist{0, std::numeric_limits<mega::byte>::max()};
    return static_cast<mega::byte>(dist(gRandomGenerator));
}

} // mt
<|endoftext|>