<commit_before>/*************************************************************************
 *
 *  $RCSfile: unoshtxt.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: dl $ $Date: 2001-04-20 09:41:08 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

//#include <tools/debug.hxx>
//#include <svx/editeng.hxx>

#include <unoshtxt.hxx>

#ifndef _SFXHINT_HXX //autogen
#include <svtools/hint.hxx>
#endif
#ifndef _SVDMODEL_HXX //autogen
#include <svdmodel.hxx>
#endif
#ifndef _SVDOUTL_HXX //autogen
#include <svdoutl.hxx>
#endif
#ifndef _SVDOBJ_HXX
#include <svdobj.hxx>
#endif
#ifndef _SVDETC_HXX
#include <svdetc.hxx>
#endif
#ifndef _OUTLINER_HXX
#include <outliner.hxx>
#endif
#ifndef _SVX_UNOFOROU_HXX
#include <unoforou.hxx>
#endif
#include "svdotext.hxx"
#include "svdpage.hxx"
#include "editeng.hxx"

#include "unotext.hxx"

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

SvxTextEditSource::SvxTextEditSource( SdrObject* pObject ) :
    pObj            ( pObject ),
    pOutliner       ( NULL ),
    pTextForwarder  ( NULL ),
    bDataValid      ( FALSE ),
    bDestroyed      ( FALSE )
{
    DBG_ASSERT( pObj, "invalid pObject!" );

    if( pObj )
        StartListening( *pObj->GetModel() );
}

//------------------------------------------------------------------------
SvxTextEditSource::~SvxTextEditSource()
{
    if( pObj )
        EndListening( *pObj->GetModel() );

    delete pTextForwarder;
    delete pOutliner;
}

//------------------------------------------------------------------------
SvxEditSource* SvxTextEditSource::Clone() const
{
    return new SvxTextEditSource( pObj );
}

//------------------------------------------------------------------------
SvxTextForwarder* SvxTextEditSource::GetTextForwarder()
{
    if( bDestroyed || pObj == NULL )
        return NULL;

    if (!pTextForwarder)
    {
        if( pOutliner == NULL )
        {
            SdrTextObj* pTextObj = PTR_CAST( SdrTextObj, pObj );
            USHORT nOutlMode = OUTLINERMODE_TEXTOBJECT;
            if( pTextObj && pTextObj->IsTextFrame() && pTextObj->GetTextKind() == OBJ_OUTLINETEXT )
                nOutlMode = OUTLINERMODE_OUTLINEOBJECT;
            SdrModel* pModel = pObj->GetModel();
            pOutliner = SdrMakeOutliner( nOutlMode, pModel );
            Outliner& aDrawOutliner = pModel->GetDrawOutliner();
            pOutliner->SetCalcFieldValueHdl( aDrawOutliner.GetCalcFieldValueHdl() );
        }

        pTextForwarder = new SvxOutlinerForwarder( *pOutliner );
    }

    if( pObj && !bDataValid )
    {
        OutlinerParaObject* pOutlinerParaObject = NULL;
        SdrTextObj* pTextObj = PTR_CAST( SdrTextObj, pObj );
        if( pTextObj )
            pOutlinerParaObject = pTextObj->GetEditOutlinerParaObject(); // Get the OutlinerParaObject if text edit is active
        if( !pOutlinerParaObject )
            pOutlinerParaObject = pObj->GetOutlinerParaObject();  // no text edit active

        if( pOutlinerParaObject && (!pObj->IsEmptyPresObj() || pObj->GetPage()->IsMasterPage()) )
        {
            pOutliner->SetText( *pOutlinerParaObject );
        }
        else
        {
            // set objects style sheet on empty outliner
            SfxStyleSheetPool* pPool = (SfxStyleSheetPool*)pObj->GetModel()->GetStyleSheetPool();
            if( pPool )
                pOutliner->SetStyleSheetPool( pPool );

            SfxStyleSheet* pStyleSheet = pObj->GetPage()->GetTextStyleSheetForObject( pObj );
            if( pStyleSheet )
                pOutliner->SetStyleSheet( 0, pStyleSheet );
        }

        bDataValid = TRUE;
    }

    return pTextForwarder;
}

//------------------------------------------------------------------------
void SvxTextEditSource::UpdateData()
{
    if( pOutliner && pObj && !bDestroyed )
    {
        if( pOutliner->GetParagraphCount() != 1 || pOutliner->GetEditEngine().GetTextLen( 0 ) )
            pObj->SetOutlinerParaObject( pOutliner->CreateParaObject() );
        else
            pObj->SetOutlinerParaObject( NULL );

        if( pObj->IsEmptyPresObj() )
            pObj->SetEmptyPresObj(sal_False);
    }
}

//------------------------------------------------------------------------
void SvxTextEditSource::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    const SdrHint* pSdrHint = PTR_CAST( SdrHint, &rHint );

    if( pSdrHint )
    {
        if( pSdrHint->GetKind() == HINT_OBJCHG )
            bDataValid = FALSE;                     // Text muss neu geholt werden
        if( pSdrHint->GetKind() == HINT_OBJREMOVED )
        {
            if( pObj == pSdrHint->GetObject() )
            {
                pObj = NULL;
                bDestroyed = TRUE;
            }
        }
        else if( pSdrHint->GetKind() == HINT_MODELCLEARED ||
                 pSdrHint->GetKind() == HINT_OBJLISTCLEARED )
        {
            if( pObj )
                EndListening( *pObj->GetModel() );
            pObj = NULL;
            bDestroyed = TRUE;
        }
    }

    if( bDestroyed )
    {
        delete pTextForwarder;
        delete pOutliner;
        pOutliner = NULL;

        pTextForwarder = NULL;
    }
}

<commit_msg>#85804# GetTextForwarder(): handling of EmptyPresObj<commit_after>/*************************************************************************
 *
 *  $RCSfile: unoshtxt.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: dl $ $Date: 2001-05-04 09:07:10 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

//#include <tools/debug.hxx>
//#include <svx/editeng.hxx>

#include <unoshtxt.hxx>

#ifndef _SFXHINT_HXX //autogen
#include <svtools/hint.hxx>
#endif
#ifndef _SVDMODEL_HXX //autogen
#include <svdmodel.hxx>
#endif
#ifndef _SVDOUTL_HXX //autogen
#include <svdoutl.hxx>
#endif
#ifndef _SVDOBJ_HXX
#include <svdobj.hxx>
#endif
#ifndef _SVDETC_HXX
#include <svdetc.hxx>
#endif
#ifndef _OUTLINER_HXX
#include <outliner.hxx>
#endif
#ifndef _SVX_UNOFOROU_HXX
#include <unoforou.hxx>
#endif
#include "svdotext.hxx"
#include "svdpage.hxx"
#include "editeng.hxx"

#include "unotext.hxx"

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

SvxTextEditSource::SvxTextEditSource( SdrObject* pObject ) :
    pObj            ( pObject ),
    pOutliner       ( NULL ),
    pTextForwarder  ( NULL ),
    bDataValid      ( FALSE ),
    bDestroyed      ( FALSE )
{
    DBG_ASSERT( pObj, "invalid pObject!" );

    if( pObj )
        StartListening( *pObj->GetModel() );
}

//------------------------------------------------------------------------
SvxTextEditSource::~SvxTextEditSource()
{
    if( pObj )
        EndListening( *pObj->GetModel() );

    delete pTextForwarder;
    delete pOutliner;
}

//------------------------------------------------------------------------
SvxEditSource* SvxTextEditSource::Clone() const
{
    return new SvxTextEditSource( pObj );
}

//------------------------------------------------------------------------
SvxTextForwarder* SvxTextEditSource::GetTextForwarder()
{
    if( bDestroyed || pObj == NULL )
        return NULL;

    if (!pTextForwarder)
    {
        if( pOutliner == NULL )
        {
            SdrTextObj* pTextObj = PTR_CAST( SdrTextObj, pObj );
            USHORT nOutlMode = OUTLINERMODE_TEXTOBJECT;
            if( pTextObj && pTextObj->IsTextFrame() && pTextObj->GetTextKind() == OBJ_OUTLINETEXT )
                nOutlMode = OUTLINERMODE_OUTLINEOBJECT;
            SdrModel* pModel = pObj->GetModel();
            pOutliner = SdrMakeOutliner( nOutlMode, pModel );
            Outliner& aDrawOutliner = pModel->GetDrawOutliner();
            pOutliner->SetCalcFieldValueHdl( aDrawOutliner.GetCalcFieldValueHdl() );
        }

        pTextForwarder = new SvxOutlinerForwarder( *pOutliner );
    }

    if( pObj && !bDataValid )
    {
        OutlinerParaObject* pOutlinerParaObject = NULL;
        BOOL bTextEditActive = FALSE;
        SdrTextObj* pTextObj = PTR_CAST( SdrTextObj, pObj );
        if( pTextObj )
            pOutlinerParaObject = pTextObj->GetEditOutlinerParaObject(); // Get the OutlinerParaObject if text edit is active

        if( pOutlinerParaObject )
            bTextEditActive = TRUE; // text edit active
        else
            pOutlinerParaObject = pObj->GetOutlinerParaObject();

        if( pOutlinerParaObject && ( bTextEditActive || !pObj->IsEmptyPresObj() || pObj->GetPage()->IsMasterPage() ) )
        {
            pOutliner->SetText( *pOutlinerParaObject );

            if( pObj->IsEmptyPresObj() )
                pObj->SetEmptyPresObj( FALSE );
        }
        else
        {
            // set objects style sheet on empty outliner
            SfxStyleSheetPool* pPool = (SfxStyleSheetPool*)pObj->GetModel()->GetStyleSheetPool();
            if( pPool )
                pOutliner->SetStyleSheetPool( pPool );

            SfxStyleSheet* pStyleSheet = pObj->GetPage()->GetTextStyleSheetForObject( pObj );
            if( pStyleSheet )
                pOutliner->SetStyleSheet( 0, pStyleSheet );
        }

        bDataValid = TRUE;
    }

    return pTextForwarder;
}

//------------------------------------------------------------------------
void SvxTextEditSource::UpdateData()
{
    if( pOutliner && pObj && !bDestroyed )
    {
        if( pOutliner->GetParagraphCount() != 1 || pOutliner->GetEditEngine().GetTextLen( 0 ) )
            pObj->SetOutlinerParaObject( pOutliner->CreateParaObject() );
        else
            pObj->SetOutlinerParaObject( NULL );

        if( pObj->IsEmptyPresObj() )
            pObj->SetEmptyPresObj(sal_False);
    }
}

//------------------------------------------------------------------------
void SvxTextEditSource::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    const SdrHint* pSdrHint = PTR_CAST( SdrHint, &rHint );

    if( pSdrHint )
    {
        if( pSdrHint->GetKind() == HINT_OBJCHG )
            bDataValid = FALSE;                     // Text muss neu geholt werden
        if( pSdrHint->GetKind() == HINT_OBJREMOVED )
        {
            if( pObj == pSdrHint->GetObject() )
            {
                pObj = NULL;
                bDestroyed = TRUE;
            }
        }
        else if( pSdrHint->GetKind() == HINT_MODELCLEARED ||
                 pSdrHint->GetKind() == HINT_OBJLISTCLEARED )
        {
            if( pObj )
                EndListening( *pObj->GetModel() );
            pObj = NULL;
            bDestroyed = TRUE;
        }
    }

    if( bDestroyed )
    {
        delete pTextForwarder;
        delete pOutliner;
        pOutliner = NULL;

        pTextForwarder = NULL;
    }
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007-2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/io/FileFunctions.h"
#include "db/io/File.h"
#include "db/io/FileList.h"
#include "db/util/StringTokenizer.h"

#include <sys/stat.h>
#include <dirent.h>

using namespace std;
using namespace db::io;
using namespace db::rt;
using namespace db::util;

File::File()
{
   mName = strdup("");
}

File::File(const char* name)
{
   mName = strdup(name);
}

File::~File()
{
   free(mName);
}

bool File::operator==(const File& rhs)
{
   bool rval = false;

   File* file = (File*)&rhs;

   // compare names and types for equality
   if(strcmp(mName, file->getName()) == 0)
   {
      rval = (getType() == file->getType());
   }

   return rval;
}

bool File::exists()
{
   bool rval = false;

   struct stat s;
   int rc = stat(mName, &s);
   if(rc == 0)
   {
      rval = true;
   }
   else
   {
      // FIXME: ENOENT (2) is errno for file not found
      // FIXME: add error handling
   }

   return rval;
}

bool File::remove()
{
   bool rval = false;

   int rc = ::remove(mName);
   if(rc == 0)
   {
      rval = true;
   }
   else
   {
      // FIXME: add error handling
   }

   return rval;
}

const char* File::getName() const
{
   return mName;
}

off_t File::getLength()
{
   struct stat s;
   int rc = stat(mName, &s);
   if(rc != 0)
   {
      // FIXME: add error handling
   }

   return s.st_size;
}

File::Type File::getType()
{
   Type rval = Unknown;

   // use lstat so symbolic links aren't followed
   struct stat s;
   int rc = stat(mName, &s);
   if(rc != 0)
   {
   }
   else
   {
      switch(s.st_mode & S_IFMT)
      {
         case S_IFREG:
            rval = RegularFile;
            break;
         case S_IFDIR:
            rval = Directory;
            break;
         case S_IFLNK:
            rval = SymbolicLink;
            break;
         default:
            break;
      }
   }

   return rval;
}

bool File::isFile()
{
   return getType() == RegularFile;
}

bool File::contains(const char* path)
{
   bool rval = false;
   string normalizedContainer;
   string normalizedFile;

   if((normalizePath(getName(), normalizedContainer) != NULL) &&
      (normalizePath(path, normalizedFile) != NULL) &&
      (normalizedFile.find(normalizedContainer, 0) == 0))
   {
      rval = true;
   }

   return rval;
}

bool File::contains(File* path)
{
   return contains(path->getName());
}

bool File::isDirectory()
{
   return getType() == Directory;
}

bool File::isReadable()
{
   bool rval = false;
   string npath;

   if(normalizePath(getName(), npath) != NULL)
   {
      rval = isPathReadable(npath.c_str());
   }

   return rval;
}

bool File::isSymbolicLink()
{
   return getType() == SymbolicLink;
}

bool File::isWritable()
{
   bool rval = false;
   string npath;

   if(normalizePath(getName(), npath) != NULL)
   {
      rval = isPathWritable(npath.c_str());
   }

   return rval;
}

void File::listFiles(FileList* files)
{
   if(isDirectory())
   {
      // open directory
      DIR* dir = opendir(mName);
      if(dir == NULL)
      {
         // FIXME: add error handling
      }
      else
      {
         // read each directory entry
         struct dirent* entry;
         unsigned int len1 = strlen(mName);
         bool separator = mName[len1 - 1] != '/';
         while((entry = readdir(dir)) != NULL)
         {
            // d_name is null-terminated name for file, without path name
            // so copy file name before d_name to get full path
            unsigned int len2 = strlen(entry->d_name);
            char path[len1 + len2 + 2];
            memcpy(path, mName, len1);
            if(separator)
            {
               // add path separator as appropriate
               path[len1] = '/';
               memcpy(path + len1 + 1, entry->d_name, len2 + 1);
            }
            else
            {
               memcpy(path + len1, entry->d_name, len2 + 1);
            }

            // add new File to list
            File* file = new File(path);
            files->add(file);
         }

         // close directory
         closedir(dir);
      }
   }
}

Exception* File::normalizePath(const char* path, string& normalizedPath)
{
   Exception* rval = NULL;
   string tempPath;

   if(strlen(path) > 0)
   {
      // if the path isn't absolute, pre-pend the current working directory
      // to the path.
      if(path[0] != '/')
      {
         rval = getCurrentWorkingDirectory(tempPath);

         tempPath.push_back('/');
         tempPath.append(path);
      }
      else
      {
         tempPath.append(path);
      }

      // clean up the relative directory references
      // TODO: This is a somewhat slow process because the string tokenizer
      //       isn't setup to be run in reverse, which is the most efficient
      //       way to build a directory path. This could become an issue if
      //       the application is doing a ton of path normalizations. -- manu
      StringTokenizer st(tempPath.c_str(), '/');
      int nTokens = st.getTokenCount();
      int skipNum = 0;
      tempPath.erase();
      for(int i = nTokens - 1; i > 0; i--)
      {
         const char* token = st.getToken(i);
         if(strcmp(token, "..") == 0)
         {
            skipNum++;
         }
         else if(strcmp(token, ".") == 0)
         {

         }
         else
         {
            if(skipNum == 0)
            {
               tempPath.insert(0, token);
               tempPath.insert(0, 1, '/');
            }
            else
            {
               skipNum--;
            }
         }
      }
   }

   normalizedPath.assign(tempPath);

   return rval;
}

Exception* File::normalizePath(File* path, string& normalizedPath)
{
   return normalizePath(path->getName(), normalizedPath);
}

Exception* File::getCurrentWorkingDirectory(string& cwd)
{
   Exception* rval = NULL;

   char* b = (char*)malloc(PATH_MAX);
   if(getcwd(b, PATH_MAX) != NULL)
   {
      cwd.assign(b);
   }
   else
   {
      // path was too large for getcwd
      rval = new Exception(
         "Could not get current working directory, path too long!");
      Exception::setLast(rval);
   }
   free(b);

   return rval;
}

bool File::isPathReadable(const char* path)
{
   return (access(path, R_OK) == 0);
}

bool File::isPathWritable(const char* path)
{
   return (access(path, W_OK) == 0);
}
<commit_msg>Fixed a bug in the isReadable()/isWritable(). When the new Exception* stuff was written, the tests checked for != NULL, when they should have been checking for == NULL.<commit_after>/*
 * Copyright (c) 2007-2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/io/FileFunctions.h"
#include "db/io/File.h"
#include "db/io/FileList.h"
#include "db/util/StringTokenizer.h"

#include <sys/stat.h>
#include <dirent.h>

using namespace std;
using namespace db::io;
using namespace db::rt;
using namespace db::util;

File::File()
{
   mName = strdup("");
}

File::File(const char* name)
{
   mName = strdup(name);
}

File::~File()
{
   free(mName);
}

bool File::operator==(const File& rhs)
{
   bool rval = false;

   File* file = (File*)&rhs;

   // compare names and types for equality
   if(strcmp(mName, file->getName()) == 0)
   {
      rval = (getType() == file->getType());
   }

   return rval;
}

bool File::exists()
{
   bool rval = false;

   struct stat s;
   int rc = stat(mName, &s);
   if(rc == 0)
   {
      rval = true;
   }
   else
   {
      // FIXME: ENOENT (2) is errno for file not found
      // FIXME: add error handling
   }

   return rval;
}

bool File::remove()
{
   bool rval = false;

   int rc = ::remove(mName);
   if(rc == 0)
   {
      rval = true;
   }
   else
   {
      // FIXME: add error handling
   }

   return rval;
}

const char* File::getName() const
{
   return mName;
}

off_t File::getLength()
{
   struct stat s;
   int rc = stat(mName, &s);
   if(rc != 0)
   {
      // FIXME: add error handling
   }

   return s.st_size;
}

File::Type File::getType()
{
   Type rval = Unknown;

   // use lstat so symbolic links aren't followed
   struct stat s;
   int rc = stat(mName, &s);
   if(rc != 0)
   {
   }
   else
   {
      switch(s.st_mode & S_IFMT)
      {
         case S_IFREG:
            rval = RegularFile;
            break;
         case S_IFDIR:
            rval = Directory;
            break;
         case S_IFLNK:
            rval = SymbolicLink;
            break;
         default:
            break;
      }
   }

   return rval;
}

bool File::isFile()
{
   return getType() == RegularFile;
}

bool File::contains(const char* path)
{
   bool rval = false;
   string normalizedContainer;
   string normalizedFile;

   if((normalizePath(getName(), normalizedContainer) == NULL) &&
      (normalizePath(path, normalizedFile) == NULL))
   {
      rval = (normalizedFile.find(normalizedContainer, 0) == 0);
   }

   return rval;
}

bool File::contains(File* path)
{
   return contains(path->getName());
}

bool File::isDirectory()
{
   return getType() == Directory;
}

bool File::isReadable()
{
   bool rval = false;
   string npath;

   if(normalizePath(getName(), npath) == NULL)
   {
      rval = isPathReadable(npath.c_str());
   }

   return rval;
}

bool File::isSymbolicLink()
{
   return getType() == SymbolicLink;
}

bool File::isWritable()
{
   bool rval = false;
   string npath;

   if(normalizePath(getName(), npath))
   {
      rval = isPathWritable(npath.c_str());
   }

   return rval;
}

void File::listFiles(FileList* files)
{
   if(isDirectory())
   {
      // open directory
      DIR* dir = opendir(mName);
      if(dir == NULL)
      {
         // FIXME: add error handling
      }
      else
      {
         // read each directory entry
         struct dirent* entry;
         unsigned int len1 = strlen(mName);
         bool separator = mName[len1 - 1] != '/';
         while((entry = readdir(dir)) != NULL)
         {
            // d_name is null-terminated name for file, without path name
            // so copy file name before d_name to get full path
            unsigned int len2 = strlen(entry->d_name);
            char path[len1 + len2 + 2];
            memcpy(path, mName, len1);
            if(separator)
            {
               // add path separator as appropriate
               path[len1] = '/';
               memcpy(path + len1 + 1, entry->d_name, len2 + 1);
            }
            else
            {
               memcpy(path + len1, entry->d_name, len2 + 1);
            }

            // add new File to list
            File* file = new File(path);
            files->add(file);
         }

         // close directory
         closedir(dir);
      }
   }
}

Exception* File::normalizePath(const char* path, string& normalizedPath)
{
   Exception* rval = NULL;
   string tempPath;

   if(strlen(path) > 0)
   {
      // if the path isn't absolute, pre-pend the current working directory
      // to the path.
      if(path[0] != '/')
      {
         rval = getCurrentWorkingDirectory(tempPath);

         tempPath.push_back('/');
         tempPath.append(path);
      }
      else
      {
         tempPath.append(path);
      }

      // clean up the relative directory references
      // TODO: This is a somewhat slow process because the string tokenizer
      //       isn't setup to be run in reverse, which is the most efficient
      //       way to build a directory path. This could become an issue if
      //       the application is doing a ton of path normalizations. -- manu
      StringTokenizer st(tempPath.c_str(), '/');
      int nTokens = st.getTokenCount();
      int skipNum = 0;
      tempPath.erase();
      for(int i = nTokens - 1; i > 0; i--)
      {
         const char* token = st.getToken(i);
         if(strcmp(token, "..") == 0)
         {
            skipNum++;
         }
         else if(strcmp(token, ".") == 0)
         {

         }
         else
         {
            if(skipNum == 0)
            {
               tempPath.insert(0, token);
               tempPath.insert(0, 1, '/');
            }
            else
            {
               skipNum--;
            }
         }
      }
   }

   normalizedPath.assign(tempPath);

   return rval;
}

Exception* File::normalizePath(File* path, string& normalizedPath)
{
   return normalizePath(path->getName(), normalizedPath);
}

Exception* File::getCurrentWorkingDirectory(string& cwd)
{
   Exception* rval = NULL;

   char* b = (char*)malloc(PATH_MAX);
   if(getcwd(b, PATH_MAX) != NULL)
   {
      cwd.assign(b);
   }
   else
   {
      // path was too large for getcwd
      rval = new Exception(
         "Could not get current working directory, path too long!");
      Exception::setLast(rval);
   }
   free(b);

   return rval;
}

bool File::isPathReadable(const char* path)
{
   return (access(path, R_OK) == 0);
}

bool File::isPathWritable(const char* path)
{
   return (access(path, W_OK) == 0);
}
<|endoftext|>


<commit_before><commit_msg>fdo#72650: Get thumbnails only from the local documents.<commit_after><|endoftext|>


<commit_before>/* Copyright 2013 - 2015 Yurii Litvinov and CyberTech Labs Ltd.
 *
 * 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 "controller.h"

#include <QtCore/QProcess>
#include <QtCore/QFileInfo>

#include <QtXml/QDomDocument>

#include <trikKernel/configurer.h>
#include <trikKernel/fileUtils.h>
#include <trikKernel/paths.h>
#include <trikKernel/exceptions/internalErrorException.h>
#include <trikControl/brickFactory.h>
#include <trikNetwork/mailboxFactory.h>
#include <trikNetwork/gamepadFactory.h>
#include <trikWiFi/trikWiFi.h>

#include "runningWidget.h"
#include "autoRunner.h"

using namespace trikGui;

const int communicatorPort = 8888;
const int telemetryPort = 9000;

Controller::Controller(const QString &configPath)
	: mBrick(trikControl::BrickFactory::create(configPath, trikKernel::Paths::mediaPath()))
{
	if (configPath.isEmpty()) {
		throw trikKernel::InternalErrorException("Config path is empty");
	}

	auto correctedConfigPath = configPath.endsWith('/') ? configPath : configPath + '/';

	trikKernel::Configurer configurer(correctedConfigPath + "system-config.xml"
			, correctedConfigPath + "model-config.xml");

	mGamepad.reset(trikNetwork::GamepadFactory::create(configurer));
	connect(mGamepad.data(), SIGNAL(disconnect()), this, SIGNAL(gamepadDisconnected()));
	connect(mGamepad.data(), SIGNAL(connected()), this, SIGNAL(gamepadConnected()));

	mMailbox.reset(trikNetwork::MailboxFactory::create(configurer));
	mTelemetry.reset(new trikTelemetry::TrikTelemetry(*mBrick, *mGamepad));
	mScriptRunner.reset(new trikScriptRunner::TrikScriptRunner(*mBrick, mMailbox.data(), mGamepad.data()));
	mCommunicator.reset(new trikCommunicator::TrikCommunicator(*mScriptRunner, configurer.version()));

	mWiFi.reset(new trikWiFi::TrikWiFi("/tmp/trikwifi", "/var/run/wpa_supplicant/wlan0", this));
	connect(mWiFi.data(), SIGNAL(connected()), this, SIGNAL(wiFiConnected()));
	connect(mWiFi.data(), SIGNAL(disconnected(trikWiFi::DisconnectReason)), this, SIGNAL(wiFiDisconnected()));

	connect(mCommunicator.data(), SIGNAL(stopCommandReceived()), this, SLOT(abortExecution()));
	connect(mCommunicator.data(), SIGNAL(connected()), this, SLOT(updateCommunicatorStatus()));
	connect(mCommunicator.data(), SIGNAL(disconnected()), this, SLOT(updateCommunicatorStatus()));
	connect(mTelemetry.data(), SIGNAL(connected()), this, SLOT(updateCommunicatorStatus()));
	connect(mTelemetry.data(), SIGNAL(disconnected()), this, SLOT(updateCommunicatorStatus()));
	connect(mMailbox.data(), SIGNAL(connectionStatusChanged(bool)), this, SIGNAL(mailboxStatusChanged(bool)));

	connect(mScriptRunner.data(), SIGNAL(completed(QString, int)), this, SLOT(scriptExecutionCompleted(QString, int)));

	connect(mScriptRunner.data(), SIGNAL(startedScript(QString, int))
			, this, SLOT(scriptExecutionFromFileStarted(QString, int)));

	connect(mScriptRunner.data(), SIGNAL(startedDirectScript(int))
			, this, SLOT(directScriptExecutionStarted(int)));

	connect(mBrick.data(), SIGNAL(stopped()), this, SIGNAL(brickStopped()));

	mCommunicator->startServer(communicatorPort);
	mTelemetry->startServer(telemetryPort);

	mAutoRunner.reset(new AutoRunner(*this));

	mBrick->led()->green();
}

Controller::~Controller()
{
	mBrick->led()->orange();
}

void Controller::runFile(const QString &filePath)
{
	QFileInfo const fileInfo(filePath);
	if (fileInfo.suffix() == "qts" || fileInfo.suffix() == "js") {
		mScriptRunner->run(trikKernel::FileUtils::readFromFile(fileInfo.canonicalFilePath()), fileInfo.baseName());
	} else if (fileInfo.suffix() == "wav" || fileInfo.suffix() == "mp3") {
		mScriptRunner->run("brick.playSound(\"" + fileInfo.canonicalFilePath() + "\");", fileInfo.baseName());
	} else if (fileInfo.suffix() == "sh") {
		QProcess::startDetached("sh", {filePath});
	} else if (fileInfo.isExecutable()) {
		QProcess::startDetached(filePath);
	}
}

void Controller::abortExecution()
{
	emit hideScriptWidgets();
	mScriptRunner->abort();

	// Now script engine will stop (after some time maybe) and send "completed" signal, which will be caught and
	// processed as if a script finished by itself.
}

trikControl::BrickInterface &Controller::brick()
{
	return *mBrick;
}

trikNetwork::MailboxInterface *Controller::mailbox()
{
	return mMailbox.data();
}

trikWiFi::TrikWiFi &Controller::wiFi()
{
	return *mWiFi;
}

bool Controller::communicatorConnectionStatus()
{
	return mTelemetry->activeConnections() > 0 && mCommunicator->activeConnections() > 0;
}

bool Controller::gamepadConnectionStatus() const
{
	return mGamepad->isConnected();
}

void Controller::updateCommunicatorStatus()
{
	emit communicatorStatusChanged(communicatorConnectionStatus());
}

void Controller::scriptExecutionCompleted(const QString &error, int scriptId)
{
	if (error.isEmpty()) {
		emit hideRunningWidget(scriptId);
	} else {
		mCommunicator->sendMessage("error: " + error);
		emit showError(error, scriptId);
	}

	mBrick->reset();

	if (mMailbox) {
		mMailbox->clearQueue();
	}

	if (mGamepad) {
		mGamepad->reset();
	}

	mBrick->led()->green();
}

void Controller::scriptExecutionFromFileStarted(const QString &fileName, int scriptId)
{
	emit showRunningWidget(fileName, scriptId);
}

void Controller::directScriptExecutionStarted(int scriptId)
{
	scriptExecutionFromFileStarted(tr("direct command"), scriptId);
}
<commit_msg>treatment disable gamepad<commit_after>/* Copyright 2013 - 2015 Yurii Litvinov and CyberTech Labs Ltd.
 *
 * 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 "controller.h"

#include <QtCore/QProcess>
#include <QtCore/QFileInfo>

#include <QtXml/QDomDocument>

#include <trikKernel/configurer.h>
#include <trikKernel/fileUtils.h>
#include <trikKernel/paths.h>
#include <trikKernel/exceptions/internalErrorException.h>
#include <trikControl/brickFactory.h>
#include <trikNetwork/mailboxFactory.h>
#include <trikNetwork/gamepadFactory.h>
#include <trikWiFi/trikWiFi.h>

#include "runningWidget.h"
#include "autoRunner.h"

using namespace trikGui;

const int communicatorPort = 8888;
const int telemetryPort = 9000;

Controller::Controller(const QString &configPath)
	: mBrick(trikControl::BrickFactory::create(configPath, trikKernel::Paths::mediaPath()))
{
	if (configPath.isEmpty()) {
		throw trikKernel::InternalErrorException("Config path is empty");
	}

	auto correctedConfigPath = configPath.endsWith('/') ? configPath : configPath + '/';

	trikKernel::Configurer configurer(correctedConfigPath + "system-config.xml"
			, correctedConfigPath + "model-config.xml");
	//configurer.attributeByDevice("gamepad", "optional");

	mGamepad.reset(trikNetwork::GamepadFactory::create(configurer));
	connect(mGamepad.data(), SIGNAL(disconnect()), this, SIGNAL(gamepadDisconnected()));
	connect(mGamepad.data(), SIGNAL(connected()), this, SIGNAL(gamepadConnected()));

	mMailbox.reset(trikNetwork::MailboxFactory::create(configurer));
	mTelemetry.reset(new trikTelemetry::TrikTelemetry(*mBrick, *mGamepad));
	mScriptRunner.reset(new trikScriptRunner::TrikScriptRunner(*mBrick, mMailbox.data(), mGamepad.data()));
	mCommunicator.reset(new trikCommunicator::TrikCommunicator(*mScriptRunner, configurer.version()));

	mWiFi.reset(new trikWiFi::TrikWiFi("/tmp/trikwifi", "/var/run/wpa_supplicant/wlan0", this));
	connect(mWiFi.data(), SIGNAL(connected()), this, SIGNAL(wiFiConnected()));
	connect(mWiFi.data(), SIGNAL(disconnected(trikWiFi::DisconnectReason)), this, SIGNAL(wiFiDisconnected()));

	connect(mCommunicator.data(), SIGNAL(stopCommandReceived()), this, SLOT(abortExecution()));
	connect(mCommunicator.data(), SIGNAL(connected()), this, SLOT(updateCommunicatorStatus()));
	connect(mCommunicator.data(), SIGNAL(disconnected()), this, SLOT(updateCommunicatorStatus()));
	connect(mTelemetry.data(), SIGNAL(connected()), this, SLOT(updateCommunicatorStatus()));
	connect(mTelemetry.data(), SIGNAL(disconnected()), this, SLOT(updateCommunicatorStatus()));
	connect(mMailbox.data(), SIGNAL(connectionStatusChanged(bool)), this, SIGNAL(mailboxStatusChanged(bool)));

	connect(mScriptRunner.data(), SIGNAL(completed(QString, int)), this, SLOT(scriptExecutionCompleted(QString, int)));

	connect(mScriptRunner.data(), SIGNAL(startedScript(QString, int))
			, this, SLOT(scriptExecutionFromFileStarted(QString, int)));

	connect(mScriptRunner.data(), SIGNAL(startedDirectScript(int))
			, this, SLOT(directScriptExecutionStarted(int)));

	connect(mBrick.data(), SIGNAL(stopped()), this, SIGNAL(brickStopped()));

	mCommunicator->startServer(communicatorPort);
	mTelemetry->startServer(telemetryPort);

	mAutoRunner.reset(new AutoRunner(*this));

	mBrick->led()->green();
}

Controller::~Controller()
{
	mBrick->led()->orange();
}

void Controller::runFile(const QString &filePath)
{
	QFileInfo const fileInfo(filePath);
	if (fileInfo.suffix() == "qts" || fileInfo.suffix() == "js") {
		mScriptRunner->run(trikKernel::FileUtils::readFromFile(fileInfo.canonicalFilePath()), fileInfo.baseName());
	} else if (fileInfo.suffix() == "wav" || fileInfo.suffix() == "mp3") {
		mScriptRunner->run("brick.playSound(\"" + fileInfo.canonicalFilePath() + "\");", fileInfo.baseName());
	} else if (fileInfo.suffix() == "sh") {
		QProcess::startDetached("sh", {filePath});
	} else if (fileInfo.isExecutable()) {
		QProcess::startDetached(filePath);
	}
}

void Controller::abortExecution()
{
	emit hideScriptWidgets();
	mScriptRunner->abort();

	// Now script engine will stop (after some time maybe) and send "completed" signal, which will be caught and
	// processed as if a script finished by itself.
}

trikControl::BrickInterface &Controller::brick()
{
	return *mBrick;
}

trikNetwork::MailboxInterface *Controller::mailbox()
{
	return mMailbox.data();
}

trikWiFi::TrikWiFi &Controller::wiFi()
{
	return *mWiFi;
}

bool Controller::communicatorConnectionStatus()
{
	return mTelemetry->activeConnections() > 0 && mCommunicator->activeConnections() > 0;
}

bool Controller::gamepadConnectionStatus() const
{
	if (mGamepad != nullptr){
		return mGamepad->isConnected();
	}
	return false;
}

void Controller::updateCommunicatorStatus()
{
	emit communicatorStatusChanged(communicatorConnectionStatus());
}

void Controller::scriptExecutionCompleted(const QString &error, int scriptId)
{
	if (error.isEmpty()) {
		emit hideRunningWidget(scriptId);
	} else {
		mCommunicator->sendMessage("error: " + error);
		emit showError(error, scriptId);
	}

	mBrick->reset();

	if (mMailbox) {
		mMailbox->clearQueue();
	}

	if (mGamepad) {
		mGamepad->reset();
	}

	mBrick->led()->green();
}

void Controller::scriptExecutionFromFileStarted(const QString &fileName, int scriptId)
{
	emit showRunningWidget(fileName, scriptId);
}

void Controller::directScriptExecutionStarted(int scriptId)
{
	scriptExecutionFromFileStarted(tr("direct command"), scriptId);
}
<|endoftext|>


<commit_before>#include "poke.h"
#include <nds/dma.h>
#include <nds/arm9/video.h>

#define VRAM_F_SIZE 16*1024
#define VRAM_G_SIZE 16*1024
#define VRAM_H_SIZE 32*1024
#define VRAM_I_SIZE 16*1024

static bool pointerInRange(void *needle, void *base, size_t size);
static bool pointerInRange(volatile void *needle, volatile void *base, size_t size);

Poke::Poke() : size(0), mode(PM_NOOP) {}
Poke::Poke(uint8_t val, volatile uint8_t *addr_) : size(sizeof(uint8_t)), mode(PM_INT), addr(addr_), value8(val) {
}
Poke::Poke(uint16_t val, volatile uint16_t *addr_) : size(sizeof(uint16_t)), mode(PM_INT), addr(addr_), value16(val) {
}
Poke::Poke(uint32_t val, volatile uint32_t *addr_) : size(sizeof(uint32_t)), mode(PM_INT), addr(addr_), value32(val) {
}
Poke::Poke(std::unique_ptr<uint8_t[]> &&dataPtr, size_t dataSize, hwPtr addr_) : size(dataSize), mode(PM_MEMCPY), addr(addr_), valuePtr(std::move(dataPtr)) {
}

Poke::Poke(uint8_t val, uint8_t mask, volatile uint8_t *addr_) : size(sizeof(uint8_t)), mode(PM_BITFIELD), addr(addr_), bitField8(val, mask) {
}
Poke::Poke(uint16_t val, uint16_t mask, volatile uint16_t *addr_) : size(sizeof(uint16_t)), mode(PM_BITFIELD), addr(addr_), bitField16(val, mask) {
}
Poke::Poke(uint32_t val, uint32_t mask, volatile uint32_t *addr_) : size(sizeof(uint32_t)), mode(PM_BITFIELD), addr(addr_), bitField32(val,mask) {
}

Poke::Poke(Poke &&p2) : size(p2.size), mode(p2.mode), addr(p2.addr) {

	switch(p2.mode) {
		case PM_NOOP:
		break;
		case PM_INT:
			switch(p2.size) {
				case sizeof(uint8_t):
					value8=p2.value8;
				break;
				case sizeof(uint16_t):
					value16=p2.value16;
				break;
				case sizeof(uint32_t):
					value32=p2.value32;
				break;
			}
		break;

		case PM_BITFIELD:
			switch (p2.size) {
				case sizeof(uint8_t) :
					bitField8 = p2.bitField8;
					break;
				case sizeof(uint16_t) :
					bitField16 = p2.bitField16;
					break;
				case sizeof(uint32_t) :
					bitField32 = p2.bitField32;
					break;
			}
		break;

		case PM_DMA_16:
		case PM_DMA_32:
		case PM_MEMCPY:
			valuePtr=std::move(p2.valuePtr);
		break;
	}
	p2.mode=PM_NOOP;
	p2.size=0;
}

Poke::~Poke() {
	switch(mode) {
		case PM_DMA_16:
		case PM_DMA_32:
		case PM_MEMCPY:
			valuePtr.~unique_ptr();
		break;
		case PM_BITFIELD://no destructor to call
		default:
		break;
	}
}

void Poke::Perform() {
	uint8_t oldMode;

	if (pointerInRange(addr, VRAM_F, VRAM_F_SIZE)) {
		oldMode = VRAM_F_CR;
		vramSetBankF(VRAM_F_LCD);
	} else if (pointerInRange(addr, VRAM_G, VRAM_G_SIZE)) {
		oldMode = VRAM_G_CR;
		vramSetBankG(VRAM_G_LCD);
	} else if (pointerInRange(addr, VRAM_H, VRAM_H_SIZE)) {
		oldMode = VRAM_H_CR;
		vramSetBankH(VRAM_H_LCD);
	} else if (pointerInRange(addr, VRAM_I, VRAM_I_SIZE)) {
		oldMode = VRAM_I_CR;
		vramSetBankI(VRAM_I_LCD);
	}

	switch(mode) {
		case PM_NOOP:
		break;
		case PM_INT:
			switch(size) {
				case sizeof(uint8_t):
					*((volatile uint8_t*)addr)=value8;
				break;
				case sizeof(uint16_t):
					*((volatile uint16_t*)addr)=value16;
				break;
				case sizeof(uint32_t):
					*((volatile uint32_t*)addr)=value32;
				break;
			}
		break;
		case PM_BITFIELD:
			switch (size) {
			case sizeof(uint8_t) :
				bitField8.Poke((volatile uint8_t*)addr);
				break;
			case sizeof(uint16_t) :
				bitField16.Poke((volatile uint16_t*)addr);
				break;
			case sizeof(uint32_t) :
				bitField32.Poke((volatile uint32_t*)addr);
				break;
			}
		break;
		case PM_DMA_16:
			dmaCopyHalfWords(3, valuePtr.get(), (void*)addr, size);
		break;
		case PM_DMA_32:
			dmaCopyWords(3, valuePtr.get(), (void*)addr, size);
			break;
		case PM_MEMCPY: {
			volatile uint8_t *dst=valuePtr.get();
			std::copy(dst,dst+size,(uint8_t *)addr);
		} break;
	}

	if(pointerInRange(addr, VRAM_F, VRAM_F_SIZE)) {
		VRAM_F_CR = oldMode;
	} else if(pointerInRange(addr, VRAM_G, VRAM_G_SIZE)) {
		VRAM_G_CR = oldMode;
	} else if(pointerInRange(addr, VRAM_H, VRAM_H_SIZE)) {
		VRAM_H_CR = oldMode;
	} else if(pointerInRange(addr, VRAM_I, VRAM_I_SIZE)) {
		VRAM_I_CR = oldMode;
	}
}

PokeChainLink::PokeChainLink() {}
PokeChainLink::PokeChainLink(PokeChainLink &&pch2) : next(std::move(pch2.next)), poke(std::move(pch2.poke)) {}
PokeChainLink::PokeChainLink(Poke &&p) : next(nullptr), poke(std::move(p)) {}
PokeChainLink::PokeChainLink(Poke &&p, std::unique_ptr<PokeChainLink> &&next_) : next(std::move(next_)), poke(std::move(p)) {}
PokeChainLink::~PokeChainLink() {}

static bool pointerInRange(uintptr_t needle, uintptr_t base, size_t size) {
	return needle >= base && needle < (base + size);
}
static bool pointerInRange(volatile void *needle, volatile void *base, size_t size) {
	return pointerInRange((uintptr_t)needle, (uintptr_t)base, size);
}
static bool pointerInRange(void *needle, void *base, size_t size) {
	return pointerInRange((uintptr_t)needle, (uintptr_t)base, size);
}<commit_msg>Move bitfields, not copy<commit_after>#include "poke.h"
#include <nds/dma.h>
#include <nds/arm9/video.h>

#define VRAM_F_SIZE 16*1024
#define VRAM_G_SIZE 16*1024
#define VRAM_H_SIZE 32*1024
#define VRAM_I_SIZE 16*1024

static bool pointerInRange(void *needle, void *base, size_t size);
static bool pointerInRange(volatile void *needle, volatile void *base, size_t size);

Poke::Poke() : size(0), mode(PM_NOOP) {}
Poke::Poke(uint8_t val, volatile uint8_t *addr_) : size(sizeof(uint8_t)), mode(PM_INT), addr(addr_), value8(val) {
}
Poke::Poke(uint16_t val, volatile uint16_t *addr_) : size(sizeof(uint16_t)), mode(PM_INT), addr(addr_), value16(val) {
}
Poke::Poke(uint32_t val, volatile uint32_t *addr_) : size(sizeof(uint32_t)), mode(PM_INT), addr(addr_), value32(val) {
}
Poke::Poke(std::unique_ptr<uint8_t[]> &&dataPtr, size_t dataSize, hwPtr addr_) : size(dataSize), mode(PM_MEMCPY), addr(addr_), valuePtr(std::move(dataPtr)) {
}

Poke::Poke(uint8_t val, uint8_t mask, volatile uint8_t *addr_) : size(sizeof(uint8_t)), mode(PM_BITFIELD), addr(addr_), bitField8(val, mask) {
}
Poke::Poke(uint16_t val, uint16_t mask, volatile uint16_t *addr_) : size(sizeof(uint16_t)), mode(PM_BITFIELD), addr(addr_), bitField16(val, mask) {
}
Poke::Poke(uint32_t val, uint32_t mask, volatile uint32_t *addr_) : size(sizeof(uint32_t)), mode(PM_BITFIELD), addr(addr_), bitField32(val,mask) {
}

Poke::Poke(Poke &&p2) : size(p2.size), mode(p2.mode), addr(p2.addr) {

	switch(p2.mode) {
		case PM_NOOP:
		break;
		case PM_INT:
			switch(p2.size) {
				case sizeof(uint8_t):
					value8=p2.value8;
				break;
				case sizeof(uint16_t):
					value16=p2.value16;
				break;
				case sizeof(uint32_t):
					value32=p2.value32;
				break;
			}
		break;

		case PM_BITFIELD:
			switch (p2.size) {
				case sizeof(uint8_t) :
					bitField8 = std::move(p2.bitField8);
					break;
				case sizeof(uint16_t) :
					bitField16 = std::move(p2.bitField16);
					break;
				case sizeof(uint32_t) :
					bitField32 = std::move(p2.bitField32);
					break;
			}
		break;

		case PM_DMA_16:
		case PM_DMA_32:
		case PM_MEMCPY:
			valuePtr=std::move(p2.valuePtr);
		break;
	}
	p2.mode=PM_NOOP;
	p2.size=0;
}

Poke::~Poke() {
	switch(mode) {
		case PM_DMA_16:
		case PM_DMA_32:
		case PM_MEMCPY:
			valuePtr.~unique_ptr();
		break;
		case PM_BITFIELD://no destructor to call
		default:
		break;
	}
}

void Poke::Perform() {
	uint8_t oldMode;

	if (pointerInRange(addr, VRAM_F, VRAM_F_SIZE)) {
		oldMode = VRAM_F_CR;
		vramSetBankF(VRAM_F_LCD);
	} else if (pointerInRange(addr, VRAM_G, VRAM_G_SIZE)) {
		oldMode = VRAM_G_CR;
		vramSetBankG(VRAM_G_LCD);
	} else if (pointerInRange(addr, VRAM_H, VRAM_H_SIZE)) {
		oldMode = VRAM_H_CR;
		vramSetBankH(VRAM_H_LCD);
	} else if (pointerInRange(addr, VRAM_I, VRAM_I_SIZE)) {
		oldMode = VRAM_I_CR;
		vramSetBankI(VRAM_I_LCD);
	}

	switch(mode) {
		case PM_NOOP:
		break;
		case PM_INT:
			switch(size) {
				case sizeof(uint8_t):
					*((volatile uint8_t*)addr)=value8;
				break;
				case sizeof(uint16_t):
					*((volatile uint16_t*)addr)=value16;
				break;
				case sizeof(uint32_t):
					*((volatile uint32_t*)addr)=value32;
				break;
			}
		break;
		case PM_BITFIELD:
			switch (size) {
			case sizeof(uint8_t) :
				bitField8.Poke((volatile uint8_t*)addr);
				break;
			case sizeof(uint16_t) :
				bitField16.Poke((volatile uint16_t*)addr);
				break;
			case sizeof(uint32_t) :
				bitField32.Poke((volatile uint32_t*)addr);
				break;
			}
		break;
		case PM_DMA_16:
			dmaCopyHalfWords(3, valuePtr.get(), (void*)addr, size);
		break;
		case PM_DMA_32:
			dmaCopyWords(3, valuePtr.get(), (void*)addr, size);
			break;
		case PM_MEMCPY: {
			volatile uint8_t *dst=valuePtr.get();
			std::copy(dst,dst+size,(uint8_t *)addr);
		} break;
	}

	if(pointerInRange(addr, VRAM_F, VRAM_F_SIZE)) {
		VRAM_F_CR = oldMode;
	} else if(pointerInRange(addr, VRAM_G, VRAM_G_SIZE)) {
		VRAM_G_CR = oldMode;
	} else if(pointerInRange(addr, VRAM_H, VRAM_H_SIZE)) {
		VRAM_H_CR = oldMode;
	} else if(pointerInRange(addr, VRAM_I, VRAM_I_SIZE)) {
		VRAM_I_CR = oldMode;
	}
}

PokeChainLink::PokeChainLink() {}
PokeChainLink::PokeChainLink(PokeChainLink &&pch2) : next(std::move(pch2.next)), poke(std::move(pch2.poke)) {}
PokeChainLink::PokeChainLink(Poke &&p) : next(nullptr), poke(std::move(p)) {}
PokeChainLink::PokeChainLink(Poke &&p, std::unique_ptr<PokeChainLink> &&next_) : next(std::move(next_)), poke(std::move(p)) {}
PokeChainLink::~PokeChainLink() {}

static bool pointerInRange(uintptr_t needle, uintptr_t base, size_t size) {
	return needle >= base && needle < (base + size);
}
static bool pointerInRange(volatile void *needle, volatile void *base, size_t size) {
	return pointerInRange((uintptr_t)needle, (uintptr_t)base, size);
}
static bool pointerInRange(void *needle, void *base, size_t size) {
	return pointerInRange((uintptr_t)needle, (uintptr_t)base, size);
}<|endoftext|>


<commit_before>#include "primes.h"

#include <algorithm>
#include <cmath>

using plist = std::vector<long>;

namespace {

long next(const plist& ps) {
  if (ps.empty()) {
    return 2;
  } else if (ps.back() == 2) {
    return 3;
  }
  for (auto i = ps.back() + 2; ; i += 2) {
    auto it = std::find_if(
        ps.begin(), ps.end(), [i](long p) { return p * p > i; });
    if (std::all_of(ps.begin(), it, [i](long p) { return i % p != 0; })) {
      return i;
    }
  }
}

}

namespace primes {

plist upTo(long v) {
  plist result;
  if (v < 2) {
    return result;
  }
  result.push_back(2);
  for (auto p = next(result); p <= v; p = next(result)) {
    result.push_back(p);
  }
  return result;
}

plist factorsOf(long v) {
  auto max = static_cast<long>(std::sqrt(v)) + 1;
  auto ps = upTo(max);
  auto it = std::remove_if(
      ps.begin(), ps.end(), [v](long p) { return v % p != 0; });
  ps.erase(it, ps.end());
  return ps;
}

plist first(int n) {
  plist result;
  result.reserve(n);
  std::generate_n(
      std::back_inserter(result), n, [&result]() { return next(result); });
  return result;
}

}
<commit_msg>primes: fix factor calculation<commit_after>#include "primes.h"

#include <algorithm>
#include <cmath>

using plist = std::vector<long>;

namespace primes {

namespace {

long next(const plist& ps) {
  if (ps.empty()) {
    return 2;
  } else if (ps.back() == 2) {
    return 3;
  }
  for (auto i = ps.back() + 2; ; i += 2) {
    auto it = std::find_if(
        ps.begin(), ps.end(), [i](long p) { return p * p > i; });
    if (std::all_of(ps.begin(), it, [i](long p) { return i % p != 0; })) {
      return i;
    }
  }
}

}

plist upTo(long v) {
  plist result;
  if (v < 2) {
    return result;
  }
  result.push_back(2);
  for (auto p = next(result); p <= v; p = next(result)) {
    result.push_back(p);
  }
  return result;
}

plist factorsOf(long v) {
  auto max = static_cast<long>(std::sqrt(v)) + 1;
  auto ps = upTo(max);
  plist result;
  auto it = std::remove_if(
      ps.begin(), ps.end(), [v](long p) { return v % p != 0; });
  ps.erase(it, ps.end());
  for (auto p : ps) {
    while (v % p == 0) { v /= p; }
  }
  if (v > 1) {
    ps.push_back(v);
  }
  return ps;
}

plist first(int n) {
  plist result;
  result.reserve(n);
  std::generate_n(
      std::back_inserter(result), n, [&result]() { return next(result); });
  return result;
}

}
<|endoftext|>


<commit_before>#include "number.h"

#include <random>

static std::mt19937 g_gen;

namespace rtl {

Number random$uint32()
{
    return number_from_uint32(g_gen());
}

} // namespace rtl
<commit_msg>Properly seed random number generator<commit_after>#include "number.h"

#include <random>

static std::random_device g_rd;
static std::mt19937 g_gen(g_rd());

namespace rtl {

Number random$uint32()
{
    return number_from_uint32(g_gen());
}

} // namespace rtl
<|endoftext|>


<commit_before>#include "./wrapped_re2.h"

#include <algorithm>
#include <memory>
#include <string>
#include <vector>

#include <node_buffer.h>

using std::min;
using std::string;
using std::vector;

using v8::Array;
using v8::Function;
using v8::Integer;
using v8::Local;
using v8::String;
using v8::Value;

using node::Buffer;

inline int getMaxSubmatch(const NanUtf8String& replacer) {
	int maxSubmatch = 0, index, index2;
	for (size_t i = 0, n = len(replacer); i < n;) {
		char ch = (*replacer)[i];
		if (ch == '$') {
			if (i + 1 < n) {
				ch = (*replacer)[i + 1];
				switch (ch) {
					case '$':
					case '&':
					case '`':
					case '\'':
						i += 2;
						continue;
					case '0':
					case '1':
					case '2':
					case '3':
					case '4':
					case '5':
					case '6':
					case '7':
					case '8':
					case '9':
						index = ch - '0';
						if (i + 2 < n) {
							ch = (*replacer)[i + 2];
							if ('0' <= ch && ch <= '9') {
								index2 = index * 10 + (ch - '0');
								if (maxSubmatch < index2) maxSubmatch = index2;
								i += 3;
								continue;
							}
						}
						if (maxSubmatch < index) maxSubmatch = index;
						i += 2;
						continue;
				}
			}
			++i;
			continue;
		}
		i += getUtf8CharSize(ch);
	}
	return maxSubmatch;
}

inline string replace(const NanUtf8String& replacer, const vector<StringPiece>& groups, const StringPiece& str) {
	string result;
	size_t index, index2;
	for (size_t i = 0, n = len(replacer); i < n;) {
		char ch = (*replacer)[i];
		if (ch == '$') {
			if (i + 1 < n) {
				ch = (*replacer)[i + 1];
				switch (ch) {
					case '$':
						result += ch;
						i += 2;
						continue;
					case '&':
						result += groups[0].as_string();
						i += 2;
						continue;
					case '`':
						result += string(str.data(), groups[0].data() - str.data());
						i += 2;
						continue;
					case '\'':
						result += string(groups[0].data() + groups[0].size(),
							str.data() + str.size() - groups[0].data() - groups[0].size());
						i += 2;
						continue;
					case '0':
					case '1':
					case '2':
					case '3':
					case '4':
					case '5':
					case '6':
					case '7':
					case '8':
					case '9':
						index = ch - '0';
						if (i + 2 < n) {
							ch = (*replacer)[i + 2];
							if ('0' <= ch && ch <= '9') {
								i += 3;
								index2 = index * 10 + (ch - '0');
								if (index2 && index2 < groups.size()) {
									result += groups[index2].as_string();
									continue;
								}
								result += '$';
								result += '0' + index;
								result += ch;
								continue;
							}
							ch = '0' + index;
						}
						i += 2;
						if (index && index < groups.size()) {
							result += groups[index].as_string();
							continue;
						}
						result += '$';
						result += ch;
						continue;
				}
			}
			result += '$';
			++i;
			continue;
		}
		size_t sym_size = getUtf8CharSize(ch);
		result.append(*replacer + i, sym_size);
		i += sym_size;
	}
	return result;
}

static string replace(WrappedRE2* re2, const StringPiece& str, const NanUtf8String& replacer) {

	const char* data = str.data();
	size_t      size = str.size();

	vector<StringPiece> groups(min(re2->regexp.NumberOfCapturingGroups(), getMaxSubmatch(replacer)) + 1);
	const StringPiece& match = groups[0];

	size_t lastIndex = 0;
	string result;

	while (lastIndex <= size && re2->regexp.Match(str, lastIndex, size,
				RE2::UNANCHORED, &groups[0], groups.size())) {
		if (match.size()) {
			if (match.data() == data || match.data() - data > lastIndex) {
				result += string(data + lastIndex, match.data() - data - lastIndex);
			}
			result += replace(replacer, groups, str);
			lastIndex = match.data() - data + match.size();
		} else {
			result += replace(replacer, groups, str);
			size_t sym_size = getUtf8CharSize(data[lastIndex]);
			if (lastIndex < size) {
				result.append(data + lastIndex, sym_size);
			}
			lastIndex += sym_size;
		}
		if (!re2->global) {
			break;
		}
	}
	if (lastIndex < size) {
		result += string(data + lastIndex, size - lastIndex);
	}

	return result;
}

inline string replace(const NanCallback& replacer, const vector<StringPiece>& groups,
						const StringPiece& str, const Local<Value>& input) {
	vector< Local<Value> >	argv;
	for (size_t i = 0, n = groups.size(); i < n; ++i) {
		const StringPiece& item = groups[i];
		argv.push_back(NanNew<String>(item.data(), item.size()));
	}
	argv.push_back(NanNew<Integer>(getUtf16Length(str.data(), groups[0].data())));
	argv.push_back(input);

	NanUtf8String result(replacer.Call(argv.size(), &argv[0])->ToString());

	return string(*result, len(result));
}

static string replace(WrappedRE2* re2, const StringPiece& str,
						const NanCallback& replacer, const Local<Value>& input) {

	const char* data = str.data();
	size_t      size = str.size();

	vector<StringPiece> groups(re2->regexp.NumberOfCapturingGroups() + 1);
	const StringPiece& match = groups[0];

	size_t lastIndex = 0;
	string result;

	while (lastIndex <= size && re2->regexp.Match(str, lastIndex, size,
				RE2::UNANCHORED, &groups[0], groups.size())) {
		if (match.size()) {
			if (match.data() == data || match.data() - data > lastIndex) {
				result += string(data + lastIndex, match.data() - data - lastIndex);
			}
			result += replace(replacer, groups, str, input);
			lastIndex = match.data() - data + match.size();
		} else {
			result += replace(replacer, groups, str, input);
			size_t sym_size = getUtf8CharSize(data[lastIndex]);
			if (lastIndex < size) {
				result.append(data + lastIndex, sym_size);
			}
			lastIndex += sym_size;
		}
		if (!re2->global) {
			break;
		}
	}
	if (lastIndex < size) {
		result += string(data + lastIndex, size - lastIndex);
	}

	return result;
}

NAN_METHOD(WrappedRE2::Replace) {
	NanScope();

	WrappedRE2* re2 = ObjectWrap::Unwrap<WrappedRE2>(args.This());
	if (!re2) {
		NanReturnValue(args[0]);
	}

	vector<char> buffer;

	char*  data;
	size_t size;
	//bool   isBuffer = false;

	if (args[0]->IsString()) {
		Local<String> t(args[0]->ToString());
		buffer.resize(t->Utf8Length() + 1);
		t->WriteUtf8(&buffer[0]);
		size = buffer.size() - 1;
		data = &buffer[0];
	} else if (Buffer::HasInstance(args[0])) {
		//isBuffer = true;
		size = Buffer::Length(args[0]);
		data = Buffer::Data(args[0]);
	} else {
		NanReturnValue(args[0]);
	}

	StringPiece str(data, size);

	if (args[1]->IsString()) {
		NanReturnValue(NanNew(replace(re2, str, NanUtf8String(args[1]))));
	} else if (args[1]->IsFunction()) {
		NanReturnValue(NanNew(replace(re2, str, NanCallback(args[1].As<Function>()), args[0])));
	}

	NanReturnValue(args[0]);
}
<commit_msg>Support for buffers.<commit_after>#include "./wrapped_re2.h"

#include <algorithm>
#include <memory>
#include <string>
#include <vector>

#include <node_buffer.h>

using std::min;
using std::string;
using std::vector;

using v8::Array;
using v8::Function;
using v8::Integer;
using v8::Local;
using v8::String;
using v8::Value;

using node::Buffer;

inline int getMaxSubmatch(const NanUtf8String& replacer) {
	int maxSubmatch = 0, index, index2;
	for (size_t i = 0, n = len(replacer); i < n;) {
		char ch = (*replacer)[i];
		if (ch == '$') {
			if (i + 1 < n) {
				ch = (*replacer)[i + 1];
				switch (ch) {
					case '$':
					case '&':
					case '`':
					case '\'':
						i += 2;
						continue;
					case '0':
					case '1':
					case '2':
					case '3':
					case '4':
					case '5':
					case '6':
					case '7':
					case '8':
					case '9':
						index = ch - '0';
						if (i + 2 < n) {
							ch = (*replacer)[i + 2];
							if ('0' <= ch && ch <= '9') {
								index2 = index * 10 + (ch - '0');
								if (maxSubmatch < index2) maxSubmatch = index2;
								i += 3;
								continue;
							}
						}
						if (maxSubmatch < index) maxSubmatch = index;
						i += 2;
						continue;
				}
			}
			++i;
			continue;
		}
		i += getUtf8CharSize(ch);
	}
	return maxSubmatch;
}

inline string replace(const NanUtf8String& replacer, const vector<StringPiece>& groups, const StringPiece& str) {
	string result;
	size_t index, index2;
	for (size_t i = 0, n = len(replacer); i < n;) {
		char ch = (*replacer)[i];
		if (ch == '$') {
			if (i + 1 < n) {
				ch = (*replacer)[i + 1];
				switch (ch) {
					case '$':
						result += ch;
						i += 2;
						continue;
					case '&':
						result += groups[0].as_string();
						i += 2;
						continue;
					case '`':
						result += string(str.data(), groups[0].data() - str.data());
						i += 2;
						continue;
					case '\'':
						result += string(groups[0].data() + groups[0].size(),
							str.data() + str.size() - groups[0].data() - groups[0].size());
						i += 2;
						continue;
					case '0':
					case '1':
					case '2':
					case '3':
					case '4':
					case '5':
					case '6':
					case '7':
					case '8':
					case '9':
						index = ch - '0';
						if (i + 2 < n) {
							ch = (*replacer)[i + 2];
							if ('0' <= ch && ch <= '9') {
								i += 3;
								index2 = index * 10 + (ch - '0');
								if (index2 && index2 < groups.size()) {
									result += groups[index2].as_string();
									continue;
								}
								result += '$';
								result += '0' + index;
								result += ch;
								continue;
							}
							ch = '0' + index;
						}
						i += 2;
						if (index && index < groups.size()) {
							result += groups[index].as_string();
							continue;
						}
						result += '$';
						result += ch;
						continue;
				}
			}
			result += '$';
			++i;
			continue;
		}
		size_t sym_size = getUtf8CharSize(ch);
		result.append(*replacer + i, sym_size);
		i += sym_size;
	}
	return result;
}

static string replace(WrappedRE2* re2, const StringPiece& str, const NanUtf8String& replacer) {

	const char* data = str.data();
	size_t      size = str.size();

	vector<StringPiece> groups(min(re2->regexp.NumberOfCapturingGroups(), getMaxSubmatch(replacer)) + 1);
	const StringPiece& match = groups[0];

	size_t lastIndex = 0;
	string result;

	while (lastIndex <= size && re2->regexp.Match(str, lastIndex, size,
				RE2::UNANCHORED, &groups[0], groups.size())) {
		if (match.size()) {
			if (match.data() == data || match.data() - data > lastIndex) {
				result += string(data + lastIndex, match.data() - data - lastIndex);
			}
			result += replace(replacer, groups, str);
			lastIndex = match.data() - data + match.size();
		} else {
			result += replace(replacer, groups, str);
			size_t sym_size = getUtf8CharSize(data[lastIndex]);
			if (lastIndex < size) {
				result.append(data + lastIndex, sym_size);
			}
			lastIndex += sym_size;
		}
		if (!re2->global) {
			break;
		}
	}
	if (lastIndex < size) {
		result += string(data + lastIndex, size - lastIndex);
	}

	return result;
}

inline string replace(const NanCallback& replacer, const vector<StringPiece>& groups,
						const StringPiece& str, const Local<Value>& input) {
	vector< Local<Value> >	argv;
	for (size_t i = 0, n = groups.size(); i < n; ++i) {
		const StringPiece& item = groups[i];
		argv.push_back(NanNew<String>(item.data(), item.size()));
	}
	argv.push_back(NanNew<Integer>(getUtf16Length(str.data(), groups[0].data())));
	argv.push_back(input);

	Local<Value> result(Local<Value>::New(replacer.Call(argv.size(), &argv[0])));

	if (result->IsString()) {
		NanUtf8String val(result);
		return string(*val, len(val));
	}

	if (Buffer::HasInstance(result)) {
		return string(Buffer::Data(result), Buffer::Length(result));
	}

	return string();
}

static string replace(WrappedRE2* re2, const StringPiece& str,
						const NanCallback& replacer, const Local<Value>& input) {

	const char* data = str.data();
	size_t      size = str.size();

	vector<StringPiece> groups(re2->regexp.NumberOfCapturingGroups() + 1);
	const StringPiece& match = groups[0];

	size_t lastIndex = 0;
	string result;

	while (lastIndex <= size && re2->regexp.Match(str, lastIndex, size,
				RE2::UNANCHORED, &groups[0], groups.size())) {
		if (match.size()) {
			if (match.data() == data || match.data() - data > lastIndex) {
				result += string(data + lastIndex, match.data() - data - lastIndex);
			}
			result += replace(replacer, groups, str, input);
			lastIndex = match.data() - data + match.size();
		} else {
			result += replace(replacer, groups, str, input);
			size_t sym_size = getUtf8CharSize(data[lastIndex]);
			if (lastIndex < size) {
				result.append(data + lastIndex, sym_size);
			}
			lastIndex += sym_size;
		}
		if (!re2->global) {
			break;
		}
	}
	if (lastIndex < size) {
		result += string(data + lastIndex, size - lastIndex);
	}

	return result;
}

NAN_METHOD(WrappedRE2::Replace) {
	NanScope();

	WrappedRE2* re2 = ObjectWrap::Unwrap<WrappedRE2>(args.This());
	if (!re2) {
		NanReturnValue(args[0]);
	}

	vector<char> buffer;

	char*  data;
	size_t size;
	bool   isBuffer = false;

	if (args[0]->IsString()) {
		Local<String> t(args[0]->ToString());
		buffer.resize(t->Utf8Length() + 1);
		t->WriteUtf8(&buffer[0]);
		size = buffer.size() - 1;
		data = &buffer[0];
	} else if (Buffer::HasInstance(args[0])) {
		isBuffer = true;
		size = Buffer::Length(args[0]);
		data = Buffer::Data(args[0]);
	} else {
		NanReturnValue(args[0]);
	}

	StringPiece str(data, size);

	if (args[1]->IsString()) {
		string result = replace(re2, str, NanUtf8String(args[1]));
		if (isBuffer) {
			NanReturnValue(NanNewBufferHandle(result.data(), result.size()));
		}
		NanReturnValue(NanNew(result));
	}

	if (args[1]->IsFunction()) {
		string result = replace(re2, str, NanCallback(args[1].As<Function>()), args[0]);
		if (isBuffer) {
			NanReturnValue(NanNewBufferHandle(result.data(), result.size()));
		}
		NanReturnValue(NanNew(result));
	}

	NanReturnValue(args[0]);
}
<|endoftext|>


<commit_before>// $Id: ballAndStickModel.C,v 1.9 2000/12/12 16:19:24 oliver Exp $

#include <BALL/MOLVIEW/FUNCTOR/ballAndStickModel.h>

using namespace std;

namespace BALL
{

	namespace MOLVIEW
	{

		AddBallAndStickModel::AddBallAndStickModel()
			: AtomBondModelBaseProcessor(),
				ball_radius_((Real)0.4),
				stick_radius_((Real)0.2),
				ball_and_stick_(true)
		{
		}

		AddBallAndStickModel::AddBallAndStickModel
			(const AddBallAndStickModel &add_ball_and_stick,
			 bool deep)
				:
				AtomBondModelBaseProcessor(add_ball_and_stick, deep),
				ball_radius_(add_ball_and_stick.ball_radius_),
				stick_radius_(add_ball_and_stick.stick_radius_),
				ball_and_stick_(add_ball_and_stick.ball_and_stick_)
		{
		}

		AddBallAndStickModel::~AddBallAndStickModel()
			throw()
		{
			#ifdef BALL_VIEW_DEBUG
				cout << "Destructing object " << (void *)this
			 << " of class " << getBallClass().getName() << endl;
			#endif

			destroy();
		}

		void AddBallAndStickModel::clear()
			throw()
		{
			AtomBondModelBaseProcessor::clear();

			ball_radius_ = (Real)0.4;
			stick_radius_ = (Real)0.2;
			ball_and_stick_ = true;
		}

		void AddBallAndStickModel::destroy()
			throw()
		{
			AtomBondModelBaseProcessor::destroy();

			ball_radius_ = (Real)0.4;
			stick_radius_ = (Real)0.2;
			ball_and_stick_ = true;
		}

		void
		AddBallAndStickModel::set
			(const AddBallAndStickModel &add_ball_and_stick,
			 bool deep)
		{
			AtomBondModelBaseProcessor::set(add_ball_and_stick, deep);

			ball_radius_ = add_ball_and_stick.ball_radius_;
			stick_radius_ = add_ball_and_stick.stick_radius_;
			ball_and_stick_ = add_ball_and_stick.ball_and_stick_;
		}

		AddBallAndStickModel &
		AddBallAndStickModel::operator =
			(const AddBallAndStickModel &add_ball_and_stick)
		{
			set(add_ball_and_stick);

			return *this;
		}

		void
		AddBallAndStickModel::get
			(AddBallAndStickModel &add_ball_and_stick,
			 bool deep) const
		{
			add_ball_and_stick.set(*this, deep);
		}

		void
		AddBallAndStickModel::swap
			(AddBallAndStickModel &add_ball_and_stick)
		{
			AtomBondModelBaseProcessor::swap(add_ball_and_stick);

			Real temp__Real = ball_radius_;
			ball_radius_ = add_ball_and_stick.ball_radius_;
			add_ball_and_stick.ball_radius_ = temp__Real;

			temp__Real = stick_radius_;
			stick_radius_ = add_ball_and_stick.stick_radius_;
			add_ball_and_stick.stick_radius_ = temp__Real;

			bool temp__bool = ball_and_stick_;
			ball_and_stick_ = add_ball_and_stick.ball_and_stick_;
			add_ball_and_stick.ball_and_stick_ = temp__bool;
		}

		void
		AddBallAndStickModel::setBallRadius
			(const Real radius)
		{
			BALL_PRECONDITION
				(radius > (Real)0,
				 BALL_MOLVIEW_BALLANDSTICKMODEL_ERROR_HANDLER
				 (AddBallAndStickModel::ERROR_BALL_RADIUS_LOWER_OR_EQUAL_ZERO));

			ball_radius_ = radius;
		}

		void
		AddBallAndStickModel::setStickRadius
			(const Real radius)
		{
			BALL_PRECONDITION
				(radius > (Real)0,
				 BALL_MOLVIEW_BALLANDSTICKMODEL_ERROR_HANDLER
				 (AddBallAndStickModel::ERROR__STICK_RADIUS_LOWER_OR_EQUAL_ZERO));

			stick_radius_ = radius;
		}

		bool
		AddBallAndStickModel::start
			()
		{
			// init model connector
			getModelConnector()->setProperties(*this);
			getModelConnector()->setProperty(String("STICK_RADIUS"), (float)stick_radius_);
			getModelConnector()->setProperty(String("BALL_RADIUS"), (float)ball_radius_);

			return AtomBondModelBaseProcessor::start();
		}

		bool
		AddBallAndStickModel::finish
			()
		{
			buildBondModels_();

			return true;
		}

		Processor::Result
		AddBallAndStickModel::operator()
			(Composite &composite)
		{
			// composite is an atom ?
			if (!RTTI::isKindOf<Atom>(composite))
			{
				return Processor::CONTINUE;
			}

			Atom *atom = RTTI::castTo<Atom>(composite);

			// remove only models appended to atom
			removeGeometricObjects_(*atom, true);

			// generate BallPrimitive
			Sphere *__pSphere = createSphere_();

			BALL_PRECONDITION
				(__pSphere != 0,
				 BALL_MOLVIEW_BALLANDSTICKMODEL_ERROR_HANDLER
				 (AddBallAndStickModel::ERROR__CANNOT_CREATE_SPHERE));

			// carry on selected flag
			__pSphere->Selectable::set(*atom);

			__pSphere->PropertyManager::set(*this);
			__pSphere->PropertyManager::setProperty(GeometricObject::PROPERTY__MODEL_BALL_AND_STICK);

			if (ball_and_stick_ == true)
			{
				__pSphere->setRadius(ball_radius_);
			}
			else
			{
				__pSphere->setRadius(stick_radius_);
			}

			__pSphere->setVertexAddress(atom->getPosition());

			atom->host(*getColorCalculator());

			__pSphere->setColor(getColorCalculator()->getColor());

			// append sphere in Atom
			composite.appendChild(*__pSphere);

			// collect used atoms
			insertAtom_(atom);

			return Processor::CONTINUE;
		}

		void AddBallAndStickModel::dump
			(std::ostream& s, Size depth) const
			throw()
		{
			BALL_DUMP_STREAM_PREFIX(s);

			BALL_DUMP_DEPTH(s, depth);
			BALL_DUMP_HEADER(s, this, this);

			AtomBondModelBaseProcessor::dump(s, depth + 1);

			BALL_DUMP_DEPTH(s, depth);
			s << "ball radius: " << ball_radius_ << endl;

			BALL_DUMP_DEPTH(s, depth);
			s << "stick radius: " << stick_radius_ << endl;

			BALL_DUMP_DEPTH(s, depth);
			s << "b&s model: " << ((bool)(ball_and_stick_ == true)) << endl;

			BALL_DUMP_DEPTH(s, depth);
			s << "s model: " << ((bool)(ball_and_stick_ == false)) << endl;

			BALL_DUMP_STREAM_SUFFIX(s);
		}

		void
		AddBallAndStickModel::read
			(std::istream & /* s */)
		{
			throw ::BALL::Exception::NotImplemented(__FILE__, __LINE__);
		}

		void
		AddBallAndStickModel::write
			(std::ostream & /* s */) const
		{
			throw ::BALL::Exception::NotImplemented(__FILE__, __LINE__);
		}

		Sphere *
		AddBallAndStickModel::createSphere_
			()
		{
			return (Sphere *)(new Sphere());
		}

		Tube *
		AddBallAndStickModel::createTube_
			()
		{
			return (Tube *)(new Tube());
		}

		TwoColoredTube *
		AddBallAndStickModel::createTwoColoredTube_
			()
		{
			return (TwoColoredTube *)(new TwoColoredTube());
		}

#		ifdef BALL_NO_INLINE_FUNCTIONS
#			include <BALL/MOLVIEW/FUNCTOR/ballAndStickModel.iC>
#		endif

	} // namespace MOLVIEW

} // namespace BALL
<commit_msg>fixed: naming massive cosmetic changes<commit_after>// $Id: ballAndStickModel.C,v 1.10 2001/01/26 00:20:01 amoll Exp $

#include <BALL/MOLVIEW/FUNCTOR/ballAndStickModel.h>

using namespace std;

namespace BALL
{
	namespace MOLVIEW
	{

		AddBallAndStickModel::AddBallAndStickModel()
			: AtomBondModelBaseProcessor(),
				ball_radius_((Real)0.4),
				stick_radius_((Real)0.2),
				ball_and_stick_(true)
		{
		}

		AddBallAndStickModel::AddBallAndStickModel
			(const AddBallAndStickModel &add_ball_and_stick, bool deep)
			: AtomBondModelBaseProcessor(add_ball_and_stick, deep),
				ball_radius_(add_ball_and_stick.ball_radius_),
				stick_radius_(add_ball_and_stick.stick_radius_),
				ball_and_stick_(add_ball_and_stick.ball_and_stick_)
		{
		}

		AddBallAndStickModel::~AddBallAndStickModel()
			throw()
		{
			#ifdef BALL_VIEW_DEBUG
				cout << "Destructing object " << (void *)this
			 << " of class " << getBallClass().getName() << endl;
			#endif

			destroy();
		}

		void AddBallAndStickModel::clear()
			throw()
		{
			AtomBondModelBaseProcessor::clear();

			ball_radius_ = (Real)0.4;
			stick_radius_ = (Real)0.2;
			ball_and_stick_ = true;
		}

		void AddBallAndStickModel::destroy()
			throw()
		{
			AtomBondModelBaseProcessor::destroy();

			ball_radius_ = (Real)0.4;
			stick_radius_ = (Real)0.2;
			ball_and_stick_ = true;
		}

		void AddBallAndStickModel::set
			(const AddBallAndStickModel &add_ball_and_stick, bool deep)
		{
			AtomBondModelBaseProcessor::set(add_ball_and_stick, deep);

			ball_radius_ = add_ball_and_stick.ball_radius_;
			stick_radius_ = add_ball_and_stick.stick_radius_;
			ball_and_stick_ = add_ball_and_stick.ball_and_stick_;
		}

		AddBallAndStickModel &AddBallAndStickModel::operator =
			(const AddBallAndStickModel &add_ball_and_stick)
		{
			set(add_ball_and_stick);

			return *this;
		}

		void AddBallAndStickModel::get(AddBallAndStickModel &add_ball_and_stick, bool deep) const
		{
			add_ball_and_stick.set(*this, deep);
		}

		void AddBallAndStickModel::swap(AddBallAndStickModel &add_ball_and_stick)
		{
			AtomBondModelBaseProcessor::swap(add_ball_and_stick);

			Real temp_Real = ball_radius_;
			ball_radius_ = add_ball_and_stick.ball_radius_;
			add_ball_and_stick.ball_radius_ = temp_Real;

			temp_Real = stick_radius_;
			stick_radius_ = add_ball_and_stick.stick_radius_;
			add_ball_and_stick.stick_radius_ = temp_Real;

			bool temp_bool = ball_and_stick_;
			ball_and_stick_ = add_ball_and_stick.ball_and_stick_;
			add_ball_and_stick.ball_and_stick_ = temp_bool;
		}

		void AddBallAndStickModel::setBallRadius(const Real radius)
		{
			BALL_PRECONDITION
				(radius > (Real)0,
				 BALL_MOLVIEW_BALLANDSTICKMODEL_ERROR_HANDLER
				 (AddBallAndStickModel::ERROR_BALL_RADIUS_LOWER_OR_EQUAL_ZERO));

			ball_radius_ = radius;
		}

		void AddBallAndStickModel::setStickRadius(const Real radius)
		{
			BALL_PRECONDITION
				(radius > (Real)0,
				 BALL_MOLVIEW_BALLANDSTICKMODEL_ERROR_HANDLER
				 (AddBallAndStickModel::ERROR_STICK_RADIUS_LOWER_OR_EQUAL_ZERO));

			stick_radius_ = radius;
		}

		bool AddBallAndStickModel::start()
		{
			// init model connector
			getModelConnector()->setProperties(*this);
			getModelConnector()->setProperty(String("STICK_RADIUS"), (float)stick_radius_);
			getModelConnector()->setProperty(String("BALL_RADIUS"), (float)ball_radius_);

			return AtomBondModelBaseProcessor::start();
		}

		bool AddBallAndStickModel::finish()
		{
			buildBondModels_();

			return true;
		}

		Processor::Result AddBallAndStickModel::operator() (Composite &composite)
		{
			// composite is an atom ?
			if (!RTTI::isKindOf<Atom>(composite))
			{
				return Processor::CONTINUE;
			}

			Atom *atom = RTTI::castTo<Atom>(composite);

			// remove only models appended to atom
			removeGeometricObjects_(*atom, true);

			// generate BallPrimitive
			Sphere* pSphere = createSphere_();

			BALL_PRECONDITION
				(pSphere != 0,
				 BALL_MOLVIEW_BALLANDSTICKMODEL_ERROR_HANDLER
				 (AddBallAndStickModel::ERROR_CANNOT_CREATE_SPHERE));

			// carry on selected flag
			pSphere->Selectable::set(*atom);

			pSphere->PropertyManager::set(*this);
			pSphere->PropertyManager::setProperty(GeometricObject::PROPERTY__MODEL_BALL_AND_STICK);

			if (ball_and_stick_ == true)
			{
				pSphere->setRadius(ball_radius_);
			}
			else
			{
				pSphere->setRadius(stick_radius_);
			}

			pSphere->setVertexAddress(atom->getPosition());

			atom->host(*getColorCalculator());

			pSphere->setColor(getColorCalculator()->getColor());

			// append sphere in Atom
			composite.appendChild(*pSphere);

			// collect used atoms
			insertAtom_(atom);

			return Processor::CONTINUE;
		}

		void AddBallAndStickModel::dump(std::ostream& s, Size depth) const
			throw()
		{
			BALL_DUMP_STREAM_PREFIX(s);

			BALL_DUMP_DEPTH(s, depth);
			BALL_DUMP_HEADER(s, this, this);

			AtomBondModelBaseProcessor::dump(s, depth + 1);

			BALL_DUMP_DEPTH(s, depth);
			s << "ball radius: " << ball_radius_ << endl;

			BALL_DUMP_DEPTH(s, depth);
			s << "stick radius: " << stick_radius_ << endl;

			BALL_DUMP_DEPTH(s, depth);
			s << "b&s model: " << ((bool)(ball_and_stick_ == true)) << endl;

			BALL_DUMP_DEPTH(s, depth);
			s << "s model: " << ((bool)(ball_and_stick_ == false)) << endl;

			BALL_DUMP_STREAM_SUFFIX(s);
		}

		void AddBallAndStickModel::read(std::istream & /* s */)
		{
			throw ::BALL::Exception::NotImplemented(__FILE__, __LINE__);
		}

		void AddBallAndStickModel::write(std::ostream & /* s */) const
		{
			throw ::BALL::Exception::NotImplemented(__FILE__, __LINE__);
		}

		Sphere* AddBallAndStickModel::createSphere_()
		{
			return (Sphere *)(new Sphere());
		}

		Tube* AddBallAndStickModel::createTube_()
		{
			return (Tube *)(new Tube());
		}

		TwoColoredTube*AddBallAndStickModel::createTwoColoredTube_()
		{
			return (TwoColoredTube *)(new TwoColoredTube());
		}

#		ifdef BALL_NO_INLINE_FUNCTIONS
#			include <BALL/MOLVIEW/FUNCTOR/ballAndStickModel.iC>
#		endif

	} // namespace MOLVIEW

} // namespace BALL
<|endoftext|>


<commit_before>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * adiosMpiHandshake.cpp
 *
 *  Created on: Mar 1, 2020
 *      Author: Jason Wang
 */

#include "adiosMpiHandshake.h"
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <fstream>
#include <thread>
#include <unordered_set>

namespace adios2
{
namespace helper
{

const std::vector<std::vector<int>> Handshake(const std::string &filename,
                                              const char mode,
                                              const int timeoutSeconds,
                                              MPI_Comm localComm)
{
    std::vector<std::vector<int>> ret(3);

    int localRank;
    int localSize;
    int worldRank;
    int worldSize;

    MPI_Comm_rank(localComm, &localRank);
    MPI_Comm_size(localComm, &localSize);

    MPI_Comm_rank(MPI_COMM_WORLD, &worldRank);
    MPI_Comm_size(MPI_COMM_WORLD, &worldSize);

    std::vector<int> allLocalRanks(localSize);

    MPI_Gather(&worldRank, 1, MPI_INT, allLocalRanks.data(), 1, MPI_INT, 0,
               localComm);

    if (localRank == 0)
    {
        std::ofstream fs;
        fs.open(filename + "." + mode);
        for (auto rank : allLocalRanks)
        {
            fs << rank << std::endl;
        }
        fs.close();

        if (mode == 'r')
        {

            for (auto i : allLocalRanks)
            {
                ret[0].push_back(i);
                ret[2].push_back(i);
            }

            std::ofstream fsc;
            fsc.open(filename + ".r.c");
            fsc << "completed";
            fsc.close();

            while (true)
            {
                std::ifstream fs;
                try
                {
                    fs.open(filename + ".w.c");
                    std::string line;
                    std::getline(fs, line);
                    if (line != "completed")
                    {
                        continue;
                    }
                    fs.close();
                    remove((filename + ".w.c\0").c_str());
                    break;
                }
                catch (...)
                {
                    continue;
                }
            }

            std::ifstream fs;
            fs.open(filename + ".w");
            for (std::string line; std::getline(fs, line);)
            {
                ret[0].push_back(std::stoi(line));
                ret[1].push_back(std::stoi(line));
            }
            fs.close();
            remove((filename + ".w\0").c_str());
        }
        else if (mode == 'w')
        {
            for (auto i : allLocalRanks)
            {
                ret[0].push_back(i);
                ret[1].push_back(i);
            }

            std::ofstream fsc;
            fsc.open(filename + ".w.c");
            fsc << "completed";
            fsc.close();

            while (true)
            {
                std::ifstream fs;
                try
                {
                    fs.open(filename + ".r.c");
                    std::string line;
                    std::getline(fs, line);
                    if (line != "completed")
                    {
                        continue;
                    }
                    fs.close();
                    remove((filename + ".r.c\0").c_str());
                    break;
                }
                catch (...)
                {
                    continue;
                }
            }

            std::ifstream fs;
            fs.open(filename + ".r");
            for (std::string line; std::getline(fs, line);)
            {
                ret[0].push_back(std::stoi(line));
                ret[2].push_back(std::stoi(line));
            }
            fs.close();
            remove((filename + ".r\0").c_str());
        }
    }

    int dims[3];

    if (localRank == 0)
    {
        for (int i = 0; i < 3; ++i)
        {
            dims[i] = static_cast<int>(ret[i].size());
            std::sort(ret[i].begin(), ret[i].end());
        }
    }

    MPI_Bcast(dims, 3, MPI_INT, 0, localComm);

    if (localRank != 0)
    {
        for (int i = 0; i < 3; ++i)
        {
            ret[i].resize(dims[i]);
        }
    }

    for (int i = 0; i < 3; ++i)
    {
        MPI_Bcast(ret[i].data(), ret[i].size(), MPI_INT, 0, localComm);
    }

    return ret;
}

} // end namespace helper
} // end namespace adios2
<commit_msg>the third try to pass the windows CI<commit_after>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * adiosMpiHandshake.cpp
 *
 *  Created on: Mar 1, 2020
 *      Author: Jason Wang
 */

#include "adiosMpiHandshake.h"
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <fstream>
#include <thread>
#include <unordered_set>

namespace adios2
{
namespace helper
{

const std::vector<std::vector<int>> Handshake(const std::string &filename,
                                              const char mode,
                                              const int timeoutSeconds,
                                              MPI_Comm localComm)
{
    std::vector<std::vector<int>> ret(3);

    int localRank;
    int localSize;
    int worldRank;
    int worldSize;

    MPI_Comm_rank(localComm, &localRank);
    MPI_Comm_size(localComm, &localSize);

    MPI_Comm_rank(MPI_COMM_WORLD, &worldRank);
    MPI_Comm_size(MPI_COMM_WORLD, &worldSize);

    std::vector<int> allLocalRanks(localSize);

    MPI_Gather(&worldRank, 1, MPI_INT, allLocalRanks.data(), 1, MPI_INT, 0,
               localComm);

    if (localRank == 0)
    {
        std::ofstream fs;
        fs.open(filename + "." + mode);
        for (auto rank : allLocalRanks)
        {
            fs << rank << std::endl;
        }
        fs.close();

        if (mode == 'r')
        {

            for (auto i : allLocalRanks)
            {
                ret[0].push_back(i);
                ret[2].push_back(i);
            }

            std::ofstream fsc;
            fsc.open(filename + ".r.c");
            fsc << "completed";
            fsc.close();

            while (true)
            {
                std::ifstream fs;
                try
                {
                    fs.open(filename + ".w.c");
                    std::string line;
                    std::getline(fs, line);
                    if (line != "completed")
                    {
                        continue;
                    }
                    fs.close();
                    remove((filename + ".w.c\0").c_str());
                    break;
                }
                catch (...)
                {
                    continue;
                }
            }

            std::ifstream fs;
            fs.open(filename + ".w");
            for (std::string line; std::getline(fs, line);)
            {
                ret[0].push_back(std::stoi(line));
                ret[1].push_back(std::stoi(line));
            }
            fs.close();
            remove((filename + ".w\0").c_str());
        }
        else if (mode == 'w')
        {
            for (auto i : allLocalRanks)
            {
                ret[0].push_back(i);
                ret[1].push_back(i);
            }

            std::ofstream fsc;
            fsc.open(filename + ".w.c");
            fsc << "completed";
            fsc.close();

            while (true)
            {
                std::ifstream fs;
                try
                {
                    fs.open(filename + ".r.c");
                    std::string line;
                    std::getline(fs, line);
                    if (line != "completed")
                    {
                        continue;
                    }
                    fs.close();
                    remove((filename + ".r.c\0").c_str());
                    break;
                }
                catch (...)
                {
                    continue;
                }
            }

            std::ifstream fs;
            fs.open(filename + ".r");
            for (std::string line; std::getline(fs, line);)
            {
                ret[0].push_back(std::stoi(line));
                ret[2].push_back(std::stoi(line));
            }
            fs.close();
            remove((filename + ".r\0").c_str());
        }
    }

    int dims[3];

    if (localRank == 0)
    {
        for (int i = 0; i < 3; ++i)
        {
            dims[i] = static_cast<int>(ret[i].size());
            std::sort(ret[i].begin(), ret[i].end());
        }
    }

    MPI_Bcast(dims, 3, MPI_INT, 0, localComm);

    if (localRank != 0)
    {
        for (int i = 0; i < 3; ++i)
        {
            ret[i].resize(dims[i]);
        }
    }

    for (int i = 0; i < 3; ++i)
    {
        MPI_Bcast(ret[i].data(), static_cast<int>(ret[i].size()), MPI_INT, 0,
                  localComm);
    }

    return ret;
}

} // end namespace helper
} // end namespace adios2
<|endoftext|>


<commit_before>// @(#)root/base:$Name:  $:$Id: TFriendProxy.cxx,v 1.3 2005/11/11 23:21:43 pcanal Exp $
// Author: Philippe Canal  13/05/2003

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun, Fons Rademakers and al.           *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TFriendProxy                                                         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TFriendProxy.h"
#include "TTree.h"
#include "TList.h"
#include "TFriendElement.h"

namespace ROOT {

   //------------------------------------------------------------------------------------
   TFriendProxy::TFriendProxy() : fDirector(0,-1), fIndex(-1)
   {
   }

   //------------------------------------------------------------------------------------
   TFriendProxy::TFriendProxy(TBranchProxyDirector *director, TTree *main, Int_t index) :
      fDirector(0,-1), fIndex(index)
   {
      // Constructor.

      if (main) {
         TObject *obj = main->GetListOfFriends()->At(fIndex);
         TFriendElement *element = dynamic_cast<TFriendElement*>( obj );
         fDirector.SetTree(element->GetTree());
      }
      director->Attach(this);
   }

   //------------------------------------------------------------------------------------
   Long64_t TFriendProxy::GetReadEntry() const
   {
      // Return the entry number currently being looked at.

      return fDirector.GetReadEntry();
   }

   //------------------------------------------------------------------------------------
   void TFriendProxy::ResetReadEntry()
   {
      // Refresh the cached read entry number from the original tree.

      if (fDirector.GetTree()) fDirector.SetReadEntry(fDirector.GetTree()->GetReadEntry());
   }

  //------------------------------------------------------------------------------------
   void TFriendProxy::Update(TTree *newmain)
   {
      // Update the address of the underlying tree.

      if (newmain) {
         TObject *obj = newmain->GetListOfFriends()->At(fIndex);
         TFriendElement *element = dynamic_cast<TFriendElement*>( obj );
         fDirector.SetTree(element->GetTree());
      } else {
         fDirector.SetTree(0);
      }
   }
}
<commit_msg>add protection in case the friend tree is missing<commit_after>// @(#)root/base:$Name:  $:$Id: TFriendProxy.cxx,v 1.4 2007/02/01 15:26:19 brun Exp $
// Author: Philippe Canal  13/05/2003

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun, Fons Rademakers and al.           *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TFriendProxy                                                         //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TFriendProxy.h"
#include "TTree.h"
#include "TList.h"
#include "TFriendElement.h"

namespace ROOT {

   //------------------------------------------------------------------------------------
   TFriendProxy::TFriendProxy() : fDirector(0,-1), fIndex(-1)
   {
   }

   //------------------------------------------------------------------------------------
   TFriendProxy::TFriendProxy(TBranchProxyDirector *director, TTree *main, Int_t index) :
      fDirector(0,-1), fIndex(index)
   {
      // Constructor.

      if (main) {
         TObject *obj = main->GetListOfFriends()->At(fIndex);
         TFriendElement *element = dynamic_cast<TFriendElement*>( obj );
         if (element) fDirector.SetTree(element->GetTree());
      }
      director->Attach(this);
   }

   //------------------------------------------------------------------------------------
   Long64_t TFriendProxy::GetReadEntry() const
   {
      // Return the entry number currently being looked at.

      return fDirector.GetReadEntry();
   }

   //------------------------------------------------------------------------------------
   void TFriendProxy::ResetReadEntry()
   {
      // Refresh the cached read entry number from the original tree.

      if (fDirector.GetTree()) fDirector.SetReadEntry(fDirector.GetTree()->GetReadEntry());
   }

  //------------------------------------------------------------------------------------
   void TFriendProxy::Update(TTree *newmain)
   {
      // Update the address of the underlying tree.

      if (newmain) {
         TObject *obj = newmain->GetListOfFriends()->At(fIndex);
         TFriendElement *element = dynamic_cast<TFriendElement*>( obj );
         if (element) fDirector.SetTree(element->GetTree());
         else fDirector.SetTree(0);
      } else {
         fDirector.SetTree(0);
      }
   }
}
<|endoftext|>