<commit_before>/*************************************************************************
 *
 *  $RCSfile: EResultSet.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: oj $ $Date: 2001-08-24 06:01: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 EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_SDBCX_COMPAREBOOKMARK_HPP_
#include <com/sun/star/sdbcx/CompareBookmark.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XDELETEROWS_HPP_
#include <com/sun/star/sdbcx/XDeleteRows.hpp>
#endif
#ifndef _CONNECTIVITY_FLAT_ERESULTSET_HXX_
#include "flat/EResultSet.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif

using namespace ::comphelper;

using namespace connectivity::flat;
using namespace connectivity::file;
using namespace ::cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::sdbcx;
//  using namespace com::sun::star::container;
//  using namespace com::sun::star::util;
//------------------------------------------------------------------------------
OFlatResultSet::OFlatResultSet( OStatement_Base* pStmt,connectivity::OSQLParseTreeIterator& _aSQLIterator)
                : file::OResultSet(pStmt,_aSQLIterator)
                ,m_bBookmarkable(sal_True)
{
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISBOOKMARKABLE),         PROPERTY_ID_ISBOOKMARKABLE,       PropertyAttribute::READONLY,&m_bBookmarkable,                ::getBooleanCppuType());
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OFlatResultSet::getImplementationName(  ) throw ( RuntimeException)
{
    return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.flat.ResultSet");
}
// -------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL OFlatResultSet::getSupportedServiceNames(  ) throw( RuntimeException)
{
     Sequence< ::rtl::OUString > aSupported(2);
    aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbc.ResultSet");
    aSupported[1] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.ResultSet");
    return aSupported;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OFlatResultSet::supportsService( const ::rtl::OUString& _rServiceName ) throw( RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
    const ::rtl::OUString* pSupported = aSupported.getConstArray();
    const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
    for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
        ;

    return pSupported != pEnd;
}
// -------------------------------------------------------------------------
Any SAL_CALL OFlatResultSet::queryInterface( const Type & rType ) throw(RuntimeException)
{
    if(rType == ::getCppuType((const Reference<XDeleteRows>*)0) || rType == ::getCppuType((const Reference<XResultSetUpdate>*)0)
        || rType == ::getCppuType((const Reference<XRowUpdate>*)0))
        return Any();

    Any aRet = OResultSet::queryInterface(rType);
    return aRet.hasValue() ? aRet : OFlatResultSet_BASE::queryInterface(rType);
}
// -------------------------------------------------------------------------
Sequence<  Type > SAL_CALL OFlatResultSet::getTypes(  ) throw( RuntimeException)
{
    Sequence< Type > aTypes = OResultSet::getTypes();
    Sequence< Type > aRet(aTypes.getLength()-2);
    const Type* pBegin = aTypes.getConstArray();
    const Type* pEnd = pBegin + aTypes.getLength();
    sal_Int32 i=0;
    for(;pBegin != pEnd;++pBegin)
    {
        if(!(*pBegin == ::getCppuType((const Reference<XDeleteRows>*)0) ||
            *pBegin == ::getCppuType((const Reference<XResultSetUpdate>*)0) ||
            *pBegin == ::getCppuType((const Reference<XRowUpdate>*)0)))
        {
            aRet.getArray()[i++] = *pBegin;
        }
    }

    return ::comphelper::concatSequences(aRet,OFlatResultSet_BASE::getTypes());
}

// -------------------------------------------------------------------------
// XRowLocate
Any SAL_CALL OFlatResultSet::getBookmark(  ) throw( SQLException,  RuntimeException)
{
     ::osl::MutexGuard aGuard( m_aMutex );
        checkDisposed(OResultSet_BASE::rBHelper.bDisposed);

    return makeAny((sal_Int32)(*m_aRow)[0]);
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OFlatResultSet::moveToBookmark( const  Any& bookmark ) throw( SQLException,  RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
        checkDisposed(OResultSet_BASE::rBHelper.bDisposed);

    m_bRowDeleted = m_bRowInserted = m_bRowUpdated = sal_False;

    return Move(OFileTable::FILE_BOOKMARK,comphelper::getINT32(bookmark),sal_True);
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OFlatResultSet::moveRelativeToBookmark( const  Any& bookmark, sal_Int32 rows ) throw( SQLException,  RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
        checkDisposed(OResultSet_BASE::rBHelper.bDisposed);

    m_bRowDeleted = m_bRowInserted = m_bRowUpdated = sal_False;

    Move(OFileTable::FILE_BOOKMARK,comphelper::getINT32(bookmark),sal_False);

    return relative(rows);
}

// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OFlatResultSet::compareBookmarks( const  Any& first, const  Any& second ) throw( SQLException,  RuntimeException)
{
    return (first == second) ? 0 : 2;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OFlatResultSet::hasOrderedBookmarks(  ) throw( SQLException,  RuntimeException)
{
    return sal_True;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OFlatResultSet::hashBookmark( const  Any& bookmark ) throw( SQLException,  RuntimeException)
{
    return comphelper::getINT32(bookmark);
}
// -------------------------------------------------------------------------
IPropertyArrayHelper* OFlatResultSet::createArrayHelper( ) const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    return new ::cppu::OPropertyArrayHelper(aProps);
}
// -------------------------------------------------------------------------
IPropertyArrayHelper & OFlatResultSet::getInfoHelper()
{
    return *OFlatResultSet_BASE3::getArrayHelper();
}
// -----------------------------------------------------------------------------
void SAL_CALL OFlatResultSet::acquire() throw(::com::sun::star::uno::RuntimeException)
{
    OFlatResultSet_BASE2::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OFlatResultSet::release() throw(::com::sun::star::uno::RuntimeException)
{
    OFlatResultSet_BASE2::release();
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OFlatResultSet::getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException)
{
    return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());
}
// -----------------------------------------------------------------------------

<commit_msg>#92924#: exception specifications<commit_after>/*************************************************************************
 *
 *  $RCSfile: EResultSet.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: hr $ $Date: 2001-10-18 12:17:36 $
 *
 *  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 EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_SDBCX_COMPAREBOOKMARK_HPP_
#include <com/sun/star/sdbcx/CompareBookmark.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XDELETEROWS_HPP_
#include <com/sun/star/sdbcx/XDeleteRows.hpp>
#endif
#ifndef _CONNECTIVITY_FLAT_ERESULTSET_HXX_
#include "flat/EResultSet.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif

using namespace ::comphelper;

using namespace connectivity::flat;
using namespace connectivity::file;
using namespace ::cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::sdbcx;
//  using namespace com::sun::star::container;
//  using namespace com::sun::star::util;
//------------------------------------------------------------------------------
OFlatResultSet::OFlatResultSet( OStatement_Base* pStmt,connectivity::OSQLParseTreeIterator& _aSQLIterator)
                : file::OResultSet(pStmt,_aSQLIterator)
                ,m_bBookmarkable(sal_True)
{
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISBOOKMARKABLE),         PROPERTY_ID_ISBOOKMARKABLE,       PropertyAttribute::READONLY,&m_bBookmarkable,                ::getBooleanCppuType());
}
// -------------------------------------------------------------------------
::rtl::OUString SAL_CALL OFlatResultSet::getImplementationName(  ) throw ( RuntimeException)
{
    return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.flat.ResultSet");
}
// -------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL OFlatResultSet::getSupportedServiceNames(  ) throw( RuntimeException)
{
     Sequence< ::rtl::OUString > aSupported(2);
    aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbc.ResultSet");
    aSupported[1] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.ResultSet");
    return aSupported;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OFlatResultSet::supportsService( const ::rtl::OUString& _rServiceName ) throw( RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
    const ::rtl::OUString* pSupported = aSupported.getConstArray();
    const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
    for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
        ;

    return pSupported != pEnd;
}
// -------------------------------------------------------------------------
Any SAL_CALL OFlatResultSet::queryInterface( const Type & rType ) throw(RuntimeException)
{
    if(rType == ::getCppuType((const Reference<XDeleteRows>*)0) || rType == ::getCppuType((const Reference<XResultSetUpdate>*)0)
        || rType == ::getCppuType((const Reference<XRowUpdate>*)0))
        return Any();

    Any aRet = OResultSet::queryInterface(rType);
    return aRet.hasValue() ? aRet : OFlatResultSet_BASE::queryInterface(rType);
}
// -------------------------------------------------------------------------
Sequence<  Type > SAL_CALL OFlatResultSet::getTypes(  ) throw( RuntimeException)
{
    Sequence< Type > aTypes = OResultSet::getTypes();
    Sequence< Type > aRet(aTypes.getLength()-2);
    const Type* pBegin = aTypes.getConstArray();
    const Type* pEnd = pBegin + aTypes.getLength();
    sal_Int32 i=0;
    for(;pBegin != pEnd;++pBegin)
    {
        if(!(*pBegin == ::getCppuType((const Reference<XDeleteRows>*)0) ||
            *pBegin == ::getCppuType((const Reference<XResultSetUpdate>*)0) ||
            *pBegin == ::getCppuType((const Reference<XRowUpdate>*)0)))
        {
            aRet.getArray()[i++] = *pBegin;
        }
    }

    return ::comphelper::concatSequences(aRet,OFlatResultSet_BASE::getTypes());
}

// -------------------------------------------------------------------------
// XRowLocate
Any SAL_CALL OFlatResultSet::getBookmark(  ) throw( SQLException,  RuntimeException)
{
     ::osl::MutexGuard aGuard( m_aMutex );
        checkDisposed(OResultSet_BASE::rBHelper.bDisposed);

    return makeAny((sal_Int32)(*m_aRow)[0]);
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OFlatResultSet::moveToBookmark( const  Any& bookmark ) throw( SQLException,  RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
        checkDisposed(OResultSet_BASE::rBHelper.bDisposed);

    m_bRowDeleted = m_bRowInserted = m_bRowUpdated = sal_False;

    return Move(OFileTable::FILE_BOOKMARK,comphelper::getINT32(bookmark),sal_True);
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OFlatResultSet::moveRelativeToBookmark( const  Any& bookmark, sal_Int32 rows ) throw( SQLException,  RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
        checkDisposed(OResultSet_BASE::rBHelper.bDisposed);

    m_bRowDeleted = m_bRowInserted = m_bRowUpdated = sal_False;

    Move(OFileTable::FILE_BOOKMARK,comphelper::getINT32(bookmark),sal_False);

    return relative(rows);
}

// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OFlatResultSet::compareBookmarks( const  Any& first, const  Any& second ) throw( SQLException,  RuntimeException)
{
    return (first == second) ? 0 : 2;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL OFlatResultSet::hasOrderedBookmarks(  ) throw( SQLException,  RuntimeException)
{
    return sal_True;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OFlatResultSet::hashBookmark( const  Any& bookmark ) throw( SQLException,  RuntimeException)
{
    return comphelper::getINT32(bookmark);
}
// -------------------------------------------------------------------------
IPropertyArrayHelper* OFlatResultSet::createArrayHelper( ) const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    return new ::cppu::OPropertyArrayHelper(aProps);
}
// -------------------------------------------------------------------------
IPropertyArrayHelper & OFlatResultSet::getInfoHelper()
{
    return *OFlatResultSet_BASE3::getArrayHelper();
}
// -----------------------------------------------------------------------------
void SAL_CALL OFlatResultSet::acquire() throw()
{
    OFlatResultSet_BASE2::acquire();
}
// -----------------------------------------------------------------------------
void SAL_CALL OFlatResultSet::release() throw()
{
    OFlatResultSet_BASE2::release();
}
// -----------------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OFlatResultSet::getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException)
{
    return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper());
}
// -----------------------------------------------------------------------------

<|endoftext|>


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

#include <cinttypes>
#include <random>

#include "../Characters/Format.h"
#include "../DataExchange/CheckedConverter.h"

#include "GUID.h"

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Common;
using namespace Stroika::Foundation::Characters;

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

#define G32 "%8" SCNx32
#define G16 "%4" SCNx16
#define G8 "%2" SCNx8

/*
 ********************************************************************************
 *********************************** Common::GUID *******************************
 ********************************************************************************
 */
Common::GUID::GUID (const string& src)
{
    // Allow on parsing EITHER {} delimited, or not
    DISABLE_COMPILER_MSC_WARNING_START (4996) // MSVC SILLY WARNING ABOUT USING swscanf_s
    int nchars = -1;
    int nfields =
        sscanf (src.c_str (), "{" G32 "-" G16 "-" G16 "-" G8 G8 "-" G8 G8 G8 G8 G8 G8 "}%n",
                &Data1, &Data2, &Data3,
                &Data4[0], &Data4[1], &Data4[2], &Data4[3], &Data4[4], &Data4[5], &Data4[6], &Data4[7],
                &nchars);
    if (nfields != 11 || nchars != 38) {
        nchars = -1;
        nfields =
            sscanf (src.c_str (), G32 "-" G16 "-" G16 "-" G8 G8 "-" G8 G8 G8 G8 G8 G8 "%n",
                    &Data1, &Data2, &Data3,
                    &Data4[0], &Data4[1], &Data4[2], &Data4[3], &Data4[4], &Data4[5], &Data4[6], &Data4[7],
                    &nchars);
    }
    DISABLE_COMPILER_MSC_WARNING_END (4996) // MSVC SILLY WARNING ABOUT USING swscanf_s
    if (nfields != 11 and nchars != 36) {
        Execution::Throw (DataExchange::BadFormatException{L"Badly formatted GUID"sv});
    }
}

Common::GUID::GUID (const Characters::String& src)
    : GUID (src.AsASCII ())
{
}

Characters::String Common::GUID::ToString () const
{
    return Characters::Format (L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
                               Data1, Data2, Data3,
                               Data4[0], Data4[1], Data4[2], Data4[3], Data4[4], Data4[5], Data4[6], Data4[7]);
}

Common::GUID Common::GUID::GenerateNew ()
{
    array<uint8_t, 16>                randomData;
    random_device                     rd;
    mt19937                           gen (rd ()); //Standard mersenne_twister_engine seeded with rd()
    uniform_int_distribution<>        uniformDist (0, 255);
    for (size_t i = 0; i < 16; ++i) {
        randomData[i] = static_cast<uint8_t> (uniformDist (gen));
    }
    return GUID{randomData};
}
<commit_msg>make format-code<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2019.  All rights reserved
 */
#include "../StroikaPreComp.h"

#include <cinttypes>
#include <random>

#include "../Characters/Format.h"
#include "../DataExchange/CheckedConverter.h"

#include "GUID.h"

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Common;
using namespace Stroika::Foundation::Characters;

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

#define G32 "%8" SCNx32
#define G16 "%4" SCNx16
#define G8 "%2" SCNx8

/*
 ********************************************************************************
 *********************************** Common::GUID *******************************
 ********************************************************************************
 */
Common::GUID::GUID (const string& src)
{
    // Allow on parsing EITHER {} delimited, or not
    DISABLE_COMPILER_MSC_WARNING_START (4996) // MSVC SILLY WARNING ABOUT USING swscanf_s
    int nchars = -1;
    int nfields =
        sscanf (src.c_str (), "{" G32 "-" G16 "-" G16 "-" G8 G8 "-" G8 G8 G8 G8 G8 G8 "}%n",
                &Data1, &Data2, &Data3,
                &Data4[0], &Data4[1], &Data4[2], &Data4[3], &Data4[4], &Data4[5], &Data4[6], &Data4[7],
                &nchars);
    if (nfields != 11 || nchars != 38) {
        nchars = -1;
        nfields =
            sscanf (src.c_str (), G32 "-" G16 "-" G16 "-" G8 G8 "-" G8 G8 G8 G8 G8 G8 "%n",
                    &Data1, &Data2, &Data3,
                    &Data4[0], &Data4[1], &Data4[2], &Data4[3], &Data4[4], &Data4[5], &Data4[6], &Data4[7],
                    &nchars);
    }
    DISABLE_COMPILER_MSC_WARNING_END (4996) // MSVC SILLY WARNING ABOUT USING swscanf_s
    if (nfields != 11 and nchars != 36) {
        Execution::Throw (DataExchange::BadFormatException{L"Badly formatted GUID"sv});
    }
}

Common::GUID::GUID (const Characters::String& src)
    : GUID (src.AsASCII ())
{
}

Characters::String Common::GUID::ToString () const
{
    return Characters::Format (L"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
                               Data1, Data2, Data3,
                               Data4[0], Data4[1], Data4[2], Data4[3], Data4[4], Data4[5], Data4[6], Data4[7]);
}

Common::GUID Common::GUID::GenerateNew ()
{
    array<uint8_t, 16>         randomData;
    random_device              rd;
    mt19937                    gen (rd ()); //Standard mersenne_twister_engine seeded with rd()
    uniform_int_distribution<> uniformDist (0, 255);
    for (size_t i = 0; i < 16; ++i) {
        randomData[i] = static_cast<uint8_t> (uniformDist (gen));
    }
    return GUID{randomData};
}
<|endoftext|>


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

  Library:   CTK

  Copyright (c) Kitware Inc.

  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.txt

  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.

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

// Qt includes
#include <QDebug>
#include <QMouseEvent>

// CTK includes
#include "ctkLogger.h"
#include "ctkVTKChartView.h"

// VTK includes
#include <vtkAxis.h>
#include <vtkChartXY.h>
#include <vtkContext2D.h>
#include <vtkContextMouseEvent.h>
#include <vtkContextScene.h>
#include <vtkContextView.h>
#include <vtkOpenGLContextDevice2D.h>
#include <vtkPlot.h>
#include <vtkRenderWindow.h>

//----------------------------------------------------------------------------
static ctkLogger logger("org.commontk.visualization.vtk.widgets.ctkVTKChartView");
//----------------------------------------------------------------------------

class ctkVTKChartViewPrivate
{
  Q_DECLARE_PUBLIC(ctkVTKChartView);
protected:
  ctkVTKChartView* const q_ptr;
public:
  ctkVTKChartViewPrivate(ctkVTKChartView& object);
  void init();
  void chartBounds(double* bounds)const;

  vtkSmartPointer<vtkContextView> ContextView;
  vtkSmartPointer<vtkChartXY> Chart;
  double UserBounds[8];
  mutable double OldBounds[8];
};

// ----------------------------------------------------------------------------
// ctkVTKChartViewPrivate methods

// ----------------------------------------------------------------------------
ctkVTKChartViewPrivate::ctkVTKChartViewPrivate(ctkVTKChartView& object)
  :q_ptr(&object)
{
  this->ContextView = vtkSmartPointer<vtkContextView>::New();
  this->Chart = vtkSmartPointer<vtkChartXY>::New();
  this->ContextView->GetScene()->AddItem(this->Chart);
  this->UserBounds[0] = this->UserBounds[2] = this->UserBounds[4] = this->UserBounds[6] = 0.;
  this->UserBounds[1] = this->UserBounds[3] = this->UserBounds[5] = this->UserBounds[7] = -1.;
  this->OldBounds[0] = this->OldBounds[2] = this->OldBounds[4] = this->OldBounds[6] = 0.;
  this->OldBounds[1] = this->OldBounds[3] = this->OldBounds[5] = this->OldBounds[7] = -1.;
}

// ----------------------------------------------------------------------------
void ctkVTKChartViewPrivate::init()
{
  Q_Q(ctkVTKChartView);
  this->ContextView->SetInteractor(q->GetInteractor());
  q->SetRenderWindow(this->ContextView->GetRenderWindow());
  // low def for now (faster)
  //q->GetRenderWindow()->SetMultiSamples(0);
  //vtkOpenGLContextDevice2D::SafeDownCast(this->ContextView->GetContext()->GetDevice())
  //                                       ->SetStringRendererToQt();
#ifndef Q_WS_X11
  q->GetRenderWindow()->SetLineSmoothing(true);
#endif
  this->Chart->SetActionToButton(vtkChart::PAN, vtkContextMouseEvent::MIDDLE_BUTTON);
  this->Chart->SetActionToButton(vtkChart::SELECT, vtkContextMouseEvent::RIGHT_BUTTON);
}

// ----------------------------------------------------------------------------
void ctkVTKChartViewPrivate::chartBounds(double* bounds)const
{
  Q_Q(const ctkVTKChartView);
  bounds[0] = bounds[2] = bounds[4] = bounds[6] = VTK_DOUBLE_MAX;
  bounds[1] = bounds[3] = bounds[5] = bounds[7] = VTK_DOUBLE_MIN;
  vtkChartXY* chart = q->chart();
  const vtkIdType plotCount = chart->GetNumberOfPlots();
  for (vtkIdType i = 0; i < plotCount; ++i)
    {
    vtkPlot* plot = chart->GetPlot(i);

    int corner = chart->GetPlotCorner(plot);
    double plotBounds[4];
    plot->GetBounds(plotBounds);
    switch (corner)
      {
      // bottom left
      case 0:
        // x
        bounds[2] = bounds[2] > plotBounds[0] ?
          plotBounds[0] : bounds[2];
        bounds[3] = bounds[3] < plotBounds[1] ?
          plotBounds[1] : bounds[3];
        // y
        bounds[0] = bounds[0] > plotBounds[2] ?
          plotBounds[2] : bounds[0];
        bounds[1] = bounds[1] < plotBounds[3] ?
          plotBounds[3] : bounds[1];
        break;
      // bottom right
      case 1:
        // x
        bounds[2] = bounds[2] > plotBounds[0] ?
          plotBounds[0] : bounds[2];
        bounds[3] = bounds[3] < plotBounds[1] ?
          plotBounds[1] : bounds[3];
        // y
        bounds[4] = bounds[4] > plotBounds[2] ?
          plotBounds[2] : bounds[4];
        bounds[5] = bounds[5] < plotBounds[3] ?
          plotBounds[3] : bounds[5];
        break;
      // top right
      case 2:
        // x
        bounds[6] = bounds[6] > plotBounds[0] ?
          plotBounds[0] : bounds[6];
        bounds[7] = bounds[7] < plotBounds[1] ?
          plotBounds[1] : bounds[7];
        // y
        bounds[4] = bounds[4] > plotBounds[2] ?
          plotBounds[2] : bounds[4];
        bounds[5] = bounds[5] < plotBounds[3] ?
          plotBounds[3] : bounds[5];
        break;
      // top left
      case 3:
        // x
        bounds[6] = bounds[6] > plotBounds[0] ?
          plotBounds[0] : bounds[6];
        bounds[7] = bounds[7] < plotBounds[1] ?
          plotBounds[1] : bounds[7];
        // y
        bounds[0] = bounds[0] > plotBounds[2] ?
          plotBounds[2] : bounds[1];
        bounds[1] = bounds[0] < plotBounds[3] ?
          plotBounds[3] : bounds[1];
        break;
      }
    }
}

// ----------------------------------------------------------------------------
// ctkVTKChartView methods

// ----------------------------------------------------------------------------
ctkVTKChartView::ctkVTKChartView(QWidget* parentWidget)
  :Superclass(parentWidget)
  , d_ptr(new ctkVTKChartViewPrivate(*this))
{
  Q_D(ctkVTKChartView);
  d->init();
  this->setAutomaticImageCacheEnabled(true);
}

// ----------------------------------------------------------------------------
ctkVTKChartView::~ctkVTKChartView()
{
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::setTitle(const QString& newTitle)
{
  Q_D(ctkVTKChartView);
  d->Chart->SetTitle(newTitle.toLatin1().data());
}

// ----------------------------------------------------------------------------
QString ctkVTKChartView::title()const
{
  Q_D(const ctkVTKChartView);
  return QString(d->Chart->GetTitle());
}

// ----------------------------------------------------------------------------
vtkChartXY* ctkVTKChartView::chart()const
{
  Q_D(const ctkVTKChartView);
  return d->Chart;
}

// ----------------------------------------------------------------------------
vtkContextScene* ctkVTKChartView::scene()const
{
  Q_D(const ctkVTKChartView);
  return d->ContextView->GetScene();
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::addPlot(vtkPlot* plot)
{
  Q_D(ctkVTKChartView);
  d->Chart->AddPlot(plot);
  emit this->plotAdded(plot);
  this->onChartUpdated();
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::onChartUpdated()
{
  Q_D(ctkVTKChartView);
  double oldBounds[8];
  memcpy(oldBounds, d->OldBounds, 8 * sizeof(double));
  double newBounds[8];
  this->chartBounds(newBounds);
  if (oldBounds[0] != newBounds[0] ||
      oldBounds[1] != newBounds[1] ||
      oldBounds[2] != newBounds[2] ||
      oldBounds[3] != newBounds[3] ||
      oldBounds[4] != newBounds[4] ||
      oldBounds[5] != newBounds[5] ||
      oldBounds[6] != newBounds[6] ||
      oldBounds[7] != newBounds[7])
    {
    emit boundsChanged();
    }
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::chartBounds(double* bounds)const
{
  Q_D(const ctkVTKChartView);
  if (d->UserBounds[1] < d->UserBounds[0])
    {
    // Invalid user bounds, return the real chart bounds
    d->chartBounds(bounds);
    }
  else
    {
    this->chartUserBounds(bounds);
    }
  memcpy(d->OldBounds, bounds, 8 * sizeof(double));
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::setChartUserBounds(double* userBounds)
{
  Q_D(ctkVTKChartView);
  for (int i= 0; i < 8; ++i)
    {
    d->UserBounds[i] = userBounds[i];
    }
  this->onChartUpdated();
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::chartUserBounds(double* bounds)const
{
  Q_D(const ctkVTKChartView);
  for (int i= 0; i < 8; ++i)
    {
    bounds[i] = d->UserBounds[i];
    }
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::setAxesToChartBounds()
{
  vtkChartXY* chart = this->chart();
  double bounds[8];
  this->chartBounds(bounds);
  for (int i = 0; i < chart->GetNumberOfAxes(); ++i)
    {
    if (bounds[2*i] != VTK_DOUBLE_MAX)
      {
      chart->GetAxis(i)->SetRange(bounds[2*i], bounds[2*i+1]);
      //chart->GetAxis(i)->SetBehavior(2);
      }
    }
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::boundAxesToChartBounds()
{
  vtkChartXY* chart = this->chart();
  double bounds[8];
  this->chartBounds(bounds);
  for (int i = 0; i < chart->GetNumberOfAxes(); ++i)
    {
    if (bounds[2*i] != VTK_DOUBLE_MAX)
      {
      chart->GetAxis(i)->SetMinimumLimit(bounds[2*i]);
      chart->GetAxis(i)->SetMaximumLimit(bounds[2*i + 1]);
      }
    }
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::chartBoundsToPlotBounds(double bounds[8], double plotBounds[4])const
{
  plotBounds[0] = bounds[vtkAxis::BOTTOM*2];
  plotBounds[1] = bounds[vtkAxis::BOTTOM*2 + 1];
  plotBounds[2] = bounds[vtkAxis::LEFT*2];
  plotBounds[3] = bounds[vtkAxis::LEFT*2+1];
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::mouseDoubleClickEvent(QMouseEvent* event)
{
  if (event->button() == Qt::MidButton)
    {
    this->setAxesToChartBounds();
    }
  this->Superclass::mouseDoubleClickEvent(event);
}
<commit_msg>Disable image cache for ctkVTKChartViews<commit_after>/*=========================================================================

  Library:   CTK

  Copyright (c) Kitware Inc.

  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.txt

  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.

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

// Qt includes
#include <QDebug>
#include <QMouseEvent>

// CTK includes
#include "ctkLogger.h"
#include "ctkVTKChartView.h"

// VTK includes
#include <vtkAxis.h>
#include <vtkChartXY.h>
#include <vtkContext2D.h>
#include <vtkContextMouseEvent.h>
#include <vtkContextScene.h>
#include <vtkContextView.h>
#include <vtkOpenGLContextDevice2D.h>
#include <vtkPlot.h>
#include <vtkRenderWindow.h>

//----------------------------------------------------------------------------
static ctkLogger logger("org.commontk.visualization.vtk.widgets.ctkVTKChartView");
//----------------------------------------------------------------------------

class ctkVTKChartViewPrivate
{
  Q_DECLARE_PUBLIC(ctkVTKChartView);
protected:
  ctkVTKChartView* const q_ptr;
public:
  ctkVTKChartViewPrivate(ctkVTKChartView& object);
  void init();
  void chartBounds(double* bounds)const;

  vtkSmartPointer<vtkContextView> ContextView;
  vtkSmartPointer<vtkChartXY> Chart;
  double UserBounds[8];
  mutable double OldBounds[8];
};

// ----------------------------------------------------------------------------
// ctkVTKChartViewPrivate methods

// ----------------------------------------------------------------------------
ctkVTKChartViewPrivate::ctkVTKChartViewPrivate(ctkVTKChartView& object)
  :q_ptr(&object)
{
  this->ContextView = vtkSmartPointer<vtkContextView>::New();
  this->Chart = vtkSmartPointer<vtkChartXY>::New();
  this->ContextView->GetScene()->AddItem(this->Chart);
  this->UserBounds[0] = this->UserBounds[2] = this->UserBounds[4] = this->UserBounds[6] = 0.;
  this->UserBounds[1] = this->UserBounds[3] = this->UserBounds[5] = this->UserBounds[7] = -1.;
  this->OldBounds[0] = this->OldBounds[2] = this->OldBounds[4] = this->OldBounds[6] = 0.;
  this->OldBounds[1] = this->OldBounds[3] = this->OldBounds[5] = this->OldBounds[7] = -1.;
}

// ----------------------------------------------------------------------------
void ctkVTKChartViewPrivate::init()
{
  Q_Q(ctkVTKChartView);
  this->ContextView->SetInteractor(q->GetInteractor());
  q->SetRenderWindow(this->ContextView->GetRenderWindow());
  // low def for now (faster)
  //q->GetRenderWindow()->SetMultiSamples(0);
  //vtkOpenGLContextDevice2D::SafeDownCast(this->ContextView->GetContext()->GetDevice())
  //                                       ->SetStringRendererToQt();
#ifndef Q_WS_X11
  q->GetRenderWindow()->SetLineSmoothing(true);
#endif
  this->Chart->SetActionToButton(vtkChart::PAN, vtkContextMouseEvent::MIDDLE_BUTTON);
  this->Chart->SetActionToButton(vtkChart::SELECT, vtkContextMouseEvent::RIGHT_BUTTON);
}

// ----------------------------------------------------------------------------
void ctkVTKChartViewPrivate::chartBounds(double* bounds)const
{
  Q_Q(const ctkVTKChartView);
  bounds[0] = bounds[2] = bounds[4] = bounds[6] = VTK_DOUBLE_MAX;
  bounds[1] = bounds[3] = bounds[5] = bounds[7] = VTK_DOUBLE_MIN;
  vtkChartXY* chart = q->chart();
  const vtkIdType plotCount = chart->GetNumberOfPlots();
  for (vtkIdType i = 0; i < plotCount; ++i)
    {
    vtkPlot* plot = chart->GetPlot(i);

    int corner = chart->GetPlotCorner(plot);
    double plotBounds[4];
    plot->GetBounds(plotBounds);
    switch (corner)
      {
      // bottom left
      case 0:
        // x
        bounds[2] = bounds[2] > plotBounds[0] ?
          plotBounds[0] : bounds[2];
        bounds[3] = bounds[3] < plotBounds[1] ?
          plotBounds[1] : bounds[3];
        // y
        bounds[0] = bounds[0] > plotBounds[2] ?
          plotBounds[2] : bounds[0];
        bounds[1] = bounds[1] < plotBounds[3] ?
          plotBounds[3] : bounds[1];
        break;
      // bottom right
      case 1:
        // x
        bounds[2] = bounds[2] > plotBounds[0] ?
          plotBounds[0] : bounds[2];
        bounds[3] = bounds[3] < plotBounds[1] ?
          plotBounds[1] : bounds[3];
        // y
        bounds[4] = bounds[4] > plotBounds[2] ?
          plotBounds[2] : bounds[4];
        bounds[5] = bounds[5] < plotBounds[3] ?
          plotBounds[3] : bounds[5];
        break;
      // top right
      case 2:
        // x
        bounds[6] = bounds[6] > plotBounds[0] ?
          plotBounds[0] : bounds[6];
        bounds[7] = bounds[7] < plotBounds[1] ?
          plotBounds[1] : bounds[7];
        // y
        bounds[4] = bounds[4] > plotBounds[2] ?
          plotBounds[2] : bounds[4];
        bounds[5] = bounds[5] < plotBounds[3] ?
          plotBounds[3] : bounds[5];
        break;
      // top left
      case 3:
        // x
        bounds[6] = bounds[6] > plotBounds[0] ?
          plotBounds[0] : bounds[6];
        bounds[7] = bounds[7] < plotBounds[1] ?
          plotBounds[1] : bounds[7];
        // y
        bounds[0] = bounds[0] > plotBounds[2] ?
          plotBounds[2] : bounds[1];
        bounds[1] = bounds[0] < plotBounds[3] ?
          plotBounds[3] : bounds[1];
        break;
      }
    }
}

// ----------------------------------------------------------------------------
// ctkVTKChartView methods

// ----------------------------------------------------------------------------
ctkVTKChartView::ctkVTKChartView(QWidget* parentWidget)
  :Superclass(parentWidget)
  , d_ptr(new ctkVTKChartViewPrivate(*this))
{
  Q_D(ctkVTKChartView);
  d->init();
  //this->setAutomaticImageCacheEnabled(true);
}

// ----------------------------------------------------------------------------
ctkVTKChartView::~ctkVTKChartView()
{
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::setTitle(const QString& newTitle)
{
  Q_D(ctkVTKChartView);
  d->Chart->SetTitle(newTitle.toLatin1().data());
}

// ----------------------------------------------------------------------------
QString ctkVTKChartView::title()const
{
  Q_D(const ctkVTKChartView);
  return QString(d->Chart->GetTitle());
}

// ----------------------------------------------------------------------------
vtkChartXY* ctkVTKChartView::chart()const
{
  Q_D(const ctkVTKChartView);
  return d->Chart;
}

// ----------------------------------------------------------------------------
vtkContextScene* ctkVTKChartView::scene()const
{
  Q_D(const ctkVTKChartView);
  return d->ContextView->GetScene();
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::addPlot(vtkPlot* plot)
{
  Q_D(ctkVTKChartView);
  d->Chart->AddPlot(plot);
  emit this->plotAdded(plot);
  this->onChartUpdated();
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::onChartUpdated()
{
  Q_D(ctkVTKChartView);
  double oldBounds[8];
  memcpy(oldBounds, d->OldBounds, 8 * sizeof(double));
  double newBounds[8];
  this->chartBounds(newBounds);
  if (oldBounds[0] != newBounds[0] ||
      oldBounds[1] != newBounds[1] ||
      oldBounds[2] != newBounds[2] ||
      oldBounds[3] != newBounds[3] ||
      oldBounds[4] != newBounds[4] ||
      oldBounds[5] != newBounds[5] ||
      oldBounds[6] != newBounds[6] ||
      oldBounds[7] != newBounds[7])
    {
    emit boundsChanged();
    }
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::chartBounds(double* bounds)const
{
  Q_D(const ctkVTKChartView);
  if (d->UserBounds[1] < d->UserBounds[0])
    {
    // Invalid user bounds, return the real chart bounds
    d->chartBounds(bounds);
    }
  else
    {
    this->chartUserBounds(bounds);
    }
  memcpy(d->OldBounds, bounds, 8 * sizeof(double));
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::setChartUserBounds(double* userBounds)
{
  Q_D(ctkVTKChartView);
  for (int i= 0; i < 8; ++i)
    {
    d->UserBounds[i] = userBounds[i];
    }
  this->onChartUpdated();
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::chartUserBounds(double* bounds)const
{
  Q_D(const ctkVTKChartView);
  for (int i= 0; i < 8; ++i)
    {
    bounds[i] = d->UserBounds[i];
    }
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::setAxesToChartBounds()
{
  vtkChartXY* chart = this->chart();
  double bounds[8];
  this->chartBounds(bounds);
  for (int i = 0; i < chart->GetNumberOfAxes(); ++i)
    {
    if (bounds[2*i] != VTK_DOUBLE_MAX)
      {
      chart->GetAxis(i)->SetRange(bounds[2*i], bounds[2*i+1]);
      //chart->GetAxis(i)->SetBehavior(2);
      }
    }
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::boundAxesToChartBounds()
{
  vtkChartXY* chart = this->chart();
  double bounds[8];
  this->chartBounds(bounds);
  for (int i = 0; i < chart->GetNumberOfAxes(); ++i)
    {
    if (bounds[2*i] != VTK_DOUBLE_MAX)
      {
      chart->GetAxis(i)->SetMinimumLimit(bounds[2*i]);
      chart->GetAxis(i)->SetMaximumLimit(bounds[2*i + 1]);
      }
    }
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::chartBoundsToPlotBounds(double bounds[8], double plotBounds[4])const
{
  plotBounds[0] = bounds[vtkAxis::BOTTOM*2];
  plotBounds[1] = bounds[vtkAxis::BOTTOM*2 + 1];
  plotBounds[2] = bounds[vtkAxis::LEFT*2];
  plotBounds[3] = bounds[vtkAxis::LEFT*2+1];
}

// ----------------------------------------------------------------------------
void ctkVTKChartView::mouseDoubleClickEvent(QMouseEvent* event)
{
  if (event->button() == Qt::MidButton)
    {
    this->setAxesToChartBounds();
    }
  this->Superclass::mouseDoubleClickEvent(event);
}
<|endoftext|>


<commit_before><commit_msg>Create 1197 - Back to High School Physics.cpp<commit_after><|endoftext|>


<commit_before>// Copyright 2018 Google LLC. All Rights Reserved.
/*
  Copyright (C) 2007 Steven L. Scott

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

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/

#include "Models/Glm/PosteriorSamplers/MLVS_data_imputer.hpp"

#include "cpputil/lse.hpp"
#include "cpputil/math_utils.hpp"

#include "stats/logit.hpp"

#include <cmath>
#include "distributions.hpp"

namespace BOOM {

  MlvsDataImputer::MlvsDataImputer(SufficientStatistics &global_suf,
                                   std::mutex &global_suf_mutex,
                                   MultinomialLogitModel *model, RNG *rng,
                                   RNG &seeding_rng)
      : SufstatImputeWorker<ChoiceData, SufficientStatistics>(
            global_suf, global_suf_mutex, rng, seeding_rng),
        model_(model),
        mu_(Vector("5.09 3.29 1.82 1.24 0.76 0.39 0.04 -0.31 -0.67  -1.06")),
        sigsq_inv_(
            pow(Vector("4.5 2.02 1.1 0.42 0.2 0.11 0.08 0.08 0.09 0.15"), -1)),
        sd_(pow(sigsq_inv_, -0.5)),
        log_mixing_weights_(log(Vector(
            "0.004 0.04 0.168 0.147 0.125 0.101 0.104 0.116 0.107 0.088"))),
        log_sampling_probs_(model_->log_sampling_probs()),
        downsampling_(log_sampling_probs_.size() == model_->Nchoices()),
        post_prob_(log_mixing_weights_),
        u(model_->Nchoices()),
        eta(u),
        wgts(u) {}

  void MlvsDataImputer::impute_latent_data_point(const ChoiceData &dp,
                                                 SufficientStatistics *suf,
                                                 RNG &rng) {
    model_->fill_eta(dp, eta);  // eta+= downsampling_logprob
    if (downsampling_) eta += log_sampling_probs_;  //
    uint M = model_->Nchoices();
    uint y = dp.value();
    assert(y < M);
    double loglam = lse(eta);
    double logzmin = rlexp_mt(rng, loglam);
    u[y] = -logzmin;
    for (uint m = 0; m < M; ++m) {
      if (m != y) {
        double tmp = rlexp_mt(rng, eta[m]);
        double logz = lse2(logzmin, tmp);
        u[m] = -logz;
      }
      uint k = unmix(rng, u[m] - eta[m]);
      u[m] -= mu_[k];
      wgts[m] = sigsq_inv_[k];
    }
    suf->update(dp, wgts, u);
  }

  //----------------------------------------------------------------------
  uint MlvsDataImputer::unmix(RNG &rng, double u) const {
    uint K = post_prob_.size();
    for (uint k = 0; k < K; ++k)
      post_prob_[k] = log_mixing_weights_[k] + dnorm(u, mu_[k], sd_[k], true);
    post_prob_.normalize_logprob();
    return rmulti_mt(rng, post_prob_);
  }

}  // namespace BOOM
<commit_msg>Changed Vector string constructor to initializer list.<commit_after>// Copyright 2018 Google LLC. All Rights Reserved.
/*
  Copyright (C) 2007 Steven L. Scott

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

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/

#include "Models/Glm/PosteriorSamplers/MLVS_data_imputer.hpp"

#include "cpputil/lse.hpp"
#include "cpputil/math_utils.hpp"

#include "stats/logit.hpp"

#include <cmath>
#include "distributions.hpp"

namespace BOOM {

  MlvsDataImputer::MlvsDataImputer(SufficientStatistics &global_suf,
                                   std::mutex &global_suf_mutex,
                                   MultinomialLogitModel *model, RNG *rng,
                                   RNG &seeding_rng)
      : SufstatImputeWorker<ChoiceData, SufficientStatistics>(
            global_suf, global_suf_mutex, rng, seeding_rng),
        model_(model),
        mu_(Vector{5.09, 3.29, 1.82, 1.24, 0.76, 0.39, 0.04, -0.31, -0.67, -1.06}),
        sigsq_inv_(pow(Vector({4.5, 2.02, 1.1, 0.42, 0.2, 0.11, 0.08, 0.08, 0.09, 0.15}), -1)),
        sd_(pow(sigsq_inv_, -0.5)),
        log_mixing_weights_(log(Vector({
                0.004, 0.04, 0.168, 0.147, 0.125, 0.101, 0.104, 0.116, 0.107, 0.088}))),
        log_sampling_probs_(model_->log_sampling_probs()),
        downsampling_(log_sampling_probs_.size() == model_->Nchoices()),
        post_prob_(log_mixing_weights_),
        u(model_->Nchoices()),
        eta(u),
        wgts(u) {}

  void MlvsDataImputer::impute_latent_data_point(const ChoiceData &dp,
                                                 SufficientStatistics *suf,
                                                 RNG &rng) {
    model_->fill_eta(dp, eta);  // eta+= downsampling_logprob
    if (downsampling_) eta += log_sampling_probs_;  //
    uint M = model_->Nchoices();
    uint y = dp.value();
    assert(y < M);
    double loglam = lse(eta);
    double logzmin = rlexp_mt(rng, loglam);
    u[y] = -logzmin;
    for (uint m = 0; m < M; ++m) {
      if (m != y) {
        double tmp = rlexp_mt(rng, eta[m]);
        double logz = lse2(logzmin, tmp);
        u[m] = -logz;
      }
      uint k = unmix(rng, u[m] - eta[m]);
      u[m] -= mu_[k];
      wgts[m] = sigsq_inv_[k];
    }
    suf->update(dp, wgts, u);
  }

  //----------------------------------------------------------------------
  uint MlvsDataImputer::unmix(RNG &rng, double u) const {
    uint K = post_prob_.size();
    for (uint k = 0; k < K; ++k)
      post_prob_[k] = log_mixing_weights_[k] + dnorm(u, mu_[k], sd_[k], true);
    post_prob_.normalize_logprob();
    return rmulti_mt(rng, post_prob_);
  }

}  // namespace BOOM
<|endoftext|>


<commit_before>#include <string>
#include <iostream>
#include <vector>

#include <SDL/SDL.h>
#include <glm/glm.hpp>

#include "Text.h"
#include "Gines.h"
#include "InputManager.h"
#include "Time.h"

// InputManager initialization.
InputManager inputManager;
//

//DEEBUGGIA...
void handleInput();
void increaseTextCount();
bool run = true;
std::vector<gines::Text*> texts;

extern SDL_Window *mWindow;
extern int WINDOW_HEIGHT;

int main(int argc, char** argv)
{
	if (!gines::initialize())
	{
		std::getchar();
		return false;
	}

	/////////////////////////
	// Test area...
	increaseTextCount();

	//Temp game loop
	while (run)
	{
		gines::beginMainLoop();

		//Event handling
		handleInput();

		//Rendering
		for (unsigned i = 0; i < texts.size(); i++)
		{texts[i]->render();}

		gines::endMainLoop();
	}

	//Deallocate text memory...
	while (!texts.empty())
	{
		delete texts.back();
		texts.pop_back();
	}

	// End of test area....
	/////////////////////////

	gines::uninitialize();
	std::cout << "\nExited succesfully";
	std::getchar();
	return 0;
}

//DEEBUGGIA...
void handleInput()
{
	float moveSpeed = texts.size();
	SDL_Event mEvent;
	while (SDL_PollEvent(&mEvent))
	{
		switch (mEvent.type)
		{
		case SDL_KEYDOWN:
			inputManager.keyPress(mEvent.key.keysym.sym);
			break;

			// Useless, Teogod shalt smite this commented area once he graces us with his presence.

			/*
			switch (mEvent.key.keysym.sym)
			{
			case SDLK_ESCAPE:
				run = false;
				break;
			case SDLK_RETURN:
				increaseTextCount();
				std::cout << "\nText count increased! texts.size(): " << texts.size();
				break;
			case SDLK_UP:
				for (unsigned i = 0; i < texts.size(); i++)
				{texts[i]->translate(vec2f(0, float(moveSpeed * (float(i+1)/texts.size()))));}
				break;
			case SDLK_DOWN:
				for (unsigned i = 0; i < texts.size(); i++)
				{texts[i]->translate(vec2f(0, float(-moveSpeed * (float(i + 1) / texts.size()))));}
				break;
			case SDLK_LEFT:
				for (unsigned i = 0; i < texts.size(); i++)
				{texts[i]->translate(vec2f(float(-moveSpeed * (float(i + 1) / texts.size())), 0));}
				break;
			case SDLK_RIGHT:
				for (unsigned i = 0; i < texts.size(); i++)
				{texts[i]->translate(vec2f(float(moveSpeed * (float(i + 1) / texts.size())), 0));}
				break;
			}
			break;
			*/

		case SDL_KEYUP:
			inputManager.keyRelease(mEvent.key.keysym.sym);
			break;

		case SDL_QUIT:
			run = false;
			break;
		}

		// These will likely be handled within the inputManager's handleInput function in the future. Will remain here for now.

		if (inputManager.isKeyHeld(SDLK_ESCAPE))
		{
			run = false;
		}
		if (inputManager.isKeyHeld(SDLK_RETURN))
		{
			increaseTextCount();
			std::cout << "\nText count increased! texts.size(): " << texts.size();
		}
		if (inputManager.isKeyHeld(SDLK_UP))
		{
			for (unsigned i = 0; i < texts.size(); i++)
			{
				texts[i]->translate(glm::vec2(0, float(moveSpeed * (float(i + 1) / texts.size()))));
			}
		}
		if (inputManager.isKeyHeld(SDLK_DOWN))
		{
			for (unsigned i = 0; i < texts.size(); i++)
			{
				texts[i]->translate(glm::vec2(0, float(-moveSpeed * (float(i + 1) / texts.size()))));
			}
		}
		if (inputManager.isKeyHeld(SDLK_LEFT))
		{
			for (unsigned i = 0; i < texts.size(); i++)
			{
				texts[i]->translate(glm::vec2(float(-moveSpeed * (float(i + 1) / texts.size())), 0));
			}
		}
		if (inputManager.isKeyHeld(SDLK_RIGHT))
		{
			for (unsigned i = 0; i < texts.size(); i++)
			{
				texts[i]->translate(glm::vec2(float(moveSpeed * (float(i + 1) / texts.size())), 0));
			}
		}

	}
}
void increaseTextCount()
{
	char* fontPath = "Fonts/Anonymous.ttf";
	if (texts.size() == 1)
		fontPath = "Fonts/Ponderosa.ttf";
	else if (texts.size() == 2)
		fontPath = "Fonts/VeraMono.ttf";
	else if (texts.size() == 3)
		fontPath = "Fonts/DroidSansMono.ttf";

	texts.push_back(new gines::Text);
	if (texts.back()->setFont(fontPath, 14))
	{
		//texts.back()->setFontSize(72);
		texts.back()->setPosition(glm::vec2(1, WINDOW_HEIGHT - 1 - texts.back()->getFontHeight()));
		//texts.back()->setString("A very small string this is A very small string \nthis is A very small string this is 100 glyphs total");
		texts.back()->setString("Hey ma!I wanna be a rock star\nI told all my friends and bought myself a guitar\nWell the voice of disbelief was deafening\nThe look upon their faces, almost threatening\nAll that you could hear were cries of laughter\nSomeone even said I was a disaster, can you believe it ? (I can)\nHey ma!I wanna be a rock star\nI told all my friends and bought myself a guitar\nWell the voice of disbelief was deafening\nThe look upon their faces, almost threatening\nMaybe you'll be pleasantly surprised, you'd be right to trust me\nI believe the ghost of good news is gonna be haunting me\nWhy? I'll never know\nMaybe soon I'll find out\nI guess I'm in with a shout\nNever know if you don't try\nI don't know, I don't ask why\nThe voice of disbelief was deafening\nThe voice of disbelief was deafening\nHey ma!I wanna be a rock star\nHey ma why are you not listening?\nWhy are you not listening?\nThe voice of disbelief\nSaid the voice of disbelief\nHey ma!");
		//texts.back()->setString("Black bird from evening sky\nRaven from heaths of night\nCome and take my cares\nCarry away the grief\nBereave me of my woes\nRend off these earthly throes\nFly them to deepest lakes\nTo the starlit shores");
		texts.back()->setColor(glm::vec4(0.12f, 0.45f, 0.07f, 1.0f));
		texts.back()->render();//updates glyphs to render
	}

	int glyphsToRender = 0;
	for (unsigned i = 0; i < texts.size(); i++)
		glyphsToRender += texts[i]->glyphsToRender;
	std::cout << "\nGlyphs to render: " << glyphsToRender;
}
/////////////<commit_msg>Fixed input delay<commit_after>#include <string>
#include <iostream>
#include <vector>

#include <SDL/SDL.h>
#include <glm/glm.hpp>

#include "Text.h"
#include "Gines.h"
#include "InputManager.h"
#include "Time.h"

// InputManager initialization.
InputManager inputManager;
//

//DEEBUGGIA...
void handleInput();
void increaseTextCount();
bool run = true;
std::vector<gines::Text*> texts;

extern SDL_Window *mWindow;
extern int WINDOW_HEIGHT;

int main(int argc, char** argv)
{
	if (!gines::initialize())
	{
		std::getchar();
		return false;
	}

	/////////////////////////
	// Test area...
	increaseTextCount();

	//Temp game loop
	while (run)
	{
		gines::beginMainLoop();

		//Event handling
		inputManager.update();
		handleInput();

		//Rendering
		for (unsigned i = 0; i < texts.size(); i++)
		{texts[i]->render();}

		gines::endMainLoop();
	}

	//Deallocate text memory...
	while (!texts.empty())
	{
		delete texts.back();
		texts.pop_back();
	}

	// End of test area....
	/////////////////////////

	gines::uninitialize();
	std::cout << "\nExited succesfully";
	std::getchar();
	return 0;
}

//DEEBUGGIA...
void handleInput()
{
	static SDL_Event mEvent;
	while (SDL_PollEvent(&mEvent))
	{
		switch (mEvent.type)
		{
		default:
			break;
		case SDL_KEYDOWN:
			inputManager.keyPress(mEvent.key.keysym.sym);
			break;
		case SDL_KEYUP:
			inputManager.keyRelease(mEvent.key.keysym.sym);
			break;
		case SDL_QUIT:
			run = false;
			break;
		}
	}

	float moveSpeed = 5 * texts.size();
	// These will likely be handled within the inputManager's handleInput function in the future. Will remain here for now.
	if (inputManager.isKeyHeld(SDLK_ESCAPE))
	{
		run = false;
	}
	if (inputManager.isKeyHeld(SDLK_RETURN))
	{
		increaseTextCount();
		std::cout << "\nText count increased! texts.size(): " << texts.size();
	}
	if (inputManager.isKeyHeld(SDLK_UP))
	{
		for (unsigned i = 0; i < texts.size(); i++)
		{
			texts[i]->translate(glm::vec2(0, float(moveSpeed * (float(i + 1) / texts.size()))));
		}
	}
	if (inputManager.isKeyHeld(SDLK_DOWN))
	{
		for (unsigned i = 0; i < texts.size(); i++)
		{
			texts[i]->translate(glm::vec2(0, float(-moveSpeed * (float(i + 1) / texts.size()))));
		}
	}
	if (inputManager.isKeyHeld(SDLK_LEFT))
	{
		for (unsigned i = 0; i < texts.size(); i++)
		{
			texts[i]->translate(glm::vec2(float(-moveSpeed * (float(i + 1) / texts.size())), 0));
		}
	}
	if (inputManager.isKeyHeld(SDLK_RIGHT))
	{
		for (unsigned i = 0; i < texts.size(); i++)
		{
			texts[i]->translate(glm::vec2(float(moveSpeed * (float(i + 1) / texts.size())), 0));
		}
	}
}
void increaseTextCount()
{
	char* fontPath = "Fonts/Anonymous.ttf";
	if (texts.size() == 1)
		fontPath = "Fonts/Ponderosa.ttf";
	else if (texts.size() == 2)
		fontPath = "Fonts/VeraMono.ttf";
	else if (texts.size() == 3)
		fontPath = "Fonts/DroidSansMono.ttf";

	texts.push_back(new gines::Text);
	if (texts.back()->setFont(fontPath, 14))
	{
		//texts.back()->setFontSize(72);
		texts.back()->setPosition(glm::vec2(1, WINDOW_HEIGHT - 1 - texts.back()->getFontHeight()));
		//texts.back()->setString("A very small string this is A very small string \nthis is A very small string this is 100 glyphs total");
		texts.back()->setString("Hey ma!I wanna be a rock star\nI told all my friends and bought myself a guitar\nWell the voice of disbelief was deafening\nThe look upon their faces, almost threatening\nAll that you could hear were cries of laughter\nSomeone even said I was a disaster, can you believe it ? (I can)\nHey ma!I wanna be a rock star\nI told all my friends and bought myself a guitar\nWell the voice of disbelief was deafening\nThe look upon their faces, almost threatening\nMaybe you'll be pleasantly surprised, you'd be right to trust me\nI believe the ghost of good news is gonna be haunting me\nWhy? I'll never know\nMaybe soon I'll find out\nI guess I'm in with a shout\nNever know if you don't try\nI don't know, I don't ask why\nThe voice of disbelief was deafening\nThe voice of disbelief was deafening\nHey ma!I wanna be a rock star\nHey ma why are you not listening?\nWhy are you not listening?\nThe voice of disbelief\nSaid the voice of disbelief\nHey ma!");
		//texts.back()->setString("Black bird from evening sky\nRaven from heaths of night\nCome and take my cares\nCarry away the grief\nBereave me of my woes\nRend off these earthly throes\nFly them to deepest lakes\nTo the starlit shores");
		texts.back()->setColor(glm::vec4(0.12f, 0.45f, 0.07f, 1.0f));
		texts.back()->render();//updates glyphs to render
	}

	int glyphsToRender = 0;
	for (unsigned i = 0; i < texts.size(); i++)
		glyphsToRender += texts[i]->glyphsToRender;
	std::cout << "\nGlyphs to render: " << glyphsToRender;
}
/////////////<|endoftext|>


<commit_before>// -------------------------------------------------------------------------
//    @FileName				:    NFCCreateRoleModule.cpp
//    @Author               :    LvSheng.Huang
//    @Date                 :    2013-03-29
//    @Module               :    NFCCreateRoleModule
//    @Desc                 :
// -------------------------------------------------------------------------

#include "NFCCreateRoleModule.h"
#include "NFComm/NFMessageDefine/NFProtocolDefine.hpp"

bool NFCCreateRoleModule::Init()
{
	m_pPVPModule = pPluginManager->FindModule<NFIPVPModule>();
	m_pElementModule = pPluginManager->FindModule<NFIElementModule>();
	m_pClassModule = pPluginManager->FindModule<NFIClassModule>();
	m_pPlayerRedisModule = pPluginManager->FindModule<NFIPlayerRedisModule>();
	m_pAccountRedisModule = pPluginManager->FindModule<NFIAccountRedisModule>();
	m_pNetModule = pPluginManager->FindModule<NFINetModule>();
	m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();
	m_pNoSqlModule = pPluginManager->FindModule<NFINoSqlModule>();
	m_pSceneAOIModule = pPluginManager->FindModule<NFISceneAOIModule>();
	m_pSceneProcessModule = pPluginManager->FindModule<NFISceneProcessModule>();
	m_pGameServerNet_ServerModule = pPluginManager->FindModule<NFIGameServerNet_ServerModule>();

    return true;
}

bool NFCCreateRoleModule::AfterInit()
{

	return true;
}

void NFCCreateRoleModule::OnReqiureRoleListProcess(const NFSOCK nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen)
{
	NFGUID nClientID;
	NFMsg::ReqRoleList xMsg;
	if (!m_pNetModule->ReceivePB( nMsgID, msg, nLen, xMsg, nClientID))
	{
		return;
	}

	NFGUID xPlayerID;
	std::string strRoleName;
	if (!m_pAccountRedisModule->GetRoleInfo(xMsg.account(), strRoleName, xPlayerID))
	{
		NFMsg::AckRoleLiteInfoList xAckRoleLiteInfoList;
		m_pNetModule->SendMsgPB(NFMsg::EGMI_ACK_ROLE_LIST, xAckRoleLiteInfoList, nSockIndex, nClientID);
		return;
	}

	//NF_SHARE_PTR<NFIPropertyManager> xPlayerProperty = m_pPlayerRedisModule->LoadPlayerCacheProperty(xPlayerID);
	//if (xPlayerProperty)
	{
		NFMsg::AckRoleLiteInfoList xAckRoleLiteInfoList;
		NFMsg::RoleLiteInfo* pData = xAckRoleLiteInfoList.add_char_data();
		pData->mutable_id()->CopyFrom(NFINetModule::NFToPB(xPlayerID));
		pData->set_game_id(pPluginManager->GetAppID());
		pData->set_career(0);
		pData->set_sex(0);
		pData->set_race(0);
		pData->set_noob_name(strRoleName);
		pData->set_role_level(0);
		pData->set_delete_time(0);
		pData->set_reg_time(0);
		pData->set_last_offline_time(0);
		pData->set_last_offline_ip(0);
		pData->set_view_record("");

		m_pNetModule->SendMsgPB(NFMsg::EGMI_ACK_ROLE_LIST, xAckRoleLiteInfoList, nSockIndex, nClientID);
	}
	//else
	//{
	//	NFMsg::AckRoleLiteInfoList xAckRoleLiteInfoList;
	//	m_pNetModule->SendMsgPB(NFMsg::EGMI_ACK_ROLE_LIST, xAckRoleLiteInfoList, nSockIndex, nClientID);
	//}
}

void NFCCreateRoleModule::OnCreateRoleGameProcess(const NFSOCK nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen)
{
	NFGUID nClientID;
	NFMsg::ReqCreateRole xMsg;
	if (!m_pNetModule->ReceivePB( nMsgID, msg, nLen, xMsg, nClientID))
	{
		return;
	}

	const std::string& strAccount = xMsg.account();
	const std::string& strName = xMsg.noob_name();

	NFGUID xID = m_pKernelModule->CreateGUID();
	if (m_pAccountRedisModule->CreateRole(strAccount, strName, xID))
	{
		NFMsg::AckRoleLiteInfoList xAckRoleLiteInfoList;
		NFMsg::RoleLiteInfo* pData = xAckRoleLiteInfoList.add_char_data();
		pData->mutable_id()->CopyFrom(NFINetModule::NFToPB(xID));
		pData->set_career(xMsg.career());
		pData->set_game_id(pPluginManager->GetAppID());
		pData->set_sex(xMsg.sex());
		pData->set_race(xMsg.race());
		pData->set_noob_name(xMsg.noob_name());
		pData->set_role_level(1);
		pData->set_delete_time(0);
		pData->set_reg_time(0);
		pData->set_last_offline_time(0);
		pData->set_last_offline_ip(0);
		pData->set_view_record("");

		m_pNetModule->SendMsgPB(NFMsg::EGMI_ACK_ROLE_LIST, xAckRoleLiteInfoList, nSockIndex, nClientID);
	}
}

void NFCCreateRoleModule::OnDeleteRoleGameProcess(const NFSOCK nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen)
{
	NFGUID nClientID;
	NFMsg::ReqRoleList xMsg;
	if (!m_pNetModule->ReceivePB( nMsgID, msg, nLen, xMsg, nClientID))
	{
		return;
	}

	NFMsg::AckRoleLiteInfoList xAckRoleLiteInfoList;
	m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGMI_ACK_ROLE_LIST, xAckRoleLiteInfoList, nClientID);
}

void NFCCreateRoleModule::OnClienEnterGameProcess(const NFSOCK nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen)
{
	NFGUID nClientID;
	NFMsg::ReqEnterGameServer xMsg;
	if (!m_pNetModule->ReceivePB( nMsgID, msg, nLen, xMsg, nClientID))
	{
		return;
	}

	NFGUID nRoleID = NFINetModule::PBToNF(xMsg.id());

	if (m_pKernelModule->GetObject(nRoleID))
	{
		//it should be rebind with proxy's netobject
		m_pKernelModule->DestroyObject(nRoleID);
	}

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

	NF_SHARE_PTR<NFIGameServerNet_ServerModule::GateBaseInfo>  pGateInfo = m_pGameServerNet_ServerModule->GetPlayerGateInfo(nRoleID);
	if (nullptr != pGateInfo)
	{
		m_pGameServerNet_ServerModule->RemovePlayerGateInfo(nRoleID);
	}

	NF_SHARE_PTR<NFIGameServerNet_ServerModule::GateServerInfo> pGateServerinfo = m_pGameServerNet_ServerModule->GetGateServerInfoBySockIndex(nSockIndex);
	if (nullptr == pGateServerinfo)
	{
		return;
	}

	int nGateID = -1;
	if (pGateServerinfo->xServerData.pData)
	{
		nGateID = pGateServerinfo->xServerData.pData->server_id();
	}

	if (nGateID < 0)
	{
		return;
	}

	if (!m_pGameServerNet_ServerModule->AddPlayerGateInfo(nRoleID, nClientID, nGateID))
	{
		return;
	}

	if (m_pPlayerRedisModule->LoadPlayerData(nRoleID))
	{
		int nHomeSceneID = m_pPlayerRedisModule->GetPlayerHomeSceneID(nRoleID);
		if (nHomeSceneID <= 0)
		{
			nHomeSceneID = m_pPVPModule->RandomTileScene();
		}

		NFDataList var;
		var.AddString(NFrame::Player::Name());
		var.AddString(xMsg.name());

		var.AddString(NFrame::Player::GateID());
		var.AddInt(nGateID);

		var.AddString(NFrame::Player::GameID());
		var.AddInt(pPluginManager->GetAppID());

		var.AddString(NFrame::Player::HomeSceneID());
		var.AddInt(nHomeSceneID);

		var.AddString(NFrame::Player::SceneID());
		var.AddInt(nHomeSceneID);

		NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->CreateObject(nRoleID, nHomeSceneID, 0, NFrame::Player::ThisName(), "", var);
		if (nullptr == pObject)
		{
			//mRoleBaseData
			//mRoleFDData
			return;
		}

		//get data first then create player
		m_pSceneProcessModule->RequestEnterScene(pObject->Self(), nHomeSceneID, -1, 0, NFDataList());
	}
}

bool NFCCreateRoleModule::ReadyExecute()
{
	m_pNetModule->RemoveReceiveCallBack(NFMsg::EGMI_REQ_ROLE_LIST);
	m_pNetModule->RemoveReceiveCallBack(NFMsg::EGMI_REQ_CREATE_ROLE);
	m_pNetModule->RemoveReceiveCallBack(NFMsg::EGMI_REQ_DELETE_ROLE);
	m_pNetModule->RemoveReceiveCallBack(NFMsg::EGMI_REQ_ENTER_GAME);

	m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_ROLE_LIST, this, &NFCCreateRoleModule::OnReqiureRoleListProcess);
	m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_CREATE_ROLE, this, &NFCCreateRoleModule::OnCreateRoleGameProcess);
	m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_DELETE_ROLE, this, &NFCCreateRoleModule::OnDeleteRoleGameProcess);
	m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_ENTER_GAME, this, &NFCCreateRoleModule::OnClienEnterGameProcess);

	return true;
}

bool NFCCreateRoleModule::Shut()
{
    return true;
}

bool NFCCreateRoleModule::Execute()
{
    return true;
}<commit_msg>* Temporarily modified to enter the number 1 scene only<commit_after>// -------------------------------------------------------------------------
//    @FileName				:    NFCCreateRoleModule.cpp
//    @Author               :    LvSheng.Huang
//    @Date                 :    2013-03-29
//    @Module               :    NFCCreateRoleModule
//    @Desc                 :
// -------------------------------------------------------------------------

#include "NFCCreateRoleModule.h"
#include "NFComm/NFMessageDefine/NFProtocolDefine.hpp"

bool NFCCreateRoleModule::Init()
{
	m_pPVPModule = pPluginManager->FindModule<NFIPVPModule>();
	m_pElementModule = pPluginManager->FindModule<NFIElementModule>();
	m_pClassModule = pPluginManager->FindModule<NFIClassModule>();
	m_pPlayerRedisModule = pPluginManager->FindModule<NFIPlayerRedisModule>();
	m_pAccountRedisModule = pPluginManager->FindModule<NFIAccountRedisModule>();
	m_pNetModule = pPluginManager->FindModule<NFINetModule>();
	m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();
	m_pNoSqlModule = pPluginManager->FindModule<NFINoSqlModule>();
	m_pSceneAOIModule = pPluginManager->FindModule<NFISceneAOIModule>();
	m_pSceneProcessModule = pPluginManager->FindModule<NFISceneProcessModule>();
	m_pGameServerNet_ServerModule = pPluginManager->FindModule<NFIGameServerNet_ServerModule>();

    return true;
}

bool NFCCreateRoleModule::AfterInit()
{

	return true;
}

void NFCCreateRoleModule::OnReqiureRoleListProcess(const NFSOCK nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen)
{
	NFGUID nClientID;
	NFMsg::ReqRoleList xMsg;
	if (!m_pNetModule->ReceivePB( nMsgID, msg, nLen, xMsg, nClientID))
	{
		return;
	}

	NFGUID xPlayerID;
	std::string strRoleName;
	if (!m_pAccountRedisModule->GetRoleInfo(xMsg.account(), strRoleName, xPlayerID))
	{
		NFMsg::AckRoleLiteInfoList xAckRoleLiteInfoList;
		m_pNetModule->SendMsgPB(NFMsg::EGMI_ACK_ROLE_LIST, xAckRoleLiteInfoList, nSockIndex, nClientID);
		return;
	}

	//NF_SHARE_PTR<NFIPropertyManager> xPlayerProperty = m_pPlayerRedisModule->LoadPlayerCacheProperty(xPlayerID);
	//if (xPlayerProperty)
	{
		NFMsg::AckRoleLiteInfoList xAckRoleLiteInfoList;
		NFMsg::RoleLiteInfo* pData = xAckRoleLiteInfoList.add_char_data();
		pData->mutable_id()->CopyFrom(NFINetModule::NFToPB(xPlayerID));
		pData->set_game_id(pPluginManager->GetAppID());
		pData->set_career(0);
		pData->set_sex(0);
		pData->set_race(0);
		pData->set_noob_name(strRoleName);
		pData->set_role_level(0);
		pData->set_delete_time(0);
		pData->set_reg_time(0);
		pData->set_last_offline_time(0);
		pData->set_last_offline_ip(0);
		pData->set_view_record("");

		m_pNetModule->SendMsgPB(NFMsg::EGMI_ACK_ROLE_LIST, xAckRoleLiteInfoList, nSockIndex, nClientID);
	}
	//else
	//{
	//	NFMsg::AckRoleLiteInfoList xAckRoleLiteInfoList;
	//	m_pNetModule->SendMsgPB(NFMsg::EGMI_ACK_ROLE_LIST, xAckRoleLiteInfoList, nSockIndex, nClientID);
	//}
}

void NFCCreateRoleModule::OnCreateRoleGameProcess(const NFSOCK nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen)
{
	NFGUID nClientID;
	NFMsg::ReqCreateRole xMsg;
	if (!m_pNetModule->ReceivePB( nMsgID, msg, nLen, xMsg, nClientID))
	{
		return;
	}

	const std::string& strAccount = xMsg.account();
	const std::string& strName = xMsg.noob_name();

	NFGUID xID = m_pKernelModule->CreateGUID();
	if (m_pAccountRedisModule->CreateRole(strAccount, strName, xID))
	{
		NFMsg::AckRoleLiteInfoList xAckRoleLiteInfoList;
		NFMsg::RoleLiteInfo* pData = xAckRoleLiteInfoList.add_char_data();
		pData->mutable_id()->CopyFrom(NFINetModule::NFToPB(xID));
		pData->set_career(xMsg.career());
		pData->set_game_id(pPluginManager->GetAppID());
		pData->set_sex(xMsg.sex());
		pData->set_race(xMsg.race());
		pData->set_noob_name(xMsg.noob_name());
		pData->set_role_level(1);
		pData->set_delete_time(0);
		pData->set_reg_time(0);
		pData->set_last_offline_time(0);
		pData->set_last_offline_ip(0);
		pData->set_view_record("");

		m_pNetModule->SendMsgPB(NFMsg::EGMI_ACK_ROLE_LIST, xAckRoleLiteInfoList, nSockIndex, nClientID);
	}
}

void NFCCreateRoleModule::OnDeleteRoleGameProcess(const NFSOCK nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen)
{
	NFGUID nClientID;
	NFMsg::ReqRoleList xMsg;
	if (!m_pNetModule->ReceivePB( nMsgID, msg, nLen, xMsg, nClientID))
	{
		return;
	}

	NFMsg::AckRoleLiteInfoList xAckRoleLiteInfoList;
	m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGMI_ACK_ROLE_LIST, xAckRoleLiteInfoList, nClientID);
}

void NFCCreateRoleModule::OnClienEnterGameProcess(const NFSOCK nSockIndex, const int nMsgID, const char * msg, const uint32_t nLen)
{
	NFGUID nClientID;
	NFMsg::ReqEnterGameServer xMsg;
	if (!m_pNetModule->ReceivePB( nMsgID, msg, nLen, xMsg, nClientID))
	{
		return;
	}

	NFGUID nRoleID = NFINetModule::PBToNF(xMsg.id());

	if (m_pKernelModule->GetObject(nRoleID))
	{
		//it should be rebind with proxy's netobject
		m_pKernelModule->DestroyObject(nRoleID);
	}

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

	NF_SHARE_PTR<NFIGameServerNet_ServerModule::GateBaseInfo>  pGateInfo = m_pGameServerNet_ServerModule->GetPlayerGateInfo(nRoleID);
	if (nullptr != pGateInfo)
	{
		m_pGameServerNet_ServerModule->RemovePlayerGateInfo(nRoleID);
	}

	NF_SHARE_PTR<NFIGameServerNet_ServerModule::GateServerInfo> pGateServerinfo = m_pGameServerNet_ServerModule->GetGateServerInfoBySockIndex(nSockIndex);
	if (nullptr == pGateServerinfo)
	{
		return;
	}

	int nGateID = -1;
	if (pGateServerinfo->xServerData.pData)
	{
		nGateID = pGateServerinfo->xServerData.pData->server_id();
	}

	if (nGateID < 0)
	{
		return;
	}

	if (!m_pGameServerNet_ServerModule->AddPlayerGateInfo(nRoleID, nClientID, nGateID))
	{
		return;
	}

	if (m_pPlayerRedisModule->LoadPlayerData(nRoleID))
	{
		int nHomeSceneID = m_pPlayerRedisModule->GetPlayerHomeSceneID(nRoleID);
		if (nHomeSceneID <= 0)
		{
			nHomeSceneID = m_pPVPModule->RandomTileScene();
		}
		// test scene one
		nHomeSceneID = 1;

		NFDataList var;
		var.AddString(NFrame::Player::Name());
		var.AddString(xMsg.name());

		var.AddString(NFrame::Player::GateID());
		var.AddInt(nGateID);

		var.AddString(NFrame::Player::GameID());
		var.AddInt(pPluginManager->GetAppID());

		var.AddString(NFrame::Player::HomeSceneID());
		var.AddInt(nHomeSceneID);

		var.AddString(NFrame::Player::SceneID());
		var.AddInt(nHomeSceneID);

		NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->CreateObject(nRoleID, nHomeSceneID, 0, NFrame::Player::ThisName(), "", var);
		if (nullptr == pObject)
		{
			//mRoleBaseData
			//mRoleFDData
			return;
		}

		//get data first then create player
		m_pSceneProcessModule->RequestEnterScene(pObject->Self(), nHomeSceneID, -1, 0, NFDataList());
	}
}

bool NFCCreateRoleModule::ReadyExecute()
{
	m_pNetModule->RemoveReceiveCallBack(NFMsg::EGMI_REQ_ROLE_LIST);
	m_pNetModule->RemoveReceiveCallBack(NFMsg::EGMI_REQ_CREATE_ROLE);
	m_pNetModule->RemoveReceiveCallBack(NFMsg::EGMI_REQ_DELETE_ROLE);
	m_pNetModule->RemoveReceiveCallBack(NFMsg::EGMI_REQ_ENTER_GAME);

	m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_ROLE_LIST, this, &NFCCreateRoleModule::OnReqiureRoleListProcess);
	m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_CREATE_ROLE, this, &NFCCreateRoleModule::OnCreateRoleGameProcess);
	m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_DELETE_ROLE, this, &NFCCreateRoleModule::OnDeleteRoleGameProcess);
	m_pNetModule->AddReceiveCallBack(NFMsg::EGMI_REQ_ENTER_GAME, this, &NFCCreateRoleModule::OnClienEnterGameProcess);

	return true;
}

bool NFCCreateRoleModule::Shut()
{
    return true;
}

bool NFCCreateRoleModule::Execute()
{
    return true;
}<|endoftext|>


<commit_before>/*
    Copyright (c) 2009 Tobias Koenig <tokoe@kde.org>

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

    This library is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "qcsvmodel.h"
#include "qcsvmodel_p.h"
#include "qcsvreader.h"

#include <QtCore/QMap>
#include <QtCore/QPair>
#include <QtCore/QStringList>

CsvParser::CsvParser( QObject *parent )
  : QThread( parent ), mDevice( 0 )
{
  mReader = new QCsvReader( this );
}

CsvParser::~CsvParser()
{
  delete mReader;
}

void CsvParser::load( QIODevice *device )
{
  mDevice = device;

  start();
}

void CsvParser::begin()
{
  mCacheCounter = 0;
  mRowCount = 0;
  mColumnCount = 0;
}

void CsvParser::beginLine()
{
  mRowCount++;
}

void CsvParser::field( const QString &data, uint row, uint column )
{
  const int tmp = qMax( mColumnCount, (int)column + 1 );
  if ( tmp != mColumnCount ) {
    mColumnCount = tmp;
    emit columnCountChanged( tmp );
  }

  emit dataChanged( data, row, column );
}

void CsvParser::endLine()
{
  mCacheCounter++;
  if ( mCacheCounter == 50 ) {
    emit rowCountChanged( mRowCount );
    mCacheCounter = 0;
  }
}

void CsvParser::end()
{
  emit rowCountChanged( mRowCount );
}

void CsvParser::error( const QString& )
{
}

void CsvParser::run()
{
  if ( !mDevice->isOpen() )
    mDevice->open( QIODevice::ReadOnly );

  mDevice->reset();
  mReader->read( mDevice );
}

class QCsvModel::Private
{
  public:
    Private( QCsvModel *model )
      : mParent( model ),
        mDevice( 0 ), mRowCount( 0 ), mColumnCount( 0 )
    {
    }

    void columnCountChanged( int columns );
    void rowCountChanged( int rows );
    void fieldChanged( const QString &data, int row, int column );

    QCsvModel *mParent;
    CsvParser *mParser;
    QMap< QPair<int, int>, QString> mFields;
    QIODevice *mDevice;

    int mRowCount;
    int mColumnCount;
};

void QCsvModel::Private::columnCountChanged( int columns )
{
  mColumnCount = columns;
  emit mParent->layoutChanged();
}

void QCsvModel::Private::rowCountChanged( int rows )
{
  mRowCount = rows;
  emit mParent->layoutChanged();
}

void QCsvModel::Private::fieldChanged( const QString &data, int row, int column )
{
  mFields.insert( QPair<int, int>( row, column ), data );
}

QCsvModel::QCsvModel( QObject *parent )
  : QAbstractTableModel( parent ), d( new Private( this ) )
{
  d->mParser = new CsvParser( this );

  connect( d->mParser, SIGNAL( columnCountChanged( int ) ),
           this, SLOT( columnCountChanged( int ) ), Qt::QueuedConnection );
  connect( d->mParser, SIGNAL( rowCountChanged( int ) ),
           this, SLOT( rowCountChanged( int ) ), Qt::QueuedConnection );
  connect( d->mParser, SIGNAL( dataChanged( const QString&, int, int ) ),
           this, SLOT( fieldChanged( const QString&, int, int ) ), Qt::QueuedConnection );
  connect( d->mParser, SIGNAL( finished() ), this, SIGNAL( finished() ) );
}

QCsvModel::~QCsvModel()
{
}

bool QCsvModel::load( QIODevice *device )
{
  d->mDevice = device;
  d->mRowCount = 0;
  d->mColumnCount = 0;
  d->mFields.clear();

  emit layoutChanged();

  d->mParser->load( device );

  return true;
}

void QCsvModel::setTextQuote( const QChar &textQuote )
{
  const bool isRunning = d->mParser->isRunning();

  if ( isRunning ) {
    d->mParser->terminate();
    d->mParser->wait();
  }

  d->mParser->reader()->setTextQuote( textQuote );

  if ( isRunning )
    load( d->mDevice );
}

QChar QCsvModel::textQuote() const
{
  return d->mParser->reader()->textQuote();
}

void QCsvModel::setDelimiter( const QChar &delimiter )
{
  const bool isRunning = d->mParser->isRunning();

  if ( isRunning ) {
    d->mParser->terminate();
    d->mParser->wait();
  }

  d->mParser->reader()->setDelimiter( delimiter );

  if ( isRunning )
    load( d->mDevice );
}

QChar QCsvModel::delimiter() const
{
  return d->mParser->reader()->delimiter();
}

void QCsvModel::setStartRow( uint startRow )
{
  const bool isRunning = d->mParser->isRunning();

  if ( isRunning ) {
    d->mParser->terminate();
    d->mParser->wait();
  }

  d->mParser->reader()->setStartRow( startRow );

  if ( isRunning )
    load( d->mDevice );
}

uint QCsvModel::startRow() const
{
  return d->mParser->reader()->startRow();
}

void QCsvModel::setTextCodec( QTextCodec *textCodec )
{
  const bool isRunning = d->mParser->isRunning();

  if ( isRunning ) {
    d->mParser->terminate();
    d->mParser->wait();
  }

  d->mParser->reader()->setTextCodec( textCodec );

  if ( isRunning )
    load( d->mDevice );
}

QTextCodec *QCsvModel::textCodec() const
{
  return d->mParser->reader()->textCodec();
}

int QCsvModel::columnCount( const QModelIndex& ) const
{
  return d->mColumnCount;
}

int QCsvModel::rowCount( const QModelIndex& ) const
{
  return d->mRowCount;
}

QVariant QCsvModel::data( const QModelIndex &index, int role ) const
{
  if ( !index.isValid() )
    return QVariant();

  const QPair<int, int> pair( index.row(), index.column() );
  if ( !d->mFields.contains( pair ) )
    return QVariant();

  const QString data = d->mFields.value( pair );

  if ( role == Qt::DisplayRole )
    return data;
  else
    return QVariant();
}

#include "qcsvmodel.moc"
#include "qcsvmodel_p.moc"
<commit_msg>Fix mem leak<commit_after>/*
    Copyright (c) 2009 Tobias Koenig <tokoe@kde.org>

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

    This library is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "qcsvmodel.h"
#include "qcsvmodel_p.h"
#include "qcsvreader.h"

#include <QtCore/QMap>
#include <QtCore/QPair>
#include <QtCore/QStringList>

CsvParser::CsvParser( QObject *parent )
  : QThread( parent ), mDevice( 0 )
{
  mReader = new QCsvReader( this );
}

CsvParser::~CsvParser()
{
  delete mReader;
}

void CsvParser::load( QIODevice *device )
{
  mDevice = device;

  start();
}

void CsvParser::begin()
{
  mCacheCounter = 0;
  mRowCount = 0;
  mColumnCount = 0;
}

void CsvParser::beginLine()
{
  mRowCount++;
}

void CsvParser::field( const QString &data, uint row, uint column )
{
  const int tmp = qMax( mColumnCount, (int)column + 1 );
  if ( tmp != mColumnCount ) {
    mColumnCount = tmp;
    emit columnCountChanged( tmp );
  }

  emit dataChanged( data, row, column );
}

void CsvParser::endLine()
{
  mCacheCounter++;
  if ( mCacheCounter == 50 ) {
    emit rowCountChanged( mRowCount );
    mCacheCounter = 0;
  }
}

void CsvParser::end()
{
  emit rowCountChanged( mRowCount );
}

void CsvParser::error( const QString& )
{
}

void CsvParser::run()
{
  if ( !mDevice->isOpen() )
    mDevice->open( QIODevice::ReadOnly );

  mDevice->reset();
  mReader->read( mDevice );
}

class QCsvModel::Private
{
  public:
    Private( QCsvModel *model )
      : mParent( model ),
        mDevice( 0 ), mRowCount( 0 ), mColumnCount( 0 )
    {
    }

    void columnCountChanged( int columns );
    void rowCountChanged( int rows );
    void fieldChanged( const QString &data, int row, int column );

    QCsvModel *mParent;
    CsvParser *mParser;
    QMap< QPair<int, int>, QString> mFields;
    QIODevice *mDevice;

    int mRowCount;
    int mColumnCount;
};

void QCsvModel::Private::columnCountChanged( int columns )
{
  mColumnCount = columns;
  emit mParent->layoutChanged();
}

void QCsvModel::Private::rowCountChanged( int rows )
{
  mRowCount = rows;
  emit mParent->layoutChanged();
}

void QCsvModel::Private::fieldChanged( const QString &data, int row, int column )
{
  mFields.insert( QPair<int, int>( row, column ), data );
}

QCsvModel::QCsvModel( QObject *parent )
  : QAbstractTableModel( parent ), d( new Private( this ) )
{
  d->mParser = new CsvParser( this );

  connect( d->mParser, SIGNAL( columnCountChanged( int ) ),
           this, SLOT( columnCountChanged( int ) ), Qt::QueuedConnection );
  connect( d->mParser, SIGNAL( rowCountChanged( int ) ),
           this, SLOT( rowCountChanged( int ) ), Qt::QueuedConnection );
  connect( d->mParser, SIGNAL( dataChanged( const QString&, int, int ) ),
           this, SLOT( fieldChanged( const QString&, int, int ) ), Qt::QueuedConnection );
  connect( d->mParser, SIGNAL( finished() ), this, SIGNAL( finished() ) );
}

QCsvModel::~QCsvModel()
{
  delete d;
}

bool QCsvModel::load( QIODevice *device )
{
  d->mDevice = device;
  d->mRowCount = 0;
  d->mColumnCount = 0;
  d->mFields.clear();

  emit layoutChanged();

  d->mParser->load( device );

  return true;
}

void QCsvModel::setTextQuote( const QChar &textQuote )
{
  const bool isRunning = d->mParser->isRunning();

  if ( isRunning ) {
    d->mParser->terminate();
    d->mParser->wait();
  }

  d->mParser->reader()->setTextQuote( textQuote );

  if ( isRunning )
    load( d->mDevice );
}

QChar QCsvModel::textQuote() const
{
  return d->mParser->reader()->textQuote();
}

void QCsvModel::setDelimiter( const QChar &delimiter )
{
  const bool isRunning = d->mParser->isRunning();

  if ( isRunning ) {
    d->mParser->terminate();
    d->mParser->wait();
  }

  d->mParser->reader()->setDelimiter( delimiter );

  if ( isRunning )
    load( d->mDevice );
}

QChar QCsvModel::delimiter() const
{
  return d->mParser->reader()->delimiter();
}

void QCsvModel::setStartRow( uint startRow )
{
  const bool isRunning = d->mParser->isRunning();

  if ( isRunning ) {
    d->mParser->terminate();
    d->mParser->wait();
  }

  d->mParser->reader()->setStartRow( startRow );

  if ( isRunning )
    load( d->mDevice );
}

uint QCsvModel::startRow() const
{
  return d->mParser->reader()->startRow();
}

void QCsvModel::setTextCodec( QTextCodec *textCodec )
{
  const bool isRunning = d->mParser->isRunning();

  if ( isRunning ) {
    d->mParser->terminate();
    d->mParser->wait();
  }

  d->mParser->reader()->setTextCodec( textCodec );

  if ( isRunning )
    load( d->mDevice );
}

QTextCodec *QCsvModel::textCodec() const
{
  return d->mParser->reader()->textCodec();
}

int QCsvModel::columnCount( const QModelIndex& ) const
{
  return d->mColumnCount;
}

int QCsvModel::rowCount( const QModelIndex& ) const
{
  return d->mRowCount;
}

QVariant QCsvModel::data( const QModelIndex &index, int role ) const
{
  if ( !index.isValid() )
    return QVariant();

  const QPair<int, int> pair( index.row(), index.column() );
  if ( !d->mFields.contains( pair ) )
    return QVariant();

  const QString data = d->mFields.value( pair );

  if ( role == Qt::DisplayRole )
    return data;
  else
    return QVariant();
}

#include "qcsvmodel.moc"
#include "qcsvmodel_p.moc"
<|endoftext|>