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

#ifndef _XMLOFF_XMLINDEXBIBLIOGRAPHYENTRYCONTEXT_HXX_
#include "XMLIndexBibliographyEntryContext.hxx"
#endif

#ifndef _XMLOFF_XMLINDEXTEMPLATECONTEXT_HXX_
#include "XMLIndexTemplateContext.hxx"
#endif

#ifndef _XMLOFF_XMLICTXT_HXX
#include "xmlictxt.hxx"
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif

#ifndef _XMLOFF_TEXTIMP_HXX_
#include "txtimp.hxx"
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif

#ifndef _XMLOFF_XMLKYWD_HXX
#include "xmlkywd.hxx"
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif

#ifndef _COM_SUN_STAR_TEXT_BIBLIOGRAPHYDATAFIELD_HPP_
#include <com/sun/star/text/BibliographyDataField.hpp>
#endif

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

using ::rtl::OUString;
using ::com::sun::star::beans::PropertyValue;
using ::com::sun::star::beans::PropertyValues;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Any;
using ::com::sun::star::xml::sax::XAttributeList;

const sal_Char sAPI_TokenType[] = "TokenType";
const sal_Char sAPI_CharacterStyleName[] = "CharacterStyleName";

TYPEINIT1( XMLIndexBibliographyEntryContext, XMLIndexSimpleEntryContext);

XMLIndexBibliographyEntryContext::XMLIndexBibliographyEntryContext(
    SvXMLImport& rImport,
    XMLIndexTemplateContext& rTemplate,
    sal_uInt16 nPrfx,
    const OUString& rLocalName ) :
        XMLIndexSimpleEntryContext(rImport,
                                   rTemplate.sTokenBibliographyDataField,
                                   rTemplate,
                                   nPrfx, rLocalName),
        nBibliographyInfo(BibliographyDataField::IDENTIFIER),
        bBibliographyInfoOK(sal_False)
{
}

XMLIndexBibliographyEntryContext::~XMLIndexBibliographyEntryContext()
{
}

static const SvXMLEnumMapEntry aBibliographyDataFieldMap[] =
{
    { sXML_address,             BibliographyDataField::ADDRESS },
    { sXML_annote,              BibliographyDataField::ANNOTE },
    { sXML_author,              BibliographyDataField::AUTHOR },
    { sXML_bibiliographic_type, BibliographyDataField::BIBILIOGRAPHIC_TYPE },
    { sXML_booktitle,           BibliographyDataField::BOOKTITLE },
    { sXML_chapter,             BibliographyDataField::CHAPTER },
    { sXML_custom1,             BibliographyDataField::CUSTOM1 },
    { sXML_custom2,             BibliographyDataField::CUSTOM2 },
    { sXML_custom3,             BibliographyDataField::CUSTOM3 },
    { sXML_custom4,             BibliographyDataField::CUSTOM4 },
    { sXML_custom5,             BibliographyDataField::CUSTOM5 },
    { sXML_edition,             BibliographyDataField::EDITION },
    { sXML_editor,              BibliographyDataField::EDITOR },
    { sXML_howpublished,        BibliographyDataField::HOWPUBLISHED },
    { sXML_identifier,          BibliographyDataField::IDENTIFIER },
    { sXML_institution,         BibliographyDataField::INSTITUTION },
    { sXML_isbn,                BibliographyDataField::ISBN },
    { sXML_journal,             BibliographyDataField::JOURNAL },
    { sXML_month,               BibliographyDataField::MONTH },
    { sXML_note,                BibliographyDataField::NOTE },
    { sXML_number,              BibliographyDataField::NUMBER },
    { sXML_organizations,       BibliographyDataField::ORGANIZATIONS },
    { sXML_pages,               BibliographyDataField::PAGES },
    { sXML_publisher,           BibliographyDataField::PUBLISHER },
    { sXML_report_type,         BibliographyDataField::REPORT_TYPE },
    { sXML_school,              BibliographyDataField::SCHOOL },
    { sXML_series,              BibliographyDataField::SERIES },
    { sXML_title,               BibliographyDataField::TITLE },
    { sXML_url,                 BibliographyDataField::URL },
    { sXML_volume,              BibliographyDataField::VOLUME },
    { sXML_year,                BibliographyDataField::YEAR },
    { NULL, NULL }
};

void XMLIndexBibliographyEntryContext::StartElement(
    const Reference<XAttributeList> & xAttrList)
{
    // handle both, style name and bibliography info
    sal_Int32 nLength = xAttrList->getLength();
    for(sal_Int32 nAttr = 0; nAttr < nLength; nAttr++)
    {
        OUString sLocalName;
        sal_uInt16 nPrefix = GetImport().GetNamespaceMap().
            GetKeyByAttrName( xAttrList->getNameByIndex(nAttr),
                              &sLocalName );
        if (XML_NAMESPACE_TEXT == nPrefix)
        {
            if (sLocalName.equalsAsciiL(sXML_style_name,
                                    sizeof(sXML_style_name)-1))
            {
                sCharStyleName = xAttrList->getValueByIndex(nAttr);
                bCharStyleNameOK = sal_True;
            }
            else if (sLocalName.equalsAsciiL(sXML_bibliography_data_field,
                                    sizeof(sXML_bibliography_data_field)-1))
            {
                sal_uInt16 nTmp;
                if (SvXMLUnitConverter::convertEnum(
                    nTmp, xAttrList->getValueByIndex(nAttr),
                    aBibliographyDataFieldMap))
                {
                    nBibliographyInfo = nTmp;
                    bBibliographyInfoOK = sal_True;
                }
            }
        }
    }

    // if we have a style name, set it!
    if (bCharStyleNameOK)
    {
        nValues++;
    }

    // always bibliography; else element is not valid
    nValues++;
}

void XMLIndexBibliographyEntryContext::EndElement()
{
    // only valid, if we have bibliography info
    if (bBibliographyInfoOK)
    {
        XMLIndexSimpleEntryContext::EndElement();
    }
}

void XMLIndexBibliographyEntryContext::FillPropertyValues(
    ::com::sun::star::uno::Sequence<
        ::com::sun::star::beans::PropertyValue> & rValues)
{
    // entry name and (optionally) style name in parent class
    XMLIndexSimpleEntryContext::FillPropertyValues(rValues);

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

#ifndef _XMLOFF_XMLINDEXBIBLIOGRAPHYENTRYCONTEXT_HXX_
#include "XMLIndexBibliographyEntryContext.hxx"
#endif

#ifndef _XMLOFF_XMLINDEXTEMPLATECONTEXT_HXX_
#include "XMLIndexTemplateContext.hxx"
#endif

#ifndef _XMLOFF_XMLICTXT_HXX
#include "xmlictxt.hxx"
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include "xmlimp.hxx"
#endif

#ifndef _XMLOFF_TEXTIMP_HXX_
#include "txtimp.hxx"
#endif

#ifndef _XMLOFF_NMSPMAP_HXX
#include "nmspmap.hxx"
#endif

#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif

#ifndef _XMLOFF_XMLKYWD_HXX
#include "xmlkywd.hxx"
#endif

#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif

#ifndef _COM_SUN_STAR_TEXT_BIBLIOGRAPHYDATAFIELD_HPP_
#include <com/sun/star/text/BibliographyDataField.hpp>
#endif

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

using ::rtl::OUString;
using ::com::sun::star::beans::PropertyValue;
using ::com::sun::star::beans::PropertyValues;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Any;
using ::com::sun::star::xml::sax::XAttributeList;

const sal_Char sAPI_TokenType[] = "TokenType";
const sal_Char sAPI_CharacterStyleName[] = "CharacterStyleName";

TYPEINIT1( XMLIndexBibliographyEntryContext, XMLIndexSimpleEntryContext);

XMLIndexBibliographyEntryContext::XMLIndexBibliographyEntryContext(
    SvXMLImport& rImport,
    XMLIndexTemplateContext& rTemplate,
    sal_uInt16 nPrfx,
    const OUString& rLocalName ) :
        XMLIndexSimpleEntryContext(rImport,
                                   rTemplate.sTokenBibliographyDataField,
                                   rTemplate,
                                   nPrfx, rLocalName),
        nBibliographyInfo(BibliographyDataField::IDENTIFIER),
        bBibliographyInfoOK(sal_False)
{
}

XMLIndexBibliographyEntryContext::~XMLIndexBibliographyEntryContext()
{
}

const SvXMLEnumMapEntry aBibliographyDataFieldMap[] =
{
    { sXML_address,             BibliographyDataField::ADDRESS },
    { sXML_annote,              BibliographyDataField::ANNOTE },
    { sXML_author,              BibliographyDataField::AUTHOR },
    { sXML_bibiliographic_type, BibliographyDataField::BIBILIOGRAPHIC_TYPE },
    { sXML_booktitle,           BibliographyDataField::BOOKTITLE },
    { sXML_chapter,             BibliographyDataField::CHAPTER },
    { sXML_custom1,             BibliographyDataField::CUSTOM1 },
    { sXML_custom2,             BibliographyDataField::CUSTOM2 },
    { sXML_custom3,             BibliographyDataField::CUSTOM3 },
    { sXML_custom4,             BibliographyDataField::CUSTOM4 },
    { sXML_custom5,             BibliographyDataField::CUSTOM5 },
    { sXML_edition,             BibliographyDataField::EDITION },
    { sXML_editor,              BibliographyDataField::EDITOR },
    { sXML_howpublished,        BibliographyDataField::HOWPUBLISHED },
    { sXML_identifier,          BibliographyDataField::IDENTIFIER },
    { sXML_institution,         BibliographyDataField::INSTITUTION },
    { sXML_isbn,                BibliographyDataField::ISBN },
    { sXML_journal,             BibliographyDataField::JOURNAL },
    { sXML_month,               BibliographyDataField::MONTH },
    { sXML_note,                BibliographyDataField::NOTE },
    { sXML_number,              BibliographyDataField::NUMBER },
    { sXML_organizations,       BibliographyDataField::ORGANIZATIONS },
    { sXML_pages,               BibliographyDataField::PAGES },
    { sXML_publisher,           BibliographyDataField::PUBLISHER },
    { sXML_report_type,         BibliographyDataField::REPORT_TYPE },
    { sXML_school,              BibliographyDataField::SCHOOL },
    { sXML_series,              BibliographyDataField::SERIES },
    { sXML_title,               BibliographyDataField::TITLE },
    { sXML_url,                 BibliographyDataField::URL },
    { sXML_volume,              BibliographyDataField::VOLUME },
    { sXML_year,                BibliographyDataField::YEAR },
    { NULL, NULL }
};

void XMLIndexBibliographyEntryContext::StartElement(
    const Reference<XAttributeList> & xAttrList)
{
    // handle both, style name and bibliography info
    sal_Int32 nLength = xAttrList->getLength();
    for(sal_Int32 nAttr = 0; nAttr < nLength; nAttr++)
    {
        OUString sLocalName;
        sal_uInt16 nPrefix = GetImport().GetNamespaceMap().
            GetKeyByAttrName( xAttrList->getNameByIndex(nAttr),
                              &sLocalName );
        if (XML_NAMESPACE_TEXT == nPrefix)
        {
            if (sLocalName.equalsAsciiL(sXML_style_name,
                                    sizeof(sXML_style_name)-1))
            {
                sCharStyleName = xAttrList->getValueByIndex(nAttr);
                bCharStyleNameOK = sal_True;
            }
            else if (sLocalName.equalsAsciiL(sXML_bibliography_data_field,
                                    sizeof(sXML_bibliography_data_field)-1))
            {
                sal_uInt16 nTmp;
                if (SvXMLUnitConverter::convertEnum(
                    nTmp, xAttrList->getValueByIndex(nAttr),
                    aBibliographyDataFieldMap))
                {
                    nBibliographyInfo = nTmp;
                    bBibliographyInfoOK = sal_True;
                }
            }
        }
    }

    // if we have a style name, set it!
    if (bCharStyleNameOK)
    {
        nValues++;
    }

    // always bibliography; else element is not valid
    nValues++;
}

void XMLIndexBibliographyEntryContext::EndElement()
{
    // only valid, if we have bibliography info
    if (bBibliographyInfoOK)
    {
        XMLIndexSimpleEntryContext::EndElement();
    }
}

void XMLIndexBibliographyEntryContext::FillPropertyValues(
    ::com::sun::star::uno::Sequence<
        ::com::sun::star::beans::PropertyValue> & rValues)
{
    // entry name and (optionally) style name in parent class
    XMLIndexSimpleEntryContext::FillPropertyValues(rValues);

    // bibliography data field
    sal_Int32 nIndex = bCharStyleNameOK ? 2 : 1;
    rValues[nIndex].Name = rTemplateContext.sBibliographyDataField;
    Any aAny;
    aAny <<= nBibliographyInfo;
    rValues[nIndex].Value = aAny;
}
<|endoftext|>


<commit_before>// NullFacility.cpp
// Implements the NullFacility class

#include <iostream>

#include "NullFacility.h"

#include "GenericResource.h"
#include "Logger.h"
#include "MarketModel.h"
#include "CycException.h"
#include "InputXML.h"

using namespace std;

/**
  TICK
  send a request for your capacity minus your stocks.
  offer stocks + capacity

  TOCK
  process as much in stocks as your capacity will allow.
  send appropriate materials to fill ordersWaiting.

  RECIEVE MATERIAL
  put it in stocks

  SEND MATERIAL
  pull it from inventory, fill the transaction
 */

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::init(xmlNodePtr cur) {
  FacilityModel::init(cur);

  // move XML pointer to current model
  cur = XMLinput->get_xpath_element(cur,"model/NullFacility");

  // all facilities require commodities - possibly many
  in_commod_ = XMLinput->get_xpath_content(cur,"incommodity");
  out_commod_ = XMLinput->get_xpath_content(cur,"outcommodity");

  inventory_.setCapacity(strtod(XMLinput->get_xpath_content(cur,"inventorysize"), NULL));
  stocks_.setCapacity(strtod(XMLinput->get_xpath_content(cur,"inventorysize"), NULL));
  capacity_ = strtod(XMLinput->get_xpath_content(cur,"capacity"), NULL);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::copy(NullFacility* src) {

  FacilityModel::copy(src);

  in_commod_ = src->in_commod_;
  out_commod_ = src->out_commod_;
  inventory_.setCapacity(src->inventory_.capacity());
  stocks_.setCapacity(src->stocks_.capacity());
  capacity_ = src->capacity_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::copyFreshModel(Model* src) {
  copy(dynamic_cast<NullFacility*>(src));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::print() {
  FacilityModel::print();
  LOG(LEV_DEBUG2, "NullFac") << "    converts commodity {"
      << in_commod_
      << "} into commodity {"
      << out_commod_
      << "}, and has an inventory that holds "
      << inventory_.capacity() << " materials"
      << ", and has a stock that holds "
      << stocks_.capacity() << " materials";
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::receiveMessage(msg_ptr msg) {
  // is this a message from on high?
  if (msg->supplier()==this) {
    // file the order
    ordersWaiting_.push_front(msg);
  } else {
    throw CycException("NullFacility is not the supplier of this msg.");
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
vector<rsrc_ptr> NullFacility::removeResource(msg_ptr order) {
  Transaction trans = order->trans();
  // it should be of out_commod_ commodity type
  if (trans.commod != out_commod_) {
    string err_msg = "NullFacility can only send '" + out_commod_ ;
    err_msg += + "' materials.";
    throw CycException(err_msg);
  }

  MatManifest mats;
  try {
    mats = inventory_.popQty(trans.resource->quantity());
  } catch(CycNegQtyException err) {
    LOG(LEV_ERROR, "NulFac") << "extraction of " << trans.resource->quantity()
                   << " kg failed. Inventory is only "
                   << inventory_.quantity() << " kg.";
    throw CycException("what is going on????????????");
  }

  return MatStore::toRes(mats);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::addResource(msg_ptr msg, vector<rsrc_ptr> manifest) {
  stocks_.pushAll(MatStore::toMat(manifest));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::handleTick(int time) {
  // MAKE A REQUEST
  makeRequests();
  // MAKE OFFERS
  makeOffers();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::makeRequests() {
  double shift = inventory_.space();
  if (shift > capacity_) {
    shift = capacity_;
  }

  double cantake = stocks_.space() + shift;

  if (cantake <= 0) {
    return;
    // don't request anything
  }

  // build the transaction and message
  MarketModel* market = MarketModel::marketForCommod(in_commod_);
  Communicator* recipient = dynamic_cast<Communicator*>(market);
  Transaction trans = buildRequestTrans(cantake);
  msg_ptr request(new Message(this, recipient, trans));
  request->setNextDest(facInst());
  request->sendOn();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Transaction NullFacility::buildRequestTrans(double amt) {
  Transaction trans;
  gen_rsrc_ptr res = gen_rsrc_ptr(new GenericResource(in_commod_,"kg",amt));
  trans.commod = in_commod_;
  trans.minfrac = 0;
  trans.is_offer = false;
  trans.price = 0;
  trans.resource = res;
  return trans;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::makeOffers() {
  // decide how much to offer
  double offer_amt, inv;
  inv = inventory_.quantity();
  double possInv = inv + capacity_;

  if (possInv < inventory_.capacity()) {
    offer_amt = possInv;
  } else {
    offer_amt = inventory_.capacity();
  }

  // there is no minimum amount a null facility may send
  double min_amt = 0;
  // and it's free
  double commod_price = 0;

  // create a Resource and build transaction
  gen_rsrc_ptr res = gen_rsrc_ptr(new GenericResource(out_commod_, "kg", offer_amt));
  Transaction trans;
  trans.commod = out_commod_;
  trans.minfrac = min_amt/offer_amt;
  trans.is_offer = true;
  trans.price = commod_price;
  trans.resource = res;

  // build and send the message
  MarketModel* market = MarketModel::marketForCommod(out_commod_);
  Communicator* recipient = dynamic_cast<Communicator*>(market);
  msg_ptr msg(new Message(this, recipient, trans));
  msg->setNextDest(facInst());
  msg->sendOn();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::handleTock(int time) {
  // at rate allowed by capacity, convert material in Stocks to out_commod_ type
  // move converted material into Inventory

  double complete = 0;

  double tomake = capacity_;
  if (inventory_.space() < tomake) {
    tomake = inventory_.space();
  }
  if (stocks_.quantity() < tomake) {
    tomake = stocks_.quantity();
  }

  inventory_.pushAll(stocks_.popQty(tomake));

  // check what orders are waiting,
  while(!ordersWaiting_.empty()) {
    msg_ptr order = ordersWaiting_.front();
    order->approveTransfer();
    ordersWaiting_.pop_front();
  }
}

/* --------------------
 * all MODEL classes have these members
 * --------------------
 */

extern "C" Model* constructNullFacility() {
    return new NullFacility();
}

/* ------------------- */

<commit_msg>Finished DeckStore in null facility.  Null facility now does not make any offers for material from as yet unmatched offers (it used to before). Added logging errors if resource transfer problems occur.<commit_after>// NullFacility.cpp
// Implements the NullFacility class

#include <iostream>

#include "NullFacility.h"

#include "GenericResource.h"
#include "Logger.h"
#include "MarketModel.h"
#include "CycException.h"
#include "InputXML.h"

using namespace std;

/**
  TICK
  send a request for your capacity minus your stocks.
  offer stocks + capacity

  TOCK
  process as much in stocks as your capacity will allow.
  send appropriate materials to fill ordersWaiting.

  RECIEVE MATERIAL
  put it in stocks

  SEND MATERIAL
  pull it from inventory, fill the transaction
 */

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::init(xmlNodePtr cur) {
  FacilityModel::init(cur);

  // move XML pointer to current model
  cur = XMLinput->get_xpath_element(cur,"model/NullFacility");

  // all facilities require commodities - possibly many
  in_commod_ = XMLinput->get_xpath_content(cur,"incommodity");
  out_commod_ = XMLinput->get_xpath_content(cur,"outcommodity");

  inventory_.setCapacity(strtod(XMLinput->get_xpath_content(cur,"inventorysize"), NULL));
  stocks_.setCapacity(strtod(XMLinput->get_xpath_content(cur,"inventorysize"), NULL));
  capacity_ = strtod(XMLinput->get_xpath_content(cur,"capacity"), NULL);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::copy(NullFacility* src) {

  FacilityModel::copy(src);

  in_commod_ = src->in_commod_;
  out_commod_ = src->out_commod_;
  inventory_.setCapacity(src->inventory_.capacity());
  stocks_.setCapacity(src->stocks_.capacity());
  capacity_ = src->capacity_;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::copyFreshModel(Model* src) {
  copy(dynamic_cast<NullFacility*>(src));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::print() {
  FacilityModel::print();
  LOG(LEV_DEBUG2, "NullFac") << "    converts commodity {"
      << in_commod_
      << "} into commodity {"
      << out_commod_
      << "}, and has an inventory that holds "
      << inventory_.capacity() << " materials"
      << ", and has a stock that holds "
      << stocks_.capacity() << " materials";
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::receiveMessage(msg_ptr msg) {
  // is this a message from on high?
  if (msg->supplier()==this) {
    // file the order
    ordersWaiting_.push_front(msg);
  } else {
    throw CycException("NullFacility is not the supplier of this msg.");
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
vector<rsrc_ptr> NullFacility::removeResource(msg_ptr order) {
  Transaction trans = order->trans();
  if (trans.commod != out_commod_) {
    string err_msg = "NullFacility can only send '" + out_commod_ ;
    err_msg += + "' materials.";
    throw CycException(err_msg);
  }

  MatManifest mats;
  try {
    mats = inventory_.popQty(trans.resource->quantity());
  } catch(CycNegQtyException err) {
    LOG(LEV_ERROR, "NulFac") << "extraction of " << trans.resource->quantity()
                   << " kg failed. Inventory is only "
                   << inventory_.quantity() << " kg.";
  }

  return MatStore::toRes(mats);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::addResource(msg_ptr msg, vector<rsrc_ptr> manifest) {
  try {
    stocks_.pushAll(MatStore::toMat(manifest));
  } catch(CycOverCapException err) {
    LOG(LEV_ERROR, "NulFac") << "addition of resources"
                   << " to stocks failed. Stocks only has"
                   << stocks_.space() << " kg of space.";
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::handleTick(int time) {
  makeRequests();
  makeOffers();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::makeRequests() {
  double cantake = capacity_;
  if (cantake > inventory_.space()) {
    cantake = inventory_.space();
  } else if (cantake <= 0) {
    return;
  }
  LOG(LEV_INFO3, "NulFac") << name() << " ID=" << ID() << " requesting "
                           << cantake << "kg of " << in_commod_ <<".";

  // build the transaction and message
  MarketModel* market = MarketModel::marketForCommod(in_commod_);
  Communicator* recipient = dynamic_cast<Communicator*>(market);
  Transaction trans = buildRequestTrans(cantake);
  msg_ptr request(new Message(this, recipient, trans));
  request->setNextDest(facInst());
  request->sendOn();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Transaction NullFacility::buildRequestTrans(double amt) {
  Transaction trans;
  gen_rsrc_ptr res = gen_rsrc_ptr(new GenericResource(in_commod_,"kg",amt));
  trans.commod = in_commod_;
  trans.minfrac = 0;
  trans.is_offer = false;
  trans.price = 0;
  trans.resource = res;
  return trans;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::makeOffers() {
  // decide how much to offer
  double offer_amt = inventory_.quantity() + stocks_.quantity();
  if (capacity_ < stocks_.quantity()) {
    offer_amt = inventory_.quantity() + capacity_;
  }
  if (offer_amt >= inventory_.capacity()) {
    offer_amt = inventory_.capacity();
  }

  // there is no minimum amount a null facility may send
  double min_amt = 0;
  // and it's free
  double commod_price = 0;

  // create a Resource and build transaction
  gen_rsrc_ptr res = gen_rsrc_ptr(new GenericResource(out_commod_, "kg", offer_amt));
  Transaction trans;
  trans.commod = out_commod_;
  trans.minfrac = min_amt/offer_amt;
  trans.is_offer = true;
  trans.price = commod_price;
  trans.resource = res;

  // build and send the message
  MarketModel* market = MarketModel::marketForCommod(out_commod_);
  Communicator* recipient = dynamic_cast<Communicator*>(market);
  msg_ptr msg(new Message(this, recipient, trans));
  msg->setNextDest(facInst());
  msg->sendOn();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void NullFacility::handleTock(int time) {
  // at rate allowed by capacity, convert material in Stocks to out_commod_ type
  // move converted material into Inventory

  double tomake = capacity_;
  if (inventory_.space() < tomake) {
    tomake = inventory_.space();
  }
  if (stocks_.quantity() < tomake) {
    tomake = stocks_.quantity();
  }

  LOG(LEV_DEBUG1, "NulFac") << "Transferring " << tomake << " kg of material from "
                  << "stocks to inventory.";
  try {
    inventory_.pushAll(stocks_.popQty(tomake));
  } catch(CycNegQtyException err) {
    LOG(LEV_ERROR, "NulFac") << "extraction of " << tomake
                   << " kg from stocks failed. Stocks is only "
                   << stocks_.quantity() << " kg.";
  } catch(CycOverCapException err) {
    LOG(LEV_ERROR, "NulFac") << "addition of " << tomake
                   << " kg from stocks to inventory failed. Inventory only has"
                   << inventory_.space() << " kg of space.";
  }

  // check what orders are waiting,
  while(!ordersWaiting_.empty()) {
    msg_ptr order = ordersWaiting_.front();
    order->approveTransfer();
    ordersWaiting_.pop_front();
  }
}

/* --------------------
 * all MODEL classes have these members
 * --------------------
 */

extern "C" Model* constructNullFacility() {
    return new NullFacility();
}

/* ------------------- */

<|endoftext|>


<commit_before>#include "Monitor_reduction.hpp"
#include <sys/types.h>
#include <sys/stat.h>
#include <sstream>
#include <fstream>
#include <exception>

#include "Tools/Display/bash_tools.h"

template <typename B, typename R>
Monitor_reduction<B,R>
::Monitor_reduction(const int& K, const int& N, const int& max_fe,
                    std::vector<Monitor<B,R>*>& monitors,
                    const float snr,
                    const int& n_frames, const std::string name)
: Monitor_std<B,R>            (K, N, max_fe, n_frames, name),
  monitors                    (monitors                    ),
  snr                         (snr                         )
{
	assert(monitors.size() != 0);
	for (size_t i = 0; i < monitors.size(); ++i)
	{
		assert(monitors[i] != nullptr);
	}
}

template <typename B, typename R>
Monitor_reduction<B,R>
::~Monitor_reduction()
{
}

template <typename B, typename R>
unsigned long long Monitor_reduction<B,R>
::get_n_analyzed_fra() const
{
	unsigned long long cur_fra = this->n_analyzed_frames;
	for (unsigned i = 0; i < monitors.size(); i++)
		cur_fra += monitors[i]->get_n_analyzed_fra();

	return cur_fra;
}

template <typename B, typename R>
int Monitor_reduction<B,R>
::get_n_fe() const
{
	auto cur_fe = this->n_frame_errors;
	for (unsigned i = 0; i < monitors.size(); i++)
		cur_fe += monitors[i]->get_n_fe();

	return cur_fe;
}

template <typename B, typename R>
int Monitor_reduction<B,R>
::get_n_be() const
{
	auto cur_be = this->n_bit_errors;
	for (unsigned i = 0; i < monitors.size(); i++)
		cur_be += monitors[i]->get_n_be();

	return cur_be;
}

template <typename B, typename R>
bool Monitor_reduction<B,R>
::check_file_name(const std::string& error_tracker_head_file_name)
{
	size_t pos = error_tracker_head_file_name.find_last_of("/");

	if (pos == std::string::npos)
		return true;

	std::string pathname = error_tracker_head_file_name.substr(0, pos);

	// TODO : check compatibility on windows. Normally it is good.
	struct stat info;

	if( stat( pathname.data(), &info ) != 0 )
		return false;
	else if( info.st_mode & S_IFDIR )
		return true;
	else
		return false;
}

template <typename B, typename R>
void Monitor_reduction<B,R>
::get_tracker_filenames(const std::string& error_tracker_head_filename, const float snr,
                        std::string& filename_src, std::string& filename_enc, std::string& filename_noise)
{
	if(!check_file_name(error_tracker_head_filename))
	{
		std::cerr << bold_red("(EE) issue while trying to open error tracker log files ; check head of the filename: \"")
		          << bold_red(error_tracker_head_filename) << bold_red("\" and please create yourself the needed directory.") << std::endl;
		exit(-1);
	}

	std::stringstream snr_stream;
	snr_stream << std::fixed << std::setprecision(3) << snr;

	std::string filename_head  = error_tracker_head_filename + std::string("_") + snr_stream.str();

	filename_src   = filename_head + std::string(".src");
	filename_enc   = filename_head + std::string(".enc");
	filename_noise = filename_head + std::string(".chn");
}

template <typename B, typename R>
void Monitor_reduction<B,R>
::flush_wrong_frame(const std::string& error_tracker_head_filename, const float snr)
{
	int n_fe   = get_n_fe();

	if(n_fe == 0)
		return;

	// ************* get filename and open them ******************
	std::string filename_src, filename_enc, filename_noise;

	get_tracker_filenames(error_tracker_head_filename, snr, filename_src, filename_enc, filename_noise);

	std::ofstream file_src  (filename_src  );
	std::ofstream file_enc  (filename_enc  );
	std::ofstream file_noise(filename_noise, std::ios_base::binary);

	if (!file_src.is_open() || !file_enc.is_open() || !file_noise.is_open())
	{
		std::cerr << bold_red("(EE) issue while trying to open error tracker log files ; check file name: \"")
		          << bold_red(error_tracker_head_filename) << bold_red("\"") << std::endl;
		exit(-1);
	}

	int Y_size =0;
	// ************* get Y_size *******************
	for (unsigned i = 0; i <= monitors.size(); i++)
	{
		auto mon = (i == monitors.size()) ? this : monitors[i];

		// write noise
		auto buff_noise = mon->get_buff_noise();

		if(buff_noise.empty())
			continue;

		Y_size = buff_noise.front().size();
		break;
	}

	// ************* write headers *****************
	file_src << n_fe          << std::endl << std::endl; // write number frames
	file_src << this->get_K() << std::endl << std::endl; // write length of frames

	file_enc << n_fe          << std::endl << std::endl; // write number frames
	file_enc << this->get_K() << std::endl << std::endl; // write length of non coded frames
	file_enc << this->get_N() << std::endl << std::endl; // write length of coded frames

	file_noise.write((char *)&n_fe  , sizeof(int)); // write number frames
	file_noise.write((char *)&Y_size, sizeof(int)); // write length of frames

	// ************* write frames ********************
	for (unsigned i = 0; i <= monitors.size(); i++)
	{
		auto mon = (i == monitors.size()) ? this : monitors[i];

		// write source
		auto buff_src = mon->get_buff_src();
		for (unsigned f = 0; f < buff_src.size(); f++)
		{
			for (unsigned b = 0; b < buff_src[f].size(); b++)
				file_src << buff_src[f][b] << " ";

			file_src << std::endl << std::endl;
		}

		// write encoder
		auto buff_enc = mon->get_buff_enc();
		assert(buff_src.size() == buff_enc.size());
		for (unsigned f = 0; f < buff_enc.size(); f++)
		{
			for (unsigned b = 0; b < buff_enc[f].size(); b++)
				file_enc << buff_enc[f][b] << " ";

			file_enc << std::endl << std::endl;
		}

		// write noise
		auto buff_noise = mon->get_buff_noise();
		assert(buff_src.size() == buff_noise.size());
		for (unsigned f = 0; f < buff_noise.size(); f++)
			for (unsigned b = 0; b < buff_noise[f].size(); b++)
				file_noise.write((char *)&buff_noise[f][b], sizeof(R));
	}
}

// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class Monitor_reduction<B_8 ,R_8>;
template class Monitor_reduction<B_16,R_16>;
template class Monitor_reduction<B_32,R_32>;
template class Monitor_reduction<B_64,R_64>;
#else
template class Monitor_reduction<B,R>;
#endif
// ==================================================================================== explicit template instantiation
<commit_msg>write tracking files even whether there is no wrong frame<commit_after>#include "Monitor_reduction.hpp"
#include <sys/types.h>
#include <sys/stat.h>
#include <sstream>
#include <fstream>
#include <exception>

#include "Tools/Display/bash_tools.h"

template <typename B, typename R>
Monitor_reduction<B,R>
::Monitor_reduction(const int& K, const int& N, const int& max_fe,
                    std::vector<Monitor<B,R>*>& monitors,
                    const float snr,
                    const int& n_frames, const std::string name)
: Monitor_std<B,R>            (K, N, max_fe, n_frames, name),
  monitors                    (monitors                    ),
  snr                         (snr                         )
{
	assert(monitors.size() != 0);
	for (size_t i = 0; i < monitors.size(); ++i)
	{
		assert(monitors[i] != nullptr);
	}
}

template <typename B, typename R>
Monitor_reduction<B,R>
::~Monitor_reduction()
{
}

template <typename B, typename R>
unsigned long long Monitor_reduction<B,R>
::get_n_analyzed_fra() const
{
	unsigned long long cur_fra = this->n_analyzed_frames;
	for (unsigned i = 0; i < monitors.size(); i++)
		cur_fra += monitors[i]->get_n_analyzed_fra();

	return cur_fra;
}

template <typename B, typename R>
int Monitor_reduction<B,R>
::get_n_fe() const
{
	auto cur_fe = this->n_frame_errors;
	for (unsigned i = 0; i < monitors.size(); i++)
		cur_fe += monitors[i]->get_n_fe();

	return cur_fe;
}

template <typename B, typename R>
int Monitor_reduction<B,R>
::get_n_be() const
{
	auto cur_be = this->n_bit_errors;
	for (unsigned i = 0; i < monitors.size(); i++)
		cur_be += monitors[i]->get_n_be();

	return cur_be;
}

template <typename B, typename R>
bool Monitor_reduction<B,R>
::check_file_name(const std::string& error_tracker_head_file_name)
{
	size_t pos = error_tracker_head_file_name.find_last_of("/");

	if (pos == std::string::npos)
		return true;

	std::string pathname = error_tracker_head_file_name.substr(0, pos);

	// TODO : check compatibility on windows. Normally it is good.
	struct stat info;

	if( stat( pathname.data(), &info ) != 0 )
		return false;
	else if( info.st_mode & S_IFDIR )
		return true;
	else
		return false;
}

template <typename B, typename R>
void Monitor_reduction<B,R>
::get_tracker_filenames(const std::string& error_tracker_head_filename, const float snr,
                        std::string& filename_src, std::string& filename_enc, std::string& filename_noise)
{
	if(!check_file_name(error_tracker_head_filename))
	{
		std::cerr << bold_red("(EE) issue while trying to open error tracker log files ; check head of the filename: \"")
		          << bold_red(error_tracker_head_filename) << bold_red("\" and please create yourself the needed directory.") << std::endl;
		exit(-1);
	}

	std::stringstream snr_stream;
	snr_stream << std::fixed << std::setprecision(3) << snr;

	std::string filename_head  = error_tracker_head_filename + std::string("_") + snr_stream.str();

	filename_src   = filename_head + std::string(".src");
	filename_enc   = filename_head + std::string(".enc");
	filename_noise = filename_head + std::string(".chn");
}

template <typename B, typename R>
void Monitor_reduction<B,R>
::flush_wrong_frame(const std::string& error_tracker_head_filename, const float snr)
{
	// ************* get filename and open them ******************
	std::string filename_src, filename_enc, filename_noise;

	get_tracker_filenames(error_tracker_head_filename, snr, filename_src, filename_enc, filename_noise);

	std::ofstream file_src  (filename_src  );
	std::ofstream file_enc  (filename_enc  );
	std::ofstream file_noise(filename_noise, std::ios_base::binary);

	if (!file_src.is_open() || !file_enc.is_open() || !file_noise.is_open())
	{
		std::cerr << bold_red("(EE) issue while trying to open error tracker log files ; check file name: \"")
		          << bold_red(error_tracker_head_filename) << bold_red("\"") << std::endl;
		exit(-1);
	}

	int n_fe   = get_n_fe();
	int Y_size = 0;
	// ************* get Y_size *******************
	for (unsigned i = 0; i <= monitors.size(); i++)
	{
		auto mon = (i == monitors.size()) ? this : monitors[i];

		// write noise
		auto buff_noise = mon->get_buff_noise();

		if(buff_noise.empty())
			continue;

		Y_size = buff_noise.front().size();
		break;
	}

	// ************* write headers *****************
	file_src << n_fe          << std::endl << std::endl; // write number frames
	file_src << this->get_K() << std::endl << std::endl; // write length of frames

	file_enc << n_fe          << std::endl << std::endl; // write number frames
	file_enc << this->get_K() << std::endl << std::endl; // write length of non coded frames
	file_enc << this->get_N() << std::endl << std::endl; // write length of coded frames

	file_noise.write((char *)&n_fe  , sizeof(int)); // write number frames
	file_noise.write((char *)&Y_size, sizeof(int)); // write length of frames

	// ************* write frames ********************
	for (unsigned i = 0; i <= monitors.size(); i++)
	{
		auto mon = (i == monitors.size()) ? this : monitors[i];

		// write source
		auto buff_src = mon->get_buff_src();
		for (unsigned f = 0; f < buff_src.size(); f++)
		{
			for (unsigned b = 0; b < buff_src[f].size(); b++)
				file_src << buff_src[f][b] << " ";

			file_src << std::endl << std::endl;
		}

		// write encoder
		auto buff_enc = mon->get_buff_enc();
		assert(buff_src.size() == buff_enc.size());
		for (unsigned f = 0; f < buff_enc.size(); f++)
		{
			for (unsigned b = 0; b < buff_enc[f].size(); b++)
				file_enc << buff_enc[f][b] << " ";

			file_enc << std::endl << std::endl;
		}

		// write noise
		auto buff_noise = mon->get_buff_noise();
		assert(buff_src.size() == buff_noise.size());
		for (unsigned f = 0; f < buff_noise.size(); f++)
			for (unsigned b = 0; b < buff_noise[f].size(); b++)
				file_noise.write((char *)&buff_noise[f][b], sizeof(R));
	}
}

// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class Monitor_reduction<B_8 ,R_8>;
template class Monitor_reduction<B_16,R_16>;
template class Monitor_reduction<B_32,R_32>;
template class Monitor_reduction<B_64,R_64>;
#else
template class Monitor_reduction<B,R>;
#endif
// ==================================================================================== explicit template instantiation
<|endoftext|>


<commit_before>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * HDF5WriterP.cpp
 *
 *  Created on: March 20, 2017
 *      Author: Junmin
 */

#include "HDF5WriterP.h"

#include "adios2/ADIOSMPI.h"
#include "adios2/helper/adiosFunctions.h" //CSVToVector

namespace adios2
{

HDF5WriterP::HDF5WriterP(IO &io, const std::string &name, const Mode mode,
                         MPI_Comm mpiComm)
: Engine("HDF5Writer", io, name, mode, mpiComm), m_H5File(io.m_DebugMode)
{
    m_EndMessage = ", in call to IO HDF5Writer Open " + m_Name + "\n";
    Init();
}

HDF5WriterP::~HDF5WriterP() { Close(); }

StepStatus HDF5WriterP::BeginStep(StepMode mode, const float timeoutSeconds)
{
    return StepStatus::OK;
}

void HDF5WriterP::EndStep() { m_H5File.Advance(); }

void HDF5WriterP::Close(const int transportIndex) { m_H5File.Close(); }

// PRIVATE
void HDF5WriterP::Init()
{
    if (m_OpenMode != Mode::Write && m_OpenMode != Mode::Append)
    {
        throw std::invalid_argument(
            "ERROR: HDF5Writer only support OpenMode::Write or "
            "OpenMode::Append "
            ", in call to ADIOS Open or HDF5Writer constructor\n");
    }

    m_H5File.Init(m_Name, m_MPIComm, true);
}

#define declare_type(T)                                                        \
    void HDF5WriterP::DoPutSync(Variable<T> &variable, const T *values)        \
    {                                                                          \
        DoPutSyncCommon(variable, values);                                     \
    }

ADIOS2_FOREACH_TYPE_1ARG(declare_type)
#undef declare_type

template <class T>
void HDF5WriterP::DoPutSyncCommon(Variable<T> &variable, const T *values)
{
    variable.SetData(values);
    m_H5File.Write(variable, values);
}

} // end namespace adios2
<commit_msg>replace .bp with .h5<commit_after>/*
 * Distributed under the OSI-approved Apache License, Version 2.0.  See
 * accompanying file Copyright.txt for details.
 *
 * HDF5WriterP.cpp
 *
 *  Created on: March 20, 2017
 *      Author: Junmin
 */

#include "HDF5WriterP.h"

#include "adios2/ADIOSMPI.h"
#include "adios2/helper/adiosFunctions.h" //CSVToVector

namespace adios2
{

HDF5WriterP::HDF5WriterP(IO &io, const std::string &name, const Mode mode,
                         MPI_Comm mpiComm)
: Engine("HDF5Writer", io, name, mode, mpiComm), m_H5File(io.m_DebugMode)
{
    m_EndMessage = ", in call to IO HDF5Writer Open " + m_Name + "\n";
    Init();
}

HDF5WriterP::~HDF5WriterP() { Close(); }

StepStatus HDF5WriterP::BeginStep(StepMode mode, const float timeoutSeconds)
{
    return StepStatus::OK;
}

void HDF5WriterP::EndStep() { m_H5File.Advance(); }

void HDF5WriterP::Close(const int transportIndex) { m_H5File.Close(); }

// PRIVATE
void HDF5WriterP::Init()
{
    if (m_OpenMode != Mode::Write && m_OpenMode != Mode::Append)
    {
        throw std::invalid_argument(
            "ERROR: HDF5Writer only support OpenMode::Write or "
            "OpenMode::Append "
            ", in call to ADIOS Open or HDF5Writer constructor\n");
    }

#ifdef NEVER
    m_H5File.Init(m_Name, m_MPIComm, true);
#else
    // enforce .h5 ending
    std::string suffix = ".h5";
    std::string wrongSuffix = ".bp";

    int ss = m_Name.size();
    int wpos = m_Name.find(wrongSuffix);

    if (wpos == ss - wrongSuffix.size())
    {
        // is a file with .bp ending
        std::string updatedName = m_Name.substr(0, wpos) + suffix;
        m_H5File.Init(updatedName, m_MPIComm, true);
    }
    else
    {
        m_H5File.Init(m_Name, m_MPIComm, true);
    }

#endif
}

#define declare_type(T)                                                        \
    void HDF5WriterP::DoPutSync(Variable<T> &variable, const T *values)        \
    {                                                                          \
        DoPutSyncCommon(variable, values);                                     \
    }

ADIOS2_FOREACH_TYPE_1ARG(declare_type)
#undef declare_type

template <class T>
void HDF5WriterP::DoPutSyncCommon(Variable<T> &variable, const T *values)
{
    variable.SetData(values);
    m_H5File.Write(variable, values);
}

} // end namespace adios2
<|endoftext|>


<commit_before>// $Id$

{
  printf("\nWELCOME to the magic world of HLT\n\n");

  gSystem->Load("$(ROOTSYS)/lib/libPhysics");
  gSystem->Load("$(ROOTSYS)/lib/libEG");

  Int_t saveErrIgLevel=gErrorIgnoreLevel;
  gErrorIgnoreLevel=kFatal; //dont report errors
  if(gSystem->Load("$(ROOTSYS)/lib/libMC")==-1){
    gSystem->Load("$(ROOTSYS)/lib/libGeom");
    gSystem->Load("$(ROOTSYS)/lib/libVMC");
  }

  if(1)
    {
      gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTEER");
      gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libCONTAINERS");
      if(gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTPC")!=0){
	gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTCPbase");
	gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTCPrec");
	gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTCPsim");
	gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTCPfast");
      }
      cout<<"TPC libraries loaded"<<endl;
    }

  if(1)
    {
      gSystem->Load("$(ALIHLT_LIBDIR)/libAliL3Src");
      gSystem->Load("$(ALIHLT_LIBDIR)/libAliL3Misc");
      gSystem->Load("$(ALIHLT_LIBDIR)/libAliL3Hough");
      gSystem->Load("$(ALIHLT_LIBDIR)/libAliL3Comp");
      cout<<"HLT libraries loaded"<<endl;
    }

  gSystem->Load("MakePileup_C.so");
  gSystem->Load("Read_C.so");
  gSystem->Load("runhough_C.so");
  gSystem->Load("runrowhough_C.so");
  gSystem->Load("deconvclusters_C.so");
  gSystem->Load("runtracker_C.so");
  gErrorIgnoreLevel=saveErrIgLevel;

  gSystem->SetIncludePath(" -D do_mc -I$ALIHLT_TOPDIR/hough -I$ALIHLT_TOPDIR/src -I$ALIHLT_TOPDIR/comp -I$ALIHLT_TOPDIR/misc -I$ALICE_ROOT/include/ -I$ALICE_ROOT/TPC -I$ALICE_ROOT/CONTAINERS -I$ALICE_ROOT/STEER ");

  gStyle->SetStatColor(10);
  gStyle->SetStatBorderSize(1);
  gStyle->SetTitleBorderSize(0);
  gStyle->SetPadColor(10);
  gStyle->SetPadBorderSize(0);
  gStyle->SetPadBorderMode(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetCanvasBorderSize(0);
  gStyle->SetCanvasColor(10);
  gStyle->SetTitleSize(0.036,"X");
  gStyle->SetTitleSize(0.036,"Y");
  gStyle->SetTitleSize(0.036,"Z");
  gStyle->SetLabelSize(0.036,"X");
  gStyle->SetLabelSize(0.036,"Y");
  gStyle->SetLabelSize(0.036,"Z");
  gStyle->SetTitleOffset(1.2,"X");
  gStyle->SetTitleOffset(1.3,"Y");
  gStyle->SetTitleOffset(1.3,"Z");
  gStyle->SetTitleColor(10);
}
<commit_msg>Added rowparams.<commit_after>// $Id$

{
  printf("\nWELCOME to the magic world of HLT\n\n");

  gSystem->Load("$(ROOTSYS)/lib/libPhysics");
  gSystem->Load("$(ROOTSYS)/lib/libEG");

  Int_t saveErrIgLevel=gErrorIgnoreLevel;
  gErrorIgnoreLevel=kFatal; //dont report errors
  if(gSystem->Load("$(ROOTSYS)/lib/libMC")==-1){
    gSystem->Load("$(ROOTSYS)/lib/libGeom");
    gSystem->Load("$(ROOTSYS)/lib/libVMC");
  }

  if(1)
    {
      gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libSTEER");
      gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libCONTAINERS");
      if(gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTPC")!=0){
	gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTCPbase");
	gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTCPrec");
	gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTCPsim");
	gSystem->Load("$(ALICE_ROOT)/lib/tgt_$(ALICE_TARGET)/libTCPfast");
      }
      cout<<"TPC libraries loaded"<<endl;
    }

  if(1)
    {
      gSystem->Load("$(ALIHLT_LIBDIR)/libAliL3Src");
      gSystem->Load("$(ALIHLT_LIBDIR)/libAliL3Misc");
      gSystem->Load("$(ALIHLT_LIBDIR)/libAliL3Hough");
      gSystem->Load("$(ALIHLT_LIBDIR)/libAliL3Comp");
      cout<<"HLT libraries loaded"<<endl;
    }

  gSystem->Load("MakePileup_C.so");
  gSystem->Load("Read_C.so");
  gSystem->Load("runhough_C.so");
  gSystem->Load("runrowhough_C.so");
  gSystem->Load("deconvclusters_C.so");
  gSystem->Load("runtracker_C.so");
  gErrorIgnoreLevel=saveErrIgLevel;

  gSystem->SetIncludePath(" -DROWHOUGHPARAMS -Duse_reconstruction -Duse_newio -D do_mc -I$ALIHLT_TOPDIR/hough -I$ALIHLT_TOPDIR/src -I$ALIHLT_TOPDIR/comp -I$ALIHLT_TOPDIR/misc -I$ALICE_ROOT/include/ -I$ALICE_ROOT/TPC -I$ALICE_ROOT/CONTAINERS -I$ALICE_ROOT/STEER ");

  gStyle->SetStatColor(10);
  gStyle->SetStatBorderSize(1);
  gStyle->SetTitleBorderSize(0);
  gStyle->SetPadColor(10);
  gStyle->SetPadBorderSize(0);
  gStyle->SetPadBorderMode(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetCanvasBorderSize(0);
  gStyle->SetCanvasColor(10);
  gStyle->SetTitleSize(0.036,"X");
  gStyle->SetTitleSize(0.036,"Y");
  gStyle->SetTitleSize(0.036,"Z");
  gStyle->SetLabelSize(0.036,"X");
  gStyle->SetLabelSize(0.036,"Y");
  gStyle->SetLabelSize(0.036,"Z");
  gStyle->SetTitleOffset(1.2,"X");
  gStyle->SetTitleOffset(1.3,"Y");
  gStyle->SetTitleOffset(1.3,"Z");
  gStyle->SetTitleColor(10);
}
<|endoftext|>


<commit_before>/*
 * Copyright 2010 Martin Hebnes Pedersen, martinhpedersen @ "google mail"
 * All rights reserved. Distributed under the terms of the MIT License.
 */

#include "HTGTimeLineView.h"

/*InfoPopper constants*/
const int32 kNotify		= 1000;
const int32 kInformationType	= 1001;
const int32 kImportantType	= 1002;
const int32 kErrorType		= 1003;
const int32 kProgressType	= 1004;
const int32 kAttributeIcon	= 1005;
const int32 kContentsIcon	= 1006;

HTGTimeLineView::HTGTimeLineView(twitCurl *twitObj, const int32 TYPE, const char* requestInfo) : BScrollView("Loading...", new BView(BRect(0, 0, 300-4, 552), "ContainerView", B_FOLLOW_LEFT | B_FOLLOW_TOP, 0), B_FOLLOW_LEFT | B_FOLLOW_TOP, 0, false, true, B_FANCY_BORDER) {
	this->twitObj = twitObj;
	this->TYPE = TYPE;
	thread_id previousThread = B_NAME_NOT_FOUND;

	/*Set view name*/
	switch(TYPE) {
		case TIMELINE_HOME:
			SetName("Home");
			break;
		case TIMELINE_FRIENDS:
			SetName("Friends");
			break;
		case TIMELINE_MENTIONS:
			SetName("Mentions");
			break;
		case TIMELINE_PUBLIC:
			SetName("Public");
			break;
		case TIMELINE_USER:
			SetName(requestInfo);
			break;
		case TIMELINE_SEARCH:
			SetName(requestInfo);
			break;
		default:
			SetName("Public");
	}

	/*Set up listview*/
	this->listView = new BListView(BRect(0, 0, 300-5, 72*20), "ListView");

	/*Prepare the list for unhandled tweets*/
	unhandledList = new BList();

	/*Set up scrollview*/
	containerView = new BView(Bounds(), "ContainerView", B_FOLLOW_LEFT | B_FOLLOW_TOP, 0);
	containerView->AddChild(listView);
	this->SetTarget(containerView);

	/*Load infopopper settings (if supported)*/
	wantsNotifications = false; //Default should be false
	#ifdef INFOPOPPER_SUPPORT
	wantsNotifications = _retrieveInfoPopperBoolFromSettings();
	#endif

	/*All done, ready to display tweets*/
	waitingForUpdate = true;
	updateTimeLine();
}

void HTGTimeLineView::AttachedToWindow() {
	BScrollView::AttachedToWindow();
	if(waitingForUpdate)
		updateTimeLine();
}

void HTGTimeLineView::updateTimeLine() {
	bool looperLocked = listView->LockLooper();
	/*Update timeline only if we can lock window looper -or we want notifications for this timeline*/
	if(!looperLocked && !wantsNotifications)
		waitingForUpdate = true;
	else {
		if(looperLocked) listView->UnlockLooper(); //Assume we can lock it later
		previousThread = spawn_thread(updateTimeLineThread, "UpdateThread", 10, this);
		resume_thread(previousThread);
		waitingForUpdate = false;
	}
}

std::string& htmlFormatedString(const char *orig) {
	std::string newString(orig);
	if(orig[0] == '#') {
		newString = std::string(orig+1);
		newString.insert(0, "%23");
	}
	std::string *returnPtr = new std::string(newString);
	return *returnPtr;
}

status_t updateTimeLineThread(void *data) {
	//Could not figure out how to update a BListItem with a child view (BTextView).
	//Could be a bug in Haiku API's. After hours of investigation without any
	//result, I just don't care anymore. Reallocating all HTGTweetItem on update.

	HTGTimeLineView *super = (HTGTimeLineView*)data;

	/*Wait for previous thread to end*/
	status_t junkId;
	wait_for_thread(find_thread("UpdateThread"), &junkId);

	BListView *listView = super->listView;
	BView *containerView;
	char *tabName;

	TimeLineParser *timeLineParser = new TimeLineParser();
	twitCurl *twitObj = super->twitObj;
	int32 TYPE = super->TYPE;

	switch(TYPE) {
		case TIMELINE_HOME:
			twitObj->timelineHomeGet();
			break;
		case TIMELINE_FRIENDS:
			twitObj->timelineFriendsGet();
			break;
		case TIMELINE_MENTIONS:
			twitObj->mentionsGet();
			break;
		case TIMELINE_PUBLIC:
			twitObj->timelinePublicGet();
			break;
		case TIMELINE_USER:
			twitObj->timelineUserGet(*new std::string(super->Name()), false);
			break;
		case TIMELINE_SEARCH:
			twitObj->search(htmlFormatedString(super->Name()));
			break;
		default:
			twitObj->timelinePublicGet();
	}
	std::string replyMsg(" ");
	twitObj->getLastWebResponse(replyMsg);
	if(replyMsg.length() < 100)  { //Length of data is less than 100 characters. Clearly,
		replyMsg = "error";				//something is wrong... abort.
	}

	timeLineParser->readData(replyMsg.c_str());

	HTGTweetItem *mostRecentItem;
	HTTweet *mostRecentTweet;
	HTTweet *currentTweet;

	bool initialLoad = (listView->FirstItem() == NULL);

	if(!initialLoad) {
		mostRecentItem = (HTGTweetItem *)listView->FirstItem();
		mostRecentTweet = mostRecentItem->getTweetPtr();
		currentTweet = timeLineParser->getTweets()[0];

		/*If we are up to date, clean up and return*/
		if(!(*mostRecentTweet < *currentTweet)) {
			delete timeLineParser;
			timeLineParser = NULL;
			return B_OK;
		}
	}

	/*Check to see if there is some unhandled tweets*/
	if(!super->unhandledList->IsEmpty()) {
		mostRecentItem = (HTGTweetItem *)super->unhandledList->FirstItem();
		mostRecentTweet = mostRecentItem->getTweetPtr();
	}

	BList *newList = new BList();

	for (int i = 0; i < timeLineParser->count(); i++) {
		currentTweet = timeLineParser->getTweets()[i];
		bool addItem = initialLoad;
		if(!initialLoad)
			addItem = (*mostRecentTweet < *currentTweet);
		if(addItem) {
			/*Make a copy, download bitmap and add it to newList*/
			HTTweet *copiedTweet = new HTTweet(currentTweet);
			copiedTweet->downloadBitmap();
			newList->AddItem(new HTGTweetItem(copiedTweet));

			if(!initialLoad && super->wantsNotifications) { //New tweet arrived, send notification
				super->sendNotificationFor(copiedTweet);
			}
		}
		else
			break;
	}

	/*Try to lock listView*/
	if(!listView->LockLooper()) {
		/*Not active view: Copy tweetptrs to unhandledList and return*/
		super->unhandledList->AddList(newList, 0); //Add new tweets to the top
		super->waitingForUpdate = true;
		delete timeLineParser;
		timeLineParser = NULL;
		if(newList->IsEmpty())
			delete newList;
		return B_OK;
	}

	/*Add the unhandled tweets to newList*/
	newList->AddList(super->unhandledList);
	super->unhandledList->MakeEmpty();

	HTGTweetItem *currentItem;
	while(!listView->IsEmpty()) {
		currentItem = (HTGTweetItem *)listView->FirstItem();
		currentTweet = currentItem->getTweetPtr();
		listView->RemoveItem(currentItem); //Must lock looper before we do this!
		if(newList->CountItems() < 20) //Only allow 20 tweets to be displayed at once... for now.
			newList->AddItem(new HTGTweetItem(new HTTweet(currentTweet)));

		delete currentItem;
	}

	/*Update the view*/
	listView->AddList(newList); //Must lock looper before we do this!

	/*Cleanup*/
	super->waitingForUpdate = false;
	listView->UnlockLooper();
	delete timeLineParser;
	timeLineParser = NULL;
	delete newList;

	return B_OK;
}

void HTGTimeLineView::sendNotificationFor(HTTweet *theTweet) {
	std::string title("New tweet from ");
	title.append(theTweet->getScreenName());
	std::cout << title << std::endl;

	#ifdef INFOPOPPER_SUPPORT

	IPConnection *conn = new IPConnection;
	IPMessage *msg = new IPMessage(InfoPopper::Information);

	//Prepare the message
	msg->Application("HaikuTwitter");
	msg->Title(title.c_str());
	msg->Content(theTweet->getText().c_str());

	// Icon maybe in the future
	/*if (strlen(fIconFile->Text()) > 0) {
		entry_ref ref;

		if (get_ref_for_path(fIconFile->Text(), &ref) == B_OK) {
			if (fSelectedIconType == InfoPopper::Attribute) {
				msg->MainIcon(ref);
				msg->MainIconType(fSelectedIconType);
			}
			if (fSelectedIconType == InfoPopper::Contents) {
				msg->OverlayIcon(ref);
				msg->OverlayIconType(fSelectedIconType);
			}
		}
	}*/

	//Send the notification
	conn->Send(msg);

	delete msg;
	delete conn;

	#endif
}

bool HTGTimeLineView::_retrieveInfoPopperBoolFromSettings() {
	BPath path;
	infopopper_settings theSettings;

	if (HTGInfoPopperSettingsWindow::_getSettingsPath(path) < B_OK) {
		theSettings = HTGInfoPopperSettingsWindow::_getDefaults();
		switch(TYPE) {
		case TIMELINE_FRIENDS:
			return theSettings.friendsNotify;
			break;
		case TIMELINE_MENTIONS:
			return theSettings.mentionsNotify;
			break;
		case TIMELINE_PUBLIC:
			return theSettings.publicNotify;
			break;
		}
	}

	BFile file(path.Path(), B_READ_ONLY);
	if (file.InitCheck() < B_OK) {
		theSettings = HTGInfoPopperSettingsWindow::_getDefaults();
		switch(TYPE) {
		case TIMELINE_FRIENDS:
			return theSettings.friendsNotify;
			break;
		case TIMELINE_MENTIONS:
			return theSettings.mentionsNotify;
			break;
		case TIMELINE_PUBLIC:
			return theSettings.publicNotify;
			break;
		}
	}

	file.ReadAt(0, &theSettings, sizeof(infopopper_settings));
	switch(TYPE) {
		case TIMELINE_FRIENDS:
			return theSettings.friendsNotify;
			break;
		case TIMELINE_MENTIONS:
			return theSettings.mentionsNotify;
			break;
		case TIMELINE_PUBLIC:
			return theSettings.publicNotify;
			break;
		}

}

HTGTimeLineView::~HTGTimeLineView() {
	/*Kill the update thread*/
	kill_thread(previousThread);

	listView->RemoveSelf();
	while(!listView->IsEmpty()) {
		HTGTweetItem *currentItem = (HTGTweetItem *)listView->FirstItem();
		listView->RemoveItem(currentItem);
		delete currentItem;
	}
	delete listView;
	delete twitObj;
	containerView->RemoveSelf();
	delete containerView;
}
<commit_msg>Fixed bug related to InfoPopper<commit_after>/*
 * Copyright 2010 Martin Hebnes Pedersen, martinhpedersen @ "google mail"
 * All rights reserved. Distributed under the terms of the MIT License.
 */

#include "HTGTimeLineView.h"

/*InfoPopper constants*/
const int32 kNotify		= 1000;
const int32 kInformationType	= 1001;
const int32 kImportantType	= 1002;
const int32 kErrorType		= 1003;
const int32 kProgressType	= 1004;
const int32 kAttributeIcon	= 1005;
const int32 kContentsIcon	= 1006;

HTGTimeLineView::HTGTimeLineView(twitCurl *twitObj, const int32 TYPE, const char* requestInfo) : BScrollView("Loading...", new BView(BRect(0, 0, 300-4, 552), "ContainerView", B_FOLLOW_LEFT | B_FOLLOW_TOP, 0), B_FOLLOW_LEFT | B_FOLLOW_TOP, 0, false, true, B_FANCY_BORDER) {
	this->twitObj = twitObj;
	this->TYPE = TYPE;
	thread_id previousThread = B_NAME_NOT_FOUND;

	/*Set view name*/
	switch(TYPE) {
		case TIMELINE_HOME:
			SetName("Home");
			break;
		case TIMELINE_FRIENDS:
			SetName("Friends");
			break;
		case TIMELINE_MENTIONS:
			SetName("Mentions");
			break;
		case TIMELINE_PUBLIC:
			SetName("Public");
			break;
		case TIMELINE_USER:
			SetName(requestInfo);
			break;
		case TIMELINE_SEARCH:
			SetName(requestInfo);
			break;
		default:
			SetName("Public");
	}

	/*Set up listview*/
	this->listView = new BListView(BRect(0, 0, 300-5, 72*20), "ListView");

	/*Prepare the list for unhandled tweets*/
	unhandledList = new BList();

	/*Set up scrollview*/
	containerView = new BView(Bounds(), "ContainerView", B_FOLLOW_LEFT | B_FOLLOW_TOP, 0);
	containerView->AddChild(listView);
	this->SetTarget(containerView);

	/*Load infopopper settings (if supported)*/
	wantsNotifications = false; //Default should be false
	#ifdef INFOPOPPER_SUPPORT
	wantsNotifications = _retrieveInfoPopperBoolFromSettings();
	#endif

	/*All done, ready to display tweets*/
	waitingForUpdate = true;
	updateTimeLine();
}

void HTGTimeLineView::AttachedToWindow() {
	BScrollView::AttachedToWindow();
	if(waitingForUpdate)
		updateTimeLine();
}

void HTGTimeLineView::updateTimeLine() {
	bool looperLocked = listView->LockLooper();
	/*Update timeline only if we can lock window looper -or we want notifications for this timeline*/
	if(!looperLocked && !wantsNotifications)
		waitingForUpdate = true;
	else {
		if(looperLocked) listView->UnlockLooper(); //Assume we can lock it later
		previousThread = spawn_thread(updateTimeLineThread, "UpdateThread", 10, this);
		resume_thread(previousThread);
		waitingForUpdate = false;
	}
}

std::string& htmlFormatedString(const char *orig) {
	std::string newString(orig);
	if(orig[0] == '#') {
		newString = std::string(orig+1);
		newString.insert(0, "%23");
	}
	std::string *returnPtr = new std::string(newString);
	return *returnPtr;
}

status_t updateTimeLineThread(void *data) {
	//Could not figure out how to update a BListItem with a child view (BTextView).
	//Could be a bug in Haiku API's. After hours of investigation without any
	//result, I just don't care anymore. Reallocating all HTGTweetItem on update.

	HTGTimeLineView *super = (HTGTimeLineView*)data;

	/*Wait for previous thread to end*/
	status_t junkId;
	wait_for_thread(find_thread("UpdateThread"), &junkId);

	BListView *listView = super->listView;
	BView *containerView;
	char *tabName;

	TimeLineParser *timeLineParser = new TimeLineParser();
	twitCurl *twitObj = super->twitObj;
	int32 TYPE = super->TYPE;

	switch(TYPE) {
		case TIMELINE_HOME:
			twitObj->timelineHomeGet();
			break;
		case TIMELINE_FRIENDS:
			twitObj->timelineFriendsGet();
			break;
		case TIMELINE_MENTIONS:
			twitObj->mentionsGet();
			break;
		case TIMELINE_PUBLIC:
			twitObj->timelinePublicGet();
			break;
		case TIMELINE_USER:
			twitObj->timelineUserGet(*new std::string(super->Name()), false);
			break;
		case TIMELINE_SEARCH:
			twitObj->search(htmlFormatedString(super->Name()));
			break;
		default:
			twitObj->timelinePublicGet();
	}
	std::string replyMsg(" ");
	twitObj->getLastWebResponse(replyMsg);
	if(replyMsg.length() < 100)  { //Length of data is less than 100 characters. Clearly,
		replyMsg = "error";				//something is wrong... abort.
	}

	timeLineParser->readData(replyMsg.c_str());

	HTGTweetItem *mostRecentItem;
	HTTweet *mostRecentTweet;
	HTTweet *currentTweet;

	bool initialLoad = (listView->FirstItem() == NULL && super->unhandledList->FirstItem() == NULL);

	if(!initialLoad && listView->FirstItem() != NULL) {
		mostRecentItem = (HTGTweetItem *)listView->FirstItem();
		mostRecentTweet = mostRecentItem->getTweetPtr();
		currentTweet = timeLineParser->getTweets()[0];

		/*If we are up to date, clean up and return*/
		if(!(*mostRecentTweet < *currentTweet)) {
			delete timeLineParser;
			timeLineParser = NULL;
			return B_OK;
		}
	}

	/*Check to see if there is some unhandled tweets*/
	if(!super->unhandledList->IsEmpty()) {
		mostRecentItem = (HTGTweetItem *)super->unhandledList->FirstItem();
		mostRecentTweet = mostRecentItem->getTweetPtr();
	}

	BList *newList = new BList();

	for (int i = 0; i < timeLineParser->count(); i++) {
		currentTweet = timeLineParser->getTweets()[i];
		bool addItem = initialLoad;
		if(!initialLoad)
			addItem = (*mostRecentTweet < *currentTweet);
		if(addItem) {
			/*Make a copy, download bitmap and add it to newList*/
			HTTweet *copiedTweet = new HTTweet(currentTweet);
			copiedTweet->downloadBitmap();
			newList->AddItem(new HTGTweetItem(copiedTweet));

			if(!initialLoad && super->wantsNotifications) { //New tweet arrived, send notification
				super->sendNotificationFor(copiedTweet);
			}
		}
		else
			break;
	}

	/*Try to lock listView*/
	if(!listView->LockLooper()) {
		/*Not active view: Copy tweetptrs to unhandledList and return*/
		super->unhandledList->AddList(newList, 0); //Add new tweets to the top
		super->waitingForUpdate = true;
		delete timeLineParser;
		timeLineParser = NULL;
		if(newList->IsEmpty())
			delete newList;
		return B_OK;
	}

	/*Add the unhandled tweets to newList*/
	newList->AddList(super->unhandledList);
	super->unhandledList->MakeEmpty();

	HTGTweetItem *currentItem;
	while(!listView->IsEmpty()) {
		currentItem = (HTGTweetItem *)listView->FirstItem();
		currentTweet = currentItem->getTweetPtr();
		listView->RemoveItem(currentItem); //Must lock looper before we do this!
		if(newList->CountItems() < 20) //Only allow 20 tweets to be displayed at once... for now.
			newList->AddItem(new HTGTweetItem(new HTTweet(currentTweet)));

		delete currentItem;
	}

	/*Update the view*/
	listView->AddList(newList); //Must lock looper before we do this!

	/*Cleanup*/
	super->waitingForUpdate = false;
	listView->UnlockLooper();
	delete timeLineParser;
	timeLineParser = NULL;
	delete newList;

	return B_OK;
}

void HTGTimeLineView::sendNotificationFor(HTTweet *theTweet) {
	std::string title("New tweet from ");
	title.append(theTweet->getScreenName());
	std::cout << title << std::endl;

	#ifdef INFOPOPPER_SUPPORT

	IPConnection *conn = new IPConnection;
	IPMessage *msg = new IPMessage(InfoPopper::Information);

	//Prepare the message
	msg->Application("HaikuTwitter");
	msg->Title(title.c_str());
	msg->Content(theTweet->getText().c_str());

	// Icon maybe in the future
	/*if (strlen(fIconFile->Text()) > 0) {
		entry_ref ref;

		if (get_ref_for_path(fIconFile->Text(), &ref) == B_OK) {
			if (fSelectedIconType == InfoPopper::Attribute) {
				msg->MainIcon(ref);
				msg->MainIconType(fSelectedIconType);
			}
			if (fSelectedIconType == InfoPopper::Contents) {
				msg->OverlayIcon(ref);
				msg->OverlayIconType(fSelectedIconType);
			}
		}
	}*/

	//Send the notification
	conn->Send(msg);

	delete msg;
	delete conn;

	#endif
}

bool HTGTimeLineView::_retrieveInfoPopperBoolFromSettings() {
	BPath path;
	infopopper_settings theSettings;

	if (HTGInfoPopperSettingsWindow::_getSettingsPath(path) < B_OK) {
		theSettings = HTGInfoPopperSettingsWindow::_getDefaults();
		switch(TYPE) {
		case TIMELINE_FRIENDS:
			return theSettings.friendsNotify;
			break;
		case TIMELINE_MENTIONS:
			return theSettings.mentionsNotify;
			break;
		case TIMELINE_PUBLIC:
			return theSettings.publicNotify;
			break;
		}
	}

	BFile file(path.Path(), B_READ_ONLY);
	if (file.InitCheck() < B_OK) {
		theSettings = HTGInfoPopperSettingsWindow::_getDefaults();
		switch(TYPE) {
		case TIMELINE_FRIENDS:
			return theSettings.friendsNotify;
			break;
		case TIMELINE_MENTIONS:
			return theSettings.mentionsNotify;
			break;
		case TIMELINE_PUBLIC:
			return theSettings.publicNotify;
			break;
		}
	}

	file.ReadAt(0, &theSettings, sizeof(infopopper_settings));
	switch(TYPE) {
		case TIMELINE_FRIENDS:
			return theSettings.friendsNotify;
			break;
		case TIMELINE_MENTIONS:
			return theSettings.mentionsNotify;
			break;
		case TIMELINE_PUBLIC:
			return theSettings.publicNotify;
			break;
		}

}

HTGTimeLineView::~HTGTimeLineView() {
	/*Kill the update thread*/
	kill_thread(previousThread);

	listView->RemoveSelf();
	while(!listView->IsEmpty()) {
		HTGTweetItem *currentItem = (HTGTweetItem *)listView->FirstItem();
		listView->RemoveItem(currentItem);
		delete currentItem;
	}
	delete listView;
	delete twitObj;
	containerView->RemoveSelf();
	delete containerView;
}
<|endoftext|>


<commit_before>/*******************************************************************************
FILE : choose_enumerator_class.hpp

LAST MODIFIED : 10 March 2007

DESCRIPTION :
Class for implementing an wxList dialog control for choosing an object
from its manager (subject to an optional conditional function). Handles manager
messages to keep the menu up-to-date.
Calls the client-specified callback routine if a different object is chosen.
==============================================================================*/
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is cmgui.
 *
 * The Initial Developer of the Original Code is
 * Auckland Uniservices Ltd, Auckland, New Zealand.
 * Portions created by the Initial Developer are Copyright (C) 2005
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
#if !defined (CHOOSE_ENUMERATOR_CLASS_H)
#define CHOOSE_ENUMERATOR_CLASS_H

template < class Enumerator > class wxEnumeratorChooser : public wxChoice
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
============================================================================*/
{
private:
	Callback_base< typename Enumerator::Enumerator_type > *callback;
	int first_value;

public:
	wxEnumeratorChooser<Enumerator>(wxPanel *parent,
		int number_of_items, const char **item_names,
		int first_value,
		typename Enumerator::Enumerator_type current_value,
		User_interface *user_interface) :
		wxChoice(parent, /*id*/-1, wxPoint(0,0), wxSize(-1,-1)),
		first_value(first_value)
	{
		USE_PARAMETER(user_interface);
		callback = NULL;
		build_main_menu(number_of_items, item_names, current_value);

		Connect(wxEVT_COMMAND_CHOICE_SELECTED,
			wxCommandEventHandler(wxEnumeratorChooser::OnChoiceSelected));

		wxBoxSizer *sizer = new wxBoxSizer( wxHORIZONTAL );
		sizer->Add(this,
			wxSizerFlags(1).Align(wxALIGN_CENTER).Expand());
		parent->SetSizer(sizer);

		Show();
	}

	~wxEnumeratorChooser<Enumerator>()
		{
			if (callback)
				delete callback;
		}

	void OnChoiceSelected(wxCommandEvent& event)
	{
		USE_PARAMETER(event);
		if (callback)
		{
			callback->callback_function(get_item());
		}
   }

	typename Enumerator::Enumerator_type get_item()
	{
		return (static_cast<typename Enumerator::Enumerator_type>
			(GetSelection() + first_value));
	}

	int set_callback(Callback_base< typename Enumerator::Enumerator_type >
		*callback_object)
	{
		if (callback)
			delete callback;
		callback = callback_object;
		return (1);
	}

	int set_item(typename Enumerator::Enumerator_type new_value)
	{
		unsigned int return_code;

		SetSelection(new_value - first_value);

		// Could check to see that the value was actually set
		return_code = 1;

		return (return_code);
	}

	int build_main_menu(int number_of_items,
		const char **item_names,
		typename Enumerator::Enumerator_type current_value)
	{
		int i;
		Clear();
		for (i = 0 ; i < number_of_items ; i++)
		{
			Append(wxString::FromAscii(item_names[i]));
		}
		SetSelection(current_value);
		return 1;
	}
};

template < class Enumerator > class Enumerator_chooser
{
private:
	Enumerator *enumerator;
	wxPanel *parent;
	typename Enumerator::Conditional_function *conditional_function;
	void *conditional_function_user_data;
	wxEnumeratorChooser<Enumerator> *chooser;
	Callback_base< typename Enumerator::Enumerator_type > *update_callback;
  int number_of_items;
  const char **item_names;
	int first_value;

public:
	Enumerator_chooser(wxPanel *parent,
		typename Enumerator::Enumerator_type current_value,
		typename Enumerator::Conditional_function *conditional_function,
		void *conditional_function_user_data,
		User_interface *user_interface) :
		enumerator(new Enumerator()), parent(parent),
		conditional_function(conditional_function),
		conditional_function_user_data(conditional_function_user_data)
	{
		chooser = (wxEnumeratorChooser<Enumerator> *)NULL;
		update_callback = (Callback_base< typename Enumerator::Enumerator_type > *)NULL;
		number_of_items = 0;
		item_names = (const char **)NULL;
		first_value = 0;
		if (build_items())
		{
			chooser = new wxEnumeratorChooser<Enumerator>(parent,
				number_of_items, item_names, first_value, current_value,
				user_interface);
			typedef int (Enumerator_chooser::*Member_function)(typename Enumerator::Enumerator_type);
			Callback_base<typename Enumerator::Enumerator_type> *callback =
				new Callback_member_callback< typename Enumerator::Enumerator_type,
				Enumerator_chooser, Member_function>(
				this, &Enumerator_chooser::chooser_callback);

			chooser->set_callback(callback);
		}
		else
		{
			display_message(ERROR_MESSAGE,
				"Enumerator_chooser::Enumerator_chooser.   "
				" Could not get items");
		}

	} /* Enumerator_chooser::Enumerator_chooser */

	~Enumerator_chooser()
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
============================================================================*/
	{
		if (chooser)
		{
			  chooser->Destroy();
		}
		if (update_callback)
			delete update_callback;
		delete enumerator;
		if (item_names)
		{
			 // We only free the array, not the strings themselves for
			 // strings from an enumerator
			DEALLOCATE(item_names);
		}
	} /* Enumerator_chooser::~Enumerator_chooser() */

	int chooser_callback(typename Enumerator::Enumerator_type value)
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
Called by the
============================================================================*/
	{
		int return_code;

		if (update_callback)
		{
			/* now call the procedure with the user data */
			update_callback->callback_function(value);
		}
		return_code=1;

		return (return_code);
	} /* Enumerator_chooser::get_callback */

	Callback_base< typename Enumerator::Enumerator_type > *get_callback()
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
Returns a pointer to the callback item.
============================================================================*/
	{
		return update_callback;
	} /* Enumerator_chooser::get_callback */

	int set_callback(Callback_base< typename Enumerator::Enumerator_type > *new_callback)
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
Changes the callback item.
============================================================================*/
	{
		if (update_callback)
		{
			delete update_callback;
		}
		update_callback = new_callback;
		return(1);
	} /* Enumerator_chooser::set_callback */

	typename Enumerator::Enumerator_type get_value()
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
Returns the currently chosen object.
============================================================================*/
	{
		return(chooser->get_item());
	} /* Enumerator_chooser::get_object */

	int set_value(typename Enumerator::Enumerator_type new_value)
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
Changes the chosen object in the choose_object_widget.
============================================================================*/
	{
		return(chooser->set_item(new_value));
	} /* Enumerator_chooser::set_object */

	int set_conditional_function(
		typename Enumerator::Conditional_function *in_conditional_function,
		void *in_conditional_function_user_data, typename Enumerator::Enumerator_type new_value)
/*****************************************************************************
LAST MODIFIED : 10 March 2007

DESCRIPTION :
Changes the conditional_function and user_data limiting the available
selection of objects. Also allows new_object to be set simultaneously.
============================================================================*/
	{
		int return_code;

		conditional_function = in_conditional_function;
		conditional_function_user_data = in_conditional_function_user_data;
		if (build_items())
		{
			return_code=chooser->build_main_menu(
				number_of_items, item_names, new_value);
		}
		else
		{
			return_code=0;
		}
		if (!return_code)
		{
			display_message(ERROR_MESSAGE,
				"Enumerator_chooser::set_conditional_function"
				"Could not update menu");
		}
		return (return_code);
	} /* Enumerator_chooser::set_conditional_function */

private:

	int is_item_in_chooser(typename Enumerator::Enumerator_type value)
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
============================================================================*/
	{
		int i, return_code;

		if ((value > 0) && (value <= number_of_items))
		{
			return_code = 1;
		}
		else
		{
			return_code=0;
		}

		return (return_code);
	} /* Enumerator_chooser::is_item_in_chooser */

	int build_items()
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
Updates the arrays of all the choosable objects and their names.
============================================================================*/
	{
		int return_code;

		if (item_names)
		{
			 // We only free the array, not the strings themselves for
			 // strings from an enumerator
			DEALLOCATE(item_names);
		}

		item_names = enumerator->get_valid_strings(&number_of_items,
			conditional_function, conditional_function_user_data);
		if (enumerator->value_to_string((Enumerator::Enumerator_type(0))))
		{
			first_value = 0;
		}
		else
		{
			first_value = 1;
		}
		return_code = 1;

		return (return_code);
	}  /* Enumerator_chooser::build_items */

}; /* template < class Managed_object > class Enumerator_chooser */

#endif /* !defined (CHOOSE_ENUMERATOR_CLASS_H) */
<commit_msg>Fix typename for cast to enumeration in Enumerator_chooser class, source of compilation errors from revision C9863. Issue 2107.<commit_after>/*******************************************************************************
FILE : choose_enumerator_class.hpp

LAST MODIFIED : 10 March 2007

DESCRIPTION :
Class for implementing an wxList dialog control for choosing an object
from its manager (subject to an optional conditional function). Handles manager
messages to keep the menu up-to-date.
Calls the client-specified callback routine if a different object is chosen.
==============================================================================*/
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is cmgui.
 *
 * The Initial Developer of the Original Code is
 * Auckland Uniservices Ltd, Auckland, New Zealand.
 * Portions created by the Initial Developer are Copyright (C) 2005
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
#if !defined (CHOOSE_ENUMERATOR_CLASS_H)
#define CHOOSE_ENUMERATOR_CLASS_H

template < class Enumerator > class wxEnumeratorChooser : public wxChoice
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
============================================================================*/
{
private:
	Callback_base< typename Enumerator::Enumerator_type > *callback;
	int first_value;

public:
	wxEnumeratorChooser<Enumerator>(wxPanel *parent,
		int number_of_items, const char **item_names,
		int first_value,
		typename Enumerator::Enumerator_type current_value,
		User_interface *user_interface) :
		wxChoice(parent, /*id*/-1, wxPoint(0,0), wxSize(-1,-1)),
		first_value(first_value)
	{
		USE_PARAMETER(user_interface);
		callback = NULL;
		build_main_menu(number_of_items, item_names, current_value);

		Connect(wxEVT_COMMAND_CHOICE_SELECTED,
			wxCommandEventHandler(wxEnumeratorChooser::OnChoiceSelected));

		wxBoxSizer *sizer = new wxBoxSizer( wxHORIZONTAL );
		sizer->Add(this,
			wxSizerFlags(1).Align(wxALIGN_CENTER).Expand());
		parent->SetSizer(sizer);

		Show();
	}

	~wxEnumeratorChooser<Enumerator>()
		{
			if (callback)
				delete callback;
		}

	void OnChoiceSelected(wxCommandEvent& event)
	{
		USE_PARAMETER(event);
		if (callback)
		{
			callback->callback_function(get_item());
		}
   }

	typename Enumerator::Enumerator_type get_item()
	{
		return (static_cast<typename Enumerator::Enumerator_type>
			(GetSelection() + first_value));
	}

	int set_callback(Callback_base< typename Enumerator::Enumerator_type >
		*callback_object)
	{
		if (callback)
			delete callback;
		callback = callback_object;
		return (1);
	}

	int set_item(typename Enumerator::Enumerator_type new_value)
	{
		unsigned int return_code;

		SetSelection(new_value - first_value);

		// Could check to see that the value was actually set
		return_code = 1;

		return (return_code);
	}

	int build_main_menu(int number_of_items,
		const char **item_names,
		typename Enumerator::Enumerator_type current_value)
	{
		int i;
		Clear();
		for (i = 0 ; i < number_of_items ; i++)
		{
			Append(wxString::FromAscii(item_names[i]));
		}
		SetSelection(current_value);
		return 1;
	}
};

template < class Enumerator > class Enumerator_chooser
{
private:
	Enumerator *enumerator;
	wxPanel *parent;
	typename Enumerator::Conditional_function *conditional_function;
	void *conditional_function_user_data;
	wxEnumeratorChooser<Enumerator> *chooser;
	Callback_base< typename Enumerator::Enumerator_type > *update_callback;
  int number_of_items;
  const char **item_names;
	int first_value;

public:
	Enumerator_chooser(wxPanel *parent,
		typename Enumerator::Enumerator_type current_value,
		typename Enumerator::Conditional_function *conditional_function,
		void *conditional_function_user_data,
		User_interface *user_interface) :
		enumerator(new Enumerator()), parent(parent),
		conditional_function(conditional_function),
		conditional_function_user_data(conditional_function_user_data)
	{
		chooser = (wxEnumeratorChooser<Enumerator> *)NULL;
		update_callback = (Callback_base< typename Enumerator::Enumerator_type > *)NULL;
		number_of_items = 0;
		item_names = (const char **)NULL;
		first_value = 0;
		if (build_items())
		{
			chooser = new wxEnumeratorChooser<Enumerator>(parent,
				number_of_items, item_names, first_value, current_value,
				user_interface);
			typedef int (Enumerator_chooser::*Member_function)(typename Enumerator::Enumerator_type);
			Callback_base<typename Enumerator::Enumerator_type> *callback =
				new Callback_member_callback< typename Enumerator::Enumerator_type,
				Enumerator_chooser, Member_function>(
				this, &Enumerator_chooser::chooser_callback);

			chooser->set_callback(callback);
		}
		else
		{
			display_message(ERROR_MESSAGE,
				"Enumerator_chooser::Enumerator_chooser.   "
				" Could not get items");
		}

	} /* Enumerator_chooser::Enumerator_chooser */

	~Enumerator_chooser()
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
============================================================================*/
	{
		if (chooser)
		{
			  chooser->Destroy();
		}
		if (update_callback)
			delete update_callback;
		delete enumerator;
		if (item_names)
		{
			 // We only free the array, not the strings themselves for
			 // strings from an enumerator
			DEALLOCATE(item_names);
		}
	} /* Enumerator_chooser::~Enumerator_chooser() */

	int chooser_callback(typename Enumerator::Enumerator_type value)
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
Called by the
============================================================================*/
	{
		int return_code;

		if (update_callback)
		{
			/* now call the procedure with the user data */
			update_callback->callback_function(value);
		}
		return_code=1;

		return (return_code);
	} /* Enumerator_chooser::get_callback */

	Callback_base< typename Enumerator::Enumerator_type > *get_callback()
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
Returns a pointer to the callback item.
============================================================================*/
	{
		return update_callback;
	} /* Enumerator_chooser::get_callback */

	int set_callback(Callback_base< typename Enumerator::Enumerator_type > *new_callback)
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
Changes the callback item.
============================================================================*/
	{
		if (update_callback)
		{
			delete update_callback;
		}
		update_callback = new_callback;
		return(1);
	} /* Enumerator_chooser::set_callback */

	typename Enumerator::Enumerator_type get_value()
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
Returns the currently chosen object.
============================================================================*/
	{
		return(chooser->get_item());
	} /* Enumerator_chooser::get_object */

	int set_value(typename Enumerator::Enumerator_type new_value)
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
Changes the chosen object in the choose_object_widget.
============================================================================*/
	{
		return(chooser->set_item(new_value));
	} /* Enumerator_chooser::set_object */

	int set_conditional_function(
		typename Enumerator::Conditional_function *in_conditional_function,
		void *in_conditional_function_user_data, typename Enumerator::Enumerator_type new_value)
/*****************************************************************************
LAST MODIFIED : 10 March 2007

DESCRIPTION :
Changes the conditional_function and user_data limiting the available
selection of objects. Also allows new_object to be set simultaneously.
============================================================================*/
	{
		int return_code;

		conditional_function = in_conditional_function;
		conditional_function_user_data = in_conditional_function_user_data;
		if (build_items())
		{
			return_code=chooser->build_main_menu(
				number_of_items, item_names, new_value);
		}
		else
		{
			return_code=0;
		}
		if (!return_code)
		{
			display_message(ERROR_MESSAGE,
				"Enumerator_chooser::set_conditional_function"
				"Could not update menu");
		}
		return (return_code);
	} /* Enumerator_chooser::set_conditional_function */

private:

	int is_item_in_chooser(typename Enumerator::Enumerator_type value)
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
============================================================================*/
	{
		int i, return_code;

		if ((value > 0) && (value <= number_of_items))
		{
			return_code = 1;
		}
		else
		{
			return_code=0;
		}

		return (return_code);
	} /* Enumerator_chooser::is_item_in_chooser */

	int build_items()
/*****************************************************************************
LAST MODIFIED : 8 February 2007

DESCRIPTION :
Updates the arrays of all the choosable objects and their names.
============================================================================*/
	{
		int return_code;

		if (item_names)
		{
			 // We only free the array, not the strings themselves for
			 // strings from an enumerator
			DEALLOCATE(item_names);
		}

		item_names = enumerator->get_valid_strings(&number_of_items,
			conditional_function, conditional_function_user_data);
		if (enumerator->value_to_string((static_cast<typename Enumerator::Enumerator_type>(0))))
		{
			first_value = 0;
		}
		else
		{
			first_value = 1;
		}
		return_code = 1;

		return (return_code);
	}  /* Enumerator_chooser::build_items */

}; /* template < class Managed_object > class Enumerator_chooser */

#endif /* !defined (CHOOSE_ENUMERATOR_CLASS_H) */
<|endoftext|>