<commit_before>/*************************************************************************
 *
 *  $RCSfile: AccessiblePresentationShape.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: af $ $Date: 2002-02-08 17:01:09 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SD_ACCESSIBILITY_ACCESSIBLE_PRESENTATION_SHAPE_HXX
#define _SD_ACCESSIBILITY_ACCESSIBLE_PRESENTATION_SHAPE_HXX

#ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_SHAPE_HXX
#include <svx/AccessibleShape.hxx>
#endif

namespace accessibility {

/** This class makes Impress shapes accessible.
*/
class AccessiblePresentationShape
    :   public AccessibleShape
{
public:
    //=====  internal  ========================================================
    AccessiblePresentationShape (const ::com::sun::star::uno::Reference<
        ::com::sun::star::drawing::XShape>& rxShape,
        const ::com::sun::star::uno::Reference<
        ::drafts::com::sun::star::accessibility::XAccessible>& rxParent);
    virtual ~AccessiblePresentationShape (void);

    //=====  XServiceInfo  ====================================================

    /** Returns an identifier for the implementation of this object.
    */
    virtual ::rtl::OUString SAL_CALL
        getImplementationName (void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Create a name string that contains the accessible name.
    virtual ::rtl::OUString
        createAccessibleName ()
        throw (::com::sun::star::uno::RuntimeException);

    /// Create a description string that contains the accessible description.
    virtual ::rtl::OUString
        createAccessibleDescription ()
        throw (::com::sun::star::uno::RuntimeException);
};

} // end of namespace accessibility

#endif
<commit_msg>#95585# Name and description generation changed.<commit_after>/*************************************************************************
 *
 *  $RCSfile: AccessiblePresentationShape.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: af $ $Date: 2002-03-06 16:58:24 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SD_ACCESSIBILITY_ACCESSIBLE_PRESENTATION_SHAPE_HXX
#define _SD_ACCESSIBILITY_ACCESSIBLE_PRESENTATION_SHAPE_HXX

#ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_SHAPE_HXX
#include <svx/AccessibleShape.hxx>
#endif

namespace accessibility {

/** This class makes Impress shapes accessible.
*/
class AccessiblePresentationShape
    :   public AccessibleShape
{
public:
    //=====  internal  ========================================================
    AccessiblePresentationShape (const ::com::sun::star::uno::Reference<
        ::com::sun::star::drawing::XShape>& rxShape,
        const ::com::sun::star::uno::Reference<
        ::drafts::com::sun::star::accessibility::XAccessible>& rxParent);
    virtual ~AccessiblePresentationShape (void);

    //=====  XServiceInfo  ====================================================

    /** Returns an identifier for the implementation of this object.
    */
    virtual ::rtl::OUString SAL_CALL
        getImplementationName (void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Create a name string that contains the accessible name.
    virtual ::rtl::OUString SAL_CALL
        createAccessibleBaseName ()
        throw (::com::sun::star::uno::RuntimeException);

    /// Create a description string that contains the accessible description.
    virtual ::rtl::OUString SAL_CALL
        createAccessibleDescription ()
        throw (::com::sun::star::uno::RuntimeException);
};

} // end of namespace accessibility

#endif
<|endoftext|>


<commit_before>/*******************************************************************************
* E.S.O. - ACS project
*
* "@(#) $Id: maciTestClassImpl.cpp,v 1.95 2006/10/19 15:14:03 bjeram Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* bjeram 2002-11-28 added IDL:ALMA/MACI_TEST/ .... :1.0 to COB's type
* msekoran 2002-07-05 added hierachical COB test
* rlemke   2001-08-05 integrated with new MACI
* rlemke   2001-03-20 created from MaciTestClass
* gchiozzi 2001-02-15 Added real implementation for method descriptor()
* gchiozzi 2001-02-15 Added body of get_interface() method for Object Explorer
* gchiozzi 2001-02-15 created standard header
*/

#include <vltPort.h>

static char *rcsId="@(#) $Id: maciTestClassImpl.cpp,v 1.95 2006/10/19 15:14:03 bjeram Exp $";
static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);

#include <logging.h>
#include <maciTestClassImpl.h>
#include <maciContainerImpl.h>
#include <maciContainerServices.h>

 using namespace maci;

/////////////////////////////////////////////////
// MaciTestClass
/////////////////////////////////////////////////

MaciTestClass::MaciTestClass(
    const ACE_CString& name,
    maci::ContainerServices* containerServices) :
    acscomponent::ACSComponentImpl(name,containerServices),
  m_initialization(1), m_name(name)

{
  ACS_SHORT_LOG((LM_INFO,
                 "::MaciTestClass::MaciTestClass(%s)", m_name.c_str()));

  // simulate component failing initialization (e.g. w/o required configuration)
  if (ACE_OS::strcmp(name.c_str(), "MACI_FAKE") == 0)
      return;

  // Initialization successful
  m_initialization = 0;

}

MaciTestClass::~MaciTestClass()
{
  ACS_SHORT_LOG((LM_INFO,
                 "::MaciTestClass::~MaciTestClass(%s)", m_name.c_str()));
}

/* ----------------------------------------------------------------*/
/* --------------------- [ CORBA interface ] ----------------------*/
/* ----------------------------------------------------------------*/

CORBA::Boolean
MaciTestClass::test ()
  throw (CORBA::SystemException)
{
  ACS_SHORT_LOG((LM_INFO, "MaciTestClass::test(%s)", m_name.c_str()));
  // do some tests here
  return true;
}

CORBA::Object_ptr
MaciTestClass::get_component (
    const char *cob_url,
    CORBA::Boolean activate
    )
  throw (CORBA::SystemException)
{
  ACS_SHORT_LOG((LM_INFO, "MaciTestClass::get_component(%s,%s)",
                 m_name.c_str(), cob_url));
  return CORBA::Object::_nil();
}

CORBA::Long
MaciTestClass::release_component(
    const char *cob_url
    )
  throw (CORBA::SystemException)
{
  ACS_SHORT_LOG((LM_INFO, "MaciTestClass::release_component(%s, %s)",
                 m_name.c_str(), cob_url));
  return -1;
}

/////////////////////////////////////////////////
// MaciHierarchicalTestClass
/////////////////////////////////////////////////

MaciHierarchicalTestClass::MaciHierarchicalTestClass(
    const ACE_CString& name,
    maci::ContainerServices* containerServices) :
    acscomponent::ACSComponentImpl(name,containerServices), MaciTestClass(name, containerServices)

{
  // failure in super class
  if (m_initialization)
      return;

  // reset
  m_initialization = 1;

  ACS_SHORT_LOG((LM_INFO,
                 "::MaciHierarchicalTestClass::MaciHierarchicalTestClass(%s)", m_name.c_str()));

/*  CORBA::Object_var obj = ContainerImpl::getContainer()->get_object("MACI_SUB",0,true);

  if (CORBA::is_nil(obj.in()))
    {
      ACS_SHORT_LOG((LM_INFO,
		     "::MaciHierarchicalTestClass::MaciHierarchicalTestClass(%s) Failed to obtain SUBComponent reference.",
		     m_name.c_str()));
      return;
    }
*/
  // Initialization successful
  m_initialization = 0;

}

void MaciHierarchicalTestClass::execute() throw (acsErrTypeLifeCycle::LifeCycleExImpl)
{

    MACI_TEST::MaciTestClass_var obj =
	getContainerServices()->getComponent<MACI_TEST::MaciTestClass>("MACI_SUB");

    if (CORBA::is_nil(obj.in()))
	{
	ACS_SHORT_LOG((LM_INFO,
		       "::MaciHierarchicalTestClass(%s)::execute Failed to obtain SUBComponent reference.",
		       m_name.c_str()));
	}

}

MaciHierarchicalTestClass::~MaciHierarchicalTestClass()
{
  // release component !!!
    if (m_initialization==0);

    ACS_SHORT_LOG((LM_INFO,
                 "::MaciTHierarchicalestClass::~MaciHierarchicalTestClass(%s)", m_name.c_str()));
}

/////////////////////////////////////////////////
// MaciTestConstructableClass
/////////////////////////////////////////////////
/*
MaciTestConstructableClass::MaciTestConstructableClass(PortableServer::POA_ptr poa,
						       const ACE_CString& name)
    : m_poa(PortableServer::POA::_duplicate(poa)), m_name(name), m_initialization(1)
{
  ACS_SHORT_LOG((LM_INFO,
                 "::MaciTestConstructableClass::MaciTestConstructableClass(%s)",
                 m_name.c_str()));

  // Initialization successful
  m_initialization = 0;

}

MaciTestConstructableClass::~MaciTestConstructableClass()
{
  ACS_SHORT_LOG((LM_INFO,
                 "::MaciTestConstructableClass::~MaciTestConstructableClass(%s)",
                 m_name.c_str()));
}
*/
/* ----------------------------------------------------------------*/
/* --------------------- [ CORBA interface ] ----------------------*/
/* ----------------------------------------------------------------*/
/*
void
MaciTestConstructableClass::construct ()
  throw (CORBA::SystemException)
{
  ACS_SHORT_LOG((LM_INFO, "MaciTestConstructableClass::construct"));
}

void
MaciTestConstructableClass::destruct ()
  throw (CORBA::SystemException)
{
  ACS_SHORT_LOG((LM_INFO, "MaciTestConstructableClass::destruct"));
}

CORBA::Object_ptr
MaciTestConstructableClass::get_component (
    const char *cob_url,
    CORBA::Boolean activate,
    CORBA::ULong &status
  throw (CORBA::SystemException)
{
  ACS_SHORT_LOG((LM_INFO, "MaciTestConstructableClass::get_component"));
//  return MaciTestClass::get_component(cob_url, activate, status);
  return CORBA::Object::_nil();
}

CORBA::Long
MaciTestConstructableClass::release_component(
    const char *cob_url
  throw (CORBA::SystemException)
{
  ACS_SHORT_LOG((LM_INFO, "MaciTestConstructableClass::release_component"));
//  return MaciTestClass::release_component(cob_url);
  return 0;
}
*/
/////////////////////////////////////////////////
// MACI DLL support functions
/////////////////////////////////////////////////

ACS_DLL_UNMANGLED_EXPORT PortableServer::Servant
ConstructComponent(CORBA::ULong h,
             const char * name,
             const char * type,
             maci::ContainerServices * containerServices)
{
  ACS_SHORT_LOG((LM_INFO, "ConstructComponent(%08x, %s, %s)", h, name, type));

  if (strcmp(type, "IDL:alma/MACI_TEST/MaciTestClass:1.0") == 0)
    {
      MaciTestClass * mtc = new MaciTestClass(name,containerServices);
      if (!mtc || mtc->initialization())
	{
	  ACS_LOG(LM_RUNTIME_CONTEXT, "maciTestClassImpl::ConstructComponent",
		  (LM_ERROR, "Failed to create/initialize component: '%s'", name));
	  if (mtc)
	      mtc->_remove_ref();
	  throw ACSErrTypeCommon::CouldntCreateObjectExImpl(__FILE__, __LINE__,
							    "maciTestClassImpl::ConstructComponent");
	}
      else
	  return mtc;
    }
/*
  else if (strcmp(type, "IDL:alma/MACI_TEST/MaciTestConstructableClass:1.0") == 0)
    {
      MaciTestConstructableClass * mtcc = new MaciTestConstructableClass(poa, name);
      if (!mtcc || mtcc->initialization())
	{
	  ACS_LOG(LM_RUNTIME_CONTEXT, "maciTestClassImpl::ConstructComponent",
		  (LM_ERROR, "Failed to create/initialize component: '%s'", name));
	  if (mtcc)
	      mtcc->_remove_ref();
	  return 0;
	}
      else
	  return mtcc;
    }
*/
  else if (strcmp(type, "IDL:alma/MACI_TEST/MaciHierarchicalTestClass:1.0") == 0)
    {
      MaciHierarchicalTestClass * mhtc = new MaciHierarchicalTestClass(name,containerServices);
      if (!mhtc || mhtc->initialization())
	{
	  ACS_LOG(LM_RUNTIME_CONTEXT, "maciTestClassImpl::ConstructComponent",
		  (LM_ERROR, "Failed to create/initialize component: '%s'", name));
	  if (mhtc)
	      mhtc->_remove_ref();
	  return 0;
	}
      else
	  return mhtc;
    }
  else
    {
      ACS_LOG(LM_RUNTIME_CONTEXT, "maciTestClassImpl::ConstructComponent",
              (LM_ERROR, "Unknown component type: '%s'", type));
      return 0;
    }
}

ACS_DLL_UNMANGLED_EXPORT bool DLLOpen(int, char**)
{
  ACS_SHORT_LOG((LM_INFO, "maciTestClassImpl::DLLOpen"));
  return true;
}

ACS_DLL_UNMANGLED_EXPORT void DLLClose()
{
  ACS_SHORT_LOG((LM_INFO, "maciTestClassImpl::DLLClose"));
}

<commit_msg>in case of an error an exception is thrown rather than returning 0<commit_after>/*******************************************************************************
* E.S.O. - ACS project
*
* "@(#) $Id: maciTestClassImpl.cpp,v 1.96 2006/10/20 09:12:13 bjeram Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* bjeram 2002-11-28 added IDL:ALMA/MACI_TEST/ .... :1.0 to COB's type
* msekoran 2002-07-05 added hierachical COB test
* rlemke   2001-08-05 integrated with new MACI
* rlemke   2001-03-20 created from MaciTestClass
* gchiozzi 2001-02-15 Added real implementation for method descriptor()
* gchiozzi 2001-02-15 Added body of get_interface() method for Object Explorer
* gchiozzi 2001-02-15 created standard header
*/

#include <vltPort.h>

static char *rcsId="@(#) $Id: maciTestClassImpl.cpp,v 1.96 2006/10/20 09:12:13 bjeram Exp $";
static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId);

#include <logging.h>
#include <maciTestClassImpl.h>
#include <maciContainerImpl.h>
#include <maciContainerServices.h>

 using namespace maci;

/////////////////////////////////////////////////
// MaciTestClass
/////////////////////////////////////////////////

MaciTestClass::MaciTestClass(
    const ACE_CString& name,
    maci::ContainerServices* containerServices) :
    acscomponent::ACSComponentImpl(name,containerServices),
  m_initialization(1), m_name(name)

{
  ACS_SHORT_LOG((LM_INFO,
                 "::MaciTestClass::MaciTestClass(%s)", m_name.c_str()));

  // simulate component failing initialization (e.g. w/o required configuration)
  if (ACE_OS::strcmp(name.c_str(), "MACI_FAKE") == 0)
      return;

  // Initialization successful
  m_initialization = 0;

}

MaciTestClass::~MaciTestClass()
{
  ACS_SHORT_LOG((LM_INFO,
                 "::MaciTestClass::~MaciTestClass(%s)", m_name.c_str()));
}

/* ----------------------------------------------------------------*/
/* --------------------- [ CORBA interface ] ----------------------*/
/* ----------------------------------------------------------------*/

CORBA::Boolean
MaciTestClass::test ()
  throw (CORBA::SystemException)
{
  ACS_SHORT_LOG((LM_INFO, "MaciTestClass::test(%s)", m_name.c_str()));
  // do some tests here
  return true;
}

CORBA::Object_ptr
MaciTestClass::get_component (
    const char *cob_url,
    CORBA::Boolean activate
    )
  throw (CORBA::SystemException)
{
  ACS_SHORT_LOG((LM_INFO, "MaciTestClass::get_component(%s,%s)",
                 m_name.c_str(), cob_url));
  return CORBA::Object::_nil();
}

CORBA::Long
MaciTestClass::release_component(
    const char *cob_url
    )
  throw (CORBA::SystemException)
{
  ACS_SHORT_LOG((LM_INFO, "MaciTestClass::release_component(%s, %s)",
                 m_name.c_str(), cob_url));
  return -1;
}

/////////////////////////////////////////////////
// MaciHierarchicalTestClass
/////////////////////////////////////////////////

MaciHierarchicalTestClass::MaciHierarchicalTestClass(
    const ACE_CString& name,
    maci::ContainerServices* containerServices) :
    acscomponent::ACSComponentImpl(name,containerServices), MaciTestClass(name, containerServices)

{
  // failure in super class
  if (m_initialization)
      return;

  // reset
  m_initialization = 1;

  ACS_SHORT_LOG((LM_INFO,
                 "::MaciHierarchicalTestClass::MaciHierarchicalTestClass(%s)", m_name.c_str()));

/*  CORBA::Object_var obj = ContainerImpl::getContainer()->get_object("MACI_SUB",0,true);

  if (CORBA::is_nil(obj.in()))
    {
      ACS_SHORT_LOG((LM_INFO,
		     "::MaciHierarchicalTestClass::MaciHierarchicalTestClass(%s) Failed to obtain SUBComponent reference.",
		     m_name.c_str()));
      return;
    }
*/
  // Initialization successful
  m_initialization = 0;

}

void MaciHierarchicalTestClass::execute() throw (acsErrTypeLifeCycle::LifeCycleExImpl)
{

    MACI_TEST::MaciTestClass_var obj =
	getContainerServices()->getComponent<MACI_TEST::MaciTestClass>("MACI_SUB");

    if (CORBA::is_nil(obj.in()))
	{
	ACS_SHORT_LOG((LM_INFO,
		       "::MaciHierarchicalTestClass(%s)::execute Failed to obtain SUBComponent reference.",
		       m_name.c_str()));
	}

}

MaciHierarchicalTestClass::~MaciHierarchicalTestClass()
{
  // release component !!!
    if (m_initialization==0);

    ACS_SHORT_LOG((LM_INFO,
                 "::MaciTHierarchicalestClass::~MaciHierarchicalTestClass(%s)", m_name.c_str()));
}

/////////////////////////////////////////////////
// MaciTestConstructableClass
/////////////////////////////////////////////////
/*
MaciTestConstructableClass::MaciTestConstructableClass(PortableServer::POA_ptr poa,
						       const ACE_CString& name)
    : m_poa(PortableServer::POA::_duplicate(poa)), m_name(name), m_initialization(1)
{
  ACS_SHORT_LOG((LM_INFO,
                 "::MaciTestConstructableClass::MaciTestConstructableClass(%s)",
                 m_name.c_str()));

  // Initialization successful
  m_initialization = 0;

}

MaciTestConstructableClass::~MaciTestConstructableClass()
{
  ACS_SHORT_LOG((LM_INFO,
                 "::MaciTestConstructableClass::~MaciTestConstructableClass(%s)",
                 m_name.c_str()));
}
*/
/* ----------------------------------------------------------------*/
/* --------------------- [ CORBA interface ] ----------------------*/
/* ----------------------------------------------------------------*/
/*
void
MaciTestConstructableClass::construct ()
  throw (CORBA::SystemException)
{
  ACS_SHORT_LOG((LM_INFO, "MaciTestConstructableClass::construct"));
}

void
MaciTestConstructableClass::destruct ()
  throw (CORBA::SystemException)
{
  ACS_SHORT_LOG((LM_INFO, "MaciTestConstructableClass::destruct"));
}

CORBA::Object_ptr
MaciTestConstructableClass::get_component (
    const char *cob_url,
    CORBA::Boolean activate,
    CORBA::ULong &status
  throw (CORBA::SystemException)
{
  ACS_SHORT_LOG((LM_INFO, "MaciTestConstructableClass::get_component"));
//  return MaciTestClass::get_component(cob_url, activate, status);
  return CORBA::Object::_nil();
}

CORBA::Long
MaciTestConstructableClass::release_component(
    const char *cob_url
  throw (CORBA::SystemException)
{
  ACS_SHORT_LOG((LM_INFO, "MaciTestConstructableClass::release_component"));
//  return MaciTestClass::release_component(cob_url);
  return 0;
}
*/
/////////////////////////////////////////////////
// MACI DLL support functions
/////////////////////////////////////////////////

ACS_DLL_UNMANGLED_EXPORT PortableServer::Servant
ConstructComponent(CORBA::ULong h,
             const char * name,
             const char * type,
             maci::ContainerServices * containerServices)
{
  ACS_SHORT_LOG((LM_INFO, "ConstructComponent(%08x, %s, %s)", h, name, type));

  if (strcmp(type, "IDL:alma/MACI_TEST/MaciTestClass:1.0") == 0)
    {
      MaciTestClass * mtc = new MaciTestClass(name,containerServices);
      if (!mtc || mtc->initialization())
	{
	  ACS_LOG(LM_RUNTIME_CONTEXT, "maciTestClassImpl::ConstructComponent",
		  (LM_ERROR, "Failed to create/initialize component: '%s'", name));
	  if (mtc)
	      mtc->_remove_ref();
	  throw ACSErrTypeCommon::CouldntCreateObjectExImpl(__FILE__, __LINE__,
							    "maciTestClassImpl::ConstructComponent");
	}
      else
	  return mtc;
    }
  else if (strcmp(type, "IDL:alma/MACI_TEST/MaciHierarchicalTestClass:1.0") == 0)
    {
      MaciHierarchicalTestClass * mhtc = new MaciHierarchicalTestClass(name,containerServices);
      if (!mhtc || mhtc->initialization())
	{
	  ACS_LOG(LM_RUNTIME_CONTEXT, "maciTestClassImpl::ConstructComponent",
		  (LM_ERROR, "Failed to create/initialize component: '%s'", name));
	  if (mhtc)
	      mhtc->_remove_ref();
	  throw ACSErrTypeCommon::CouldntCreateObjectExImpl(__FILE__, __LINE__,
							    "maciTestClassImpl::ConstructComponent");
	}
      else
	  return mhtc;
    }
  else
    {
      ACS_LOG(LM_RUNTIME_CONTEXT, "maciTestClassImpl::ConstructComponent",
              (LM_ERROR, "Unknown component type: '%s'", type));
      	  return 0;
	  throw ACSErrTypeCommon::CouldntCreateObjectExImpl(__FILE__, __LINE__,
							    "maciTestClassImpl::ConstructComponent");
    }
}

ACS_DLL_UNMANGLED_EXPORT bool DLLOpen(int, char**)
{
  ACS_SHORT_LOG((LM_INFO, "maciTestClassImpl::DLLOpen"));
  return true;
}

ACS_DLL_UNMANGLED_EXPORT void DLLClose()
{
  ACS_SHORT_LOG((LM_INFO, "maciTestClassImpl::DLLClose"));
}

<|endoftext|>


<commit_before>/***********
AUTHORS:   Michael Katelman, Vijay Ganesh, Dan Liew

BEGIN DATE: Oct, 2008

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
**********************/

// g++ -DEXT_HASH_MAP <this-filename> -I/home/vganesh/stp/c_interface
// -L/home/vganesh/stp/lib -lstp -o cc
#include <gtest/gtest.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "stp/c_interface.h"

// FIXME: This test name sucks!
TEST(stpcheck, one)
{

  VC vc = vc_createValidityChecker();
  vc_setFlags(vc, 'n');
  vc_setFlags(vc, 'd');

  // 8-bit variable 'x'
  Expr x = vc_varExpr(vc, "x", vc_bvType(vc, 8));

  // 32 bit constant value 1
  Expr one = vc_bvConstExprFromInt(vc, 32, 1);

  // 24 bit constant value 0
  Expr bit24_zero = vc_bvConstExprFromInt(vc, 24, 0);
  // 32 bit constant value 0
  Expr bit32_zero = vc_bvConstExprFromInt(vc, 32, 0);

  // Extending 8-bit variable to 32-bit value
  Expr zero_concat_x = vc_bvConcatExpr(vc, bit24_zero, x);
  Expr xp1 = vc_bvPlusExpr(vc, 32, zero_concat_x, one);

  // Insteading of concat operation, I also tried with SignExtend
  // Expr signextend_x=vc_bvSignExtend(vc,x,32);
  // Expr xp1=vc_bvPlusExpr(vc,32,signextend_x,one);

  // x+1=0
  Expr eq = vc_eqExpr(vc, xp1, bit32_zero);

  // x+1!=0
  eq = vc_notExpr(vc, eq);

  vc_query(vc, eq);
  vc_printCounterExample(vc);
  // FIXME: Actually test something
  // ASSERT_TRUE(false && "FIXME: Actually test something");
}
<commit_msg>Removing useless comment<commit_after>/***********
AUTHORS:   Michael Katelman, Vijay Ganesh, Dan Liew

BEGIN DATE: Oct, 2008

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
**********************/

#include <gtest/gtest.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "stp/c_interface.h"

// FIXME: This test name sucks!
TEST(stpcheck, one)
{

  VC vc = vc_createValidityChecker();
  vc_setFlags(vc, 'n');
  vc_setFlags(vc, 'd');

  // 8-bit variable 'x'
  Expr x = vc_varExpr(vc, "x", vc_bvType(vc, 8));

  // 32 bit constant value 1
  Expr one = vc_bvConstExprFromInt(vc, 32, 1);

  // 24 bit constant value 0
  Expr bit24_zero = vc_bvConstExprFromInt(vc, 24, 0);
  // 32 bit constant value 0
  Expr bit32_zero = vc_bvConstExprFromInt(vc, 32, 0);

  // Extending 8-bit variable to 32-bit value
  Expr zero_concat_x = vc_bvConcatExpr(vc, bit24_zero, x);
  Expr xp1 = vc_bvPlusExpr(vc, 32, zero_concat_x, one);

  // Insteading of concat operation, I also tried with SignExtend
  // Expr signextend_x=vc_bvSignExtend(vc,x,32);
  // Expr xp1=vc_bvPlusExpr(vc,32,signextend_x,one);

  // x+1=0
  Expr eq = vc_eqExpr(vc, xp1, bit32_zero);

  // x+1!=0
  eq = vc_notExpr(vc, eq);

  vc_query(vc, eq);
  vc_printCounterExample(vc);
  // FIXME: Actually test something
  // ASSERT_TRUE(false && "FIXME: Actually test something");
}
<|endoftext|>


<commit_before>/// HEADER
#include <csapex/view/widgets/profiling_widget.h>

/// COMPONENT
#include <csapex/profiling/timer.h>
#include <csapex/core/settings.h>
#include <csapex/view/utility/color.hpp>
#include <csapex/utility/assert.h>

/// SYSTEM
#include <QPainter>
#include <QBoxLayout>
#include <QGraphicsProxyWidget>
#include <QPushButton>
#include <QFileDialog>
#include <fstream>
#include <functional>

using namespace csapex;

ProfilingWidget::ProfilingWidget(std::shared_ptr<Profiler> profiler, const std::string& profile, QWidget *parent)
    : QWidget(parent),
      profiler_(profiler), profile_(profile),
      space_for_painting_(nullptr)
{
    apex_assert_hard(!profile_.empty());

    int min_w = 300;
    bar_height_ = 80;

    left_space = 50;
    padding = 5;
    line_height = 14.f;

    setMinimumHeight(200);

    layout_ = new QVBoxLayout;
    setLayout(layout_);

    space_for_painting_ = new QSpacerItem(min_w, bar_height_);
    layout_->addItem(space_for_painting_);

    auto* buttons_layout = new QHBoxLayout;

    QPushButton* reset = new QPushButton("reset");
    buttons_layout->addWidget(reset);
    connect(reset, &QPushButton::clicked, this, &ProfilingWidget::reset);

    QPushButton* export_csv = new QPushButton("export");
    buttons_layout->addWidget(export_csv);
    connect(export_csv, &QPushButton::clicked, this, &ProfilingWidget::exportCsv);

    layout_->addLayout(buttons_layout);

    profiler_->getProfile(profile_).getTimer()->finished.connect([this](Interval::Ptr) { update(); });
}

ProfilingWidget::~ProfilingWidget()
{
}

void ProfilingWidget::reset()
{
    profiler_->reset();
}

void ProfilingWidget::exportCsv()
{
    QString filename = QFileDialog::getSaveFileName(0, "Save CSV File", "", "*.csv", 0, QFileDialog::DontUseNativeDialog);

    if(!filename.isEmpty()) {
        std::ofstream of(filename.toStdString());

        const Profile& profile = profiler_->getProfile(profile_);

        for(std::map<std::string, QColor>::const_iterator it = steps_.begin(); it != steps_.end(); ++it) {
            const std::string& name = it->first;

            ProfilerStats stats = profile.getStats(name);

            of << name << "," << stats.mean << "," << stats.stddev << "\n";
        }
    }
}

void ProfilingWidget::paintEvent(QPaintEvent *)
{
    apex_assert_hard(!profile_.empty());

    // update stats
    QPainter p(this);

    int w = width();
    int h = space_for_painting_->geometry().height();

    left = padding + left_space;
    right = w - padding;
    up = padding;
    bottom = h - 2 * padding - 2 * line_height - line_height * steps_.size();

    bar_height_ = bottom - padding;

    const Profile& profile = profiler_->getProfile(profile_);

    std::size_t history_length = profile.size();

    content_width_ = right - left - 2 * padding;
    indiv_width_ = content_width_ / history_length;
    content_height_ = bottom - up - 2 * padding;

    int n = history_length;

    double max_time_ms = 10;

    for(const auto& interval : profile.getIntervals()) {
        if(!interval) {
            continue;
        }

        max_time_ms = std::max(max_time_ms, interval->lengthMs());

        std::vector<std::pair<std::string, double> > names;
        interval->entries(names);
        for(auto it = names.begin(); it != names.end(); ++it) {
            const std::string& name = it->first;
            std::map<std::string, QColor>::iterator pos = steps_.find(name);
            if(pos == steps_.end()) {
                steps_[name] = color::fromCount<QColor>(steps_.size()).light();
            }
        }
    }

    // background
    QRect rect = contentsRect().adjusted(0,0,-1,-1);

    p.setBrush(QBrush(QColor(20, 20, 20)));
    p.setPen(QPen(Qt::white));
    p.setOpacity(0.6);

    p.drawRect(rect);

    // x-axis
    p.setOpacity(1.0);
    p.setPen(QPen(Qt::black));
    p.drawLine(left, bottom, right, bottom);

    // y-axis
    p.drawLine(left, bottom, left, up);

    int current_index = profile.getCurrentIndex();
    if(history_length == 0) {
        // no entries
        QFont font = p.font();
        font.setPixelSize(line_height * 2);
        p.setFont(font);
        p.setPen(QColor(0, 0, 0));
        p.drawText(rect.adjusted(left, 0, 0, 0), Qt::AlignCenter, "no data");
        return;
    }

    // bars
    if(n > 0) {
        std::stringstream txt;
        txt << max_time_ms << " ms";

        QFont font;
        font.setPixelSize(12);
        p.setFont(font);

        QFontMetrics metrics(font);

        float dy = metrics.height();

        QTextOption opt(Qt::AlignRight);

        p.setPen(QPen(QColor(20, 20, 20)));
        p.drawText(QRect(0, up, left -padding, dy), txt.str().c_str(), opt);
        p.drawText(QRect(0, bottom - dy, left - padding, dy), "0 ms", opt);

        max_time_ms_ = std::max(1.0, max_time_ms);

        current_draw_x = left + padding + (history_length - n) * indiv_width_;
        for(int time = 0; time < n; ++time) {

            static const float min_opacity = 0.25f;

            float op = ((time - current_index + n - 1) % n) / (float) n;
            p.setOpacity(min_opacity + op * (1.0f - min_opacity));

            const Interval::Ptr& interval = profile.getInterval(time);

            if(interval) {
                paintInterval(p, *interval);
            }
        }
    }

    // time line
    p.setOpacity(0.8);
    float pos = left + padding + (current_index+1) * indiv_width_;
    QPen pen(QColor(255, 20, 20));
    pen.setWidth(3);
    p.setPen(pen);
    p.drawLine(pos, bottom, pos, up);

    // legend
    p.setOpacity(1.0);
    float y = bottom;
    float text_x = left_space + 2*padding;
    float text_w = (w - text_x) / 2.0f - padding;
    float info_w = w - text_w - text_x;
    float info_x = text_x + text_w + padding;

    // label
    QFont font = p.font();
    font.setPixelSize(line_height * 0.8);
    p.setFont(font);
    p.setPen(QColor(0, 0, 0));
    p.drawText(QRectF(text_x, y, text_w, line_height), "name");
    p.drawText(QRectF(info_x , y, info_w / 2.0f, line_height), "mean");
    p.drawText(QRectF(info_x + info_w / 2.0f, y, info_w / 2.0f, line_height), "stddev");
    y += line_height;
    std::stringstream ss;
    ss << "(" << profile.count() << " frames, [ms])";
    p.drawText(QRectF(info_x, y, info_w, line_height), QString::fromStdString(ss.str()));
    y += line_height;

    // stats
    for(std::map<std::string, QColor>::const_iterator it = steps_.begin(); it != steps_.end(); ++it) {
        const std::string& name = it->first;
        QBrush brush(it->second);
        QPen pen(brush, 2);
        p.setPen(pen);
        p.fillRect(QRectF(text_x - 2*padding - line_height, y, line_height, line_height), it->second);
        p.drawText(QRectF(text_x, y, text_w, line_height), QString::fromStdString(name));

        ProfilerStats stats = profile.getStats(name);

        p.drawText(QRectF(info_x, y, info_w / 2.0f, line_height), QString::number(stats.mean));
        p.drawText(QRectF(info_x + info_w / 2.0f, y, info_w / 2.0f, line_height), QString::number(stats.stddev));
        y += line_height;
    }

    // resize to fit content
    if(space_for_painting_->geometry().height() != y) {
        space_for_painting_->changeSize(0, y, QSizePolicy::MinimumExpanding,  QSizePolicy::MinimumExpanding);
        layout()->invalidate();
    }
}

void ProfilingWidget::paintInterval(QPainter& p, const Interval& interval)
{
    paintInterval(p, interval, 0, 0);

    current_draw_x += indiv_width_;
}

float ProfilingWidget::paintInterval(QPainter& p, const Interval& interval, float height_offset, int depth)
{
    float interval_time = interval.lengthMs();

    float f = interval_time / max_time_ms_;
    f = std::max(0.0f, std::min(1.0f, f));
    float height = f * content_height_;

    p.setBrush(QBrush(steps_[interval.name()]));

    float w = indiv_width_ / (depth+1);
    p.drawRect(QRectF(current_draw_x + indiv_width_ - w, bottom - height - height_offset, w, height));

    float h = height_offset;
    for(auto sub = interval.sub.begin(); sub != interval.sub.end(); ++sub) {
        const Interval::Ptr& sub_interval = sub->second;
        h += paintInterval(p, *sub_interval, h, depth + 1);
    }

    return height;
}
/// MOC
#include "../../../include/csapex/view/widgets/moc_profiling_widget.cpp"
<commit_msg>Fixes #94: Fixes profiling widget connection not being disconnected<commit_after>/// HEADER
#include <csapex/view/widgets/profiling_widget.h>

/// COMPONENT
#include <csapex/profiling/timer.h>
#include <csapex/core/settings.h>
#include <csapex/view/utility/color.hpp>
#include <csapex/utility/assert.h>

/// SYSTEM
#include <QPainter>
#include <QBoxLayout>
#include <QGraphicsProxyWidget>
#include <QPushButton>
#include <QFileDialog>
#include <fstream>
#include <functional>

using namespace csapex;

ProfilingWidget::ProfilingWidget(std::shared_ptr<Profiler> profiler, const std::string& profile, QWidget *parent)
    : QWidget(parent),
      profiler_(profiler), profile_(profile),
      space_for_painting_(nullptr)
{
    apex_assert_hard(!profile_.empty());

    int min_w = 300;
    bar_height_ = 80;

    left_space = 50;
    padding = 5;
    line_height = 14.f;

    setMinimumHeight(200);

    layout_ = new QVBoxLayout;
    setLayout(layout_);

    space_for_painting_ = new QSpacerItem(min_w, bar_height_);
    layout_->addItem(space_for_painting_);

    auto* buttons_layout = new QHBoxLayout;

    QPushButton* reset = new QPushButton("reset");
    buttons_layout->addWidget(reset);
    connect(reset, &QPushButton::clicked, this, &ProfilingWidget::reset);

    QPushButton* export_csv = new QPushButton("export");
    buttons_layout->addWidget(export_csv);
    connect(export_csv, &QPushButton::clicked, this, &ProfilingWidget::exportCsv);

    layout_->addLayout(buttons_layout);

    connections_.emplace_back(profiler_->getProfile(profile_).getTimer()->finished.connect([this](Interval::Ptr) { update(); }));
}

ProfilingWidget::~ProfilingWidget()
{
}

void ProfilingWidget::reset()
{
    profiler_->reset();
}

void ProfilingWidget::exportCsv()
{
    QString filename = QFileDialog::getSaveFileName(0, "Save CSV File", "", "*.csv", 0, QFileDialog::DontUseNativeDialog);

    if(!filename.isEmpty()) {
        std::ofstream of(filename.toStdString());

        const Profile& profile = profiler_->getProfile(profile_);

        for(std::map<std::string, QColor>::const_iterator it = steps_.begin(); it != steps_.end(); ++it) {
            const std::string& name = it->first;

            ProfilerStats stats = profile.getStats(name);

            of << name << "," << stats.mean << "," << stats.stddev << "\n";
        }
    }
}

void ProfilingWidget::paintEvent(QPaintEvent *)
{
    apex_assert_hard(!profile_.empty());

    // update stats
    QPainter p(this);

    int w = width();
    int h = space_for_painting_->geometry().height();

    left = padding + left_space;
    right = w - padding;
    up = padding;
    bottom = h - 2 * padding - 2 * line_height - line_height * steps_.size();

    bar_height_ = bottom - padding;

    const Profile& profile = profiler_->getProfile(profile_);

    std::size_t history_length = profile.size();

    content_width_ = right - left - 2 * padding;
    indiv_width_ = content_width_ / history_length;
    content_height_ = bottom - up - 2 * padding;

    int n = history_length;

    double max_time_ms = 10;

    for(const auto& interval : profile.getIntervals()) {
        if(!interval) {
            continue;
        }

        max_time_ms = std::max(max_time_ms, interval->lengthMs());

        std::vector<std::pair<std::string, double> > names;
        interval->entries(names);
        for(auto it = names.begin(); it != names.end(); ++it) {
            const std::string& name = it->first;
            std::map<std::string, QColor>::iterator pos = steps_.find(name);
            if(pos == steps_.end()) {
                steps_[name] = color::fromCount<QColor>(steps_.size()).light();
            }
        }
    }

    // background
    QRect rect = contentsRect().adjusted(0,0,-1,-1);

    p.setBrush(QBrush(QColor(20, 20, 20)));
    p.setPen(QPen(Qt::white));
    p.setOpacity(0.6);

    p.drawRect(rect);

    // x-axis
    p.setOpacity(1.0);
    p.setPen(QPen(Qt::black));
    p.drawLine(left, bottom, right, bottom);

    // y-axis
    p.drawLine(left, bottom, left, up);

    int current_index = profile.getCurrentIndex();
    if(history_length == 0) {
        // no entries
        QFont font = p.font();
        font.setPixelSize(line_height * 2);
        p.setFont(font);
        p.setPen(QColor(0, 0, 0));
        p.drawText(rect.adjusted(left, 0, 0, 0), Qt::AlignCenter, "no data");
        return;
    }

    // bars
    if(n > 0) {
        std::stringstream txt;
        txt << max_time_ms << " ms";

        QFont font;
        font.setPixelSize(12);
        p.setFont(font);

        QFontMetrics metrics(font);

        float dy = metrics.height();

        QTextOption opt(Qt::AlignRight);

        p.setPen(QPen(QColor(20, 20, 20)));
        p.drawText(QRect(0, up, left -padding, dy), txt.str().c_str(), opt);
        p.drawText(QRect(0, bottom - dy, left - padding, dy), "0 ms", opt);

        max_time_ms_ = std::max(1.0, max_time_ms);

        current_draw_x = left + padding + (history_length - n) * indiv_width_;
        for(int time = 0; time < n; ++time) {

            static const float min_opacity = 0.25f;

            float op = ((time - current_index + n - 1) % n) / (float) n;
            p.setOpacity(min_opacity + op * (1.0f - min_opacity));

            const Interval::Ptr& interval = profile.getInterval(time);

            if(interval) {
                paintInterval(p, *interval);
            }
        }
    }

    // time line
    p.setOpacity(0.8);
    float pos = left + padding + (current_index+1) * indiv_width_;
    QPen pen(QColor(255, 20, 20));
    pen.setWidth(3);
    p.setPen(pen);
    p.drawLine(pos, bottom, pos, up);

    // legend
    p.setOpacity(1.0);
    float y = bottom;
    float text_x = left_space + 2*padding;
    float text_w = (w - text_x) / 2.0f - padding;
    float info_w = w - text_w - text_x;
    float info_x = text_x + text_w + padding;

    // label
    QFont font = p.font();
    font.setPixelSize(line_height * 0.8);
    p.setFont(font);
    p.setPen(QColor(0, 0, 0));
    p.drawText(QRectF(text_x, y, text_w, line_height), "name");
    p.drawText(QRectF(info_x , y, info_w / 2.0f, line_height), "mean");
    p.drawText(QRectF(info_x + info_w / 2.0f, y, info_w / 2.0f, line_height), "stddev");
    y += line_height;
    std::stringstream ss;
    ss << "(" << profile.count() << " frames, [ms])";
    p.drawText(QRectF(info_x, y, info_w, line_height), QString::fromStdString(ss.str()));
    y += line_height;

    // stats
    for(std::map<std::string, QColor>::const_iterator it = steps_.begin(); it != steps_.end(); ++it) {
        const std::string& name = it->first;
        QBrush brush(it->second);
        QPen pen(brush, 2);
        p.setPen(pen);
        p.fillRect(QRectF(text_x - 2*padding - line_height, y, line_height, line_height), it->second);
        p.drawText(QRectF(text_x, y, text_w, line_height), QString::fromStdString(name));

        ProfilerStats stats = profile.getStats(name);

        p.drawText(QRectF(info_x, y, info_w / 2.0f, line_height), QString::number(stats.mean));
        p.drawText(QRectF(info_x + info_w / 2.0f, y, info_w / 2.0f, line_height), QString::number(stats.stddev));
        y += line_height;
    }

    // resize to fit content
    if(space_for_painting_->geometry().height() != y) {
        space_for_painting_->changeSize(0, y, QSizePolicy::MinimumExpanding,  QSizePolicy::MinimumExpanding);
        layout()->invalidate();
    }
}

void ProfilingWidget::paintInterval(QPainter& p, const Interval& interval)
{
    paintInterval(p, interval, 0, 0);

    current_draw_x += indiv_width_;
}

float ProfilingWidget::paintInterval(QPainter& p, const Interval& interval, float height_offset, int depth)
{
    float interval_time = interval.lengthMs();

    float f = interval_time / max_time_ms_;
    f = std::max(0.0f, std::min(1.0f, f));
    float height = f * content_height_;

    p.setBrush(QBrush(steps_[interval.name()]));

    float w = indiv_width_ / (depth+1);
    p.drawRect(QRectF(current_draw_x + indiv_width_ - w, bottom - height - height_offset, w, height));

    float h = height_offset;
    for(auto sub = interval.sub.begin(); sub != interval.sub.end(); ++sub) {
        const Interval::Ptr& sub_interval = sub->second;
        h += paintInterval(p, *sub_interval, h, depth + 1);
    }

    return height;
}
/// MOC
#include "../../../include/csapex/view/widgets/moc_profiling_widget.cpp"
<|endoftext|>


<commit_before>#include <puppet/lexer/lexer.hpp>

using namespace std;
using namespace boost::spirit;

namespace puppet { namespace lexer {

    lexer_istreambuf_iterator lex_begin(ifstream& file)
    {
        return lexer_istreambuf_iterator(typename lexer_istreambuf_iterator::base_type(make_default_multi_pass(istreambuf_iterator<char>(file))));
    }

    lexer_istreambuf_iterator lex_end(ifstream& file)
    {
        return lexer_istreambuf_iterator(typename lexer_istreambuf_iterator::base_type(make_default_multi_pass(istreambuf_iterator<char>())));
    }

    lexer_string_iterator lex_begin(string const& str)
    {
        return lexer_string_iterator(typename lexer_string_iterator::base_type(str.begin()));
    }

    lexer_string_iterator lex_end(string const& str)
    {
        return lexer_string_iterator(typename lexer_string_iterator::base_type(str.end()));
    }

    struct scoped_file_position
    {
        scoped_file_position(ifstream& fs) :
            _fs(fs),
            _position(fs.tellg())
        {
        }

        ~scoped_file_position()
        {
            _fs.seekg(_position);
        }

     private:
        ifstream& _fs;
        size_t _position;
    };

    tuple<string, size_t> get_line_and_column(ifstream& fs, size_t position, size_t tab_width)
    {
        const size_t READ_SIZE = 4096;
        char buf[READ_SIZE];

        scoped_file_position guard(fs);

        // Read backwards in chunks looking for the closest newline before the given position
        size_t start;
        for (start = (position > (READ_SIZE + 1) ? position - READ_SIZE - 1 : 0); fs; start -= (start < READ_SIZE ? start : READ_SIZE)) {
            if (!fs.seekg(start)) {
                return make_tuple("", 1);
            }

            // Read data into the buffer
            if (!fs.read(buf, position < READ_SIZE ? position : READ_SIZE)) {
                return make_tuple("", 1);
            }

            // Find the last newline in the buffer
            auto it = find(reverse_iterator<char*>(buf + fs.gcount()), reverse_iterator<char*>(buf), '\n');
            if (it != reverse_iterator<char*>(buf)) {
                start += distance(buf, it.base());
                break;
            }

            if (start == 0) {
                break;
            }
        }

        // Calculate the column
        size_t column = (position - start) + 1;

        // Find the end of the current line
        size_t end = position;
        fs.seekg(end);
        auto eof =  istreambuf_iterator<char>();
        for (auto it = istreambuf_iterator<char>(fs.rdbuf()); it != eof; ++it) {
            if (*it == '\n') {
                break;
            }
            ++end;
        }

        // Read the line
        size_t size = end - start;
        fs.seekg(start);
        vector<char> line_buffer(size);
        if (!fs.read(line_buffer.data(), line_buffer.size())) {
            return make_tuple("", 1);
        }

        // Convert tabs to spaces
        string line = string(line_buffer.data(), line_buffer.size());
        if (tab_width > 1) {
            column += count(line.begin(), line.begin() + column, '\t') * (tab_width - 1);
        }

        return make_tuple(move(line), column);
    }

    tuple<string, size_t> get_line_and_column(string const& input, size_t position, size_t tab_width)
    {
        auto start = input.rfind('\n', position);
        if (start == string::npos) {
            start = 0;
        } else {
            ++start;
        }

        string line = input.substr(start, input.find('\n', start));

        // Convert tabs to spaces
        size_t column = (position - start) + 1;
        if (tab_width > 1) {
            column += count(line.begin(), line.begin() + column, '\t') * (tab_width - 1);
        }

        return make_tuple(move(line), column);
    }

    token_position get_last_position(ifstream& input)
    {
        // We need to read the entire file looking for new lines
        scoped_file_position guard(input);

        std::size_t position = 0, lines = 1;
        for (std::istreambuf_iterator<char> it(input), end; it != end; ++it) {
            if (*it == '\n') {
                ++lines;
            }
            ++position;
        }
        return make_tuple(position, lines);
    }

    token_position get_last_position(string const& input)
    {
        // Count the number of lines in the input
        return make_tuple(
            input.size(),
            count(input.begin(), input.end(), '\n') + 1
        );
    }

}}  // namespace puppet::lexer
<commit_msg>Fix lexer error positions for end-of-input tokens.<commit_after>#include <puppet/lexer/lexer.hpp>

using namespace std;
using namespace boost::spirit;

namespace puppet { namespace lexer {

    lexer_istreambuf_iterator lex_begin(ifstream& file)
    {
        return lexer_istreambuf_iterator(typename lexer_istreambuf_iterator::base_type(make_default_multi_pass(istreambuf_iterator<char>(file))));
    }

    lexer_istreambuf_iterator lex_end(ifstream& file)
    {
        return lexer_istreambuf_iterator(typename lexer_istreambuf_iterator::base_type(make_default_multi_pass(istreambuf_iterator<char>())));
    }

    lexer_string_iterator lex_begin(string const& str)
    {
        return lexer_string_iterator(typename lexer_string_iterator::base_type(str.begin()));
    }

    lexer_string_iterator lex_end(string const& str)
    {
        return lexer_string_iterator(typename lexer_string_iterator::base_type(str.end()));
    }

    struct scoped_file_position
    {
        scoped_file_position(ifstream& fs) :
            _fs(fs),
            _position(fs.tellg())
        {
        }

        ~scoped_file_position()
        {
            _fs.seekg(_position);
        }

     private:
        ifstream& _fs;
        size_t _position;
    };

    tuple<string, size_t> get_line_and_column(ifstream& fs, size_t position, size_t tab_width)
    {
        const size_t READ_SIZE = 4096;
        char buf[READ_SIZE];

        scoped_file_position guard(fs);

        // Read backwards in chunks looking for the closest newline before the given position
        size_t start;
        for (start = (position > (READ_SIZE + 1) ? position - READ_SIZE - 1 : 0); fs; start -= (start < READ_SIZE ? start : READ_SIZE)) {
            if (!fs.seekg(start)) {
                return make_tuple("", 1);
            }

            // Read data into the buffer
            if (!fs.read(buf, position < READ_SIZE ? position : READ_SIZE)) {
                return make_tuple("", 1);
            }

            // Find the last newline in the buffer
            auto it = find(reverse_iterator<char*>(buf + fs.gcount()), reverse_iterator<char*>(buf), '\n');
            if (it != reverse_iterator<char*>(buf)) {
                start += distance(buf, it.base());
                break;
            }

            if (start == 0) {
                break;
            }
        }

        // Calculate the column
        size_t column = (position - start) + 1;

        // Find the end of the current line
        size_t end = position;
        fs.seekg(end);
        auto eof =  istreambuf_iterator<char>();
        for (auto it = istreambuf_iterator<char>(fs.rdbuf()); it != eof; ++it) {
            if (*it == '\n') {
                break;
            }
            ++end;
        }

        // Read the line
        size_t size = end - start;
        fs.seekg(start);
        vector<char> line_buffer(size);
        if (!fs.read(line_buffer.data(), line_buffer.size())) {
            return make_tuple("", 1);
        }

        // Convert tabs to spaces
        string line = string(line_buffer.data(), line_buffer.size());
        if (tab_width > 1) {
            column += count(line.begin(), line.begin() + column, '\t') * (tab_width - 1);
        }

        return make_tuple(move(line), column);
    }

    tuple<string, size_t> get_line_and_column(string const& input, size_t position, size_t tab_width)
    {
        auto start = input.rfind('\n', position);
        if (start == string::npos) {
            start = 0;
        } else {
            ++start;
        }

        string line = input.substr(start, input.find('\n', start));

        // Convert tabs to spaces
        size_t column = (position - start) + 1;
        if (tab_width > 1) {
            column += count(line.begin(), line.begin() + column, '\t') * (tab_width - 1);
        }

        return make_tuple(move(line), column);
    }

    token_position get_last_position(ifstream& input)
    {
        // We need to read the entire file looking for new lines
        scoped_file_position guard(input);

        input.seekg(0);

        std::size_t position = 0, line = 1;
        std::size_t current_position = 0, current_line = 1;
        for (std::istreambuf_iterator<char> it(input), end; it != end; ++it) {
            if (*it == '\n') {
                ++current_line;
            }
            ++current_position;

            // If not whitespace, point the last position to that location
            if (!isspace(*it)) {
                position = current_position;
                line = current_line;
            }
        }
        return make_tuple(position, line);
    }

    token_position get_last_position(string const& input)
    {
        std::size_t position = 0, line = 1;
        std::size_t current_position = 0, current_line = 1;
        for (auto it = input.begin(); it != input.end(); ++it) {
            if (*it == '\n') {
                ++current_line;
            }
            ++current_position;

            // If not whitespace, point the last position to that location
            if (!isspace(*it)) {
                position = current_position;
                line = current_line;
            }
        }
        return make_tuple(position, line);
    }

}}  // namespace puppet::lexer
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2016.  All rights reserved
 */
#include    "../StroikaPreComp.h"

#include    "../Characters/Format.h"
#include    "../Characters/StringBuilder.h"
#include    "../Debug/Trace.h"

#include    "SQLite.h"

using   namespace   Stroika::Foundation;

using   namespace   Characters;
using   namespace   Debug;
using   namespace   Database;
using   namespace   Database::SQLite;
using   namespace   Execution;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

#if     qHasFeature_sqlite && defined (_MSC_VER)
// Use #pragma comment lib instead of explicit entry in the lib entry of the project file
#pragma comment (lib, "sqlite.lib")
#endif

#if     qHasFeature_sqlite
namespace {
    struct ModuleShutdown_ {
        ~ModuleShutdown_ ()
        {
            Verify (::sqlite3_shutdown () == SQLITE_OK);        // mostly pointless but avoids memory leak complaints
        }
    }   sModuleShutdown_;
}
#endif

/*
 ********************************************************************************
 ************************* SQLite::QuoteStringForDB *****************************
 ********************************************************************************
 */
String  SQLite::QuoteStringForDB (const String& s)
{
    // @todo discuss with John/review sqlite docs
    if (s.Contains ('\'')) {
        StringBuilder sb;
        for (Character c : s) {
            if (c == '\'') {
                sb += '\'';
            }
            sb += c;
        }
        return sb.str ();
    }
    else {
        return s;
    }
}

#if     qHasFeature_sqlite
/*
 ********************************************************************************
 ************************* SQLite::DB::Statement ********************************
 ********************************************************************************
 */
DB::Statement::Statement (DB* db,  const wchar_t* formatQuery, ...)
{
    RequireNotNull (db);
    RequireNotNull (db->Peek ());
    va_list     argsList;
    va_start (argsList, formatQuery);
    String  query   =   Characters::FormatV (formatQuery, argsList);
    va_end (argsList);
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
    TraceContextBumper ctx (SDKSTR ("SQLite::DB::Statement::Statement"));
    DbgTrace (L"(db=%p,query='%s')", db, query.c_str ());
#endif
    int rc = ::sqlite3_prepare_v2 (db->Peek (), query.AsUTF8 ().c_str (), -1, &fStatementObj_, NULL);
    if (rc != SQLITE_OK) {
        Execution::Throw (StringException (Characters::Format (L"SQLite Error %s:", String::FromUTF8 (::sqlite3_errmsg (db->Peek ())).c_str ())));
    }
    AssertNotNull (fStatementObj_);
    fParamsCount_ = ::sqlite3_column_count (fStatementObj_);
    for (unsigned int i = 0; i < fParamsCount_; ++i) {
        fColNames_ += String::FromUTF8 (::sqlite3_column_name (fStatementObj_, i));
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
        DbgTrace (L"sqlite3_column_decltype(i) = %s", ::sqlite3_column_decltype (fStatementObj_, i) == nullptr ? L"{nullptr}" : String::FromUTF8 (::sqlite3_column_decltype (fStatementObj_, i)).c_str ());
#endif
        // add VaroamtVa;ue"::Type list based on sqlite3_column_decltype
    }
}

DB::Statement::Statement (sqlite3* db,  const wchar_t* formatQuery, ...)
{
    RequireNotNull (db);
    va_list     argsList;
    va_start (argsList, formatQuery);
    String  query   =   Characters::FormatV (formatQuery, argsList);
    va_end (argsList);
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
    TraceContextBumper ctx (SDKSTR ("SQLite::DB::Statement::Statement"));
    DbgTrace (L"(db=%p,query='%s')", db, query.c_str ());
#endif
    int rc = ::sqlite3_prepare_v2 (db, query.AsUTF8 ().c_str (), -1, &fStatementObj_, NULL);
    if (rc != SQLITE_OK) {
        Execution::Throw (StringException (Characters::Format (L"SQLite Error %s:", String::FromUTF8 (::sqlite3_errmsg (db)).c_str ())));
    }
    AssertNotNull (fStatementObj_);
    fParamsCount_ = ::sqlite3_column_count (fStatementObj_);
    for (unsigned int i = 0; i < fParamsCount_; ++i) {
        fColNames_ += String::FromUTF8 (::sqlite3_column_name (fStatementObj_, i));
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
        DbgTrace (L"sqlite3_column_decltype(i) = %s", ::sqlite3_column_decltype (fStatementObj_, i) == nullptr ? L"{nullptr}" : String::FromUTF8 (::sqlite3_column_decltype (fStatementObj_, i)).c_str ());
#endif
        // add VaroamtVa;ue"::Type list based on sqlite3_column_decltype
    }
}

/// returns 'missing' on EOF, exception on error
auto   DB::Statement::GetNextRow () -> Optional<RowType> {
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
    TraceContextBumper ctx (SDKSTR ("SQLite::DB::Statement::GetNextRow"));
#endif
    // @todo redo with https://www.sqlite.org/c3ref/value.html
    int rc;
    AssertNotNull (fStatementObj_);
    if (( rc = ::sqlite3_step (fStatementObj_)) == SQLITE_ROW)
    {
        RowType row;
        for (unsigned int i = 0; i < fParamsCount_; ++i) {
            // redo as sqlite3_column_text16
            // @todo AND iether use value object or check INTERANL TYOPE  - https://www.sqlite.org/c3ref/column_blob.html and return the right one  - NULL, INTEGER, FLOAT, TEXT, BLOB
            VariantValue    v;
            switch (::sqlite3_column_type (fStatementObj_, i)) {
                case SQLITE_INTEGER: {
                        v = VariantValue (::sqlite3_column_int (fStatementObj_, i));
                    }
                    break;
                case SQLITE_FLOAT: {
                        v = VariantValue (::sqlite3_column_double (fStatementObj_, i));
                    }
                    break;
                case SQLITE_BLOB: {
                        const Byte* data        =   reinterpret_cast<const Byte*> (::sqlite3_column_blob (fStatementObj_, i));
                        size_t      byteCount   =   static_cast<size_t> (::sqlite3_column_bytes (fStatementObj_, i));
                        v = VariantValue (Memory::BLOB (data, data + byteCount));
                    }
                    break;
                case SQLITE_NULL: {
                        // default to null value
                    }
                    break;
                case SQLITE_TEXT: {
                        AssertNotNull (::sqlite3_column_text (fStatementObj_, i));
                        v = VariantValue (String::FromUTF8 (reinterpret_cast<const char*> (::sqlite3_column_text (fStatementObj_, i))));
                    }
                    break;
                default: {
                        AssertNotReached ();
                    }
                    break;
            }
            row.Add (fColNames_[i], v);
        }
        return row;
    }
    return Optional<RowType> ();
}

DB::Statement::~Statement ()
{
    AssertNotNull (fStatementObj_);
    ::sqlite3_finalize (fStatementObj_);
}

/*
 ********************************************************************************
 ********************************** SQLite::DB **********************************
 ********************************************************************************
 */
DB::DB (const URL& dbURL, const function<void(DB&)>& dbInitializer)
{
    TraceContextBumper ctx (SDKSTR ("SQLite::DB::DB"));
    // @todo - code cleanup!!!
    int e;
    if ((e = ::sqlite3_open_v2 (dbURL.GetFullURL ().AsUTF8 ().c_str (), &fDB_, SQLITE_OPEN_URI | SQLITE_OPEN_READWRITE, nullptr)) == SQLITE_CANTOPEN) {
        if (fDB_ == nullptr) {
            Verify (::sqlite3_close (fDB_) == SQLITE_OK);
            fDB_ = nullptr;
        }
        if ((e = ::sqlite3_open_v2 (dbURL.GetFullURL ().AsUTF8 ().c_str (), &fDB_, SQLITE_OPEN_URI | SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, nullptr)) == SQLITE_OK) {
            try {
                dbInitializer (*this);
            }
            catch (...) {
                Verify (::sqlite3_close (fDB_) == SQLITE_OK);
                Execution::ReThrow ();
            }
        }
    }
    else if (e != SQLITE_OK) {
        Assert (fDB_ == nullptr);
        // @todo add error string
        Execution::Throw (StringException (Characters::Format (L"SQLite Error %d:", e)));
    }
}

DB::DB (const String& dbPath, const function<void(DB&)>& dbInitializer)
{
    TraceContextBumper ctx (SDKSTR ("SQLite::DB::DB"));
    // @todo - code cleanup!!!
    int e;
    if ((e = ::sqlite3_open_v2 (dbPath.AsUTF8 ().c_str (), &fDB_, SQLITE_OPEN_READWRITE, nullptr)) == SQLITE_CANTOPEN) {
        if (fDB_ == nullptr) {
            Verify (::sqlite3_close (fDB_) == SQLITE_OK);
            fDB_ = nullptr;
        }
        if ((e = ::sqlite3_open_v2 (dbPath.AsUTF8 ().c_str (), &fDB_, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, nullptr)) == SQLITE_OK) {
            try {
                dbInitializer (*this);
            }
            catch (...) {
                Verify (::sqlite3_close (fDB_) == SQLITE_OK);
                Execution::ReThrow ();
            }
        }
    }
    else if (e != SQLITE_OK) {
        Assert (fDB_ == nullptr);
        // @todo add error string
        Execution::Throw (StringException (Characters::Format (L"SQLite Error %d:", e)));
    }
}

DB::DB (InMemoryDBFlag, const function<void(DB&)>& dbInitializer)
{
    TraceContextBumper ctx (SDKSTR ("SQLite::DB::DB"));
    // @todo - code cleanup!!!
    int e;
    if ((e = ::sqlite3_open_v2 ("memory:", &fDB_,  SQLITE_OPEN_MEMORY |  SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, nullptr)) == SQLITE_OK) {
        try {
            dbInitializer (*this);
        }
        catch (...) {
            Verify (::sqlite3_close (fDB_) == SQLITE_OK);
            Execution::ReThrow ();
        }
    }
    else if (e != SQLITE_OK) {
        Assert (fDB_ == nullptr);
        // @todo add error string
        Execution::Throw (StringException (Characters::Format (L"SQLite Error %d:", e)));
    }
}

DB:: ~DB ()
{
    AssertNotNull (fDB_);
    Verify (::sqlite3_close (fDB_) == SQLITE_OK);
}

void    DB::Exec (const wchar_t* formatCmd2Exec, ...)
{
    RequireNotNull (formatCmd2Exec);
    va_list     argsList;
    va_start (argsList, formatCmd2Exec);
    String  cmd2Exec    =   Characters::FormatV (formatCmd2Exec, argsList);
    va_end (argsList);
    char* db_err {};
    int e = ::sqlite3_exec (fDB_, cmd2Exec.AsUTF8 ().c_str (), NULL, 0, &db_err);
    if (e != SQLITE_OK) {
        if (db_err == nullptr or * db_err == '\0') {
            DbgTrace (L"Failed doing sqllite command: %s", cmd2Exec.c_str ());
            Execution::Throw (StringException (Characters::Format (L"SQLite Error %d", e)));
        }
        else {
            Execution::Throw (StringException (Characters::Format (L"SQLite Error %d: %s", e, String::FromUTF8 (db_err).c_str ())));
        }
    }
}
#endif
<commit_msg>refix (first fix not right) memleak in sqlite<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2016.  All rights reserved
 */
#include    "../StroikaPreComp.h"

#include    "../Characters/Format.h"
#include    "../Characters/StringBuilder.h"
#include    "../Debug/Trace.h"

#include    "SQLite.h"

using   namespace   Stroika::Foundation;

using   namespace   Characters;
using   namespace   Debug;
using   namespace   Database;
using   namespace   Database::SQLite;
using   namespace   Execution;

// Comment this in to turn on aggressive noisy DbgTrace in this module
//#define   USE_NOISY_TRACE_IN_THIS_MODULE_       1

#if     qHasFeature_sqlite && defined (_MSC_VER)
// Use #pragma comment lib instead of explicit entry in the lib entry of the project file
#pragma comment (lib, "sqlite.lib")
#endif

#if     qHasFeature_sqlite
namespace {
    struct ModuleShutdown_ {
        ~ModuleShutdown_ ()
        {
            Verify (::sqlite3_shutdown () == SQLITE_OK);        // mostly pointless but avoids memory leak complaints
        }
    }   sModuleShutdown_;
}
#endif

/*
 ********************************************************************************
 ************************* SQLite::QuoteStringForDB *****************************
 ********************************************************************************
 */
String  SQLite::QuoteStringForDB (const String& s)
{
    // @todo discuss with John/review sqlite docs
    if (s.Contains ('\'')) {
        StringBuilder sb;
        for (Character c : s) {
            if (c == '\'') {
                sb += '\'';
            }
            sb += c;
        }
        return sb.str ();
    }
    else {
        return s;
    }
}

#if     qHasFeature_sqlite
/*
 ********************************************************************************
 ************************* SQLite::DB::Statement ********************************
 ********************************************************************************
 */
DB::Statement::Statement (DB* db,  const wchar_t* formatQuery, ...)
{
    RequireNotNull (db);
    RequireNotNull (db->Peek ());
    va_list     argsList;
    va_start (argsList, formatQuery);
    String  query   =   Characters::FormatV (formatQuery, argsList);
    va_end (argsList);
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
    TraceContextBumper ctx (SDKSTR ("SQLite::DB::Statement::Statement"));
    DbgTrace (L"(db=%p,query='%s')", db, query.c_str ());
#endif
    int rc = ::sqlite3_prepare_v2 (db->Peek (), query.AsUTF8 ().c_str (), -1, &fStatementObj_, NULL);
    if (rc != SQLITE_OK) {
        Execution::Throw (StringException (Characters::Format (L"SQLite Error %s:", String::FromUTF8 (::sqlite3_errmsg (db->Peek ())).c_str ())));
    }
    AssertNotNull (fStatementObj_);
    fParamsCount_ = ::sqlite3_column_count (fStatementObj_);
    for (unsigned int i = 0; i < fParamsCount_; ++i) {
        fColNames_ += String::FromUTF8 (::sqlite3_column_name (fStatementObj_, i));
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
        DbgTrace (L"sqlite3_column_decltype(i) = %s", ::sqlite3_column_decltype (fStatementObj_, i) == nullptr ? L"{nullptr}" : String::FromUTF8 (::sqlite3_column_decltype (fStatementObj_, i)).c_str ());
#endif
        // add VaroamtVa;ue"::Type list based on sqlite3_column_decltype
    }
}

DB::Statement::Statement (sqlite3* db,  const wchar_t* formatQuery, ...)
{
    RequireNotNull (db);
    va_list     argsList;
    va_start (argsList, formatQuery);
    String  query   =   Characters::FormatV (formatQuery, argsList);
    va_end (argsList);
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
    TraceContextBumper ctx (SDKSTR ("SQLite::DB::Statement::Statement"));
    DbgTrace (L"(db=%p,query='%s')", db, query.c_str ());
#endif
    int rc = ::sqlite3_prepare_v2 (db, query.AsUTF8 ().c_str (), -1, &fStatementObj_, NULL);
    if (rc != SQLITE_OK) {
        Execution::Throw (StringException (Characters::Format (L"SQLite Error %s:", String::FromUTF8 (::sqlite3_errmsg (db)).c_str ())));
    }
    AssertNotNull (fStatementObj_);
    fParamsCount_ = ::sqlite3_column_count (fStatementObj_);
    for (unsigned int i = 0; i < fParamsCount_; ++i) {
        fColNames_ += String::FromUTF8 (::sqlite3_column_name (fStatementObj_, i));
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
        DbgTrace (L"sqlite3_column_decltype(i) = %s", ::sqlite3_column_decltype (fStatementObj_, i) == nullptr ? L"{nullptr}" : String::FromUTF8 (::sqlite3_column_decltype (fStatementObj_, i)).c_str ());
#endif
        // add VaroamtVa;ue"::Type list based on sqlite3_column_decltype
    }
}

/// returns 'missing' on EOF, exception on error
auto   DB::Statement::GetNextRow () -> Optional<RowType> {
#if     USE_NOISY_TRACE_IN_THIS_MODULE_
    TraceContextBumper ctx (SDKSTR ("SQLite::DB::Statement::GetNextRow"));
#endif
    // @todo redo with https://www.sqlite.org/c3ref/value.html
    int rc;
    AssertNotNull (fStatementObj_);
    if (( rc = ::sqlite3_step (fStatementObj_)) == SQLITE_ROW)
    {
        RowType row;
        for (unsigned int i = 0; i < fParamsCount_; ++i) {
            // redo as sqlite3_column_text16
            // @todo AND iether use value object or check INTERANL TYOPE  - https://www.sqlite.org/c3ref/column_blob.html and return the right one  - NULL, INTEGER, FLOAT, TEXT, BLOB
            VariantValue    v;
            switch (::sqlite3_column_type (fStatementObj_, i)) {
                case SQLITE_INTEGER: {
                        v = VariantValue (::sqlite3_column_int (fStatementObj_, i));
                    }
                    break;
                case SQLITE_FLOAT: {
                        v = VariantValue (::sqlite3_column_double (fStatementObj_, i));
                    }
                    break;
                case SQLITE_BLOB: {
                        const Byte* data        =   reinterpret_cast<const Byte*> (::sqlite3_column_blob (fStatementObj_, i));
                        size_t      byteCount   =   static_cast<size_t> (::sqlite3_column_bytes (fStatementObj_, i));
                        v = VariantValue (Memory::BLOB (data, data + byteCount));
                    }
                    break;
                case SQLITE_NULL: {
                        // default to null value
                    }
                    break;
                case SQLITE_TEXT: {
                        AssertNotNull (::sqlite3_column_text (fStatementObj_, i));
                        v = VariantValue (String::FromUTF8 (reinterpret_cast<const char*> (::sqlite3_column_text (fStatementObj_, i))));
                    }
                    break;
                default: {
                        AssertNotReached ();
                    }
                    break;
            }
            row.Add (fColNames_[i], v);
        }
        return row;
    }
    return Optional<RowType> ();
}

DB::Statement::~Statement ()
{
    AssertNotNull (fStatementObj_);
    ::sqlite3_finalize (fStatementObj_);
}

/*
 ********************************************************************************
 ********************************** SQLite::DB **********************************
 ********************************************************************************
 */
DB::DB (const URL& dbURL, const function<void(DB&)>& dbInitializer)
{
    TraceContextBumper ctx (SDKSTR ("SQLite::DB::DB"));
    // @todo - code cleanup!!!
    int e;
    if ((e = ::sqlite3_open_v2 (dbURL.GetFullURL ().AsUTF8 ().c_str (), &fDB_, SQLITE_OPEN_URI | SQLITE_OPEN_READWRITE, nullptr)) == SQLITE_CANTOPEN) {
        if (fDB_ != nullptr) {
            Verify (::sqlite3_close (fDB_) == SQLITE_OK);
            fDB_ = nullptr;
        }
        if ((e = ::sqlite3_open_v2 (dbURL.GetFullURL ().AsUTF8 ().c_str (), &fDB_, SQLITE_OPEN_URI | SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, nullptr)) == SQLITE_OK) {
            try {
                dbInitializer (*this);
            }
            catch (...) {
                Verify (::sqlite3_close (fDB_) == SQLITE_OK);
                Execution::ReThrow ();
            }
        }
    }
    else if (e != SQLITE_OK) {
        Assert (fDB_ == nullptr);
        // @todo add error string
        Execution::Throw (StringException (Characters::Format (L"SQLite Error %d:", e)));
    }
}

DB::DB (const String& dbPath, const function<void(DB&)>& dbInitializer)
{
    TraceContextBumper ctx (SDKSTR ("SQLite::DB::DB"));
    // @todo - code cleanup!!!
    int e;
    if ((e = ::sqlite3_open_v2 (dbPath.AsUTF8 ().c_str (), &fDB_, SQLITE_OPEN_READWRITE, nullptr)) == SQLITE_CANTOPEN) {
        if (fDB_ != nullptr) {
            Verify (::sqlite3_close (fDB_) == SQLITE_OK);
            fDB_ = nullptr;
        }
        if ((e = ::sqlite3_open_v2 (dbPath.AsUTF8 ().c_str (), &fDB_, SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, nullptr)) == SQLITE_OK) {
            try {
                dbInitializer (*this);
            }
            catch (...) {
                Verify (::sqlite3_close (fDB_) == SQLITE_OK);
                Execution::ReThrow ();
            }
        }
    }
    else if (e != SQLITE_OK) {
        Assert (fDB_ == nullptr);
        // @todo add error string
        Execution::Throw (StringException (Characters::Format (L"SQLite Error %d:", e)));
    }
}

DB::DB (InMemoryDBFlag, const function<void(DB&)>& dbInitializer)
{
    TraceContextBumper ctx (SDKSTR ("SQLite::DB::DB"));
    // @todo - code cleanup!!!
    int e;
    if ((e = ::sqlite3_open_v2 ("memory:", &fDB_,  SQLITE_OPEN_MEMORY |  SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, nullptr)) == SQLITE_OK) {
        try {
            dbInitializer (*this);
        }
        catch (...) {
            Verify (::sqlite3_close (fDB_) == SQLITE_OK);
            Execution::ReThrow ();
        }
    }
    else if (e != SQLITE_OK) {
        Assert (fDB_ == nullptr);
        // @todo add error string
        Execution::Throw (StringException (Characters::Format (L"SQLite Error %d:", e)));
    }
}

DB:: ~DB ()
{
    AssertNotNull (fDB_);
    Verify (::sqlite3_close (fDB_) == SQLITE_OK);
}

void    DB::Exec (const wchar_t* formatCmd2Exec, ...)
{
    RequireNotNull (formatCmd2Exec);
    va_list     argsList;
    va_start (argsList, formatCmd2Exec);
    String  cmd2Exec    =   Characters::FormatV (formatCmd2Exec, argsList);
    va_end (argsList);
    char* db_err {};
    int e = ::sqlite3_exec (fDB_, cmd2Exec.AsUTF8 ().c_str (), NULL, 0, &db_err);
    if (e != SQLITE_OK) {
        if (db_err == nullptr or * db_err == '\0') {
            DbgTrace (L"Failed doing sqllite command: %s", cmd2Exec.c_str ());
            Execution::Throw (StringException (Characters::Format (L"SQLite Error %d", e)));
        }
        else {
            Execution::Throw (StringException (Characters::Format (L"SQLite Error %d: %s", e, String::FromUTF8 (db_err).c_str ())));
        }
    }
}
#endif
<|endoftext|>


<commit_before>
/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <boost/bind.hpp>
#include "libtorrent/invariant_check.hpp"
#include "libtorrent/connection_queue.hpp"

namespace libtorrent
{

	connection_queue::connection_queue(io_service& ios): m_next_ticket(0)
		, m_num_connecting(0)
		, m_half_open_limit(0)
		, m_timer(ios)
#ifndef NDEBUG
		, m_in_timeout_function(false)
#endif
	{}

	bool connection_queue::free_slots() const
	{ return m_num_connecting < m_half_open_limit || m_half_open_limit <= 0; }

	void connection_queue::enqueue(boost::function<void(int)> const& on_connect
		, boost::function<void()> const& on_timeout
		, time_duration timeout)
	{
		INVARIANT_CHECK;

		m_queue.push_back(entry());
		entry& e = m_queue.back();
		e.on_connect = on_connect;
		e.on_timeout = on_timeout;
		e.ticket = m_next_ticket;
		e.timeout = timeout;
		++m_next_ticket;
		try_connect();
	}

	void connection_queue::done(int ticket)
	{
		INVARIANT_CHECK;

		std::list<entry>::iterator i = std::find_if(m_queue.begin()
			, m_queue.end(), boost::bind(&entry::ticket, _1) == ticket);
		if (i == m_queue.end())
		{
			// this might not be here in case on_timeout calls remove
			return;
		}
		if (i->connecting) --m_num_connecting;
		m_queue.erase(i);
		try_connect();
	}

	void connection_queue::limit(int limit)
	{ m_half_open_limit = limit; }

	int connection_queue::limit() const
	{ return m_half_open_limit; }

#ifndef NDEBUG

	void connection_queue::check_invariant() const
	{
		int num_connecting = 0;
		for (std::list<entry>::const_iterator i = m_queue.begin();
			i != m_queue.end(); ++i)
		{
			if (i->connecting) ++num_connecting;
		}
		assert(num_connecting == m_num_connecting);
	}

#endif

	void connection_queue::try_connect()
	{
		INVARIANT_CHECK;

		if (!free_slots() || m_queue.empty())
			return;

		std::list<entry>::iterator i = std::find_if(m_queue.begin()
			, m_queue.end(), boost::bind(&entry::connecting, _1) == false);
		while (i != m_queue.end())
		{
			assert(i->connecting == false);
			ptime expire = time_now() + i->timeout;
			if (m_num_connecting == 0)
			{
				m_timer.expires_at(expire);
				m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1));
			}
			i->connecting = true;
			++m_num_connecting;
			i->expires = expire;

			INVARIANT_CHECK;

			entry& ent = *i;
			++i;
			try { ent.on_connect(ent.ticket); } catch (std::exception&) {}

			if (!free_slots()) break;
			i = std::find_if(i, m_queue.end(), boost::bind(&entry::connecting, _1) == false);
		}
	}

#ifndef NDEBUG
	struct function_guard
	{
		function_guard(bool& v): val(v) { assert(!val); val = true; }
		~function_guard() { val = false; }

		bool& val;
	};
#endif

	void connection_queue::on_timeout(asio::error_code const& e)
	{
		INVARIANT_CHECK;
#ifndef NDEBUG
		function_guard guard_(m_in_timeout_function);
#endif

		assert(!e || e == asio::error::operation_aborted);
		if (e) return;

		ptime next_expire = max_time();
		ptime now = time_now();
		for (std::list<entry>::iterator i = m_queue.begin();
			i != m_queue.end();)
		{
			if (i->connecting && i->expires < now)
			{
				boost::function<void()> on_timeout = i->on_timeout;
				m_queue.erase(i++);
				--m_num_connecting;
				try { on_timeout(); } catch (std::exception&) {}
				continue;
			}
			if (i->expires < next_expire)
				next_expire = i->expires;
			++i;
		}
		if (next_expire < max_time())
		{
			m_timer.expires_at(next_expire);
			m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1));
		}
		try_connect();
	}

}

<commit_msg>connection queue fix<commit_after>
/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <boost/bind.hpp>
#include "libtorrent/invariant_check.hpp"
#include "libtorrent/connection_queue.hpp"

namespace libtorrent
{

	connection_queue::connection_queue(io_service& ios): m_next_ticket(0)
		, m_num_connecting(0)
		, m_half_open_limit(0)
		, m_timer(ios)
#ifndef NDEBUG
		, m_in_timeout_function(false)
#endif
	{}

	bool connection_queue::free_slots() const
	{ return m_num_connecting < m_half_open_limit || m_half_open_limit <= 0; }

	void connection_queue::enqueue(boost::function<void(int)> const& on_connect
		, boost::function<void()> const& on_timeout
		, time_duration timeout)
	{
		INVARIANT_CHECK;

		m_queue.push_back(entry());
		entry& e = m_queue.back();
		e.on_connect = on_connect;
		e.on_timeout = on_timeout;
		e.ticket = m_next_ticket;
		e.timeout = timeout;
		++m_next_ticket;
		try_connect();
	}

	void connection_queue::done(int ticket)
	{
		INVARIANT_CHECK;

		std::list<entry>::iterator i = std::find_if(m_queue.begin()
			, m_queue.end(), boost::bind(&entry::ticket, _1) == ticket);
		if (i == m_queue.end())
		{
			// this might not be here in case on_timeout calls remove
			return;
		}
		if (i->connecting) --m_num_connecting;
		m_queue.erase(i);
		try_connect();
	}

	void connection_queue::limit(int limit)
	{ m_half_open_limit = limit; }

	int connection_queue::limit() const
	{ return m_half_open_limit; }

#ifndef NDEBUG

	void connection_queue::check_invariant() const
	{
		int num_connecting = 0;
		for (std::list<entry>::const_iterator i = m_queue.begin();
			i != m_queue.end(); ++i)
		{
			if (i->connecting) ++num_connecting;
		}
		assert(num_connecting == m_num_connecting);
	}

#endif

	void connection_queue::try_connect()
	{
		INVARIANT_CHECK;

		if (!free_slots() || m_queue.empty())
			return;

		std::list<entry>::iterator i = std::find_if(m_queue.begin()
			, m_queue.end(), boost::bind(&entry::connecting, _1) == false);
		while (i != m_queue.end())
		{
			assert(i->connecting == false);
			ptime expire = time_now() + i->timeout;
			if (m_num_connecting == 0)
			{
				m_timer.expires_at(expire);
				m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1));
			}
			i->connecting = true;
			++m_num_connecting;
			i->expires = expire;

			INVARIANT_CHECK;

			entry& ent = *i;
			++i;
			try { ent.on_connect(ent.ticket); } catch (std::exception&) {}

			if (!free_slots()) break;
			i = std::find_if(i, m_queue.end(), boost::bind(&entry::connecting, _1) == false);
		}
	}

#ifndef NDEBUG
	struct function_guard
	{
		function_guard(bool& v): val(v) { assert(!val); val = true; }
		~function_guard() { val = false; }

		bool& val;
	};
#endif

	void connection_queue::on_timeout(asio::error_code const& e)
	{
		INVARIANT_CHECK;
#ifndef NDEBUG
		function_guard guard_(m_in_timeout_function);
#endif

		assert(!e || e == asio::error::operation_aborted);
		if (e) return;

		ptime next_expire = max_time();
		ptime now = time_now();
		for (std::list<entry>::iterator i = m_queue.begin();
			!m_queue.empty() && i != m_queue.end();)
		{
			if (i->connecting && i->expires < now)
			{
				boost::function<void()> on_timeout = i->on_timeout;
				m_queue.erase(i++);
				--m_num_connecting;
				try { on_timeout(); } catch (std::exception&) {}
				continue;
			}
			if (i->expires < next_expire)
				next_expire = i->expires;
			++i;
		}
		if (next_expire < max_time())
		{
			m_timer.expires_at(next_expire);
			m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1));
		}
		try_connect();
	}

}

<|endoftext|>