<commit_before>/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com>
All rights reserved.

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

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. 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.

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 <iostream>
#include <string>

#include "gtest/gtest.h"

#include <nomlib/config.hpp>

namespace nom {

class Template: public ::testing::Test
{
  public:
    Template( void )
    {
      // ...
    }

    ~Template( void )
    {
      // ...
    }

  protected:
    // Member methods & variables
};

TEST_F( Template, TemplateTestDesc )
{
  EXPECT_EQ( -1, -1 );
  ASSERT_TRUE( true );
}

} // namespace nom

int main( int argc, char** argv )
{
  ::testing::InitGoogleTest( &argc, argv );

  return RUN_ALL_TESTS();
}
<commit_msg>Update template file for unit tests<commit_after>/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com>
All rights reserved.

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

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. 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.

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 <iostream>
#include <string>

#include "gtest/gtest.h"

#include <nomlib/config.hpp>

namespace nom {

class Template: public ::testing::Test
{
  public:
    Template( void )
    {
      //
    }

    ~Template( void )
    {
      //
    }

    virtual void SetUp( void )
    {
      //
    }

    virtual void TearDown( void )
    {
      //
    }

  protected:
    // Member methods & variables
};

TEST_F( Template, TemplateTestDesc )
{
  EXPECT_EQ( -1, -1 );
  ASSERT_TRUE( true );
}

} // namespace nom

int main( int argc, char** argv )
{
  ::testing::InitGoogleTest( &argc, argv );

  return RUN_ALL_TESTS();
}
<|endoftext|>


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

#ifndef _SVX_STDDLG_HXX //autogen
#include <svx/stddlg.hxx>
#endif

#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif

#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif

#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef _FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif

#include "tox.hxx"
#ifndef _LIST_HXX //autogen
#include <tools/list.hxx>
#endif
#ifndef _TOXMGR_HXX
#include <toxmgr.hxx>
#endif
#ifndef _SVX_CHECKLBX_HXX //autogen wg. SvxCheckListBox
#include <svx/checklbx.hxx>
#endif
#ifndef _TOOLS_RESARY_HXX
#include <tools/resary.hxx>
#endif
#ifndef _SVTREEBOX_HXX
#include <svtools/svtreebx.hxx>
#endif
#ifndef _SV_MENUBTN_HXX
#include <vcl/menubtn.hxx>
#endif
#ifndef _SVX_LANGBOX_HXX
#include <svx/langbox.hxx>
#endif
#define TOX_PAGE_SELECT 1
#define TOX_PAGE_ENTRY  2
#define TOX_PAGE_STYLES 3

struct CurTOXType
{
    TOXTypes    eType;
    USHORT      nIndex; //for TOX_USER only

    BOOL operator==(const CurTOXType aCmp)
       {
        return eType == aCmp.eType && nIndex == aCmp.nIndex;
       }
    USHORT GetFlatIndex() const;

    CurTOXType () : eType (TOX_INDEX), nIndex (0) {};

    CurTOXType (TOXTypes t, USHORT i) : eType (t), nIndex (i) {};
};

class SwOLENames : public Resource
{
    ResStringArray      aNamesAry;
public:
    SwOLENames(const ResId& rResId) :
        Resource(rResId),
        aNamesAry(ResId(1,*rResId.GetResMgr())){FreeResource();}

    ResStringArray&     GetNames() { return aNamesAry;}

};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.16.188); FILE MERGED 2008/04/01 15:59:09 thb 1.16.188.3: #i85898# Stripping all external header guards 2008/04/01 12:55:25 thb 1.16.188.2: #i85898# Stripping all external header guards 2008/03/31 16:58:28 rt 1.16.188.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: cnttab.hxx,v $
 * $Revision: 1.17 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _CNTTAB_HXX
#define _CNTTAB_HXX

#include <svx/stddlg.hxx>

#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif

#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif

#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef _FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#include <vcl/lstbox.hxx>
#include <sfx2/tabdlg.hxx>

#include "tox.hxx"
#include <tools/list.hxx>
#include <toxmgr.hxx>
#include <svx/checklbx.hxx>
#include <tools/resary.hxx>
#include <svtools/svtreebx.hxx>
#include <vcl/menubtn.hxx>
#include <svx/langbox.hxx>
#define TOX_PAGE_SELECT 1
#define TOX_PAGE_ENTRY  2
#define TOX_PAGE_STYLES 3

struct CurTOXType
{
    TOXTypes    eType;
    USHORT      nIndex; //for TOX_USER only

    BOOL operator==(const CurTOXType aCmp)
       {
        return eType == aCmp.eType && nIndex == aCmp.nIndex;
       }
    USHORT GetFlatIndex() const;

    CurTOXType () : eType (TOX_INDEX), nIndex (0) {};

    CurTOXType (TOXTypes t, USHORT i) : eType (t), nIndex (i) {};
};

class SwOLENames : public Resource
{
    ResStringArray      aNamesAry;
public:
    SwOLENames(const ResId& rResId) :
        Resource(rResId),
        aNamesAry(ResId(1,*rResId.GetResMgr())){FreeResource();}

    ResStringArray&     GetNames() { return aNamesAry;}

};

#endif
<|endoftext|>


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

#include "swdetect.hxx"

#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

extern "C" {

SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment(
        const  sal_Char**   ppEnvironmentTypeName,
        uno_Environment**   ppEnvironment           )
{
    *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
}

SAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL component_writeInfo(
    void*   pServiceManager ,
    void*   pRegistryKey    )
{
    Reference< ::registry::XRegistryKey >
            xKey( reinterpret_cast< ::registry::XRegistryKey* >( pRegistryKey ) ) ;

    OUString aDelimiter( RTL_CONSTASCII_USTRINGPARAM("/") );
    OUString aUnoServices( RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") );

    // Eigentliche Implementierung und ihre Services registrieren
    sal_Int32 i;
    Reference< ::registry::XRegistryKey >  xNewKey;

    xNewKey = xKey->createKey( aDelimiter + SwFilterDetect::impl_getStaticImplementationName() +
                               aUnoServices );

    Sequence< OUString > aServices = SwFilterDetect::impl_getStaticSupportedServiceNames();
    for(i = 0; i < aServices.getLength(); i++ )
        xNewKey->createKey( aServices.getConstArray()[i] );

    return sal_True;
}

SAL_DLLPUBLIC_EXPORT void* SAL_CALL component_getFactory(
    const sal_Char* pImplementationName,
    void* pServiceManager,
    void* pRegistryKey )
{
    // Set default return value for this operation - if it failed.
    void* pReturn = NULL ;

    if  (
            ( pImplementationName   !=  NULL ) &&
            ( pServiceManager       !=  NULL )
        )
    {
        // Define variables which are used in following macros.
        Reference< XSingleServiceFactory >   xFactory                                                                                ;
        Reference< XMultiServiceFactory >    xServiceManager( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;

        if( SwFilterDetect::impl_getStaticImplementationName().equalsAscii( pImplementationName ) )
        {
            xFactory = ::cppu::createSingleFactory( xServiceManager,
            SwFilterDetect::impl_getStaticImplementationName(),
            SwFilterDetect::impl_createInstance,
            SwFilterDetect::impl_getStaticSupportedServiceNames() );
        }

        // Factory is valid - service was found.
        if ( xFactory.is() )
        {
            xFactory->acquire();
            pReturn = xFactory.get();
        }
    }

    // Return with result of this operation.
    return pReturn ;
}
} // extern "C"

<commit_msg>INTEGRATION: CWS writercorehandoff (1.3.462); FILE MERGED 2005/09/13 18:40:27 tra 1.3.462.3: RESYNC: (1.3-1.4); FILE MERGED 2005/06/07 14:16:05 fme 1.3.462.2: #i50348# General cleanup - removed unused header files, functions, members, declarations etc. 2005/06/06 09:30:09 tra 1.3.462.1: Unnecessary includes removed #i50348#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: detreg.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-14 17:59:30 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#include "swdetect.hxx"

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

extern "C" {

SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment(
        const  sal_Char**   ppEnvironmentTypeName,
        uno_Environment**   ppEnvironment           )
{
    *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
}

SAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL component_writeInfo(
    void*   pServiceManager ,
    void*   pRegistryKey    )
{
    Reference< ::registry::XRegistryKey >
            xKey( reinterpret_cast< ::registry::XRegistryKey* >( pRegistryKey ) ) ;

    OUString aDelimiter( RTL_CONSTASCII_USTRINGPARAM("/") );
    OUString aUnoServices( RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") );

    // Eigentliche Implementierung und ihre Services registrieren
    sal_Int32 i;
    Reference< ::registry::XRegistryKey >  xNewKey;

    xNewKey = xKey->createKey( aDelimiter + SwFilterDetect::impl_getStaticImplementationName() +
                               aUnoServices );

    Sequence< OUString > aServices = SwFilterDetect::impl_getStaticSupportedServiceNames();
    for(i = 0; i < aServices.getLength(); i++ )
        xNewKey->createKey( aServices.getConstArray()[i] );

    return sal_True;
}

SAL_DLLPUBLIC_EXPORT void* SAL_CALL component_getFactory(
    const sal_Char* pImplementationName,
    void* pServiceManager,
    void* pRegistryKey )
{
    // Set default return value for this operation - if it failed.
    void* pReturn = NULL ;

    if  (
            ( pImplementationName   !=  NULL ) &&
            ( pServiceManager       !=  NULL )
        )
    {
        // Define variables which are used in following macros.
        Reference< XSingleServiceFactory >   xFactory                                                                                ;
        Reference< XMultiServiceFactory >    xServiceManager( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ;

        if( SwFilterDetect::impl_getStaticImplementationName().equalsAscii( pImplementationName ) )
        {
            xFactory = ::cppu::createSingleFactory( xServiceManager,
            SwFilterDetect::impl_getStaticImplementationName(),
            SwFilterDetect::impl_createInstance,
            SwFilterDetect::impl_getStaticSupportedServiceNames() );
        }

        // Factory is valid - service was found.
        if ( xFactory.is() )
        {
            xFactory->acquire();
            pReturn = xFactory.get();
        }
    }

    // Return with result of this operation.
    return pReturn ;
}
} // extern "C"

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: unodoc.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2003-04-04 19:29:55 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

// System - Includes -----------------------------------------------------

#include <tools/string.hxx>
#include <sfx2/docfac.hxx>

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

#include "swmodule.hxx"

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

using namespace ::com::sun::star;

//============================================================
// com.sun.star.comp.Writer.TextDocument

uno::Sequence< ::rtl::OUString > SAL_CALL SwTextDocument_getSupportedServiceNames() throw()
{
    uno::Sequence< ::rtl::OUString > aRet ( 2 );
    ::rtl::OUString* pArray = aRet.getArray();
    pArray[0] = ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.text.TextDocument" ) );
    pArray[1] = ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.document.OfficeDocument" ) );

    return aRet;
}

::rtl::OUString SAL_CALL SwTextDocument_getImplementationName() throw()
{
    return ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.TextDocument" ) );
}

uno::Reference< uno::XInterface > SAL_CALL SwTextDocument_createInstance( const uno::Reference< lang::XMultiServiceFactory > &rSMgr )
    throw( uno::Exception )
{
    ::vos::OGuard aGuard( Application::GetSolarMutex() );

    // to create the service the SW_MOD should be already initialized
    DBG_ASSERT( SW_MOD(), "No StarWriter module!" );

    if ( SW_MOD() )
    {
        ::rtl::OUString aFactoryURL( RTL_CONSTASCII_USTRINGPARAM ( "private:factory/swriter" ) );
        const SfxObjectFactory* pFactory = SfxObjectFactory::GetFactory( aFactoryURL );
        if ( pFactory )
        {
            SfxObjectShell* pShell = pFactory->CreateObject();
            if( pShell )
                return uno::Reference< uno::XInterface >( pShell->GetModel() );
        }
    }

    return uno::Reference< uno::XInterface >();
}

//============================================================
// com.sun.star.comp.Writer.WebDocument

uno::Sequence< ::rtl::OUString > SAL_CALL SwWebDocument_getSupportedServiceNames() throw()
{
    uno::Sequence< ::rtl::OUString > aRet ( 3 );
    ::rtl::OUString* pArray = aRet.getArray();
    pArray[0] = ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.text.TextDocument" ) );
    pArray[1] = ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.document.OfficeDocument" ) );
    pArray[2] = ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.text.WebDocument" ) );

    return aRet;
}

::rtl::OUString SAL_CALL SwWebDocument_getImplementationName() throw()
{
    return ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.WebDocument" ) );
}

uno::Reference< uno::XInterface > SAL_CALL SwWebDocument_createInstance( const uno::Reference< lang::XMultiServiceFactory > &rSMgr )
    throw( uno::Exception )
{
    ::vos::OGuard aGuard( Application::GetSolarMutex() );

    // to create the service the SW_MOD should be already initialized
    DBG_ASSERT( SW_MOD(), "No StarWriter module!" );

    if ( SW_MOD() )
    {
        ::rtl::OUString aFactoryURL( RTL_CONSTASCII_USTRINGPARAM ( "private:factory/swriter/web" ) );
        const SfxObjectFactory* pFactory = SfxObjectFactory::GetFactory( aFactoryURL );
        if ( pFactory )
        {
            SfxObjectShell* pShell = pFactory->CreateObject();
            if( pShell )
                return uno::Reference< uno::XInterface >( pShell->GetModel() );
        }
    }

    return uno::Reference< uno::XInterface >();
}

//============================================================
// com.sun.star.comp.Writer.GlobalDocument

uno::Sequence< ::rtl::OUString > SAL_CALL SwGlobalDocument_getSupportedServiceNames() throw()
{
    uno::Sequence< ::rtl::OUString > aRet ( 3 );
    ::rtl::OUString* pArray = aRet.getArray();
    pArray[0] = ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.text.TextDocument" ) );
    pArray[1] = ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.document.OfficeDocument" ) );
    pArray[2] = ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.text.GlobalDocument" ) );

    return aRet;
}

::rtl::OUString SAL_CALL SwGlobalDocument_getImplementationName() throw()
{
    return ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.GlobalDocument" ) );
}

uno::Reference< uno::XInterface > SAL_CALL SwGlobalDocument_createInstance( const uno::Reference< lang::XMultiServiceFactory > &rSMgr )
    throw( uno::Exception )
{
    ::vos::OGuard aGuard( Application::GetSolarMutex() );

    // to create the service the SW_MOD should be already initialized
    DBG_ASSERT( SW_MOD(), "No StarWriter module!" );

    if ( SW_MOD() )
    {
        ::rtl::OUString aFactoryURL( RTL_CONSTASCII_USTRINGPARAM ( "private:factory/swriter/GlobalDocument" ) );
        const SfxObjectFactory* pFactory = SfxObjectFactory::GetFactory( aFactoryURL );
        if ( pFactory )
        {
            SfxObjectShell* pShell = pFactory->CreateObject();
            if( pShell )
                return uno::Reference< uno::XInterface >( pShell->GetModel() );
        }
    }

    return uno::Reference< uno::XInterface >();
}

<commit_msg>INTEGRATION: CWS fwkq1 (1.2.104); FILE MERGED 2003/07/15 06:38:18 mba 1.2.104.1: #110843#: get rid of factories<commit_after>/*************************************************************************
 *
 *  $RCSfile: unodoc.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2003-09-19 08:48:56 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

// System - Includes -----------------------------------------------------

#include <tools/string.hxx>
#include <sfx2/docfac.hxx>

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

#include "swdll.hxx"
#include "docsh.hxx"
#include "globdoc.hxx"
#include "wdocsh.hxx"

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

using namespace ::com::sun::star;

//============================================================
// com.sun.star.comp.Writer.TextDocument

uno::Sequence< ::rtl::OUString > SAL_CALL SwTextDocument_getSupportedServiceNames() throw()
{
    uno::Sequence< ::rtl::OUString > aRet ( 2 );
    ::rtl::OUString* pArray = aRet.getArray();
    pArray[0] = ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.text.TextDocument" ) );
    pArray[1] = ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.document.OfficeDocument" ) );

    return aRet;
}

::rtl::OUString SAL_CALL SwTextDocument_getImplementationName() throw()
{
    return ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.TextDocument" ) );
}

uno::Reference< uno::XInterface > SAL_CALL SwTextDocument_createInstance( const uno::Reference< lang::XMultiServiceFactory > &rSMgr )
    throw( uno::Exception )
{
    ::vos::OGuard aGuard( Application::GetSolarMutex() );
    SwDLL::Init();
    SfxObjectShell* pShell = new SwDocShell( SFX_CREATE_MODE_STANDARD );
    return uno::Reference< uno::XInterface >( pShell->GetModel() );
}

//============================================================
// com.sun.star.comp.Writer.WebDocument

uno::Sequence< ::rtl::OUString > SAL_CALL SwWebDocument_getSupportedServiceNames() throw()
{
    uno::Sequence< ::rtl::OUString > aRet ( 3 );
    ::rtl::OUString* pArray = aRet.getArray();
    pArray[0] = ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.text.TextDocument" ) );
    pArray[1] = ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.document.OfficeDocument" ) );
    pArray[2] = ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.text.WebDocument" ) );

    return aRet;
}

::rtl::OUString SAL_CALL SwWebDocument_getImplementationName() throw()
{
    return ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.WebDocument" ) );
}

uno::Reference< uno::XInterface > SAL_CALL SwWebDocument_createInstance( const uno::Reference< lang::XMultiServiceFactory > &rSMgr )
    throw( uno::Exception )
{
    ::vos::OGuard aGuard( Application::GetSolarMutex() );
    SwDLL::Init();
    SfxObjectShell* pShell = new SwWebDocShell( SFX_CREATE_MODE_STANDARD );
    return uno::Reference< uno::XInterface >( pShell->GetModel() );
}

//============================================================
// com.sun.star.comp.Writer.GlobalDocument

uno::Sequence< ::rtl::OUString > SAL_CALL SwGlobalDocument_getSupportedServiceNames() throw()
{
    uno::Sequence< ::rtl::OUString > aRet ( 3 );
    ::rtl::OUString* pArray = aRet.getArray();
    pArray[0] = ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.text.TextDocument" ) );
    pArray[1] = ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.document.OfficeDocument" ) );
    pArray[2] = ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.text.GlobalDocument" ) );

    return aRet;
}

::rtl::OUString SAL_CALL SwGlobalDocument_getImplementationName() throw()
{
    return ::rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( "com.sun.star.comp.Writer.GlobalDocument" ) );
}

uno::Reference< uno::XInterface > SAL_CALL SwGlobalDocument_createInstance( const uno::Reference< lang::XMultiServiceFactory > &rSMgr )
    throw( uno::Exception )
{
    ::vos::OGuard aGuard( Application::GetSolarMutex() );
    SwDLL::Init();
    SfxObjectShell* pShell = new SwGlobalDocShell( SFX_CREATE_MODE_STANDARD );
    return uno::Reference< uno::XInterface >( pShell->GetModel() );
}

<|endoftext|>


<commit_before><commit_msg>Fix compile failure<commit_after><|endoftext|>


<commit_before><commit_msg>Revert 78065 - Add some checks to ToolbarView to see what's NULL.<commit_after><|endoftext|>


<commit_before><commit_msg>comment test again as the fix didnt work.<commit_after><|endoftext|>


<commit_before><commit_msg>Disabling this test since I can't run the suite without them erasing my profile.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ssl_client_certificate_selector.h"

#include <gtk/gtk.h>

#include <string>
#include <vector>

#include "app/gtk_signal.h"
#include "app/l10n_util.h"
#include "base/i18n/time_formatting.h"
#include "base/logging.h"
#include "base/nss_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/certificate_viewer.h"
#include "chrome/browser/gtk/constrained_window_gtk.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/gtk/owned_widget_gtk.h"
#include "chrome/browser/ssl/ssl_client_auth_handler.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/net/x509_certificate_model.h"
#include "gfx/native_widget_types.h"
#include "grit/generated_resources.h"
#include "net/base/x509_certificate.h"

namespace {

enum {
  RESPONSE_SHOW_CERT_INFO = 1,
};

///////////////////////////////////////////////////////////////////////////////
// SSLClientCertificateSelector

class SSLClientCertificateSelector : public ConstrainedDialogDelegate {
 public:
  explicit SSLClientCertificateSelector(
      TabContents* parent,
      net::SSLCertRequestInfo* cert_request_info,
      SSLClientAuthHandler* delegate);
  ~SSLClientCertificateSelector();

  void Show();

  // ConstrainedDialogDelegate implementation:
  virtual GtkWidget* GetWidgetRoot() { return root_widget_.get(); }
  virtual void DeleteDelegate() { delete this; }

 private:
  void PopulateCerts();

  net::X509Certificate* GetSelectedCert();

  static std::string FormatComboBoxText(
      net::X509Certificate::OSCertHandle cert,
      const std::string& nickname);
  static std::string FormatDetailsText(
      net::X509Certificate::OSCertHandle cert);

  CHROMEGTK_CALLBACK_0(SSLClientCertificateSelector, void, OnComboBoxChanged);
  CHROMEGTK_CALLBACK_0(SSLClientCertificateSelector, void, OnViewClicked);
  CHROMEGTK_CALLBACK_0(SSLClientCertificateSelector, void, OnCancelClicked);
  CHROMEGTK_CALLBACK_0(SSLClientCertificateSelector, void, OnOkClicked);
  CHROMEGTK_CALLBACK_1(SSLClientCertificateSelector, void, OnPromptShown,
                       GtkWidget*);

  scoped_refptr<net::SSLCertRequestInfo> cert_request_info_;

  std::vector<std::string> details_strings_;

  GtkWidget* cert_combo_box_;
  GtkTextBuffer* cert_details_buffer_;

  scoped_refptr<SSLClientAuthHandler> delegate_;

  OwnedWidgetGtk root_widget_;
  // Hold on to the select button to focus it.
  GtkWidget* select_button_;

  TabContents* parent_;
  ConstrainedWindow* window_;

  DISALLOW_COPY_AND_ASSIGN(SSLClientCertificateSelector);
};

SSLClientCertificateSelector::SSLClientCertificateSelector(
    TabContents* parent,
    net::SSLCertRequestInfo* cert_request_info,
    SSLClientAuthHandler* delegate)
    : cert_request_info_(cert_request_info),
      delegate_(delegate),
      parent_(parent),
      window_(NULL) {
  root_widget_.Own(gtk_vbox_new(FALSE, gtk_util::kControlSpacing));

  GtkWidget* site_vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
  gtk_box_pack_start(GTK_BOX(root_widget_.get()), site_vbox,
                     FALSE, FALSE, 0);

  GtkWidget* site_description_label = gtk_util::CreateBoldLabel(
      l10n_util::GetStringUTF8(IDS_CERT_SELECTOR_SITE_DESCRIPTION_LABEL));
  gtk_box_pack_start(GTK_BOX(site_vbox), site_description_label,
                     FALSE, FALSE, 0);

  GtkWidget* site_label = gtk_label_new(
      cert_request_info->host_and_port.c_str());
  gtk_util::LeftAlignMisc(site_label);
  gtk_box_pack_start(GTK_BOX(site_vbox), site_label, FALSE, FALSE, 0);

  GtkWidget* selector_vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
  gtk_box_pack_start(GTK_BOX(root_widget_.get()), selector_vbox,
                     TRUE, TRUE, 0);

  GtkWidget* choose_description_label = gtk_util::CreateBoldLabel(
      l10n_util::GetStringUTF8(IDS_CERT_SELECTOR_CHOOSE_DESCRIPTION_LABEL));
  gtk_box_pack_start(GTK_BOX(selector_vbox), choose_description_label,
                     FALSE, FALSE, 0);

  cert_combo_box_ = gtk_combo_box_new_text();
  g_signal_connect(cert_combo_box_, "changed",
                   G_CALLBACK(OnComboBoxChangedThunk), this);
  gtk_box_pack_start(GTK_BOX(selector_vbox), cert_combo_box_,
                     FALSE, FALSE, 0);

  GtkWidget* details_label = gtk_label_new(l10n_util::GetStringUTF8(
      IDS_CERT_SELECTOR_DETAILS_DESCRIPTION_LABEL).c_str());
  gtk_util::LeftAlignMisc(details_label);
  gtk_box_pack_start(GTK_BOX(selector_vbox), details_label, FALSE, FALSE, 0);

  // TODO(mattm): fix text view coloring (should have grey background).
  GtkWidget* cert_details_view = gtk_text_view_new();
  gtk_text_view_set_editable(GTK_TEXT_VIEW(cert_details_view), FALSE);
  gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(cert_details_view), GTK_WRAP_WORD);
  cert_details_buffer_ = gtk_text_view_get_buffer(
      GTK_TEXT_VIEW(cert_details_view));
  // We put the details in a frame instead of a scrolled window so that the
  // entirety will be visible without requiring scrolling or expanding the
  // dialog.  This does however mean the dialog will grow itself if you switch
  // to different cert that has longer details text.
  GtkWidget* details_frame = gtk_frame_new(NULL);
  gtk_frame_set_shadow_type(GTK_FRAME(details_frame), GTK_SHADOW_ETCHED_IN);
  gtk_container_add(GTK_CONTAINER(details_frame), cert_details_view);
  gtk_box_pack_start(GTK_BOX(selector_vbox), details_frame, TRUE, TRUE, 0);

  // And then create a set of buttons like a GtkDialog would.
  GtkWidget* button_box = gtk_hbutton_box_new();
  gtk_button_box_set_layout(GTK_BUTTON_BOX(button_box), GTK_BUTTONBOX_END);
  gtk_box_set_spacing(GTK_BOX(button_box), gtk_util::kControlSpacing);
  gtk_box_pack_end(GTK_BOX(root_widget_.get()), button_box, FALSE, FALSE, 0);

  GtkWidget* view_button = gtk_button_new_with_mnemonic(
      l10n_util::GetStringUTF8(IDS_PAGEINFO_CERT_INFO_BUTTON).c_str());
  gtk_box_pack_start(GTK_BOX(button_box), view_button, FALSE, FALSE, 0);
  g_signal_connect(view_button, "clicked",
                   G_CALLBACK(OnViewClickedThunk), this);

  GtkWidget* cancel_button = gtk_button_new_from_stock(GTK_STOCK_CANCEL);
  gtk_box_pack_end(GTK_BOX(button_box), cancel_button, FALSE, FALSE, 0);
  g_signal_connect(cancel_button, "clicked",
                   G_CALLBACK(OnCancelClickedThunk), this);

  GtkWidget* select_button = gtk_button_new_from_stock(GTK_STOCK_OK);
  gtk_box_pack_end(GTK_BOX(button_box), select_button, FALSE, FALSE, 0);
  g_signal_connect(select_button, "clicked",
                   G_CALLBACK(OnOkClickedThunk), this);

  // When we are attached to a window, focus the select button.
  select_button_ = select_button;
  g_signal_connect(root_widget_.get(), "hierarchy-changed",
                   G_CALLBACK(OnPromptShownThunk), this);
  PopulateCerts();

  gtk_widget_show_all(root_widget_.get());
}

SSLClientCertificateSelector::~SSLClientCertificateSelector() {
  root_widget_.Destroy();
}

void SSLClientCertificateSelector::Show() {
  DCHECK(!window_);
  window_ = parent_->CreateConstrainedDialog(this);
}

void SSLClientCertificateSelector::PopulateCerts() {
  std::vector<std::string> nicknames;
  x509_certificate_model::GetNicknameStringsFromCertList(
      cert_request_info_->client_certs,
      l10n_util::GetStringUTF8(IDS_CERT_SELECTOR_CERT_EXPIRED),
      l10n_util::GetStringUTF8(IDS_CERT_SELECTOR_CERT_NOT_YET_VALID),
      &nicknames);

  DCHECK_EQ(nicknames.size(),
            cert_request_info_->client_certs.size());

  for (size_t i = 0; i < cert_request_info_->client_certs.size(); ++i) {
    net::X509Certificate::OSCertHandle cert =
        cert_request_info_->client_certs[i]->os_cert_handle();

    details_strings_.push_back(FormatDetailsText(cert));

    gtk_combo_box_append_text(
        GTK_COMBO_BOX(cert_combo_box_),
        FormatComboBoxText(cert, nicknames[i]).c_str());
  }

  // Auto-select the first cert.
  gtk_combo_box_set_active(GTK_COMBO_BOX(cert_combo_box_), 0);
}

net::X509Certificate* SSLClientCertificateSelector::GetSelectedCert() {
  int selected = gtk_combo_box_get_active(GTK_COMBO_BOX(cert_combo_box_));
  if (selected >= 0 &&
      selected < static_cast<int>(
          cert_request_info_->client_certs.size()))
    return cert_request_info_->client_certs[selected];
  return NULL;
}

// static
std::string SSLClientCertificateSelector::FormatComboBoxText(
    net::X509Certificate::OSCertHandle cert, const std::string& nickname) {
  std::string rv(nickname);
  rv += " [";
  rv += x509_certificate_model::GetSerialNumberHexified(cert, "");
  rv += ']';
  return rv;
}

// static
std::string SSLClientCertificateSelector::FormatDetailsText(
    net::X509Certificate::OSCertHandle cert) {
  std::string rv;

  rv += l10n_util::GetStringFUTF8(
      IDS_CERT_SUBJECTNAME_FORMAT,
      UTF8ToUTF16(x509_certificate_model::GetSubjectName(cert)));;

  rv += "\n  ";
  rv += l10n_util::GetStringFUTF8(
      IDS_CERT_SERIAL_NUMBER_FORMAT,
      UTF8ToUTF16(
          x509_certificate_model::GetSerialNumberHexified(cert, "")));

  base::Time issued, expires;
  if (x509_certificate_model::GetTimes(cert, &issued, &expires)) {
    string16 issued_str = WideToUTF16(
        base::TimeFormatShortDateAndTime(issued));
    string16 expires_str = WideToUTF16(
        base::TimeFormatShortDateAndTime(expires));
    rv += "\n  ";
    rv += l10n_util::GetStringFUTF8(IDS_CERT_VALIDITY_RANGE_FORMAT,
                                    issued_str, expires_str);
  }

  std::vector<std::string> usages;
  x509_certificate_model::GetUsageStrings(cert, &usages);
  if (usages.size()) {
    rv += "\n  ";
    rv += l10n_util::GetStringFUTF8(IDS_CERT_X509_EXTENDED_KEY_USAGE_FORMAT,
                                    UTF8ToUTF16(JoinString(usages, ',')));
  }

  std::string key_usage_str = x509_certificate_model::GetKeyUsageString(cert);
  if (!key_usage_str.empty()) {
    rv += "\n  ";
    rv += l10n_util::GetStringFUTF8(IDS_CERT_X509_KEY_USAGE_FORMAT,
                                    UTF8ToUTF16(key_usage_str));
  }

  std::vector<std::string> email_addresses;
  x509_certificate_model::GetEmailAddresses(cert, &email_addresses);
  if (email_addresses.size()) {
    rv += "\n  ";
    rv += l10n_util::GetStringFUTF8(
        IDS_CERT_EMAIL_ADDRESSES_FORMAT,
        UTF8ToUTF16(JoinString(email_addresses, ',')));
  }

  rv += '\n';
  rv += l10n_util::GetStringFUTF8(
      IDS_CERT_ISSUERNAME_FORMAT,
      UTF8ToUTF16(x509_certificate_model::GetIssuerName(cert)));

  string16 token(UTF8ToUTF16(x509_certificate_model::GetTokenName(cert)));
  if (!token.empty()) {
    rv += '\n';
    rv += l10n_util::GetStringFUTF8(IDS_CERT_TOKEN_FORMAT, token);
  }

  return rv;
}

void SSLClientCertificateSelector::OnComboBoxChanged(GtkWidget* combo_box) {
  int selected = gtk_combo_box_get_active(
      GTK_COMBO_BOX(cert_combo_box_));
  if (selected < 0)
    return;
  gtk_text_buffer_set_text(cert_details_buffer_,
                           details_strings_[selected].c_str(),
                           details_strings_[selected].size());
}

void SSLClientCertificateSelector::OnViewClicked(GtkWidget* button) {
  net::X509Certificate* cert = GetSelectedCert();
  if (cert) {
    GtkWidget* toplevel = gtk_widget_get_toplevel(root_widget_.get());
    ShowCertificateViewer(GTK_WINDOW(toplevel), cert);
  }
}

void SSLClientCertificateSelector::OnCancelClicked(GtkWidget* button) {
  delegate_->CertificateSelected(NULL);
  DCHECK(window_);
  window_->CloseConstrainedWindow();
}

void SSLClientCertificateSelector::OnOkClicked(GtkWidget* button) {
  net::X509Certificate* cert = GetSelectedCert();
  delegate_->CertificateSelected(cert);
  DCHECK(window_);
  window_->CloseConstrainedWindow();
}

void SSLClientCertificateSelector::OnPromptShown(GtkWidget* widget,
                                                 GtkWidget* previous_toplevel) {
  if (!root_widget_.get() ||
      !GTK_WIDGET_TOPLEVEL(gtk_widget_get_toplevel(root_widget_.get())))
    return;
  GTK_WIDGET_SET_FLAGS(select_button_, GTK_CAN_DEFAULT);
  gtk_widget_grab_default(select_button_);
  gtk_widget_grab_focus(select_button_);
}

}  // namespace

///////////////////////////////////////////////////////////////////////////////
// SSLClientAuthHandler platform specific implementation:

namespace browser {

void ShowSSLClientCertificateSelector(
    TabContents* parent,
    net::SSLCertRequestInfo* cert_request_info,
    SSLClientAuthHandler* delegate) {
  (new SSLClientCertificateSelector(parent,
                                    cert_request_info,
                                    delegate))->Show();
}

}  // namespace browser
<commit_msg>Linux: Fix client certificate selection dialog handling of esc key.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ssl_client_certificate_selector.h"

#include <gtk/gtk.h>

#include <string>
#include <vector>

#include "app/gtk_signal.h"
#include "app/l10n_util.h"
#include "base/i18n/time_formatting.h"
#include "base/logging.h"
#include "base/nss_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/certificate_viewer.h"
#include "chrome/browser/gtk/constrained_window_gtk.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/gtk/owned_widget_gtk.h"
#include "chrome/browser/ssl/ssl_client_auth_handler.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/net/x509_certificate_model.h"
#include "gfx/native_widget_types.h"
#include "grit/generated_resources.h"
#include "net/base/x509_certificate.h"

namespace {

enum {
  RESPONSE_SHOW_CERT_INFO = 1,
};

///////////////////////////////////////////////////////////////////////////////
// SSLClientCertificateSelector

class SSLClientCertificateSelector : public ConstrainedDialogDelegate {
 public:
  explicit SSLClientCertificateSelector(
      TabContents* parent,
      net::SSLCertRequestInfo* cert_request_info,
      SSLClientAuthHandler* delegate);
  ~SSLClientCertificateSelector();

  void Show();

  // ConstrainedDialogDelegate implementation:
  virtual GtkWidget* GetWidgetRoot() { return root_widget_.get(); }
  virtual void DeleteDelegate();

 private:
  void PopulateCerts();

  net::X509Certificate* GetSelectedCert();

  static std::string FormatComboBoxText(
      net::X509Certificate::OSCertHandle cert,
      const std::string& nickname);
  static std::string FormatDetailsText(
      net::X509Certificate::OSCertHandle cert);

  CHROMEGTK_CALLBACK_0(SSLClientCertificateSelector, void, OnComboBoxChanged);
  CHROMEGTK_CALLBACK_0(SSLClientCertificateSelector, void, OnViewClicked);
  CHROMEGTK_CALLBACK_0(SSLClientCertificateSelector, void, OnCancelClicked);
  CHROMEGTK_CALLBACK_0(SSLClientCertificateSelector, void, OnOkClicked);
  CHROMEGTK_CALLBACK_1(SSLClientCertificateSelector, void, OnPromptShown,
                       GtkWidget*);

  scoped_refptr<net::SSLCertRequestInfo> cert_request_info_;

  std::vector<std::string> details_strings_;

  GtkWidget* cert_combo_box_;
  GtkTextBuffer* cert_details_buffer_;

  scoped_refptr<SSLClientAuthHandler> delegate_;

  OwnedWidgetGtk root_widget_;
  // Hold on to the select button to focus it.
  GtkWidget* select_button_;

  TabContents* parent_;
  ConstrainedWindow* window_;

  DISALLOW_COPY_AND_ASSIGN(SSLClientCertificateSelector);
};

SSLClientCertificateSelector::SSLClientCertificateSelector(
    TabContents* parent,
    net::SSLCertRequestInfo* cert_request_info,
    SSLClientAuthHandler* delegate)
    : cert_request_info_(cert_request_info),
      delegate_(delegate),
      parent_(parent),
      window_(NULL) {
  root_widget_.Own(gtk_vbox_new(FALSE, gtk_util::kControlSpacing));

  GtkWidget* site_vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
  gtk_box_pack_start(GTK_BOX(root_widget_.get()), site_vbox,
                     FALSE, FALSE, 0);

  GtkWidget* site_description_label = gtk_util::CreateBoldLabel(
      l10n_util::GetStringUTF8(IDS_CERT_SELECTOR_SITE_DESCRIPTION_LABEL));
  gtk_box_pack_start(GTK_BOX(site_vbox), site_description_label,
                     FALSE, FALSE, 0);

  GtkWidget* site_label = gtk_label_new(
      cert_request_info->host_and_port.c_str());
  gtk_util::LeftAlignMisc(site_label);
  gtk_box_pack_start(GTK_BOX(site_vbox), site_label, FALSE, FALSE, 0);

  GtkWidget* selector_vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
  gtk_box_pack_start(GTK_BOX(root_widget_.get()), selector_vbox,
                     TRUE, TRUE, 0);

  GtkWidget* choose_description_label = gtk_util::CreateBoldLabel(
      l10n_util::GetStringUTF8(IDS_CERT_SELECTOR_CHOOSE_DESCRIPTION_LABEL));
  gtk_box_pack_start(GTK_BOX(selector_vbox), choose_description_label,
                     FALSE, FALSE, 0);

  cert_combo_box_ = gtk_combo_box_new_text();
  g_signal_connect(cert_combo_box_, "changed",
                   G_CALLBACK(OnComboBoxChangedThunk), this);
  gtk_box_pack_start(GTK_BOX(selector_vbox), cert_combo_box_,
                     FALSE, FALSE, 0);

  GtkWidget* details_label = gtk_label_new(l10n_util::GetStringUTF8(
      IDS_CERT_SELECTOR_DETAILS_DESCRIPTION_LABEL).c_str());
  gtk_util::LeftAlignMisc(details_label);
  gtk_box_pack_start(GTK_BOX(selector_vbox), details_label, FALSE, FALSE, 0);

  // TODO(mattm): fix text view coloring (should have grey background).
  GtkWidget* cert_details_view = gtk_text_view_new();
  gtk_text_view_set_editable(GTK_TEXT_VIEW(cert_details_view), FALSE);
  gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(cert_details_view), GTK_WRAP_WORD);
  cert_details_buffer_ = gtk_text_view_get_buffer(
      GTK_TEXT_VIEW(cert_details_view));
  // We put the details in a frame instead of a scrolled window so that the
  // entirety will be visible without requiring scrolling or expanding the
  // dialog.  This does however mean the dialog will grow itself if you switch
  // to different cert that has longer details text.
  GtkWidget* details_frame = gtk_frame_new(NULL);
  gtk_frame_set_shadow_type(GTK_FRAME(details_frame), GTK_SHADOW_ETCHED_IN);
  gtk_container_add(GTK_CONTAINER(details_frame), cert_details_view);
  gtk_box_pack_start(GTK_BOX(selector_vbox), details_frame, TRUE, TRUE, 0);

  // And then create a set of buttons like a GtkDialog would.
  GtkWidget* button_box = gtk_hbutton_box_new();
  gtk_button_box_set_layout(GTK_BUTTON_BOX(button_box), GTK_BUTTONBOX_END);
  gtk_box_set_spacing(GTK_BOX(button_box), gtk_util::kControlSpacing);
  gtk_box_pack_end(GTK_BOX(root_widget_.get()), button_box, FALSE, FALSE, 0);

  GtkWidget* view_button = gtk_button_new_with_mnemonic(
      l10n_util::GetStringUTF8(IDS_PAGEINFO_CERT_INFO_BUTTON).c_str());
  gtk_box_pack_start(GTK_BOX(button_box), view_button, FALSE, FALSE, 0);
  g_signal_connect(view_button, "clicked",
                   G_CALLBACK(OnViewClickedThunk), this);

  GtkWidget* cancel_button = gtk_button_new_from_stock(GTK_STOCK_CANCEL);
  gtk_box_pack_end(GTK_BOX(button_box), cancel_button, FALSE, FALSE, 0);
  g_signal_connect(cancel_button, "clicked",
                   G_CALLBACK(OnCancelClickedThunk), this);

  GtkWidget* select_button = gtk_button_new_from_stock(GTK_STOCK_OK);
  gtk_box_pack_end(GTK_BOX(button_box), select_button, FALSE, FALSE, 0);
  g_signal_connect(select_button, "clicked",
                   G_CALLBACK(OnOkClickedThunk), this);

  // When we are attached to a window, focus the select button.
  select_button_ = select_button;
  g_signal_connect(root_widget_.get(), "hierarchy-changed",
                   G_CALLBACK(OnPromptShownThunk), this);
  PopulateCerts();

  gtk_widget_show_all(root_widget_.get());
}

SSLClientCertificateSelector::~SSLClientCertificateSelector() {
  root_widget_.Destroy();
}

void SSLClientCertificateSelector::Show() {
  DCHECK(!window_);
  window_ = parent_->CreateConstrainedDialog(this);
}

void SSLClientCertificateSelector::DeleteDelegate() {
  if (delegate_) {
    // The dialog was closed by escape key.
    delegate_->CertificateSelected(NULL);
  }
  delete this;
}

void SSLClientCertificateSelector::PopulateCerts() {
  std::vector<std::string> nicknames;
  x509_certificate_model::GetNicknameStringsFromCertList(
      cert_request_info_->client_certs,
      l10n_util::GetStringUTF8(IDS_CERT_SELECTOR_CERT_EXPIRED),
      l10n_util::GetStringUTF8(IDS_CERT_SELECTOR_CERT_NOT_YET_VALID),
      &nicknames);

  DCHECK_EQ(nicknames.size(),
            cert_request_info_->client_certs.size());

  for (size_t i = 0; i < cert_request_info_->client_certs.size(); ++i) {
    net::X509Certificate::OSCertHandle cert =
        cert_request_info_->client_certs[i]->os_cert_handle();

    details_strings_.push_back(FormatDetailsText(cert));

    gtk_combo_box_append_text(
        GTK_COMBO_BOX(cert_combo_box_),
        FormatComboBoxText(cert, nicknames[i]).c_str());
  }

  // Auto-select the first cert.
  gtk_combo_box_set_active(GTK_COMBO_BOX(cert_combo_box_), 0);
}

net::X509Certificate* SSLClientCertificateSelector::GetSelectedCert() {
  int selected = gtk_combo_box_get_active(GTK_COMBO_BOX(cert_combo_box_));
  if (selected >= 0 &&
      selected < static_cast<int>(
          cert_request_info_->client_certs.size()))
    return cert_request_info_->client_certs[selected];
  return NULL;
}

// static
std::string SSLClientCertificateSelector::FormatComboBoxText(
    net::X509Certificate::OSCertHandle cert, const std::string& nickname) {
  std::string rv(nickname);
  rv += " [";
  rv += x509_certificate_model::GetSerialNumberHexified(cert, "");
  rv += ']';
  return rv;
}

// static
std::string SSLClientCertificateSelector::FormatDetailsText(
    net::X509Certificate::OSCertHandle cert) {
  std::string rv;

  rv += l10n_util::GetStringFUTF8(
      IDS_CERT_SUBJECTNAME_FORMAT,
      UTF8ToUTF16(x509_certificate_model::GetSubjectName(cert)));;

  rv += "\n  ";
  rv += l10n_util::GetStringFUTF8(
      IDS_CERT_SERIAL_NUMBER_FORMAT,
      UTF8ToUTF16(
          x509_certificate_model::GetSerialNumberHexified(cert, "")));

  base::Time issued, expires;
  if (x509_certificate_model::GetTimes(cert, &issued, &expires)) {
    string16 issued_str = WideToUTF16(
        base::TimeFormatShortDateAndTime(issued));
    string16 expires_str = WideToUTF16(
        base::TimeFormatShortDateAndTime(expires));
    rv += "\n  ";
    rv += l10n_util::GetStringFUTF8(IDS_CERT_VALIDITY_RANGE_FORMAT,
                                    issued_str, expires_str);
  }

  std::vector<std::string> usages;
  x509_certificate_model::GetUsageStrings(cert, &usages);
  if (usages.size()) {
    rv += "\n  ";
    rv += l10n_util::GetStringFUTF8(IDS_CERT_X509_EXTENDED_KEY_USAGE_FORMAT,
                                    UTF8ToUTF16(JoinString(usages, ',')));
  }

  std::string key_usage_str = x509_certificate_model::GetKeyUsageString(cert);
  if (!key_usage_str.empty()) {
    rv += "\n  ";
    rv += l10n_util::GetStringFUTF8(IDS_CERT_X509_KEY_USAGE_FORMAT,
                                    UTF8ToUTF16(key_usage_str));
  }

  std::vector<std::string> email_addresses;
  x509_certificate_model::GetEmailAddresses(cert, &email_addresses);
  if (email_addresses.size()) {
    rv += "\n  ";
    rv += l10n_util::GetStringFUTF8(
        IDS_CERT_EMAIL_ADDRESSES_FORMAT,
        UTF8ToUTF16(JoinString(email_addresses, ',')));
  }

  rv += '\n';
  rv += l10n_util::GetStringFUTF8(
      IDS_CERT_ISSUERNAME_FORMAT,
      UTF8ToUTF16(x509_certificate_model::GetIssuerName(cert)));

  string16 token(UTF8ToUTF16(x509_certificate_model::GetTokenName(cert)));
  if (!token.empty()) {
    rv += '\n';
    rv += l10n_util::GetStringFUTF8(IDS_CERT_TOKEN_FORMAT, token);
  }

  return rv;
}

void SSLClientCertificateSelector::OnComboBoxChanged(GtkWidget* combo_box) {
  int selected = gtk_combo_box_get_active(
      GTK_COMBO_BOX(cert_combo_box_));
  if (selected < 0)
    return;
  gtk_text_buffer_set_text(cert_details_buffer_,
                           details_strings_[selected].c_str(),
                           details_strings_[selected].size());
}

void SSLClientCertificateSelector::OnViewClicked(GtkWidget* button) {
  net::X509Certificate* cert = GetSelectedCert();
  if (cert) {
    GtkWidget* toplevel = gtk_widget_get_toplevel(root_widget_.get());
    ShowCertificateViewer(GTK_WINDOW(toplevel), cert);
  }
}

void SSLClientCertificateSelector::OnCancelClicked(GtkWidget* button) {
  delegate_->CertificateSelected(NULL);
  delegate_ = NULL;
  DCHECK(window_);
  window_->CloseConstrainedWindow();
}

void SSLClientCertificateSelector::OnOkClicked(GtkWidget* button) {
  net::X509Certificate* cert = GetSelectedCert();
  delegate_->CertificateSelected(cert);
  delegate_ = NULL;
  DCHECK(window_);
  window_->CloseConstrainedWindow();
}

void SSLClientCertificateSelector::OnPromptShown(GtkWidget* widget,
                                                 GtkWidget* previous_toplevel) {
  if (!root_widget_.get() ||
      !GTK_WIDGET_TOPLEVEL(gtk_widget_get_toplevel(root_widget_.get())))
    return;
  GTK_WIDGET_SET_FLAGS(select_button_, GTK_CAN_DEFAULT);
  gtk_widget_grab_default(select_button_);
  gtk_widget_grab_focus(select_button_);
}

}  // namespace

///////////////////////////////////////////////////////////////////////////////
// SSLClientAuthHandler platform specific implementation:

namespace browser {

void ShowSSLClientCertificateSelector(
    TabContents* parent,
    net::SSLCertRequestInfo* cert_request_info,
    SSLClientAuthHandler* delegate) {
  (new SSLClientCertificateSelector(parent,
                                    cert_request_info,
                                    delegate))->Show();
}

}  // namespace browser
<|endoftext|>


<commit_before><commit_msg>Mark MiniInstallTest.InstallMiniInstallerUser as flaky as it fails occasionally.<commit_after><|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>

#define N 3
#define M 4

int main(int argc, char *argv[]){
    int matriz[N][M];

    for (int fila=0; fila<N; fila++){
	for (int col=0; col<M; col++)
	    printf(" %i", matriz[fila][col]);
	printf("\n");
    }

    return EXIT_SUCCESS;
}
<commit_msg>Delete mapa.cpp<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include "ext_mongo.h"
#include "bson_decode.h"
#include "contrib/encode.h"

namespace HPHP {

////////////////////////////////////////////////////////////////////////////////
// class MongoCursor

static Array HHVM_METHOD(MongoCursor, current) {
  mongoc_cursor_t *cursor = get_cursor(this_)->get();
  const bson_t *doc;

  doc = mongoc_cursor_current(cursor);
  if (doc) {
    auto ret = cbson_loads(doc); //TODO: We should return the translated PHP Array here
    return ret;
  } else {
    return Array::Create(); //Empty array means no valid document left
  }
}

static bool HHVM_METHOD(MongoCursor, hasNext) {
  bson_error_t error;
  mongoc_cursor_t *cursor = get_cursor(this_)->get();

  bool ret = mongoc_cursor_more(cursor);
  if (!mongoc_cursor_error (cursor, &error)) {
    return ret;
  } else {
    throw FatalErrorException(error.message);
  }
}

static void HHVM_METHOD(MongoCursor, next) {
  const bson_t *doc;
  mongoc_cursor_t *cursor = get_cursor(this_)->get();
  // if (!mongoc_cursor_next (cursor, &doc)) {
  //   if (mongoc_cursor_error (cursor, &error)) {
  //     throw FatalErrorException(error.message);
  //   }
  // }
  mongoc_cursor_next (cursor, &doc);   //Note: error would be catched by valid()
}

static void HHVM_METHOD(MongoCursor, reset) {
  if (get_cursor(this_)) {
    get_cursor(this_)->~MongocCursor();
  }
}

static void HHVM_METHOD(MongoCursor, rewind) {
  HHVM_MN(MongoCursor, reset)(this_);

  //TODO: need to test with null value
  auto connection = this_->o_realProp("connection", ObjectData::RealPropUnchecked, "MongoCursor")->toObject();
  auto ns = this_->o_realProp("ns", ObjectData::RealPropUnchecked, "MongoCursor")->toString();
  auto query = this_->o_realProp("query", ObjectData::RealPropUnchecked, "MongoCursor")->toArray();
  bson_t query_bs;
  query_bs = encodeToBSON(query);
  /*
  bson_init(&query_bs);
  if (!query->empty()) {
    //Currently only supports "name" query
    bson_append_utf8(&query_bs, "name", 4, query[String("name")].toString().c_str(), query[String("name")].toString().length());

  }
  */

//Parameters and their types:
//static void HHVM_METHOD(MongoCursor, __construct, const Object& connection, const String& ns, const Array& query, const Array& fields)
/*
MongocCursor(mongoc_client_t           *client,
                const char                *db_and_collection,
                mongoc_query_flags_t       flags,
                uint32_t                   skip,
                uint32_t                   limit,
                uint32_t                   batch_size,
                bool                       is_command,
                const bson_t              *query,
                const bson_t              *fields,
                const mongoc_read_prefs_t *read_prefs);
                */

  MongocCursor *cursor = new MongocCursor(get_client(connection)->get(), ns.c_str(), MONGOC_QUERY_NONE, 0, 0, 0, false, &query_bs, NULL, NULL);
  //std::cout << "Got past cursor construction with" << ns.c_str() << std::endl;
  this_->o_set(s_mongoc_cursor, cursor, s_mongocursor);
  bson_destroy(&query_bs);

  this_->o_set("started_iterating", Variant(true), "MongoCursor");

  HHVM_MN(MongoCursor, next)(this_);
}

static bool HHVM_METHOD(MongoCursor, valid) {
  auto cur = HHVM_MN(MongoCursor, current)(this_);
  return !(cur->empty());
}

////////////////////////////////////////////////////////////////////////////////

void mongoExtension::_initMongoCursorClass() {
    HHVM_ME(MongoCursor, current);
    HHVM_ME(MongoCursor, hasNext);
    HHVM_ME(MongoCursor, next);
    HHVM_ME(MongoCursor, reset);
    HHVM_ME(MongoCursor, rewind);
    HHVM_ME(MongoCursor, valid);
}

} // namespace HPHP
<commit_msg>Intermediate commit for command integration<commit_after>#include <iostream>
#include "ext_mongo.h"
#include "bson_decode.h"
#include "contrib/encode.h"

namespace HPHP {

////////////////////////////////////////////////////////////////////////////////
// class MongoCursor

static Array HHVM_METHOD(MongoCursor, current) {
  mongoc_cursor_t *cursor = get_cursor(this_)->get();
  const bson_t *doc;

  doc = mongoc_cursor_current(cursor);
  if (doc) {
    auto ret = cbson_loads(doc); //TODO: We should return the translated PHP Array here
    return ret;
  } else {
    return Array::Create(); //Empty array means no valid document left
  }
}

static bool HHVM_METHOD(MongoCursor, hasNext) {
  bson_error_t error;
  mongoc_cursor_t *cursor = get_cursor(this_)->get();

  bool ret = mongoc_cursor_more(cursor);
  if (!mongoc_cursor_error (cursor, &error)) {
    return ret;
  } else {
    throw FatalErrorException(error.message);
  }
}

static void HHVM_METHOD(MongoCursor, next) {
  const bson_t *doc;
  mongoc_cursor_t *cursor = get_cursor(this_)->get();
  // if (!mongoc_cursor_next (cursor, &doc)) {
  //   if (mongoc_cursor_error (cursor, &error)) {
  //     throw FatalErrorException(error.message);
  //   }
  // }
  mongoc_cursor_next (cursor, &doc);   //Note: error would be catched by valid()
}

static void HHVM_METHOD(MongoCursor, reset) {
  if (get_cursor(this_)) {
    get_cursor(this_)->~MongocCursor();
  }
}

static void HHVM_METHOD(MongoCursor, rewind) {
  HHVM_MN(MongoCursor, reset)(this_);

  mongoc_collection_t *collection;
  //TODO: need to test with null value
  auto connection = this_->o_realProp("connection", ObjectData::RealPropUnchecked, "MongoCursor")->toObject();
  auto ns = this_->o_realProp("ns", ObjectData::RealPropUnchecked, "MongoCursor")->toString();
  auto query = this_->o_realProp("query", ObjectData::RealPropUnchecked, "MongoCursor")->toArray();
  bson_t query_bs;
  query_bs = encodeToBSON(query);

  // TODO commands
  auto db = this_->o_realProp("db", ObjectData::RealPropUnchecked, "MongoCollection")->toObject();
  auto client = db->o_realProp("client", ObjectData::RealPropUnchecked, "MongoDB")->toObject();
  String db_name = db->o_realProp("db_name", ObjectData::RealPropUnchecked, "MongoDB")->toString();
  String collection_name = this_->o_realProp("name", ObjectData::RealPropUnchecked, "MongoCollection")->toString();

  collection = mongoc_client_get_collection (get_client(client)->get(), db_name.c_str(), collection_name.c_str());
  m_cursor = mongoc_collection_find (collection,
                                    flags,
                                    skip,
                                    limit,
                                    batch_size,
                                    query,
                                    fields,
                                    read_prefs);

  /*
  bson_init(&query_bs);
  if (!query->empty()) {
    //Currently only supports "name" query
    bson_append_utf8(&query_bs, "name", 4, query[String("name")].toString().c_str(), query[String("name")].toString().length());
    */

  }

//Parameters and their types:
//static void HHVM_METHOD(MongoCursor, __construct, const Object& connection, const String& ns, const Array& query, const Array& fields)

MongocCursor(mongoc_client_t           *client,
                const char                *db_and_collection,
                mongoc_query_flags_t       flags,
                uint32_t                   skip,
                uint32_t                   limit,
                uint32_t                   batch_size,
                bool                       is_command,
                const bson_t              *query,
                const bson_t              *fields,
                const mongoc_read_prefs_t *read_prefs);

  MongocCursor *cursor = new MongocCursor(get_client(connection)->get(), ns.c_str(), MONGOC_QUERY_NONE, 0, 0, 0, false, &query_bs, NULL, NULL);
  //std::cout << "Got past cursor construction with" << ns.c_str() << std::endl;
  this_->o_set(s_mongoc_cursor, cursor, s_mongocursor);
  bson_destroy(&query_bs);

  this_->o_set("started_iterating", Variant(true), "MongoCursor");

  HHVM_MN(MongoCursor, next)(this_);
}

static bool HHVM_METHOD(MongoCursor, valid) {
  auto cur = HHVM_MN(MongoCursor, current)(this_);
  return !(cur->empty());
}

////////////////////////////////////////////////////////////////////////////////

void mongoExtension::_initMongoCursorClass() {
    HHVM_ME(MongoCursor, current);
    HHVM_ME(MongoCursor, hasNext);
    HHVM_ME(MongoCursor, next);
    HHVM_ME(MongoCursor, reset);
    HHVM_ME(MongoCursor, rewind);
    HHVM_ME(MongoCursor, valid);
}

} // namespace HPHP
<|endoftext|>


<commit_before>/**
Copyright (c) 2016, Ubiquity Robotics
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 ubiquity_motor 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 HOLDER 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 <ubiquity_motor/motor_serial.h>
#include <ros/ros.h>
#include <serial/serial.h>

MotorSerial::MotorSerial(const std::string &port, uint32_t baud_rate, double loopRate) {
	have_input = false;

	// Make sure baud rate is valid
	switch (baud_rate) {
		case 110 :
		case 300 :
		case 600 :
		case 1200 :
		case 2400 :
		case 4800 :
		case 9600 :
		case 14400 :
		case 19200 :
		case 28800 :
		case 38400 :
		case 56000 :
		case 57600 :
		case 115200 :
		case 128000 :
		case 153600 :
		case 230400 :
		case 256000 :
		case 460800 :
		case 921600 :
		this->_baud_rate = baud_rate;
		break;
		default :
		this->_baud_rate = 9600;
		break;
	}

	// TODO verify that port is valid
	this->_port = port;

	motors = new serial::Serial(_port, _baud_rate, serial::Timeout::simpleTimeout(10000));

	serial_loop_rate = new ros::Rate(loopRate);

	serial_thread = new boost::thread(&MotorSerial::SerialThread, this);

	have_input = false;
	have_output = false;
}

MotorSerial::~MotorSerial() {
	serial_thread->interrupt();
	serial_thread->join();
	motors->close();
	delete motors;
	delete serial_thread;
	delete serial_loop_rate;
}

int MotorSerial::transmitCommand(MotorMessage command) {
	// Make sure to lock mutex before accessing the input fifo
	input_mtx_.lock();
	this->input.push(command); // add latest command to end of fifo
	this->have_input = true; //Used to avoid input locking
	input_mtx_.unlock();
	return 0;
}

int MotorSerial::transmitCommands(const std::vector<MotorMessage> &commands) {
	// Make sure to lock mutex before accessing the input fifo
	input_mtx_.lock();
	for (std::vector<MotorMessage>::const_iterator it = commands.begin(); it != commands.end(); ++it) {
		this->input.push(*it);
		this->have_input = true; //Used to avoid input locking
	}
	input_mtx_.unlock();
	return 0;
}

MotorMessage MotorSerial::receiveCommand() {
	MotorMessage mc;

	output_mtx_.lock();
	if (!this->output.empty()) {
		mc = this->output.front();
		this->output.pop();
	}

	// If we just popped the last message
	if (this->output.empty()) {
		this->have_output = false;
	}

	output_mtx_.unlock();
	return mc;
}

int MotorSerial::commandAvailable() {
	// If have_output is false return false
	// if it is true, then verify there is output and return true
	// if verification fails make sure have_output is false
	if(!this->have_output) {
		return false;
	}

	output_mtx_.lock();
	int out = !(this->output.empty());
	if(!out) {
		this->have_output = false;
	}
	output_mtx_.unlock();

	return out;
}

int MotorSerial::inputAvailable() {
	// If have_input is false return false
	// if it is true, then verify there is input and return true
	// if verification fails make sure have_input is false

	if (!this->have_input) {
		return false;
	}

	input_mtx_.lock();
	int out = !(this->input.empty());
	if (!out) {
		this->have_input = false;
	}
	input_mtx_.unlock();

	return out;
}

MotorMessage MotorSerial::getInputCommand() {
	MotorMessage mc;
	input_mtx_.lock();
	if (!this->input.empty()) {
		mc = this->input.front();
		this->input.pop();
	}

	// If we just popped the last message
	if (this->input.empty()) {
		this->have_input = false;
	}

	input_mtx_.unlock();
	return mc;
}

void MotorSerial::appendOutput(MotorMessage command) {
	output_mtx_.lock();
	this->output.push(command);
	this->have_output = true;
	output_mtx_.unlock();
}

void MotorSerial::SerialThread() {
	try {
		std::vector<uint8_t> in(0);
		bool failed_update = false;

		while (motors->isOpen()) {

			while (motors->available() >= (failed_update ? 1 : 9)) {
				std::vector<uint8_t> innew(0);
				motors->read(innew, failed_update ? 1 : 9);
				in.insert(in.end(), innew.begin(), innew.end());

				while (in.size() > 9) {
					in.erase(in.begin());
				}

				MotorMessage mc;
				int error_code = mc.deserialize(in);

				if (error_code == 0) {
					if (mc.getType() == MotorMessage::TYPE_ERROR){
						ROS_ERROR("GOT ERROR RESPONSE FROM PSOC FOR REGISTER 0x%02x", mc.getRegister());
					}
					appendOutput(mc);
					failed_update = false;
				} else if (error_code == 1) {
					failed_update = true;
					char rejected[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
					for (int i = 0; i < in.size() && i < 9; i++) {
						rejected[i] = in.at(i);
					}
					ROS_ERROR("REJECT: %s", rejected);
				} else {
					failed_update = true;
					ROS_ERROR("DESERIALIZATION ERROR! - %d", error_code);
				}
			}

			bool did_update = false;
			while (inputAvailable()) {
				did_update = true;

				std::vector<uint8_t> out(9);

				out = getInputCommand().serialize();
				// ROS_ERROR("out %x %x %x %x %x %x %x %x %x",
				// 	out[0],
				// 	out[1],
				// 	out[2],
				// 	out[3],
				// 	out[4],
				// 	out[5],
				// 	out[6],
				// 	out[7],
				// 	out[8]);
				motors->write(out);
			}

			if (did_update) {
				motors->flushOutput();
			}

			// boost::posix_time::milliseconds loopDelay(10);
			// boost::this_thread::sleep(loopDelay);
			boost::this_thread::interruption_point();
			serial_loop_rate->sleep();
		}

	}
	catch (const boost::thread_interrupted &e) {
		// ROS_INFO("boost::thread_interrupted");
		motors->close();
	}
	catch (const serial::IOException &e) {
		ROS_ERROR("%s", e.what());
	}
	catch (const serial::PortNotOpenedException &e) {
		ROS_ERROR("%s", e.what());
	}
	catch (...) {
		ROS_ERROR("Unknown Error");
		throw;
	}
}
<commit_msg>use prefix increment to avoid temp for iterating<commit_after>/**
Copyright (c) 2016, Ubiquity Robotics
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 ubiquity_motor 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 HOLDER 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 <ubiquity_motor/motor_serial.h>
#include <ros/ros.h>
#include <serial/serial.h>

MotorSerial::MotorSerial(const std::string &port, uint32_t baud_rate, double loopRate) {
	have_input = false;

	// Make sure baud rate is valid
	switch (baud_rate) {
		case 110 :
		case 300 :
		case 600 :
		case 1200 :
		case 2400 :
		case 4800 :
		case 9600 :
		case 14400 :
		case 19200 :
		case 28800 :
		case 38400 :
		case 56000 :
		case 57600 :
		case 115200 :
		case 128000 :
		case 153600 :
		case 230400 :
		case 256000 :
		case 460800 :
		case 921600 :
		this->_baud_rate = baud_rate;
		break;
		default :
		this->_baud_rate = 9600;
		break;
	}

	// TODO verify that port is valid
	this->_port = port;

	motors = new serial::Serial(_port, _baud_rate, serial::Timeout::simpleTimeout(10000));

	serial_loop_rate = new ros::Rate(loopRate);

	serial_thread = new boost::thread(&MotorSerial::SerialThread, this);

	have_input = false;
	have_output = false;
}

MotorSerial::~MotorSerial() {
	serial_thread->interrupt();
	serial_thread->join();
	motors->close();
	delete motors;
	delete serial_thread;
	delete serial_loop_rate;
}

int MotorSerial::transmitCommand(MotorMessage command) {
	// Make sure to lock mutex before accessing the input fifo
	input_mtx_.lock();
	this->input.push(command); // add latest command to end of fifo
	this->have_input = true; //Used to avoid input locking
	input_mtx_.unlock();
	return 0;
}

int MotorSerial::transmitCommands(const std::vector<MotorMessage> &commands) {
	// Make sure to lock mutex before accessing the input fifo
	input_mtx_.lock();
	for (std::vector<MotorMessage>::const_iterator it = commands.begin(); it != commands.end(); ++it) {
		this->input.push(*it);
		this->have_input = true; //Used to avoid input locking
	}
	input_mtx_.unlock();
	return 0;
}

MotorMessage MotorSerial::receiveCommand() {
	MotorMessage mc;

	output_mtx_.lock();
	if (!this->output.empty()) {
		mc = this->output.front();
		this->output.pop();
	}

	// If we just popped the last message
	if (this->output.empty()) {
		this->have_output = false;
	}

	output_mtx_.unlock();
	return mc;
}

int MotorSerial::commandAvailable() {
	// If have_output is false return false
	// if it is true, then verify there is output and return true
	// if verification fails make sure have_output is false
	if(!this->have_output) {
		return false;
	}

	output_mtx_.lock();
	int out = !(this->output.empty());
	if(!out) {
		this->have_output = false;
	}
	output_mtx_.unlock();

	return out;
}

int MotorSerial::inputAvailable() {
	// If have_input is false return false
	// if it is true, then verify there is input and return true
	// if verification fails make sure have_input is false

	if (!this->have_input) {
		return false;
	}

	input_mtx_.lock();
	int out = !(this->input.empty());
	if (!out) {
		this->have_input = false;
	}
	input_mtx_.unlock();

	return out;
}

MotorMessage MotorSerial::getInputCommand() {
	MotorMessage mc;
	input_mtx_.lock();
	if (!this->input.empty()) {
		mc = this->input.front();
		this->input.pop();
	}

	// If we just popped the last message
	if (this->input.empty()) {
		this->have_input = false;
	}

	input_mtx_.unlock();
	return mc;
}

void MotorSerial::appendOutput(MotorMessage command) {
	output_mtx_.lock();
	this->output.push(command);
	this->have_output = true;
	output_mtx_.unlock();
}

void MotorSerial::SerialThread() {
	try {
		std::vector<uint8_t> in(0);
		bool failed_update = false;

		while (motors->isOpen()) {

			while (motors->available() >= (failed_update ? 1 : 9)) {
				std::vector<uint8_t> innew(0);
				motors->read(innew, failed_update ? 1 : 9);
				in.insert(in.end(), innew.begin(), innew.end());

				while (in.size() > 9) {
					in.erase(in.begin());
				}

				MotorMessage mc;
				int error_code = mc.deserialize(in);

				if (error_code == 0) {
					if (mc.getType() == MotorMessage::TYPE_ERROR){
						ROS_ERROR("GOT ERROR RESPONSE FROM PSOC FOR REGISTER 0x%02x", mc.getRegister());
					}
					appendOutput(mc);
					failed_update = false;
				} else if (error_code == 1) {
					failed_update = true;
					char rejected[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
					for (int i = 0; i < in.size() && i < 9; ++i) {
						rejected[i] = in.at(i);
					}
					ROS_ERROR("REJECT: %s", rejected);
				} else {
					failed_update = true;
					ROS_ERROR("DESERIALIZATION ERROR! - %d", error_code);
				}
			}

			bool did_update = false;
			while (inputAvailable()) {
				did_update = true;

				std::vector<uint8_t> out(9);

				out = getInputCommand().serialize();
				// ROS_ERROR("out %x %x %x %x %x %x %x %x %x",
				// 	out[0],
				// 	out[1],
				// 	out[2],
				// 	out[3],
				// 	out[4],
				// 	out[5],
				// 	out[6],
				// 	out[7],
				// 	out[8]);
				motors->write(out);
			}

			if (did_update) {
				motors->flushOutput();
			}

			// boost::posix_time::milliseconds loopDelay(10);
			// boost::this_thread::sleep(loopDelay);
			boost::this_thread::interruption_point();
			serial_loop_rate->sleep();
		}

	}
	catch (const boost::thread_interrupted &e) {
		// ROS_INFO("boost::thread_interrupted");
		motors->close();
	}
	catch (const serial::IOException &e) {
		ROS_ERROR("%s", e.what());
	}
	catch (const serial::PortNotOpenedException &e) {
		ROS_ERROR("%s", e.what());
	}
	catch (...) {
		ROS_ERROR("Unknown Error");
		throw;
	}
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkFEMElementTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "itkFEM.h"
#include "itkFEMSolver.h"

#include <iostream>
#include <fstream>

//#include <strings>

using namespace std;
using namespace itk;
using namespace fem;

int itkFEMElementTest(int ac, char** av)
{
  // File input stream
  ifstream f;

  // Path to input file
  // char fname[] = "../../Insight/Testing/Data/Input/FEM/hexa2.fem";

  std::cout << std::endl << "FEM Input: " << av[1] << std::endl;

  // Declare the FEM solver & associated input stream and read the input file
  f.open(av[1]);

  if (!f)
  {
    std::cout << "ERROR: null file handle...terminating.\n";
    return EXIT_FAILURE;
  }

  std::cout << "Solver()" << std::endl;
  Solver S;
  std::cout << "Read()" << std::endl;
  S.Read(f);
  std::cout << "Close file handle" << std::endl;
  f.close();

  // Call the appropriate sequence of Solver methods to solve the
  // problem

  std::cout << "GenerateGFN()" << std::endl;
  S.GenerateGFN();          // Generate global freedom numbers for system DOFs
  std::cout << "AssembleK()" << std::endl;
  S.AssembleK();            // Assemble the global stiffness matrix K
  std::cout << "DecomposeK()" << std::endl;
  S.DecomposeK();           // Invert K
  std::cout << "AssembleF()" << std::endl;
  S.AssembleF();            // Assemble the global load vector F
  std::cout << "Solve()"<< std::endl;
  S.Solve();                // Solve the system Ku=F for u
  std::cout << "UpdateDisplacements()" << std::endl;
  S.UpdateDisplacements();  // Copy the solution u's back to the nodes
  std::cout << "Done" << std::endl;

  // Print the solutions (displacements)
  std::cout << "Print displacements: " << std::endl;
  for( ::itk::fem::Solver::NodeArray::iterator n = S.node.begin(); n!=S.node.end(); n++)
  {
    std::cout<<"Node "<<(*n)->GN<<": ";
    /** For each DOF in the node... */
    for( unsigned int d=0, dof; (dof=(*n)->GetDegreeOfFreedom(d))!=::itk::fem::Element::InvalidDegreeOfFreedomID; d++ )
    {
      std::cout<<S.GetSolution(dof);
      std::cout<<",  ";
    }
    std::cout<<"\b\b\b \b\n";
  }

  return EXIT_SUCCESS;
}
<commit_msg>ERR: backspaces mess up dashboard creation.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkFEMElementTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "itkFEM.h"
#include "itkFEMSolver.h"

#include <iostream>
#include <fstream>

//#include <strings>

using namespace std;
using namespace itk;
using namespace fem;

int itkFEMElementTest(int ac, char** av)
{
  // File input stream
  ifstream f;

  // Path to input file
  // char fname[] = "../../Insight/Testing/Data/Input/FEM/hexa2.fem";

  std::cout << std::endl << "FEM Input: " << av[1] << std::endl;

  // Declare the FEM solver & associated input stream and read the input file
  f.open(av[1]);

  if (!f)
  {
    std::cout << "ERROR: null file handle...terminating.\n";
    return EXIT_FAILURE;
  }

  std::cout << "Solver()" << std::endl;
  Solver S;
  std::cout << "Read()" << std::endl;
  S.Read(f);
  std::cout << "Close file handle" << std::endl;
  f.close();

  // Call the appropriate sequence of Solver methods to solve the
  // problem

  std::cout << "GenerateGFN()" << std::endl;
  S.GenerateGFN();          // Generate global freedom numbers for system DOFs
  std::cout << "AssembleK()" << std::endl;
  S.AssembleK();            // Assemble the global stiffness matrix K
  std::cout << "DecomposeK()" << std::endl;
  S.DecomposeK();           // Invert K
  std::cout << "AssembleF()" << std::endl;
  S.AssembleF();            // Assemble the global load vector F
  std::cout << "Solve()"<< std::endl;
  S.Solve();                // Solve the system Ku=F for u
  std::cout << "UpdateDisplacements()" << std::endl;
  S.UpdateDisplacements();  // Copy the solution u's back to the nodes
  std::cout << "Done" << std::endl;

  // Print the solutions (displacements)
  std::cout << "Print displacements: " << std::endl;
  for( ::itk::fem::Solver::NodeArray::iterator n = S.node.begin(); n!=S.node.end(); n++)
  {
    std::cout<<"Node "<<(*n)->GN<<": ";
    /** For each DOF in the node... */
    for( unsigned int d=0, dof; (dof=(*n)->GetDegreeOfFreedom(d))!=::itk::fem::Element::InvalidDegreeOfFreedomID; d++ )
    {
      std::cout<<S.GetSolution(dof);
      std::cout<<",  ";
    }
    std::cout<<"\n";
  }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
   Copyright 2016 Mitchell Young

   Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#include "source.hpp"

#include <algorithm>
#include <iostream>
#include "pugixml.hpp"
#include "util/error.hpp"
#include "core/constants.hpp"

namespace mocc {
Source::Source(int nreg, const XSMesh *xs_mesh, const ArrayB2 &flux)
    : xs_mesh_(xs_mesh),
      n_group_(xs_mesh->n_group()),
      n_reg_(flux.size() / n_group_),
      has_external_(false),
      source_1g_(nreg),
      flux_(flux)
{
    assert(nreg * n_group_ == (int)flux_.size());
    source_1g_.fill(0.0);
    state_.reset();
    return;
}

void Source::initialize_group(int ig)
{
    if (has_external_) {
        for (int ireg = 0; ireg < (int)n_reg_; ireg++) {
            source_1g_[ireg] = external_source_(ireg, ig);
        }
    }
    else {
        source_1g_.fill(0.0);
    }

    state_.reset();
    return;
}

std::ostream &operator<<(std::ostream &os, const Source &src)
{
    return os;
}

// Multiply the group-independent fission source by \c chi[ig] to get the
// fission source into the current group. If an external source is defines,
// start with that.
void Source::fission(const ArrayB1 &fs, int ig)
{
    assert((int)fs.size() == n_reg_);
    assert(!state_.has_fission);
    assert(!state_.is_scaled);

    for (auto &xsr : *xs_mesh_) {
        real_t xsch = xsr.xsmacch(ig);
        for (const int &ireg : xsr.reg()) {
            source_1g_[ireg] += xsch * fs(ireg);
        }
    }

    state_.has_fission = true;
    return;
}

/**
 * \brief Compute the contribution to the source from inscattering from
 * other groups.
 */
void Source::in_scatter(size_t ig)
{
    assert(!state_.has_inscatter);
    assert(!state_.is_scaled);
    for (auto &xsr : *xs_mesh_) {
        if (xsr.reg().size() == 0) {
            continue;
        }
        const ScatteringRow &scat_row = xsr.xsmacsc().to(ig);
        size_t min_g                  = scat_row.min_g;
        int igg                       = min_g;
        for (auto sc : scat_row) {
            // Dont add a contribution for self-scatter. It might be a
            // good idea to remove self-scatter from the scattering matrix
            // and store it separately. May also benefit the self-scatter
            // routine to have less indirection.
            if (igg != (int)ig) {
                for (auto &ireg : xsr.reg()) {
                    real_t scat_src = sc * flux_((int)ireg, igg);
                    source_1g_[ireg] += scat_src;
                }
            }
            igg++;
        }
    }

    return;
}

void Source::auxiliary(const ArrayB1 &aux)
{
    assert(source_1g_.size() == (int)aux.size());
    assert(!state_.is_scaled);
    for (int i = 0; i < (int)n_reg_; i++) {
        source_1g_[i] += aux(i);
    }
}

void Source::add_external(const pugi::xml_node &input)
{
    if (input.attribute("file").empty()) {
        // Nothing to do here
        return;
    }

    std::string srcfname = input.attribute("file").value();
    H5Node srcfile(srcfname, H5Access::READ);
    srcfile.read("/source", external_source_);

    // I converted this from the old HDF5 routines, and the order of these
    // could be wrong. make sure to test or change as necessary
    if (external_source_.extent(0) != (int)n_group_) {
        throw EXCEPT("Wrong group dimensions for source");
    }
    if (external_source_.extent(1) != (int)n_reg_) {
        throw EXCEPT("Wrong regions dimensions for source");
    }

    has_external_ = true;
}
}
<commit_msg>Add a useful assertion to the Source ctor<commit_after>/*
   Copyright 2016 Mitchell Young

   Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#include "source.hpp"

#include <algorithm>
#include <iostream>
#include "pugixml.hpp"
#include "util/error.hpp"
#include "core/constants.hpp"

namespace mocc {
Source::Source(int nreg, const XSMesh *xs_mesh, const ArrayB2 &flux)
    : xs_mesh_(xs_mesh),
      n_group_(xs_mesh->n_group()),
      n_reg_(flux.size() / n_group_),
      has_external_(false),
      source_1g_(nreg),
      flux_(flux)
{
    assert(nreg * n_group_ == (int)flux_.size());
    assert(xs_mesh_->n_reg_expanded() == nreg);
    source_1g_.fill(0.0);
    state_.reset();
    return;
}

void Source::initialize_group(int ig)
{
    if (has_external_) {
        for (int ireg = 0; ireg < (int)n_reg_; ireg++) {
            source_1g_[ireg] = external_source_(ireg, ig);
        }
    }
    else {
        source_1g_.fill(0.0);
    }

    state_.reset();
    return;
}

std::ostream &operator<<(std::ostream &os, const Source &src)
{
    return os;
}

// Multiply the group-independent fission source by \c chi[ig] to get the
// fission source into the current group. If an external source is defines,
// start with that.
void Source::fission(const ArrayB1 &fs, int ig)
{
    assert((int)fs.size() == n_reg_);
    assert(!state_.has_fission);
    assert(!state_.is_scaled);

    for (auto &xsr : *xs_mesh_) {
        real_t xsch = xsr.xsmacch(ig);
        for (const int &ireg : xsr.reg()) {
            source_1g_[ireg] += xsch * fs(ireg);
        }
    }

    state_.has_fission = true;
    return;
}

/**
 * \brief Compute the contribution to the source from inscattering from
 * other groups.
 */
void Source::in_scatter(size_t ig)
{
    assert(!state_.has_inscatter);
    assert(!state_.is_scaled);
    for (auto &xsr : *xs_mesh_) {
        if (xsr.reg().size() == 0) {
            continue;
        }
        const ScatteringRow &scat_row = xsr.xsmacsc().to(ig);
        size_t min_g                  = scat_row.min_g;
        int igg                       = min_g;
        for (auto sc : scat_row) {
            // Dont add a contribution for self-scatter. It might be a
            // good idea to remove self-scatter from the scattering matrix
            // and store it separately. May also benefit the self-scatter
            // routine to have less indirection.
            if (igg != (int)ig) {
                for (auto &ireg : xsr.reg()) {
                    real_t scat_src = sc * flux_((int)ireg, igg);
                    source_1g_[ireg] += scat_src;
                }
            }
            igg++;
        }
    }

    return;
}

void Source::auxiliary(const ArrayB1 &aux)
{
    assert(source_1g_.size() == (int)aux.size());
    assert(!state_.is_scaled);
    for (int i = 0; i < (int)n_reg_; i++) {
        source_1g_[i] += aux(i);
    }
}

void Source::add_external(const pugi::xml_node &input)
{
    if (input.attribute("file").empty()) {
        // Nothing to do here
        return;
    }

    std::string srcfname = input.attribute("file").value();
    H5Node srcfile(srcfname, H5Access::READ);
    srcfile.read("/source", external_source_);

    // I converted this from the old HDF5 routines, and the order of these
    // could be wrong. make sure to test or change as necessary
    if (external_source_.extent(0) != (int)n_group_) {
        throw EXCEPT("Wrong group dimensions for source");
    }
    if (external_source_.extent(1) != (int)n_reg_) {
        throw EXCEPT("Wrong regions dimensions for source");
    }

    has_external_ = true;
}
}
<|endoftext|>