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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif

#include "hintids.hxx"

#define _SVSTDARR_STRINGSDTOR
#include <svtools/svstdarr.hxx>

#ifndef _SVX_HTMLMODE_HXX
#include <svx/htmlmode.hxx>
#endif
#ifndef _SVX_SVXIDS_HRC //autogen
#include <svx/svxids.hrc>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif

#include "swtypes.hxx"
#include "wrtsh.hxx"
#include "viewopt.hxx"
#include "macassgn.hxx"
#include "swevent.hxx"
#include "docsh.hxx"
#include "globals.hrc"

SvStringsDtor* __EXPORT _GetRangeHdl( _SfxMacroTabPage*, const String& );

SwMacroAssignDlg::SwMacroAssignDlg( Window* pParent, SfxItemSet& rSet,
                                        DlgEventType eType )
    : SfxMacroAssignDlg( pParent, rSet )
{
     // TabPage holen
    SwMacroAssignDlg::AddEvents( *(SfxMacroTabPage*) GetTabPage(), eType );
}

SwMacroAssignDlg::~SwMacroAssignDlg()
{
}

void SwMacroAssignDlg::AddEvents( SfxMacroTabPage& rPg, DlgEventType eType )
{
    const SfxItemSet& rSet = rPg.GetItemSet();

    BOOL bHtmlMode = FALSE;
    USHORT nHtmlMode = ::GetHtmlMode((const SwDocShell*)SfxObjectShell::Current());
    bHtmlMode = nHtmlMode & HTMLMODE_ON ? TRUE : FALSE;

    switch( eType )
    {
    case MACASSGN_TEXTBAUST:            // Textbausteine
        rPg.SetGetRangeLink( &_GetRangeHdl );
        rPg.AddEvent( String( SW_RES(STR_EVENT_START_INS_GLOSSARY) ),
                            SW_EVENT_START_INS_GLOSSARY );
        rPg.AddEvent( String( SW_RES(STR_EVENT_END_INS_GLOSSARY) ),
                            SW_EVENT_END_INS_GLOSSARY);
        // damit der neue Handler aktiv wird!
        rPg.Reset( rSet );
        break;
    case MACASSGN_ALLFRM:
    case MACASSGN_GRAPHIC:          // Grafiken
        {
            rPg.AddEvent( String( SW_RES(STR_EVENT_IMAGE_ERROR) ),
                                SVX_EVENT_IMAGE_ERROR);
            rPg.AddEvent( String( SW_RES(STR_EVENT_IMAGE_ABORT) ),
                                SVX_EVENT_IMAGE_ABORT);
            rPg.AddEvent( String( SW_RES(STR_EVENT_IMAGE_LOAD) ),
                                SVX_EVENT_IMAGE_LOAD);
        }
        // kein break;
    case MACASSGN_FRMURL:           // Frm - URL-Attribute
        {
            if( !bHtmlMode &&
                (MACASSGN_FRMURL == eType || MACASSGN_ALLFRM == eType))
            {
                rPg.AddEvent( String( SW_RES( STR_EVENT_FRM_KEYINPUT_A ) ),
                                SW_EVENT_FRM_KEYINPUT_ALPHA );
                rPg.AddEvent( String( SW_RES( STR_EVENT_FRM_KEYINPUT_NOA ) ),
                                SW_EVENT_FRM_KEYINPUT_NOALPHA );
                rPg.AddEvent( String( SW_RES( STR_EVENT_FRM_RESIZE ) ),
                                SW_EVENT_FRM_RESIZE );
                rPg.AddEvent( String( SW_RES( STR_EVENT_FRM_MOVE ) ),
                                SW_EVENT_FRM_MOVE );
            }
        }
        // kein break;
    case MACASSGN_OLE:              // OLE
        {
            if( !bHtmlMode )
                rPg.AddEvent( String( SW_RES(STR_EVENT_OBJECT_SELECT) ),
                                SW_EVENT_OBJECT_SELECT );
        }
        // kein break;
    case MACASSGN_INETFMT:          // INetFmt-Attribute
        {
            rPg.AddEvent( String( SW_RES(STR_EVENT_MOUSEOVER_OBJECT) ),
                                SFX_EVENT_MOUSEOVER_OBJECT );
            rPg.AddEvent( String( SW_RES(STR_EVENT_MOUSECLICK_OBJECT) ),
                                SFX_EVENT_MOUSECLICK_OBJECT);
            rPg.AddEvent( String( SW_RES(STR_EVENT_MOUSEOUT_OBJECT) ),
                                SFX_EVENT_MOUSEOUT_OBJECT);
        }
        break;
    }
}

BOOL SwMacroAssignDlg::INetFmtDlg( Window* pParent, SwWrtShell& rSh,
                                    SvxMacroItem*& rpINetItem )
{
    BOOL bRet = FALSE;
    SfxItemSet aSet( rSh.GetAttrPool(), RES_FRMMACRO, RES_FRMMACRO );
    SvxMacroItem aItem( RES_FRMMACRO );
    if( !rpINetItem )
        rpINetItem = new SvxMacroItem( RES_FRMMACRO );
    else
        aItem.SetMacroTable( rpINetItem->GetMacroTable() );

    aSet.Put( aItem );

    SwMacroAssignDlg aMacDlg( pParent, aSet, MACASSGN_INETFMT );
    if( aMacDlg.Execute() == RET_OK )
    {
        const SfxItemSet* pOutSet = aMacDlg.GetOutputItemSet();
        const SfxPoolItem* pItem;
        if( SFX_ITEM_SET == pOutSet->GetItemState( RES_FRMMACRO, FALSE, &pItem ))
        {
            rpINetItem->SetMacroTable( ((SvxMacroItem*)pItem)->GetMacroTable() );
            bRet = TRUE;
        }
    }
    return bRet;
}

SvStringsDtor* __EXPORT _GetRangeHdl( _SfxMacroTabPage* pTbPg, const String& rLanguage )
{
    SvStringsDtor* pNew = new SvStringsDtor;

    SfxApplication* pSfxApp = SFX_APP();
    if ( !rLanguage.EqualsAscii(SVX_MACRO_LANGUAGE_JAVASCRIPT) )
    {
        pSfxApp->EnterBasicCall();

        String* pNewEntry = new String( pSfxApp->GetName() );
        pNew->Insert( pNewEntry, pNew->Count() );

        TypeId aType( TYPE( SwDocShell ));
        SfxObjectShell* pDoc = SfxObjectShell::GetFirst( &aType );
        while( pDoc )
        {
            pNewEntry = new String( pDoc->GetTitle() );
            pNew->Insert( pNewEntry, pNew->Count() );
            pDoc = SfxObjectShell::GetNext( *pDoc, &aType );
        }
        pSfxApp->LeaveBasicCall();
    }

    return pNew;
}

<commit_msg>INTEGRATION: CWS swwarnings (1.7.222); FILE MERGED 2007/05/29 12:25:22 os 1.7.222.2: RESYNC: (1.7-1.8); FILE MERGED 2007/02/27 11:46:24 os 1.7.222.1: #i69287# warnings removed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: macassgn.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 11:37:08 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif

#include "hintids.hxx"

#define _SVSTDARR_STRINGSDTOR
#include <svtools/svstdarr.hxx>

#ifndef _SVX_HTMLMODE_HXX
#include <svx/htmlmode.hxx>
#endif
#ifndef _SVX_SVXIDS_HRC //autogen
#include <svx/svxids.hrc>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif

#include "swtypes.hxx"
#include "wrtsh.hxx"
#include "viewopt.hxx"
#include "macassgn.hxx"
#include "swevent.hxx"
#include "docsh.hxx"
#include "globals.hrc"

SvStringsDtor* __EXPORT _GetRangeHdl( _SfxMacroTabPage*, const String& );

SwMacroAssignDlg::SwMacroAssignDlg( Window* pParent, SfxItemSet& rSet,
                                        DlgEventType eType )
    : SfxMacroAssignDlg( pParent, rSet )
{
     // TabPage holen
    SwMacroAssignDlg::AddEvents( *(SfxMacroTabPage*) GetTabPage(), eType );
}

SwMacroAssignDlg::~SwMacroAssignDlg()
{
}

void SwMacroAssignDlg::AddEvents( SfxMacroTabPage& rPg, DlgEventType eType )
{
    const SfxItemSet& rSet = rPg.GetItemSet();

    BOOL bHtmlMode = FALSE;
    USHORT nHtmlMode = ::GetHtmlMode((const SwDocShell*)SfxObjectShell::Current());
    bHtmlMode = nHtmlMode & HTMLMODE_ON ? TRUE : FALSE;

    switch( eType )
    {
    case MACASSGN_TEXTBAUST:            // Textbausteine
        rPg.SetGetRangeLink( &_GetRangeHdl );
        rPg.AddEvent( String( SW_RES(STR_EVENT_START_INS_GLOSSARY) ),
                            SW_EVENT_START_INS_GLOSSARY );
        rPg.AddEvent( String( SW_RES(STR_EVENT_END_INS_GLOSSARY) ),
                            SW_EVENT_END_INS_GLOSSARY);
        // damit der neue Handler aktiv wird!
        rPg.Reset( rSet );
        break;
    case MACASSGN_ALLFRM:
    case MACASSGN_GRAPHIC:          // Grafiken
        {
            rPg.AddEvent( String( SW_RES(STR_EVENT_IMAGE_ERROR) ),
                                SVX_EVENT_IMAGE_ERROR);
            rPg.AddEvent( String( SW_RES(STR_EVENT_IMAGE_ABORT) ),
                                SVX_EVENT_IMAGE_ABORT);
            rPg.AddEvent( String( SW_RES(STR_EVENT_IMAGE_LOAD) ),
                                SVX_EVENT_IMAGE_LOAD);
        }
        // kein break;
    case MACASSGN_FRMURL:           // Frm - URL-Attribute
        {
            if( !bHtmlMode &&
                (MACASSGN_FRMURL == eType || MACASSGN_ALLFRM == eType))
            {
                rPg.AddEvent( String( SW_RES( STR_EVENT_FRM_KEYINPUT_A ) ),
                                SW_EVENT_FRM_KEYINPUT_ALPHA );
                rPg.AddEvent( String( SW_RES( STR_EVENT_FRM_KEYINPUT_NOA ) ),
                                SW_EVENT_FRM_KEYINPUT_NOALPHA );
                rPg.AddEvent( String( SW_RES( STR_EVENT_FRM_RESIZE ) ),
                                SW_EVENT_FRM_RESIZE );
                rPg.AddEvent( String( SW_RES( STR_EVENT_FRM_MOVE ) ),
                                SW_EVENT_FRM_MOVE );
            }
        }
        // kein break;
    case MACASSGN_OLE:              // OLE
        {
            if( !bHtmlMode )
                rPg.AddEvent( String( SW_RES(STR_EVENT_OBJECT_SELECT) ),
                                SW_EVENT_OBJECT_SELECT );
        }
        // kein break;
    case MACASSGN_INETFMT:          // INetFmt-Attribute
        {
            rPg.AddEvent( String( SW_RES(STR_EVENT_MOUSEOVER_OBJECT) ),
                                SFX_EVENT_MOUSEOVER_OBJECT );
            rPg.AddEvent( String( SW_RES(STR_EVENT_MOUSECLICK_OBJECT) ),
                                SFX_EVENT_MOUSECLICK_OBJECT);
            rPg.AddEvent( String( SW_RES(STR_EVENT_MOUSEOUT_OBJECT) ),
                                SFX_EVENT_MOUSEOUT_OBJECT);
        }
        break;
    }
}

BOOL SwMacroAssignDlg::INetFmtDlg( Window* pParent, SwWrtShell& rSh,
                                    SvxMacroItem*& rpINetItem )
{
    BOOL bRet = FALSE;
    SfxItemSet aSet( rSh.GetAttrPool(), RES_FRMMACRO, RES_FRMMACRO );
    SvxMacroItem aItem( RES_FRMMACRO );
    if( !rpINetItem )
        rpINetItem = new SvxMacroItem( RES_FRMMACRO );
    else
        aItem.SetMacroTable( rpINetItem->GetMacroTable() );

    aSet.Put( aItem );

    SwMacroAssignDlg aMacDlg( pParent, aSet, MACASSGN_INETFMT );
    if( aMacDlg.Execute() == RET_OK )
    {
        const SfxItemSet* pOutSet = aMacDlg.GetOutputItemSet();
        const SfxPoolItem* pItem;
        if( SFX_ITEM_SET == pOutSet->GetItemState( RES_FRMMACRO, FALSE, &pItem ))
        {
            rpINetItem->SetMacroTable( ((SvxMacroItem*)pItem)->GetMacroTable() );
            bRet = TRUE;
        }
    }
    return bRet;
}

SvStringsDtor* __EXPORT _GetRangeHdl( _SfxMacroTabPage* /*pTbPg*/, const String& rLanguage )
{
    SvStringsDtor* pNew = new SvStringsDtor;

    SfxApplication* pSfxApp = SFX_APP();
    if ( !rLanguage.EqualsAscii(SVX_MACRO_LANGUAGE_JAVASCRIPT) )
    {
        pSfxApp->EnterBasicCall();

        String* pNewEntry = new String( pSfxApp->GetName() );
        pNew->Insert( pNewEntry, pNew->Count() );

        TypeId aType( TYPE( SwDocShell ));
        SfxObjectShell* pDoc = SfxObjectShell::GetFirst( &aType );
        while( pDoc )
        {
            pNewEntry = new String( pDoc->GetTitle() );
            pNew->Insert( pNewEntry, pNew->Count() );
            pDoc = SfxObjectShell::GetNext( *pDoc, &aType );
        }
        pSfxApp->LeaveBasicCall();
    }

    return pNew;
}

<|endoftext|>


<commit_before>/*
 * Copyright 2009-2013 The VOTCA Development Team (http://www.votca.org)
 *
 * 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 <iostream>
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem/convenience.hpp>
#include <votca/tools/getline.h>

#ifndef HAVE_NO_CONFIG
#include <votca_config.h>
#endif

#include "dlpolytopologyreader.h"
#ifdef DLPOLY_FORTRAN
#include "dlpoly/dlp_io_layer.h"
#include "fortan_mangling.h"
#endif

namespace votca { namespace csg {

bool DLPOLYTopologyReader::ReadTopology(string file, Topology &top)
{
    std::ifstream fl;
    boost::filesystem::path filepath(file.c_str());
    string filename;
#ifdef DLPOLY_FORTRAN
    if (file != ".dlpoly")
      throw std::runtime_error("Reading from different filename/directories not implemented yet. (use --top '.dlpoly')");

    struct FieldSpecsT  FieldBase;
    struct FrameSpecsT  FrameBase;
    struct MolecSpecsT *MolecBase;
    struct FieldSiteT  *FieldSite;
    struct FrameSiteT  *FrameSite;

    int idnode,matms,natms,nmols,nmolt;
    int istateF;

    int inode=matms=natms=nmols=nmolt=0;

    // TODO: istateF must be an enum!
    istateF=1;

    // TODO: we need to fix the file naming!
    FortranCInterface_GLOBAL(field_scan,FIELD_SCAN)(&istateF,&matms,&natms,&nmolt);

    MolecBase = new MolecSpecsT[nmolt];
    FieldSite = new FieldSiteT[natms];

    FieldBase.nmols = nmolt;
    FieldBase.natms = natms;

    FortranCInterface_GLOBAL(field_read,FIELD_READ)(&istateF,&FieldBase,MolecBase,FieldSite);

    // AB: if on return istateF < 0  => in the next F-call the relevant F-arrays will be deallocated (at the end)
    // AB: NOT TO RE-/DE-ALLOCATE F-arrays in the next F-call, reset istateF = 0
    istateF = 0;

    // TODO: fix residue naming / assignment
    Residue *res = top.CreateResidue("no");

    // read the atoms
    int mol_offset=0;
    for(int im=0; im<nmolt; im++){
        for(int imr=0; imr<MolecBase[im].nrept; ++imr) {
            Molecule *mi = top.CreateMolecule(MolecBase[im].name);
            for(int ims=0; ims<MolecBase[im].nsites; ims++) {
	        int is=mol_offset+ims;
                BeadType *type = top.GetOrCreateBeadType(FieldSite[is].type); // what is
	        string beadname = boost::lexical_cast<string>(FieldSite[is].name) + "#" + boost::lexical_cast<string>(ims+1);
                Bead *bead = top.CreateBead(1, beadname, type, res->getId(), FieldSite[is].m, FieldSite[is].q);

                stringstream nm;
                nm << bead->getResnr() + 1 << ":" <<  top.getResidue(bead->getResnr())->getName() << ":" << bead->getName();
                mi->AddBead(bead, nm.str());
            }
        }
	mol_offset+=MolecBase[im].nsites;
    }

    delete [] MolecBase;
    delete [] FieldSite;
#else
    // TODO: fix residue naming / assignment
    Residue *res = top.CreateResidue("no");

    if ( boost::filesystem::basename(filepath).size() == 0 ) {
      if (filepath.parent_path().string().size() == 0) {
        filename="FIELD";
      } else {
	filename=filepath.parent_path().string() + "/FIELD";
      }
    } else {
      filename=file;
    }
    fl.open(filename.c_str());
    if (!fl.is_open()){
      throw std::runtime_error("could open dlpoly file " + filename);
    } else {
      string line;
      getline(fl, line); //title
      getline(fl, line); //unit line
      fl >> line;
      if (line != "MOLECULES")
          throw std::runtime_error("unexpected line in dlpoly file " + filename + ", expected 'MOLECULES' got" + line);
      int nmol_types;
      fl >> nmol_types;
      getline(fl, line); //rest of MOLECULES line
      int id=0;
      for (int nmol_type=0;nmol_type<nmol_types; nmol_type++){
	string mol_name;
        getline(fl, mol_name); //molecule name might incl. spaces
	boost::erase_all(mol_name, " ");
        Molecule *mi = top.CreateMolecule(mol_name);
        fl >> line;
        if (line != "NUMMOLS")
          throw std::runtime_error("unexpected line in dlpoly file " + filename + ", expected 'NUMMOLS' got" + line);
	int nreplica;
	fl >> nreplica;
	fl >> line;
        if (line != "ATOMS")
          throw std::runtime_error("unexpected line in dlpoly file " + filename + ", expected 'ATOMS' got" + line);
	int natoms;
	fl >> natoms;
	//read molecule
	for (int i=0;i<natoms;){//i is altered in reapeater loop
	  string beadtype;
	  fl >> beadtype;
	  BeadType *type = top.GetOrCreateBeadType(beadtype);
	  double mass;
	  fl >> mass;
	  double charge;
	  fl >> charge;
          getline(fl,line); //rest of the atom line
          Tokenizer tok(line, " ");
          vector<int> fields;
          tok.ConvertToVector<int>(fields);
	  int repeater=1;
	  if (fields.size() > 1)
	    repeater=fields[0];
	  for(int j=0;j<repeater;j++){
	    string beadname = beadtype + "#" + boost::lexical_cast<string>(j+1);
	    Bead *bead = top.CreateBead(1, beadname , type, res->getId(), mass, charge);
            stringstream nm;
            nm << bead->getResnr() + 1 << ":" <<  top.getResidue(bead->getResnr())->getName() << ":" << bead->getName();
            mi->AddBead(bead, nm.str());
	    i++;
	  }
	}
	while (line != "FINISH"){
	  fl >> line;
	  if (fl.eof())
            throw std::runtime_error("unexpected end of dlpoly file " + filename + " while scanning for 'FINISH'");
	}
	getline(fl, line); //rest of the FINISH line
	//replicate molecule
	for (int replica=1;replica<nreplica;replica++){
          Molecule *mi_replica = top.CreateMolecule(mol_name);
	  for(int i=0;i<mi->BeadCount();i++){
	    Bead *bead=mi->getBead(i);
	    BeadType *type = top.GetOrCreateBeadType(bead->Type()->getName());
	    string beadname=mi->getBeadName(i);
	    Bead *bead_replica = top.CreateBead(1, bead->getName(), type, res->getId(), bead->getM(), bead->getQ());
	    mi_replica->AddBead(bead_replica,beadname);
	  }
	}
      }
    }
    //we don't need the rest.
    fl.close();
#endif
    if ( boost::filesystem::basename(filepath).size() == 0 ) {
      if (filepath.parent_path().string().size() == 0) {
        filename="CONFIG";
      } else {
	filename=filepath.parent_path().string() + "/CONFIG";
      }
    } else {
      cout << "NOTE: Explicit dlploy topology filename given, so no config will be openend and no boundary conditions will set in the topology." << endl;
      return true;
    }
    fl.open(filename.c_str());
    if(fl.is_open()) {
      string line;
      getline(fl, line); //title
      getline(fl, line); // 2nd header line
      vec box_vectors[3];
      for (int i=0;i<3;i++){ // read 3 box lines
        getline(fl, line);
        if(fl.eof())
          throw std::runtime_error("unexpected end of file in dlpoly file " + filename +", when reading box vector"  +
              boost::lexical_cast<string>(i));
        Tokenizer tok(line, " ");
        vector<double> fields;
        tok.ConvertToVector<double>(fields);
        box_vectors[i]=vec(fields[0],fields[1],fields[2]);
      }
      matrix box(box_vectors[0],box_vectors[1],box_vectors[2]);
      top.setBox(box);
      fl.close();
    }
    else {
      cout << "NOTE: Could not open dlploy file " << filename << "so no boundary conditions, where set in the topology." << endl;
    }
    return true;
}

}}

<commit_msg>dlpolytopologyreader: read in angles<commit_after>/*
 * Copyright 2009-2013 The VOTCA Development Team (http://www.votca.org)
 *
 * 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 <iostream>
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem/convenience.hpp>
#include <votca/tools/getline.h>

#ifndef HAVE_NO_CONFIG
#include <votca_config.h>
#endif

#include "dlpolytopologyreader.h"
#ifdef DLPOLY_FORTRAN
#include "dlpoly/dlp_io_layer.h"
#include "fortan_mangling.h"
#endif

namespace votca { namespace csg {

bool DLPOLYTopologyReader::ReadTopology(string file, Topology &top)
{
    std::ifstream fl;
    boost::filesystem::path filepath(file.c_str());
    string filename;
#ifdef DLPOLY_FORTRAN
    if (file != ".dlpoly")
      throw std::runtime_error("Reading from different filename/directories not implemented yet. (use --top '.dlpoly')");

    struct FieldSpecsT  FieldBase;
    struct FrameSpecsT  FrameBase;
    struct MolecSpecsT *MolecBase;
    struct FieldSiteT  *FieldSite;
    struct FrameSiteT  *FrameSite;

    int idnode,matms,natms,nmols,nmolt;
    int istateF;

    int inode=matms=natms=nmols=nmolt=0;

    // TODO: istateF must be an enum!
    istateF=1;

    // TODO: we need to fix the file naming!
    FortranCInterface_GLOBAL(field_scan,FIELD_SCAN)(&istateF,&matms,&natms,&nmolt);

    MolecBase = new MolecSpecsT[nmolt];
    FieldSite = new FieldSiteT[natms];

    FieldBase.nmols = nmolt;
    FieldBase.natms = natms;

    FortranCInterface_GLOBAL(field_read,FIELD_READ)(&istateF,&FieldBase,MolecBase,FieldSite);

    // AB: if on return istateF < 0  => in the next F-call the relevant F-arrays will be deallocated (at the end)
    // AB: NOT TO RE-/DE-ALLOCATE F-arrays in the next F-call, reset istateF = 0
    istateF = 0;

    // TODO: fix residue naming / assignment
    Residue *res = top.CreateResidue("no");

    // read the atoms
    int mol_offset=0;
    for(int im=0; im<nmolt; im++){
        for(int imr=0; imr<MolecBase[im].nrept; ++imr) {
            Molecule *mi = top.CreateMolecule(MolecBase[im].name);
            for(int ims=0; ims<MolecBase[im].nsites; ims++) {
	        int is=mol_offset+ims;
                BeadType *type = top.GetOrCreateBeadType(FieldSite[is].type); // what is
	        string beadname = boost::lexical_cast<string>(FieldSite[is].name) + "#" + boost::lexical_cast<string>(ims+1);
                Bead *bead = top.CreateBead(1, beadname, type, res->getId(), FieldSite[is].m, FieldSite[is].q);

                stringstream nm;
                nm << bead->getResnr() + 1 << ":" <<  top.getResidue(bead->getResnr())->getName() << ":" << bead->getName();
                mi->AddBead(bead, nm.str());
            }
        }
	mol_offset+=MolecBase[im].nsites;
    }

    delete [] MolecBase;
    delete [] FieldSite;
#else
    // TODO: fix residue naming / assignment
    Residue *res = top.CreateResidue("no");

    if ( boost::filesystem::basename(filepath).size() == 0 ) {
      if (filepath.parent_path().string().size() == 0) {
        filename="FIELD";
      } else {
	filename=filepath.parent_path().string() + "/FIELD";
      }
    } else {
      filename=file;
    }
    fl.open(filename.c_str());
    if (!fl.is_open()){
      throw std::runtime_error("could open dlpoly file " + filename);
    } else {
      string line;
      getline(fl, line); //title
      getline(fl, line); //unit line
      fl >> line;
      if (line != "MOLECULES")
          throw std::runtime_error("unexpected line in dlpoly file " + filename + ", expected 'MOLECULES' got" + line);
      int nmol_types;
      fl >> nmol_types;
      getline(fl, line); //rest of MOLECULES line
      int id=0;
      for (int nmol_type=0;nmol_type<nmol_types; nmol_type++){
	string mol_name;
        getline(fl, mol_name); //molecule name might incl. spaces
	boost::erase_all(mol_name, " ");
        Molecule *mi = top.CreateMolecule(mol_name);
        fl >> line;
        if (line != "NUMMOLS")
          throw std::runtime_error("unexpected line in dlpoly file " + filename + ", expected 'NUMMOLS' got" + line);
	int nreplica;
	fl >> nreplica;
	fl >> line;
        if (line != "ATOMS")
          throw std::runtime_error("unexpected line in dlpoly file " + filename + ", expected 'ATOMS' got" + line);
	int natoms;
	fl >> natoms;
	//read molecule
	int id_map[natoms];
	for (int i=0;i<natoms;){//i is altered in reapeater loop
	  string beadtype;
	  fl >> beadtype;
	  BeadType *type = top.GetOrCreateBeadType(beadtype);
	  double mass;
	  fl >> mass;
	  double charge;
	  fl >> charge;
          getline(fl,line); //rest of the atom line
          Tokenizer tok(line, " ");
          vector<int> fields;
          tok.ConvertToVector<int>(fields);
	  int repeater=1;
	  if (fields.size() > 1)
	    repeater=fields[0];
	  for(int j=0;j<repeater;j++){
	    string beadname = beadtype + "#" + boost::lexical_cast<string>(j+1);
	    Bead *bead = top.CreateBead(1, beadname , type, res->getId(), mass, charge);
            stringstream nm;
            nm << bead->getResnr() + 1 << ":" <<  top.getResidue(bead->getResnr())->getName() << ":" << bead->getName();
            mi->AddBead(bead, nm.str());
	    id_map[i]=bead->getId();
	    i++;
	  }
	}
	while (line != "FINISH"){
	  if ((line == "BONDS")||(line == "ANGLES")||(line == "DIHEDRALS")) {
	    string type = line;
	    int count;
	    fl >> count;
	    for (int i=0;i<count;i++){
	      fl >> line; //bond/angle/dih type not used
	      int ids[4];
              Interaction *ic;
	      fl >> ids[0]; fl>>ids[1];
	      if (type == "BONDS"){
	        ic = new IBond(id_map[ids[0]-1],id_map[ids[1]-1]); // -1 due to fortran vs c
	      } else if (type == "ANGLES"){
		fl >> ids[2];
	        ic = new IAngle(id_map[ids[0]-1],id_map[ids[1]-1],id_map[ids[2]-1]); // -1 due to fortran vs c
	      } else if (type == "DIHEDRALS"){
		fl >> ids[2]; fl >> ids[3];
	        ic = new IDihedral(id_map[ids[0]-1],id_map[ids[1]-1],id_map[ids[2]-1],id_map[ids[3]-1]); // -1 due to fortran vs c
	      }
              ic->setGroup(type);
              ic->setIndex(i);
              ic->setMolecule(mi->getId());
              top.AddBondedInteraction(ic);
              mi->AddInteraction(ic);
	      getline(fl,line);
	    }
	  }
	  fl >> line;
	  if (fl.eof())
            throw std::runtime_error("unexpected end of dlpoly file " + filename + " while scanning for 'FINISH'");
	}
	getline(fl, line); //rest of the FINISH line
	//replicate molecule
	for (int replica=1;replica<nreplica;replica++){
          Molecule *mi_replica = top.CreateMolecule(mol_name);
	  for(int i=0;i<mi->BeadCount();i++){
	    Bead *bead=mi->getBead(i);
	    BeadType *type = top.GetOrCreateBeadType(bead->Type()->getName());
	    string beadname=mi->getBeadName(i);
	    Bead *bead_replica = top.CreateBead(1, bead->getName(), type, res->getId(), bead->getM(), bead->getQ());
	    mi_replica->AddBead(bead_replica,beadname);
	    //TODO copy interactions
	  }
	}
      }
    }
    //we don't need the rest.
    fl.close();
#endif
    if ( boost::filesystem::basename(filepath).size() == 0 ) {
      if (filepath.parent_path().string().size() == 0) {
        filename="CONFIG";
      } else {
	filename=filepath.parent_path().string() + "/CONFIG";
      }
    } else {
      cout << "NOTE: Explicit dlploy topology filename given, so no config will be openend and no boundary conditions will set in the topology." << endl;
      return true;
    }
    fl.open(filename.c_str());
    if(fl.is_open()) {
      string line;
      getline(fl, line); //title
      getline(fl, line); // 2nd header line
      vec box_vectors[3];
      for (int i=0;i<3;i++){ // read 3 box lines
        getline(fl, line);
        if(fl.eof())
          throw std::runtime_error("unexpected end of file in dlpoly file " + filename +", when reading box vector"  +
              boost::lexical_cast<string>(i));
        Tokenizer tok(line, " ");
        vector<double> fields;
        tok.ConvertToVector<double>(fields);
        box_vectors[i]=vec(fields[0],fields[1],fields[2]);
      }
      matrix box(box_vectors[0],box_vectors[1],box_vectors[2]);
      top.setBox(box);
      fl.close();
    }
    else {
      cout << "NOTE: Could not open dlploy file " << filename << "so no boundary conditions, where set in the topology." << endl;
    }
    return true;
}

}}

<|endoftext|>


<commit_before>// -*- mode: c++, coding: utf-8 -*-
/**
 * tbrpg – Text based roll playing game
 *
 * Copyright © 2012  Mattias Andrée (maandree@kth.se)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "CharacterCreator.hpp"

/**
 * Text based roll playing game
 *
 * DD2387 Program construction with C++
 * Laboration 3
 *
 * @author  Mattias Andrée <maandree@kth.se>
 */
namespace tbrpg
{
  /**
   * Constructor
   *
   * @param  rules  The game's rules
   */
  CharacterCreator::CharacterCreator(const RuleSet& rules)
  {
    this->ruleset = rules;
  }

  /**
   * Destructor
   */
  CharacterCreator::~CharacterCreator()
  {
  }

  /**
   * Create a character sheet
   *
   * @return  A character sheet, nullptr if aborted
   */
  CharacterSheet* create() const
  {
    std::vector<std::string> genders = {"male", "female"};

    std::vector<std::string> races = std::vector<std::string>();
    std::unordered_map<std::string, Race> raceMap = std::unordered_map<std::string, Race>();
    for (Race& r : this->ruleset.races)
      {
	raceMap[r.name] = r;
	races.push_back(r);
      }

    std::vector<std::string> prestiges;
    std::unordered_map<std::string, std::vector<Class>> prestigeMap;

    std::vector<std::string> specialisations = std::vector<std::string>();
    std::unordered_map<std::string, MagicSchool> specialisationMap = std::unordered_map<std::string, MagicSchool>();

    std::vector<std::string> alignments;
    std::vector<std::string> all_alignments = {"chaotic evil", "neutral evil", "lawful evil",
					       "chaotic neutral", "true neutral", "lawful neutral",
					       "chaotic good", "neutral good", "lawful good"};
    std::unordered_map<std::string, char> alignmentMap = std::unordered_map<std::string, char>();
    for (long i = 0; i < all_alignments.size(); i++)
      alignmentMap[all_alignments[i]] = (char)i;

    std::string input;
    CharacterSheet sheet = CharacterSheet();

  _01:
    input = promptList("Select gender: ", genders);
    if (input == "")
      return nullptr;
    sheet.female = input == "female";

  _02:
    input = promptList("Select race: ", races);
    if (input == "")
      goto _01;
    sheet.race = raceMap[input];

  _03:
    std::string c;
    prestiges = std::vector<std::string>();
    prestigeMap = std::unordered_map<std::string, std::vector<Class>>();
    for (std::vector<Class>& p : sheet.race.allowed_classes)
      {
	c = "";
	for (Class& c : p)
	  if (c == "")
	    c = p.name;
	  else
	    c += "/" + p.name;
	prestigeMap[c] = p;
        prestiges.push_back(p);
      }
    input = promptList("Select class: ", prestiges);
    if (input == "")
      goto _02;
    sheet.prestige = prestigeMap[input];
    sheet.class_abondoned = {};
    sheet.experience = {};
    sheet.level = {};
    for (long i = 0, n = sheet.prestige.size(); i < n; i++)
      {
	sheet.class_abondoned.push_back(false);
	sheet.experience.push_back(0);
	sheet.level.push_back(1);
      }

  _04:
    sheet.specialisation = GENERAL_MAGE;
    for (Class& c : sheet.prestige)
      if (c.specialisations.size() > 0)
	{
	  specialisations = std::vector<std::string>();
	  specialisationMap = std::unordered_map<std::string, MagicSchool>();
	  input = promptList("Select mage specialisation: ", specialisations);
	  for (MagicSchool& s : c.specialisations)
	    {
	      specialisationMap[s.practicer] = s;
	      specialisations.push_back(s);
	    }
	  if (input == "")
	    goto _03;
	  break;
	}

  _05:
    std::vector<std::string> alignments = std::vector<std::string>();
    boolean ok;
    for (long i = 0; i < all_alignments.size(); i++)
      {
	ok = true;
	for (Class& c : sheet.prestige)
	  ok &= *(c.alignments + i);
	if (ok)
	  alignments.push_back(all_alignments[i]);
      }
    input = promptList("Select alignment: ", alignments.size() == 0
		                           ? all_alignments /* fail safe */
		                           : alignments);
    if (input == "")
      goto _04;
    sheet.alignment = alignmentMap[input];

    // AbilityBonus abilities
    // std::unordered_map<WeaponGroup, int> proficiencies
    // Race racial_enemy
    // SpellBook spells
    // std::string portrait
    // char colour
    // std::string name

    return &sheet;
  }

}

<commit_msg>m + colour, name, portrait, specialisation(race)<commit_after>// -*- mode: c++, coding: utf-8 -*-
/**
 * tbrpg – Text based roll playing game
 *
 * Copyright © 2012  Mattias Andrée (maandree@kth.se)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "CharacterCreator.hpp"

/**
 * Text based roll playing game
 *
 * DD2387 Program construction with C++
 * Laboration 3
 *
 * @author  Mattias Andrée <maandree@kth.se>
 */
namespace tbrpg
{
  /**
   * Constructor
   *
   * @param  rules  The game's rules
   */
  CharacterCreator::CharacterCreator(const RuleSet& rules)
  {
    this->ruleset = rules;
  }

  /**
   * Destructor
   */
  CharacterCreator::~CharacterCreator()
  {
  }

  /**
   * Create a character sheet
   *
   * @return  A character sheet, nullptr if aborted
   */
  CharacterSheet* create() const
  {
    std::vector<std::string> genders = {"male", "female"};

    std::vector<std::string> races = std::vector<std::string>();
    std::unordered_map<std::string, Race> raceMap = std::unordered_map<std::string, Race>();
    for (Race& r : this->ruleset.races)
      {
	raceMap[r.name] = r;
	races.push_back(r);
      }

    std::vector<std::string> prestiges;
    std::unordered_map<std::string, std::vector<Class>> prestigeMap;

    std::vector<std::string> specialisations = std::vector<std::string>();
    std::unordered_map<std::string, MagicSchool> specialisationMap = std::unordered_map<std::string, MagicSchool>();

    std::vector<std::string> alignments;
    std::vector<std::string> all_alignments = {"chaotic evil", "neutral evil", "lawful evil",
					       "chaotic neutral", "true neutral", "lawful neutral",
					       "chaotic good", "neutral good", "lawful good"};
    std::unordered_map<std::string, char> alignmentMap = std::unordered_map<std::string, char>();
    for (long i = 0; i < all_alignments.size(); i++)
      alignmentMap[all_alignments[i]] = (char)i;

    std::string input;
    long indexInput;
    std::string c;
    boolean ok;
    CharacterSheet sheet = CharacterSheet();

  _01:
    input = promptList("Select gender: ", genders);
    if (input == "")
      return nullptr;
    sheet.female = input == "female";

  _02:
    input = promptList("Select race: ", races);
    if (input == "")
      goto _01;
    sheet.race = raceMap[input];

  _03:
    prestiges = std::vector<std::string>();
    prestigeMap = std::unordered_map<std::string, std::vector<Class>>();
    for (std::vector<Class>& p : sheet.race.allowed_classes)
      {
	c = "";
	for (Class& c : p)
	  if (c == "")
	    c = p.name;
	  else
	    c += "/" + p.name;
	prestigeMap[c] = p;
        prestiges.push_back(p);
      }
    input = promptList("Select class: ", prestiges);
    if (input == "")
      goto _02;
    sheet.prestige = prestigeMap[input];
    sheet.class_abondoned = {};
    sheet.experience = {};
    sheet.level = {};
    for (long i = 0, n = sheet.prestige.size(); i < n; i++)
      {
	sheet.class_abondoned.push_back(false);
	sheet.experience.push_back(0);
	sheet.level.push_back(1);
      }

  _04:
    sheet.specialisation = GENERAL_MAGE;
    for (Class& c : sheet.prestige)
      if (c.specialisations.size() > 0)
	{
	  specialisations = std::vector<std::string>();
	  specialisationMap = std::unordered_map<std::string, MagicSchool>();
	  input = promptList("Select mage specialisation: ", specialisations);
	  for (MagicSchool& s : c.specialisations)
	    for (MagicSchool& z : sheet.race.specialisations)
	      if (s == z)
		{
		  specialisationMap[s.practicer] = s;
		  specialisations.push_back(s);
		  break;
		}
	  if (input == "")
	    goto _03;
	  break;
	}

  _05:
    alignments = std::vector<std::string>();
    for (long i = 0; i < all_alignments.size(); i++)
      {
	ok = true;
	for (Class& c : sheet.prestige)
	  ok &= *(c.alignments + i);
	if (ok)
	  alignments.push_back(all_alignments[i]);
      }
    input = promptList("Select alignment: ", alignments.size() == 0
		                           ? all_alignments /* fail safe */
		                           : alignments);
    if (input == "")
      goto _04;
    sheet.alignment = alignmentMap[input];

  _06:
    // Abilities abilities.abilities

  _07:
    // std::unordered_map<WeaponGroup, int> proficiencies

  _08:
    // Race racial_enemy
    // SpellBook abilities.spells
    // ThiefAbilities abilities.thief_abilities

  _09:
    input = promptBoolean("Do you have a portrait: ", "yes", "no");
    if (input == "")
      goto _08;
    if (input == "no")
      sheet.portrait = "";
    else
      {
	input = promptFile("Select portrait: ", true);
	if (input == "")
	  goto _08;
	sheet.portrait = input;
      }

  _10:
    indexInput = promptIndex("Select colour: ", {"red", "green", "yellow", "blue", "magenta", "cyan"});
    if (indexInput < 0)
      goto _09;
    sheet.colour = (char)(indexInput + 1);

  _11:
    input = promptArbitrary("Select name: ");
    if (input == "")
      goto _10;
    sheet.name = input;

    return &sheet;
  }

}

<|endoftext|>


<commit_before>/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>

#include "ifcpp/model/AttributeObject.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/model/BuildingGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IFC4/include/IfcColourRgbList.h"
#include "ifcpp/IFC4/include/IfcNormalisedRatioMeasure.h"

// ENTITY IfcColourRgbList
IfcColourRgbList::IfcColourRgbList( int id ) { m_entity_id = id; }
shared_ptr<BuildingObject> IfcColourRgbList::getDeepCopy( BuildingCopyOptions& options )
{
	shared_ptr<IfcColourRgbList> copy_self( new IfcColourRgbList() );
	copy_self->m_ColourList.resize( m_ColourList.size() );
	for( size_t ii=0; ii<m_ColourList.size(); ++ii )
	{
		std::vector<shared_ptr<IfcNormalisedRatioMeasure> >& vec_ii = m_ColourList[ii];
		std::vector<shared_ptr<IfcNormalisedRatioMeasure> >& vec_ii_target = copy_self->m_ColourList[ii];
		for( size_t jj=0; jj<vec_ii.size(); ++jj )
		{
			shared_ptr<IfcNormalisedRatioMeasure>& item_jj = vec_ii[jj];
			if( item_jj )
			{
				vec_ii_target.emplace_back( dynamic_pointer_cast<IfcNormalisedRatioMeasure>( item_jj->getDeepCopy(options) ) );
			}
		}
	}
	return copy_self;
}
void IfcColourRgbList::getStepLine( std::stringstream& stream ) const
{
	stream << "#" << m_entity_id << "= IFCCOLOURRGBLIST" << "(";
	stream << ");";
}
void IfcColourRgbList::getStepParameter( std::stringstream& stream, bool /*is_select_type*/ ) const { stream << "#" << m_entity_id; }
const std::wstring IfcColourRgbList::toString() const { return L"IfcColourRgbList"; }
void IfcColourRgbList::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
	const size_t num_args = args.size();
	if( num_args != 1 ){ std::stringstream err; err << "Wrong parameter count for entity IfcColourRgbList, expecting 1, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); }
	readTypeOfRealList2D( args[0], m_ColourList );
}
void IfcColourRgbList::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const
{
	IfcPresentationItem::getAttributes( vec_attributes );
}
void IfcColourRgbList::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const
{
	IfcPresentationItem::getAttributesInverse( vec_attributes_inverse );
}
void IfcColourRgbList::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity )
{
	IfcPresentationItem::setInverseCounterparts( ptr_self_entity );
}
void IfcColourRgbList::unlinkFromInverseCounterparts()
{
	IfcPresentationItem::unlinkFromInverseCounterparts();
}
<commit_msg>Update IfcColourRgbList.cpp<commit_after>/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>

#include "ifcpp/model/AttributeObject.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/model/BuildingGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IFC4/include/IfcColourRgbList.h"
#include "ifcpp/IFC4/include/IfcNormalisedRatioMeasure.h"

// ENTITY IfcColourRgbList
IfcColourRgbList::IfcColourRgbList( int id ) { m_entity_id = id; }
shared_ptr<BuildingObject> IfcColourRgbList::getDeepCopy( BuildingCopyOptions& options )
{
	shared_ptr<IfcColourRgbList> copy_self( new IfcColourRgbList() );
	copy_self->m_ColourList.resize( m_ColourList.size() );
	for( size_t ii=0; ii<m_ColourList.size(); ++ii )
	{
		std::vector<shared_ptr<IfcNormalisedRatioMeasure> >& vec_ii = m_ColourList[ii];
		std::vector<shared_ptr<IfcNormalisedRatioMeasure> >& vec_ii_target = copy_self->m_ColourList[ii];
		for( size_t jj=0; jj<vec_ii.size(); ++jj )
		{
			shared_ptr<IfcNormalisedRatioMeasure>& item_jj = vec_ii[jj];
			if( item_jj )
			{
				vec_ii_target.emplace_back( dynamic_pointer_cast<IfcNormalisedRatioMeasure>( item_jj->getDeepCopy(options) ) );
			}
		}
	}
	return copy_self;
}
void IfcColourRgbList::getStepLine( std::stringstream& stream ) const
{
	stream << "#" << m_entity_id << "= IFCCOLOURRGBLIST" << "(";
	writeTypeOfRealList2D( stream, m_ColourList, false );
	stream << ");";
}
void IfcColourRgbList::getStepParameter( std::stringstream& stream, bool /*is_select_type*/ ) const { stream << "#" << m_entity_id; }
const std::wstring IfcColourRgbList::toString() const { return L"IfcColourRgbList"; }
void IfcColourRgbList::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
	const size_t num_args = args.size();
	if( num_args != 1 ){ std::stringstream err; err << "Wrong parameter count for entity IfcColourRgbList, expecting 1, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); }
	readTypeOfRealList2D( args[0], m_ColourList );
}
void IfcColourRgbList::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const
{
	IfcPresentationItem::getAttributes( vec_attributes );
}
void IfcColourRgbList::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const
{
	IfcPresentationItem::getAttributesInverse( vec_attributes_inverse );
}
void IfcColourRgbList::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity )
{
	IfcPresentationItem::setInverseCounterparts( ptr_self_entity );
}
void IfcColourRgbList::unlinkFromInverseCounterparts()
{
	IfcPresentationItem::unlinkFromInverseCounterparts();
}
<|endoftext|>


<commit_before># Items marked with "*" need compiler extensions to handle
# Experimental -- run with
#   ./motto.byte --disable_inlining --disable_var_erasure --no_type_check \
#     -o test examples/hadoop_more1.cp

type k_v : record
  key : integer
    {hadoop_vint = true}
  value : integer
    {hadoop_vint = true}

#fun peek : (type k_v/- c) -> (type k_v)
#  ? c # should be a peek -- not a receive
fun peek : (c''' : type k_v) -> (type k_v)
  c'''
fun send : (c'' : type k_v, x' : type k_v) -> ()
  c''
  <> #x' # FIXME
fun consume : (c' : type k_v) -> (type k_v)
  c'

#fun Wc_node : (type k_v/- x, type k_v/- y, -/type k_v z) -> ()
fun Wc_node : (type k_v/- chan; x : type k_v, y : type k_v, z : type k_v) -> ()
  # Instead of "vs" could have pattern matching, to give v1 and v2
#  let vs = peek_all () #([x, y])
#  let v1 = vs[0] # * check if can project from lists like this
#  let v2 = vs[1]
#  let v1 = peek (x)
#  let v2 = peek (y)
  let v1 = ?? chan
  let v2 = ?? chan

#  if v1 > v2:
#    <>
#  else: <>

  if v1.key = 0-1 and v2.key = 0-1: # * i think "-" cannot be prefix
#    z ! ? x
    ? chan
    chan ! 5 # FIXME test
    send (z, consume (x))
    consume (y)
    <>
  else: if v1.key = 0-1:
#    z ! ? y
    send (z, consume (y))
#    <>
  else: if v2.key = 0-1:
#    z ! ? x
    send (z, consume (x))
#    <>
  else: if v1.key < v2.key:
#    z ! ? x
    send (z, consume (x))
#    <>
  else: if v2.key < v1.key:
#    z ! ? y
    send (z, consume (y))
#    <>
  else:
#    z ! v1 with value = v1.value + v2.value
#    send (z, 5) # need record update
    send (z, v1 with value = v1.value + v2.value)
#    ? x
#    ? y
    consume (x)
    consume (y)
    <>

#    # NOTE experimental area
#    #x := y
#    let v = x
  <> #x # FIXME should be <>
<commit_msg>added type annotations to v1 and v2, since we're running this example with type inference switched off; added commented test code i've been using -- this can eventually be purged;<commit_after># Items marked with "*" need compiler extensions to handle
# Experimental -- run with
#   ./motto.byte --disable_inlining --disable_var_erasure --no_type_check \
#     -o test examples/hadoop_more1.cp

type k_v : record
  key : integer
    {hadoop_vint = true}
  value : integer
    {hadoop_vint = true}

#fun peek : (type k_v/- c) -> (type k_v)
#  ? c # should be a peek -- not a receive
fun peek : (c''' : type k_v) -> (type k_v)
  c'''
fun send : (c'' : type k_v, x' : type k_v) -> ()
  c''
  <> #x' # FIXME
fun consume : (c' : type k_v) -> (type k_v)
  c'

#fun Wc_node : (type k_v/- x, type k_v/- y, -/type k_v z) -> ()
fun Wc_node : (type k_v/- chan; x : type k_v, y : type k_v, z : type k_v) -> ()
  # Instead of "vs" could have pattern matching, to give v1 and v2
#  let vs = peek_all () #([x, y])
#  let v1 = vs[0] # * check if can project from lists like this
#  let v2 = vs[1]
#  let v1 = peek (x)
#  let v2 = peek (y)
  let v1 : type k_v = ?? chan
  let v2 : type k_v = ?? chan

#  if v1 > v2:
#    <>
#  else: <>

#  chan ! ? chan
#  x
#  z
#  consume (x)
##  send (z, consume (x))

  if v1.key = 0-1 and v2.key = 0-1: # * i think "-" cannot be prefix
#    z ! ? x
    ? chan
    chan ! 5 # FIXME test
    send (z, consume (x))
    consume (y)
    <>
  else: if v1.key = 0-1:
#    z ! ? y
    send (z, consume (y))
#    <>
  else: if v2.key = 0-1:
#    z ! ? x
    send (z, consume (x))
#    <>
  else: if v1.key < v2.key:
#    z ! ? x
    send (z, consume (x))
#    <>
  else: if v2.key < v1.key:
#    z ! ? y
    send (z, consume (y))
#    <>
  else:
#    z ! v1 with value = v1.value + v2.value
#    send (z, 5) # need record update
    send (z, v1 with value = v1.value + v2.value)
#    ? x
#    ? y
    consume (x)
    consume (y)
    <>

#    # NOTE experimental area
#    #x := y
#    let v = x
  <> #x # FIXME should be <>
<|endoftext|>


<commit_before>/* Copyright (c) 2013-2015 Jeffrey Pfau
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "LoadSaveState.h"

#include "GameController.h"
#include "GamepadAxisEvent.h"
#include "GamepadButtonEvent.h"
#include "VFileDevice.h"

#include <QKeyEvent>
#include <QPainter>

extern "C" {
#include "gba/serialize.h"
#include "gba/video.h"
}

using namespace QGBA;

LoadSaveState::LoadSaveState(GameController* controller, QWidget* parent)
	: QWidget(parent)
	, m_controller(controller)
	, m_currentFocus(0)
{
	m_ui.setupUi(this);

	m_slots[0] = m_ui.state1;
	m_slots[1] = m_ui.state2;
	m_slots[2] = m_ui.state3;
	m_slots[3] = m_ui.state4;
	m_slots[4] = m_ui.state5;
	m_slots[5] = m_ui.state6;
	m_slots[6] = m_ui.state7;
	m_slots[7] = m_ui.state8;
	m_slots[8] = m_ui.state9;

	int i;
	for (i = 0; i < NUM_SLOTS; ++i) {
		loadState(i + 1);
		m_slots[i]->installEventFilter(this);
		connect(m_slots[i], &QAbstractButton::clicked, this, [this, i]() { triggerState(i + 1); });
	}

	QAction* escape = new QAction(this);
	escape->connect(escape, SIGNAL(triggered()), this, SLOT(close()));
	escape->setShortcut(QKeySequence("Esc"));
	escape->setShortcutContext(Qt::WidgetWithChildrenShortcut);
	addAction(escape);
}

void LoadSaveState::setMode(LoadSave mode) {
	m_mode = mode;
	QString text = mode == LoadSave::LOAD ? tr("Load State") : tr("Save State");
	setWindowTitle(text);
	m_ui.lsLabel->setText(text);
}

bool LoadSaveState::eventFilter(QObject* object, QEvent* event) {
	if (event->type() == QEvent::KeyPress) {
		int column = m_currentFocus % 3;
		int row = m_currentFocus / 3;
		switch (static_cast<QKeyEvent*>(event)->key()) {
		case Qt::Key_Up:
			row += 2;
			break;
		case Qt::Key_Down:
			row += 1;
			break;
		case Qt::Key_Left:
			column += 2;
			break;
		case Qt::Key_Right:
			column += 1;
			break;
		case Qt::Key_1:
		case Qt::Key_2:
		case Qt::Key_3:
		case Qt::Key_4:
		case Qt::Key_5:
		case Qt::Key_6:
		case Qt::Key_7:
		case Qt::Key_8:
		case Qt::Key_9:
			triggerState(static_cast<QKeyEvent*>(event)->key() - Qt::Key_1 + 1);
			break;
		case Qt::Key_Enter:
		case Qt::Key_Return:
			triggerState(m_currentFocus + 1);
			break;
		default:
			return false;
		}
		column %= 3;
		row %= 3;
		m_currentFocus = column + row * 3;
		m_slots[m_currentFocus]->setFocus();
		return true;
	}
	if (event->type() == QEvent::Enter) {
		int i;
		for (i = 0; i < 9; ++i) {
			if (m_slots[i] == object) {
				m_currentFocus = i;
				m_slots[m_currentFocus]->setFocus();
				return true;
			}
		}
	}
	if (event->type() == GamepadButtonEvent::Down() || event->type() == GamepadAxisEvent::Type()) {
		int column = m_currentFocus % 3;
		int row = m_currentFocus - column;
		GBAKey key = GBA_KEY_NONE;
		if (event->type() == GamepadButtonEvent::Down()) {
			key = static_cast<GamepadButtonEvent*>(event)->gbaKey();
		} else if (event->type() == GamepadAxisEvent::Type()) {
			GamepadAxisEvent* gae = static_cast<GamepadAxisEvent*>(event);
			if (gae->isNew()) {
				key = gae->gbaKey();
			} else {
				return false;
			}
		}
		switch (key) {
		case GBA_KEY_UP:
			row += 6;
			break;
		case GBA_KEY_DOWN:
			row += 3;
			break;
		case GBA_KEY_LEFT:
			column += 2;
			break;
		case GBA_KEY_RIGHT:
			column += 1;
			break;
		case GBA_KEY_B:
			event->accept();
			close();
			return true;
		case GBA_KEY_A:
		case GBA_KEY_START:
			event->accept();
			triggerState(m_currentFocus + 1);
			return true;
		default:
			return false;
		}
		column %= 3;
		row %= 9;
		m_currentFocus = column + row;
		m_slots[m_currentFocus]->setFocus();
		event->accept();
		return true;
	}
	return false;
}

void LoadSaveState::loadState(int slot) {
	GBAThread* thread = m_controller->thread();
	VFile* vf = GBAGetState(thread->gba, thread->stateDir, slot, false);
	if (!vf) {
		m_slots[slot - 1]->setText(tr("Empty"));
		return;
	}
	VFileDevice vdev(vf);
	QImage stateImage;
	stateImage.load(&vdev, "PNG");
	if (!stateImage.isNull()) {
		QPixmap statePixmap;
		statePixmap.convertFromImage(stateImage);
		m_slots[slot - 1]->setIcon(statePixmap);
		m_slots[slot - 1]->setText(QString());
	} else {
		m_slots[slot - 1]->setText(tr("Slot %1").arg(slot));
	}
}

void LoadSaveState::triggerState(int slot) {
	if (m_mode == LoadSave::SAVE) {
		m_controller->saveState(slot);
	} else {
		m_controller->loadState(slot);
	}
	close();
}

void LoadSaveState::closeEvent(QCloseEvent* event) {
	emit closed();
	QWidget::closeEvent(event);
}

void LoadSaveState::showEvent(QShowEvent* event) {
	m_slots[m_currentFocus]->setFocus();
	QWidget::showEvent(event);
}

void LoadSaveState::paintEvent(QPaintEvent*) {
	QPainter painter(this);
	QRect full(QPoint(), size());
	painter.drawPixmap(full, m_currentImage);
	painter.fillRect(full, QColor(0, 0, 0, 128));
}
<commit_msg>Qt: Initialize LoadStoreState mode<commit_after>/* Copyright (c) 2013-2015 Jeffrey Pfau
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "LoadSaveState.h"

#include "GameController.h"
#include "GamepadAxisEvent.h"
#include "GamepadButtonEvent.h"
#include "VFileDevice.h"

#include <QKeyEvent>
#include <QPainter>

extern "C" {
#include "gba/serialize.h"
#include "gba/video.h"
}

using namespace QGBA;

LoadSaveState::LoadSaveState(GameController* controller, QWidget* parent)
	: QWidget(parent)
	, m_controller(controller)
	, m_currentFocus(0)
	, m_mode(LoadSave::LOAD)
{
	m_ui.setupUi(this);

	m_slots[0] = m_ui.state1;
	m_slots[1] = m_ui.state2;
	m_slots[2] = m_ui.state3;
	m_slots[3] = m_ui.state4;
	m_slots[4] = m_ui.state5;
	m_slots[5] = m_ui.state6;
	m_slots[6] = m_ui.state7;
	m_slots[7] = m_ui.state8;
	m_slots[8] = m_ui.state9;

	int i;
	for (i = 0; i < NUM_SLOTS; ++i) {
		loadState(i + 1);
		m_slots[i]->installEventFilter(this);
		connect(m_slots[i], &QAbstractButton::clicked, this, [this, i]() { triggerState(i + 1); });
	}

	QAction* escape = new QAction(this);
	escape->connect(escape, SIGNAL(triggered()), this, SLOT(close()));
	escape->setShortcut(QKeySequence("Esc"));
	escape->setShortcutContext(Qt::WidgetWithChildrenShortcut);
	addAction(escape);
}

void LoadSaveState::setMode(LoadSave mode) {
	m_mode = mode;
	QString text = mode == LoadSave::LOAD ? tr("Load State") : tr("Save State");
	setWindowTitle(text);
	m_ui.lsLabel->setText(text);
}

bool LoadSaveState::eventFilter(QObject* object, QEvent* event) {
	if (event->type() == QEvent::KeyPress) {
		int column = m_currentFocus % 3;
		int row = m_currentFocus / 3;
		switch (static_cast<QKeyEvent*>(event)->key()) {
		case Qt::Key_Up:
			row += 2;
			break;
		case Qt::Key_Down:
			row += 1;
			break;
		case Qt::Key_Left:
			column += 2;
			break;
		case Qt::Key_Right:
			column += 1;
			break;
		case Qt::Key_1:
		case Qt::Key_2:
		case Qt::Key_3:
		case Qt::Key_4:
		case Qt::Key_5:
		case Qt::Key_6:
		case Qt::Key_7:
		case Qt::Key_8:
		case Qt::Key_9:
			triggerState(static_cast<QKeyEvent*>(event)->key() - Qt::Key_1 + 1);
			break;
		case Qt::Key_Enter:
		case Qt::Key_Return:
			triggerState(m_currentFocus + 1);
			break;
		default:
			return false;
		}
		column %= 3;
		row %= 3;
		m_currentFocus = column + row * 3;
		m_slots[m_currentFocus]->setFocus();
		return true;
	}
	if (event->type() == QEvent::Enter) {
		int i;
		for (i = 0; i < 9; ++i) {
			if (m_slots[i] == object) {
				m_currentFocus = i;
				m_slots[m_currentFocus]->setFocus();
				return true;
			}
		}
	}
	if (event->type() == GamepadButtonEvent::Down() || event->type() == GamepadAxisEvent::Type()) {
		int column = m_currentFocus % 3;
		int row = m_currentFocus - column;
		GBAKey key = GBA_KEY_NONE;
		if (event->type() == GamepadButtonEvent::Down()) {
			key = static_cast<GamepadButtonEvent*>(event)->gbaKey();
		} else if (event->type() == GamepadAxisEvent::Type()) {
			GamepadAxisEvent* gae = static_cast<GamepadAxisEvent*>(event);
			if (gae->isNew()) {
				key = gae->gbaKey();
			} else {
				return false;
			}
		}
		switch (key) {
		case GBA_KEY_UP:
			row += 6;
			break;
		case GBA_KEY_DOWN:
			row += 3;
			break;
		case GBA_KEY_LEFT:
			column += 2;
			break;
		case GBA_KEY_RIGHT:
			column += 1;
			break;
		case GBA_KEY_B:
			event->accept();
			close();
			return true;
		case GBA_KEY_A:
		case GBA_KEY_START:
			event->accept();
			triggerState(m_currentFocus + 1);
			return true;
		default:
			return false;
		}
		column %= 3;
		row %= 9;
		m_currentFocus = column + row;
		m_slots[m_currentFocus]->setFocus();
		event->accept();
		return true;
	}
	return false;
}

void LoadSaveState::loadState(int slot) {
	GBAThread* thread = m_controller->thread();
	VFile* vf = GBAGetState(thread->gba, thread->stateDir, slot, false);
	if (!vf) {
		m_slots[slot - 1]->setText(tr("Empty"));
		return;
	}
	VFileDevice vdev(vf);
	QImage stateImage;
	stateImage.load(&vdev, "PNG");
	if (!stateImage.isNull()) {
		QPixmap statePixmap;
		statePixmap.convertFromImage(stateImage);
		m_slots[slot - 1]->setIcon(statePixmap);
		m_slots[slot - 1]->setText(QString());
	} else {
		m_slots[slot - 1]->setText(tr("Slot %1").arg(slot));
	}
}

void LoadSaveState::triggerState(int slot) {
	if (m_mode == LoadSave::SAVE) {
		m_controller->saveState(slot);
	} else {
		m_controller->loadState(slot);
	}
	close();
}

void LoadSaveState::closeEvent(QCloseEvent* event) {
	emit closed();
	QWidget::closeEvent(event);
}

void LoadSaveState::showEvent(QShowEvent* event) {
	m_slots[m_currentFocus]->setFocus();
	QWidget::showEvent(event);
}

void LoadSaveState::paintEvent(QPaintEvent*) {
	QPainter painter(this);
	QRect full(QPoint(), size());
	painter.drawPixmap(full, m_currentImage);
	painter.fillRect(full, QColor(0, 0, 0, 128));
}
<|endoftext|>


<commit_before>/*
 *  MUI.cpp
 *  iPhoneEmptyExample
 *
 *  Created by hansi on 28.01.11.
 *  Copyright 2011 __MyCompanyName__. All rights reserved.
 *
 */

#include "MUI.h"
#include <Poco/Util/Application.h>

#if TARGET_OS_IPHONE
	#include "ofAppiOSWindow.h"
	#include <CoreFoundation/CoreFoundation.h>
#elif TARGET_OS_MAC
	#include "ofAppGLFWWindow.h
#elif _WIN32
	#include <windows.h>
	#include "ofAppGLFWWindow.h"
#endif

void mui_init(){
	#if TARGET_OS_IPHONE
	if( mui::MuiConfig::detectRetina ){
		ofAppiOSWindow * w = ofAppiOSWindow::getInstance();
		if( w->isRetinaEnabled() ){
			mui::MuiConfig::scaleFactor = 2;
			mui::MuiConfig::useRetinaAssets = true;
		}
	}
	#endif

	Poco::Path appPath;
	#if TARGET_OS_IPHONE
		// http://www.cocoabuilder.com/archive/cocoa/193451-finding-out-executable-location-from-c-program.html
		CFBundleRef bundle = CFBundleGetMainBundle();
		CFURLRef    url  = CFBundleCopyExecutableURL(bundle); // CFBundleCopyResourcesDirectoryURL(bundle);
		CFURLRef absolute = CFURLCopyAbsoluteURL(url);
		CFStringRef path  = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
		CFIndex    maxLength = CFStringGetMaximumSizeOfFileSystemRepresentation(path);
		char        *result = (char*)malloc(maxLength);

		if(result) {
			if(!CFStringGetFileSystemRepresentation(path,result, maxLength)) {
				free(result);
				result = NULL;
			}
		}

		CFRelease(path);
		CFRelease(url);
		CFRelease(absolute);
		appPath = Poco::Path(result);
		appPath = appPath.parent();
	#elif TARGET_OS_MAC
		// http://www.cocoabuilder.com/archive/cocoa/193451-finding-out-executable-location-from-c-program.html
		CFBundleRef bundle = CFBundleGetMainBundle();
		CFURLRef    url  = CFBundleCopyExecutableURL(bundle); // CFBundleCopyResourcesDirectoryURL(bundle);
		CFURLRef absolute = CFURLCopyAbsoluteURL(url);
		CFStringRef path  = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
		CFIndex    maxLength = CFStringGetMaximumSizeOfFileSystemRepresentation(path);
		char        *result = (char*)malloc(maxLength);

		if(result) {
			if(!CFStringGetFileSystemRepresentation(path,result, maxLength)) {
				free(result);
				result = NULL;
			}
		}

		CFRelease(path);
		CFRelease(url);
		CFRelease(absolute);
		appPath = Poco::Path(result);
		if(result != NULL ) free(result);
		appPath = appPath.parent().parent().pushDirectory("Resources");

		if( mui::MuiConfig::detectRetina ){
			ofAppGLFWWindow * window = dynamic_cast<ofAppGLFWWindow*>(ofGetWindowPtr());
			if( window != NULL ){
				mui::MuiConfig::scaleFactor = window->getPixelScreenCoordScale();
			}
		}
	#elif _WIN32
		if (mui::MuiConfig::detectRetina) {
			SetProcessDPIAware(); //true
			HDC screen = GetDC(NULL);
			double hPixelsPerInch = GetDeviceCaps(screen, LOGPIXELSX);
			double vPixelsPerInch = GetDeviceCaps(screen, LOGPIXELSY);
			ReleaseDC(NULL, screen);
			float dpi = (hPixelsPerInch + vPixelsPerInch) * 0.5/96.0;
			mui::MuiConfig::scaleFactor = dpi;
			cout << "scale factor = " << dpi << endl;
		}
		appPath = Poco::Path(ofToDataPath("./", true));
	#else
		appPath = Poco::Path(ofToDataPath("./", true));
	#endif

	mui::MuiConfig::dataPath = appPath.absolute();
	mui::Helpers::getFontStash().setup(1024);
	mui::Helpers::getFontStash().pixelDensity = mui::MuiConfig::scaleFactor;
	mui::Helpers::getFontStash().fontScale = 1.3;
}

<commit_msg>huh, how did this happen?<commit_after>/*
 *  MUI.cpp
 *  iPhoneEmptyExample
 *
 *  Created by hansi on 28.01.11.
 *  Copyright 2011 __MyCompanyName__. All rights reserved.
 *
 */

#include "MUI.h"
#include <Poco/Util/Application.h>

#if TARGET_OS_IPHONE
	#include "ofAppiOSWindow.h"
	#include <CoreFoundation/CoreFoundation.h>
#elif TARGET_OS_MAC
	#include "ofAppGLFWWindow.h"
#elif _WIN32
	#include <windows.h>
	#include "ofAppGLFWWindow.h"
#endif

void mui_init(){
	#if TARGET_OS_IPHONE
	if( mui::MuiConfig::detectRetina ){
		ofAppiOSWindow * w = ofAppiOSWindow::getInstance();
		if( w->isRetinaEnabled() ){
			mui::MuiConfig::scaleFactor = 2;
			mui::MuiConfig::useRetinaAssets = true;
		}
	}
	#endif

	Poco::Path appPath;
	#if TARGET_OS_IPHONE
		// http://www.cocoabuilder.com/archive/cocoa/193451-finding-out-executable-location-from-c-program.html
		CFBundleRef bundle = CFBundleGetMainBundle();
		CFURLRef    url  = CFBundleCopyExecutableURL(bundle); // CFBundleCopyResourcesDirectoryURL(bundle);
		CFURLRef absolute = CFURLCopyAbsoluteURL(url);
		CFStringRef path  = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
		CFIndex    maxLength = CFStringGetMaximumSizeOfFileSystemRepresentation(path);
		char        *result = (char*)malloc(maxLength);

		if(result) {
			if(!CFStringGetFileSystemRepresentation(path,result, maxLength)) {
				free(result);
				result = NULL;
			}
		}

		CFRelease(path);
		CFRelease(url);
		CFRelease(absolute);
		appPath = Poco::Path(result);
		appPath = appPath.parent();
	#elif TARGET_OS_MAC
		// http://www.cocoabuilder.com/archive/cocoa/193451-finding-out-executable-location-from-c-program.html
		CFBundleRef bundle = CFBundleGetMainBundle();
		CFURLRef    url  = CFBundleCopyExecutableURL(bundle); // CFBundleCopyResourcesDirectoryURL(bundle);
		CFURLRef absolute = CFURLCopyAbsoluteURL(url);
		CFStringRef path  = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
		CFIndex    maxLength = CFStringGetMaximumSizeOfFileSystemRepresentation(path);
		char        *result = (char*)malloc(maxLength);

		if(result) {
			if(!CFStringGetFileSystemRepresentation(path,result, maxLength)) {
				free(result);
				result = NULL;
			}
		}

		CFRelease(path);
		CFRelease(url);
		CFRelease(absolute);
		appPath = Poco::Path(result);
		if(result != NULL ) free(result);
		appPath = appPath.parent().parent().pushDirectory("Resources");

		if( mui::MuiConfig::detectRetina ){
			ofAppGLFWWindow * window = dynamic_cast<ofAppGLFWWindow*>(ofGetWindowPtr());
			if( window != NULL ){
				mui::MuiConfig::scaleFactor = window->getPixelScreenCoordScale();
			}
		}
	#elif _WIN32
		if (mui::MuiConfig::detectRetina) {
			SetProcessDPIAware(); //true
			HDC screen = GetDC(NULL);
			double hPixelsPerInch = GetDeviceCaps(screen, LOGPIXELSX);
			double vPixelsPerInch = GetDeviceCaps(screen, LOGPIXELSY);
			ReleaseDC(NULL, screen);
			float dpi = (hPixelsPerInch + vPixelsPerInch) * 0.5/96.0;
			mui::MuiConfig::scaleFactor = dpi;
			cout << "scale factor = " << dpi << endl;
		}
		appPath = Poco::Path(ofToDataPath("./", true));
	#else
		appPath = Poco::Path(ofToDataPath("./", true));
	#endif

	mui::MuiConfig::dataPath = appPath.absolute();
	mui::Helpers::getFontStash().setup(1024);
	mui::Helpers::getFontStash().pixelDensity = mui::MuiConfig::scaleFactor;
	mui::Helpers::getFontStash().fontScale = 1.3;
}

<|endoftext|>


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

 This file is part of the GLC-lib library.
 Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
 Version 1.0.0, packaged on August, 2008.

 http://glc-lib.sourceforge.net

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

 GLC-lib 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 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GLC-lib; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*****************************************************************************/

//! \file glc_shader.cpp implementation of the GLC_Shader class.

#include "glc_shader.h"
#include <QTextStream>
#include "glc_exception.h"

QStack<GLuint> GLC_Shader::m_ProgrammStack;

GLuint GLC_Shader::m_CurrentProgramm= 0;

GLC_Shader::GLC_Shader()
: m_VertexByteArray()
, m_VertexShader(0)
, m_FragmentByteArray()
, m_FragmentShader(0)
, m_ProgramShader(0)
{
}

// Construct shader with specifie vertex and fragment
GLC_Shader::GLC_Shader(QFile& vertex, QFile& fragment)
: m_VertexByteArray()
, m_VertexShader(0)
, m_FragmentByteArray()
, m_FragmentShader(0)
, m_ProgramShader(0)
{
	setVertexAndFragmentShader(vertex, fragment);
}

// Copy constructor
GLC_Shader::GLC_Shader(const GLC_Shader& shader)
: m_VertexByteArray(shader.m_VertexByteArray)
, m_VertexShader(0)
, m_FragmentByteArray(shader.m_FragmentByteArray)
, m_FragmentShader(0)
, m_ProgramShader(0)

{

}

GLC_Shader::~GLC_Shader()
{
	//qDebug() << "GLC_Shader::~GLC_Shader";
	if (m_ProgramShader != 0)
	{
		// Test if the shader is the current one
		if (m_CurrentProgramm == m_ProgramShader)
		{
			qDebug() << "Warning deleting current shader";
		}
		//removing shader id from the stack
		if (m_ProgrammStack.contains(m_ProgramShader))
		{
			int indexToDelete= m_ProgrammStack.indexOf(m_ProgramShader);
			while (indexToDelete != -1)
			{
				m_ProgrammStack.remove(indexToDelete);
				indexToDelete= m_ProgrammStack.indexOf(m_ProgramShader);
			}
		}
		// Detach shaders associated with the programm
		glDetachShader(m_ProgramShader, m_VertexShader);
		glDetachShader(m_ProgramShader, m_FragmentShader);
		// Delete the shader
		glDeleteShader(m_VertexShader);
		glDeleteShader(m_FragmentShader);
		// Delete the programm
		glDeleteProgram(m_ProgramShader);
	}
	// If m_ProgramShader == 0 then there is no vertex and fragment shader
}

//////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////

// Return true if the shader can be deleted
bool GLC_Shader::canBeDeleted() const
{
	return m_CurrentProgramm != m_ProgramShader;
}

//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////

// Use this shader programm
void GLC_Shader::useProgramm()
{
	// Program shader must be valid
	Q_ASSERT(0 != m_ProgramShader);
	// Test if the program shader is not already the current one
	if (m_CurrentProgramm != m_ProgramShader)
	{
		if (m_CurrentProgramm != 0)
		{
			m_ProgrammStack.push(m_CurrentProgramm);
		}
		m_CurrentProgramm= m_ProgramShader;
		glUseProgram(m_CurrentProgramm);
	}
}

// Use previous programm shader
void GLC_Shader::usePreviousProgramm()
{
	if (m_ProgrammStack.isEmpty())
	{
		m_CurrentProgramm= 0;
	}
	else
	{
		m_CurrentProgramm= m_ProgrammStack.pop();
	}
	glUseProgram(m_CurrentProgramm);
}
// Compile and attach shaders to a program shader
void GLC_Shader::createAndCompileProgrammShader()
{
	Q_ASSERT(0 == m_ProgramShader);

	createAndLinkVertexShader();
	createAndLinkFragmentShader();

	m_ProgramShader = glCreateProgram();
	glAttachShader(m_ProgramShader, m_VertexShader);
	glAttachShader(m_ProgramShader, m_FragmentShader);

	glLinkProgram(m_ProgramShader);

	// Check if the program as been linked successfully
	GLint params;
	glGetProgramiv(m_ProgramShader, GL_LINK_STATUS, &params);
	if (params != GL_TRUE)
	{
		QString message("GLC_Shader::setVertexAndFragmentShader Failed to link program ");
		GLC_Exception exception(message);
		throw(exception);
	}
}

// Create and compile vertex shader
void GLC_Shader::createAndLinkVertexShader()
{
	const char* pVertexShaderData= m_VertexByteArray.data();

	m_VertexShader = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(m_VertexShader, 1, &pVertexShaderData, NULL);
	glCompileShader(m_VertexShader);

	// Check if the shader compilation is successfull
	GLint params;
	glGetShaderiv(m_VertexShader, GL_COMPILE_STATUS, &params);
	if (params != GL_TRUE)
	{
		QString message("GLC_Shader::createAndLinkVertexShader Failed to compile Vertex shader");
		GLC_Exception exception(message);
		throw(exception);
	}
}

// Create and compile fragment shader
void GLC_Shader::createAndLinkFragmentShader()
{
	const char* pFragmentShaderData= m_FragmentByteArray.data();

	m_FragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(m_FragmentShader, 1, &pFragmentShaderData, NULL);
	glCompileShader(m_FragmentShader);

	// Check if the shader compilation is successfull
	GLint params;
	glGetShaderiv(m_FragmentShader, GL_COMPILE_STATUS, &params);
	if (params != GL_TRUE)
	{
		QString message("GLC_Shader::createAndLinkFragmentShader Failed to compile fragment shader");
		GLC_Exception exception(message);
		throw(exception);
	}
}

//////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////

// Set Vertex and fragment shaders
void GLC_Shader::setVertexAndFragmentShader(QFile& vertexFile, QFile& fragmentFile)
{
	setVertexShader(vertexFile);
	setFragmentShader(fragmentFile);
}

// Replace this shader by a copy of another shader
void GLC_Shader::replaceShader(GLC_Shader& sourceShader)
{
	Q_ASSERT(isUsable() == sourceShader.isUsable());

	m_VertexByteArray= sourceShader.m_VertexByteArray;
	m_FragmentByteArray= sourceShader.m_FragmentByteArray;

	if (isUsable())
	{
		const GLuint oldShaderId= m_ProgramShader;

		// Detach shaders associated with the programm
		glDetachShader(m_ProgramShader, m_VertexShader);
		glDetachShader(m_ProgramShader, m_FragmentShader);
		// Delete the shader
		glDeleteShader(m_VertexShader);
		glDeleteShader(m_FragmentShader);
		// Delete the programm
		glDeleteProgram(m_ProgramShader);

		// Init shaders ID
		m_ProgramShader= 0;
		m_VertexShader= 0;
		m_FragmentShader= 0;

		// Rebuilt shader
		createAndCompileProgrammShader();

		// Update the shader program stack
		if (m_ProgrammStack.contains(oldShaderId))
		{
			int indexToReplace= m_ProgrammStack.indexOf(oldShaderId);
			while (indexToReplace != -1)
			{
				m_ProgrammStack.replace(indexToReplace, m_ProgramShader);
				indexToReplace= m_ProgrammStack.indexOf(oldShaderId);
			}
		}
		// Check the value of current shader
		if (oldShaderId == m_CurrentProgramm)
		{
			m_CurrentProgramm= m_ProgramShader;
			// Use the new One
			glUseProgram(m_CurrentProgramm);
		}
	}
}

//////////////////////////////////////////////////////////////////////
// Private services Functions
//////////////////////////////////////////////////////////////////////
// Set Vertex shader
void GLC_Shader::setVertexShader(QFile& vertexFile)
{
	Q_ASSERT(0 == m_ProgramShader);
	m_VertexByteArray= readShaderFile(vertexFile);
}

// Set fragment shaders
void GLC_Shader::setFragmentShader(QFile& fragmentFile)
{
	Q_ASSERT(0 == m_ProgramShader);
	m_FragmentByteArray= readShaderFile(fragmentFile);
}

// Return char* of an Ascii file
QByteArray GLC_Shader::readShaderFile(QFile& shaderFile)
{
	if (!shaderFile.open(QIODevice::ReadOnly))
	{
		QString message(QString("GLC_Shader::readShaderFile Failed to open file : ") + shaderFile.fileName());
		GLC_Exception exception(message);
		throw(exception);
	}
	QByteArray result(shaderFile.readAll());
	result.append('\0');
	return result;
}

<commit_msg>presentation Update (Ganymede)<commit_after>/****************************************************************************

 This file is part of the GLC-lib library.
 Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net)
 Version 1.0.0, packaged on August, 2008.

 http://glc-lib.sourceforge.net

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

 GLC-lib 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 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GLC-lib; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*****************************************************************************/

//! \file glc_shader.cpp implementation of the GLC_Shader class.

#include "glc_shader.h"
#include <QTextStream>
#include <QMutexLocker>
#include "glc_exception.h"

// Static member initialization
QStack<GLuint> GLC_Shader::m_ProgrammStack;

GLuint GLC_Shader::m_CurrentProgramm= 0;

QMutex GLC_Shader::m_Mutex;

GLC_Shader::GLC_Shader()
: m_VertexByteArray()
, m_VertexShader(0)
, m_FragmentByteArray()
, m_FragmentShader(0)
, m_ProgramShader(0)
{
}

// Construct shader with specifie vertex and fragment
GLC_Shader::GLC_Shader(QFile& vertex, QFile& fragment)
: m_VertexByteArray()
, m_VertexShader(0)
, m_FragmentByteArray()
, m_FragmentShader(0)
, m_ProgramShader(0)
{
	setVertexAndFragmentShader(vertex, fragment);
}

// Copy constructor
GLC_Shader::GLC_Shader(const GLC_Shader& shader)
: m_VertexByteArray(shader.m_VertexByteArray)
, m_VertexShader(0)
, m_FragmentByteArray(shader.m_FragmentByteArray)
, m_FragmentShader(0)
, m_ProgramShader(0)

{

}

GLC_Shader::~GLC_Shader()
{
	//qDebug() << "GLC_Shader::~GLC_Shader";
	if (m_ProgramShader != 0)
	{
		// Test if the shader is the current one
		if (m_CurrentProgramm == m_ProgramShader)
		{
			qDebug() << "Warning deleting current shader";
		}
		//removing shader id from the stack
		if (m_ProgrammStack.contains(m_ProgramShader))
		{
			int indexToDelete= m_ProgrammStack.indexOf(m_ProgramShader);
			while (indexToDelete != -1)
			{
				m_ProgrammStack.remove(indexToDelete);
				indexToDelete= m_ProgrammStack.indexOf(m_ProgramShader);
			}
		}
		// Detach shader associated with the program
		glDetachShader(m_ProgramShader, m_VertexShader);
		glDetachShader(m_ProgramShader, m_FragmentShader);
		// Delete the shader
		glDeleteShader(m_VertexShader);
		glDeleteShader(m_FragmentShader);
		// Delete the program
		glDeleteProgram(m_ProgramShader);
	}
	// If m_ProgramShader == 0 then there is no vertex and fragment shader
}

//////////////////////////////////////////////////////////////////////
// Get Functions
//////////////////////////////////////////////////////////////////////

// Return true if the shader can be deleted
bool GLC_Shader::canBeDeleted() const
{
	return m_CurrentProgramm != m_ProgramShader;
}

//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////

// Use this shader programm
void GLC_Shader::use()
{
	// Program shader must be valid
	Q_ASSERT(0 != m_ProgramShader);
	QMutexLocker locker(&m_Mutex);
	// Test if the program shader is not already the current one
	if (m_CurrentProgramm != m_ProgramShader)
	{
		if (m_CurrentProgramm != 0)
		{
			m_ProgrammStack.push(m_CurrentProgramm);
		}
		m_CurrentProgramm= m_ProgramShader;
		glUseProgram(m_CurrentProgramm);
	}
}

// Use previous program shader
void GLC_Shader::unuse()
{
	QMutexLocker locker(&m_Mutex);
	if (m_ProgrammStack.isEmpty())
	{
		m_CurrentProgramm= 0;
	}
	else
	{
		m_CurrentProgramm= m_ProgrammStack.pop();
	}
	glUseProgram(m_CurrentProgramm);
}
// Compile and attach shader to a program shader
void GLC_Shader::createAndCompileProgrammShader()
{
	Q_ASSERT(0 == m_ProgramShader);

	createAndLinkVertexShader();
	createAndLinkFragmentShader();

	m_ProgramShader = glCreateProgram();
	glAttachShader(m_ProgramShader, m_VertexShader);
	glAttachShader(m_ProgramShader, m_FragmentShader);

	glLinkProgram(m_ProgramShader);

	// Check if the program as been linked successfully
	GLint params;
	glGetProgramiv(m_ProgramShader, GL_LINK_STATUS, &params);
	if (params != GL_TRUE)
	{
		QString message("GLC_Shader::setVertexAndFragmentShader Failed to link program ");
		GLC_Exception exception(message);
		throw(exception);
	}
}

// Create and compile vertex shader
void GLC_Shader::createAndLinkVertexShader()
{
	const char* pVertexShaderData= m_VertexByteArray.data();

	m_VertexShader = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(m_VertexShader, 1, &pVertexShaderData, NULL);
	glCompileShader(m_VertexShader);

	// Check if the shader compilation is successful
	GLint params;
	glGetShaderiv(m_VertexShader, GL_COMPILE_STATUS, &params);
	if (params != GL_TRUE)
	{
		QString message("GLC_Shader::createAndLinkVertexShader Failed to compile Vertex shader");
		GLC_Exception exception(message);
		throw(exception);
	}
}

// Create and compile fragment shader
void GLC_Shader::createAndLinkFragmentShader()
{
	const char* pFragmentShaderData= m_FragmentByteArray.data();

	m_FragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
	glShaderSource(m_FragmentShader, 1, &pFragmentShaderData, NULL);
	glCompileShader(m_FragmentShader);

	// Check if the shader compilation is successful
	GLint params;
	glGetShaderiv(m_FragmentShader, GL_COMPILE_STATUS, &params);
	if (params != GL_TRUE)
	{
		QString message("GLC_Shader::createAndLinkFragmentShader Failed to compile fragment shader");
		GLC_Exception exception(message);
		throw(exception);
	}
}

//////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////

// Set Vertex and fragment shader
void GLC_Shader::setVertexAndFragmentShader(QFile& vertexFile, QFile& fragmentFile)
{
	setVertexShader(vertexFile);
	setFragmentShader(fragmentFile);
}

// Replace this shader by a copy of another shader
void GLC_Shader::replaceShader(GLC_Shader& sourceShader)
{
	Q_ASSERT(isUsable() == sourceShader.isUsable());

	m_VertexByteArray= sourceShader.m_VertexByteArray;
	m_FragmentByteArray= sourceShader.m_FragmentByteArray;

	if (isUsable())
	{
		const GLuint oldShaderId= m_ProgramShader;

		// Detach shader associated with the program
		glDetachShader(m_ProgramShader, m_VertexShader);
		glDetachShader(m_ProgramShader, m_FragmentShader);
		// Delete the shader
		glDeleteShader(m_VertexShader);
		glDeleteShader(m_FragmentShader);
		// Delete the program
		glDeleteProgram(m_ProgramShader);

		// Init shader ID
		m_ProgramShader= 0;
		m_VertexShader= 0;
		m_FragmentShader= 0;

		// Rebuilt shader
		createAndCompileProgrammShader();

		// Update the shader program stack
		if (m_ProgrammStack.contains(oldShaderId))
		{
			int indexToReplace= m_ProgrammStack.indexOf(oldShaderId);
			while (indexToReplace != -1)
			{
				m_ProgrammStack.replace(indexToReplace, m_ProgramShader);
				indexToReplace= m_ProgrammStack.indexOf(oldShaderId);
			}
		}
		// Check the value of current shader
		if (oldShaderId == m_CurrentProgramm)
		{
			m_CurrentProgramm= m_ProgramShader;
			// Use the new One
			glUseProgram(m_CurrentProgramm);
		}
	}
}

//////////////////////////////////////////////////////////////////////
// Private services Functions
//////////////////////////////////////////////////////////////////////
// Set Vertex shader
void GLC_Shader::setVertexShader(QFile& vertexFile)
{
	Q_ASSERT(0 == m_ProgramShader);
	m_VertexByteArray= readShaderFile(vertexFile);
}

// Set fragment shader
void GLC_Shader::setFragmentShader(QFile& fragmentFile)
{
	Q_ASSERT(0 == m_ProgramShader);
	m_FragmentByteArray= readShaderFile(fragmentFile);
}

// Return char* of an Ascii file
QByteArray GLC_Shader::readShaderFile(QFile& shaderFile)
{
	if (!shaderFile.open(QIODevice::ReadOnly))
	{
		QString message(QString("GLC_Shader::readShaderFile Failed to open file : ") + shaderFile.fileName());
		GLC_Exception exception(message);
		throw(exception);
	}
	QByteArray result(shaderFile.readAll());
	result.append('\0');
	return result;
}

<|endoftext|>


<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2014
Raffaello D. Di Napoli

This file is part of Application-Building Components (henceforth referred to as ABC).

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

ABC 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 General Public
License for more details.

You should have received a copy of the GNU General Public License along with ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

/** DOC:0101 Hello World example

This is a basic usage example of ABC; all it does is display the canonical “Hello World” text, then
it terminates. See the source code for line-by-line comments.
*/

// This should always be the first file included in any C++ source using ABC.
#include <abc.hxx>
// This needs to be included in the .cxx file that defines the application class for the program –
// see below.
#include <abc/app.hxx>
// This provides abc::io::text::stdout() and stdin(), which allow basic text interactivity for the
// program.
#include <abc/io/text/file.hxx>
// ABC does not use “using” directives in its sources or header files; if you want such convenience,
// you have to write it yourself in your own source files.
using namespace abc;

////////////////////////////////////////////////////////////////////////////////////////////////////
// example_app

/** This is a basic application class. The ABC_APP_CLASS() statement (below) indicates that this
class shall be instantiated as soon as the program is started, and its main() method should be
invoked immediately afterwards; see [DOC:1063 Application startup and abc::app].
*/
class example_app :
   public app {
public:

   /** This method is invoked when the program starts; returning from this method causes the end of
   the program.

   vsArgs
      This vector contains all the arguments that were provided to the program via command line.
   return
      The return value of this method will be available to the parent process as this program’s
      return value, accessible in a shell/command prompt as $? (Linux/POSIX) or %ERRORLEVEL%
      (Win32).
   */
   virtual int main(mvector<istr const> const & vsArgs) {
      // This should be the first line of every function/method; it allows to inspect the values of
      // the method’s arguments when an exception is raised during the execution of the method.
      ABC_TRACE_FN((this, vsArgs));

      // Write “Hello World” into the stdout text writer object.
      io::text::stdout()->write_line(SL("Hello World"));

      // Make this program return 0 to the parent process.
      return 0;
   }
};

ABC_APP_CLASS(example_app)

<commit_msg>Rename example_app to hello_world_app<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2014
Raffaello D. Di Napoli

This file is part of Application-Building Components (henceforth referred to as ABC).

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

ABC 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 General Public
License for more details.

You should have received a copy of the GNU General Public License along with ABC. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

/** DOC:0101 Hello World example

This is a basic usage example of ABC; all it does is display the canonical “Hello World” text, then
it terminates. See the source code for line-by-line comments.
*/

// This should always be the first file included in any C++ source using ABC.
#include <abc.hxx>
// This needs to be included in the .cxx file that defines the application class for the program –
// see below.
#include <abc/app.hxx>
// This provides abc::io::text::stdout() and stdin(), which allow basic text interactivity for the
// program.
#include <abc/io/text/file.hxx>
// ABC does not use “using” directives in its sources or header files; if you want such convenience,
// you have to write it yourself in your own source files.
using namespace abc;

////////////////////////////////////////////////////////////////////////////////////////////////////
// example_app

/** This is a basic application class. The ABC_APP_CLASS() statement (below) indicates that this
class shall be instantiated as soon as the program is started, and its main() method should be
invoked immediately afterwards; see [DOC:1063 Application startup and abc::app].
*/
class hello_world_app :
   public app {
public:

   /** This method is invoked when the program starts; returning from this method causes the end of
   the program.

   vsArgs
      This vector contains all the arguments that were provided to the program via command line.
   return
      The return value of this method will be available to the parent process as this program’s
      return value, accessible in a shell/command prompt as $? (Linux/POSIX) or %ERRORLEVEL%
      (Win32).
   */
   virtual int main(mvector<istr const> const & vsArgs) {
      // This should be the first line of every function/method; it allows to inspect the values of
      // the method’s arguments when an exception is raised during the execution of the method.
      ABC_TRACE_FN((this, vsArgs));

      // Write “Hello World” into the stdout text writer object.
      io::text::stdout()->write_line(SL("Hello World"));

      // Make this program return 0 to the parent process.
      return 0;
   }
};

ABC_APP_CLASS(hello_world_app)

<|endoftext|>