<commit_before>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//
//////////////////////////////////////////////////////////////////////////

#include "stdsneezy.h"
#include "cmd_trophy.h"
#include "database.h"

TTrophy::TTrophy(sstring n) :
  db(new TDatabase(DB_SNEEZY)),
  parent(NULL),
  name(n)
{
}

TTrophy::TTrophy(TBeing *p) :
  db(new TDatabase(DB_SNEEZY)),
  parent(p),
  name("")
{
}

sstring TTrophy::getMyName(){
  if(parent){

    if (parent->specials.act & ACT_POLYSELF) {
      return parent->desc->original->getName();
    } else {
      return parent->getName();
    }
  } else {
    // name should be "" if we're uninitialized, so just return it either way
    return name;
  }
}

void TTrophy::setName(sstring n){
  parent=NULL;
  name=n;
}

void TTrophy::addToCount(int vnum, double add){
  if(vnum==-1 || vnum==0 || getMyName()==""){ return; }

  int player_id=parent->getPlayerID();

  db->query("select * from trophy where player_id=%i and mobvnum=%i",
	    player_id, vnum);
  if(!db->fetchRow()){
    db->query("insert into trophy values (%i, %i, %f)",
	      player_id, vnum, add);
  } else {
    db->query("update trophy set count=count+%f where player_id=%i and mobvnum=%i",
	      add, player_id, vnum);
  }

  db->query("update trophyplayer set total=total+%f where player_id=%i",
	   add, player_id);
}

float TTrophy::getCount(int vnum)
{
  db->query("select count from trophy where player_id=%i and mobvnum=%i",
	   parent->getPlayerID(), vnum);
  if(db->fetchRow())
    return convertTo<float>((*db)["count"]);
  else
    return 0.0;
}

float TTrophy::getExpModVal(float count)
{
  float min_mod=0.3;
  float max_mod=1.0; // shouldn't ever be above 1.0
  float free_kills=8; // how many kills you get before trophy kicks in
  float step_mod=0.5; // mod per step
  float num_steps=14.0; // number of steps

  float t1, t2, t3, t4, t5;

  t1=(double)(count-free_kills);
  t2=step_mod / num_steps;
  t3=t1*t2;
  t4=max_mod-t3;
  t5=(double)(max(t4*100, min_mod*100)/100);
  t5=(double)(min(t5*100, max_mod*100)/100);

  //  vlogf(LOG_PEEL, fmt("%f %f %f %f %f") %  t1 % t2 % t3 % t4 % t5);

  return t5;
}

const char *TTrophy::getExpModDescr(float count)
{
  float f=getExpModVal(count);

  return((f == 1.0) ? "<Y>full<1>" :
	 ((f >= 0.90) ? "<o>much<1>" :
	  ((f >= 0.80) ? "a fair amount of" :
	   ((f >= 0.70) ? "<w>some<1>" : "<k>little<1>"))));
}

// this function is a little messy, I apologize
void TBeing::doTrophy(const sstring &arg)
{
  int mcount=0, vnum, header=0, zcount=0, bottom=0, zcountt=0;
  int zonesearch=0, processrow=1, active_zcount=0;
  bool summary=false;
  float count;
  sstring buf, sb, arg1, arg2;
  unsigned int zone;

  if(!isPc()){
    sendTo("Mobs can't use this command!\n\r");
    return;
  }

  TBeing *per = NULL;
  if (specials.act & ACT_POLYSELF)
    per = desc->original;
  else per = this;

  TTrophy trophy(per->getName());

  arg1=arg.word(0);
  arg2=arg.word(1);

  if(arg1=="zone"){
    if(!arg2.empty()){
      arg1=arg2;
      zonesearch=-1;
    } else {
      zonesearch=roomp->getZoneNum();
    }
  } else if(arg1=="summary"){
    summary=true;
  }

  TDatabase db(DB_SNEEZY);
  db.query("select mobvnum, count from trophy where player_id=%i order by mobvnum", per->getPlayerID());

  for (zone = 0; zone < zone_table.size(); zone++) {
    zoneData &zd = zone_table[zone];

    while(1){
      if(processrow){
	if(!db.fetchRow()){
	  break;
	}
      }

      // sometimes we get an entry of 0 for med mobs I think
      vnum=convertTo<int>(db["mobvnum"]);
      if(vnum==0){
	continue;
      }

      // this mob doesn't belong to this zone, so break out to the zone loop
      if(vnum>zd.top){
	processrow=0; // don't get the next row yet
	break;
      } else {
	processrow=1;
      }

      int rnum = real_mobile(convertTo<int>(db["mobvnum"]));
      if (rnum < 0) {
	vlogf(LOG_BUG, fmt("DoTrophy detected bad mobvnum=%d for name='%s'") %
	      convertTo<int>(db["mobvnum"]) % per->getName());
	continue;
      }

      if(zonesearch==-1){
	if(!isname(arg1, zd.name))
	  continue;
      } else if(zonesearch>0){
	if(zonesearch!=zd.zone_nr)
	  continue;
      } else if(!summary){
	if(!arg1.empty() && !isname(arg1, mob_index[rnum].name))
	  continue;
      }

      // print the zone header if we haven't already
      // we do it here, so we can prevent printing headers for empty zones
      if(!header){
	buf = fmt("\n--%s\n") % zd.name;
	sb += buf;
	header=1;
      }

      count=convertTo<float>(db["count"]);

      if(!summary){
	buf = fmt("You will gain %s experience when fighting %s.\n\r") %
		trophy.getExpModDescr(count) % mob_index[rnum].short_desc;
	sb += buf;
      }

      ++mcount;
      ++zcount;

      if(mob_index[rnum].doesLoad)
	++active_zcount;

      processrow=1; // ok to get the next row
    }

    // we have some mobs for this zone, so do some tallies
    if(header){
      buf = fmt("Total mobs: %i\n\r") % zcount;
      sb += buf;

      unsigned int objnx;
      for (objnx = 0; objnx < mob_index.size(); objnx++) {
	if(mob_index[objnx].virt >= bottom &&
	   mob_index[objnx].virt <= zd.top &&
	   mob_index[objnx].doesLoad){
	  ++zcountt;
	}
      }

      buf = fmt("You have killed %1.2f%c of mobs in this zone.\n\r") %((float)((float)active_zcount/(float)zcountt)*100.0) % '%';
      sb += buf;
    }

    header=zcount=zcountt=active_zcount=0;
    bottom=zd.top+1;
  }

  int activemobcount=0;
  for (unsigned int mobnum = 0; mobnum < mob_index.size(); mobnum++) {
    for (unsigned int zone = 0; zone < zone_table.size(); zone++) {
      if(mob_index[mobnum].virt <= zone_table[zone].top &&
	 mob_index[mobnum].doesLoad){
	if(zone_table[zone].enabled)
	  activemobcount++;
	break;
      }
    }
  }

  buf = fmt("\n--\nTotal mobs: %i\n\r") % mcount;
  sb += buf;
  if(mcount>0){
    buf = fmt("You have killed %1.2f%c of all mobs.\n\r") %((float)((float)mcount/(float)activemobcount)*100.0) % '%';
    sb += buf;
  }

  if (desc)
    desc->page_string(sb, SHOWNOW_NO, ALLOWREP_YES);

  return;
}

void TTrophy::wipe(){
  db->query("select id from player where name='%s'", getMyName());

  if(db.fetchRow())
    db->query("delete from trophy where player_id=%i", convertTo<int>(db["id"]));

}
<commit_msg>typo fix<commit_after>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//
//////////////////////////////////////////////////////////////////////////

#include "stdsneezy.h"
#include "cmd_trophy.h"
#include "database.h"

TTrophy::TTrophy(sstring n) :
  db(new TDatabase(DB_SNEEZY)),
  parent(NULL),
  name(n)
{
}

TTrophy::TTrophy(TBeing *p) :
  db(new TDatabase(DB_SNEEZY)),
  parent(p),
  name("")
{
}

sstring TTrophy::getMyName(){
  if(parent){

    if (parent->specials.act & ACT_POLYSELF) {
      return parent->desc->original->getName();
    } else {
      return parent->getName();
    }
  } else {
    // name should be "" if we're uninitialized, so just return it either way
    return name;
  }
}

void TTrophy::setName(sstring n){
  parent=NULL;
  name=n;
}

void TTrophy::addToCount(int vnum, double add){
  if(vnum==-1 || vnum==0 || getMyName()==""){ return; }

  int player_id=parent->getPlayerID();

  db->query("select * from trophy where player_id=%i and mobvnum=%i",
	    player_id, vnum);
  if(!db->fetchRow()){
    db->query("insert into trophy values (%i, %i, %f)",
	      player_id, vnum, add);
  } else {
    db->query("update trophy set count=count+%f where player_id=%i and mobvnum=%i",
	      add, player_id, vnum);
  }

  db->query("update trophyplayer set total=total+%f where player_id=%i",
	   add, player_id);
}

float TTrophy::getCount(int vnum)
{
  db->query("select count from trophy where player_id=%i and mobvnum=%i",
	   parent->getPlayerID(), vnum);
  if(db->fetchRow())
    return convertTo<float>((*db)["count"]);
  else
    return 0.0;
}

float TTrophy::getExpModVal(float count)
{
  float min_mod=0.3;
  float max_mod=1.0; // shouldn't ever be above 1.0
  float free_kills=8; // how many kills you get before trophy kicks in
  float step_mod=0.5; // mod per step
  float num_steps=14.0; // number of steps

  float t1, t2, t3, t4, t5;

  t1=(double)(count-free_kills);
  t2=step_mod / num_steps;
  t3=t1*t2;
  t4=max_mod-t3;
  t5=(double)(max(t4*100, min_mod*100)/100);
  t5=(double)(min(t5*100, max_mod*100)/100);

  //  vlogf(LOG_PEEL, fmt("%f %f %f %f %f") %  t1 % t2 % t3 % t4 % t5);

  return t5;
}

const char *TTrophy::getExpModDescr(float count)
{
  float f=getExpModVal(count);

  return((f == 1.0) ? "<Y>full<1>" :
	 ((f >= 0.90) ? "<o>much<1>" :
	  ((f >= 0.80) ? "a fair amount of" :
	   ((f >= 0.70) ? "<w>some<1>" : "<k>little<1>"))));
}

// this function is a little messy, I apologize
void TBeing::doTrophy(const sstring &arg)
{
  int mcount=0, vnum, header=0, zcount=0, bottom=0, zcountt=0;
  int zonesearch=0, processrow=1, active_zcount=0;
  bool summary=false;
  float count;
  sstring buf, sb, arg1, arg2;
  unsigned int zone;

  if(!isPc()){
    sendTo("Mobs can't use this command!\n\r");
    return;
  }

  TBeing *per = NULL;
  if (specials.act & ACT_POLYSELF)
    per = desc->original;
  else per = this;

  TTrophy trophy(per->getName());

  arg1=arg.word(0);
  arg2=arg.word(1);

  if(arg1=="zone"){
    if(!arg2.empty()){
      arg1=arg2;
      zonesearch=-1;
    } else {
      zonesearch=roomp->getZoneNum();
    }
  } else if(arg1=="summary"){
    summary=true;
  }

  TDatabase db(DB_SNEEZY);
  db.query("select mobvnum, count from trophy where player_id=%i order by mobvnum", per->getPlayerID());

  for (zone = 0; zone < zone_table.size(); zone++) {
    zoneData &zd = zone_table[zone];

    while(1){
      if(processrow){
	if(!db.fetchRow()){
	  break;
	}
      }

      // sometimes we get an entry of 0 for med mobs I think
      vnum=convertTo<int>(db["mobvnum"]);
      if(vnum==0){
	continue;
      }

      // this mob doesn't belong to this zone, so break out to the zone loop
      if(vnum>zd.top){
	processrow=0; // don't get the next row yet
	break;
      } else {
	processrow=1;
      }

      int rnum = real_mobile(convertTo<int>(db["mobvnum"]));
      if (rnum < 0) {
	vlogf(LOG_BUG, fmt("DoTrophy detected bad mobvnum=%d for name='%s'") %
	      convertTo<int>(db["mobvnum"]) % per->getName());
	continue;
      }

      if(zonesearch==-1){
	if(!isname(arg1, zd.name))
	  continue;
      } else if(zonesearch>0){
	if(zonesearch!=zd.zone_nr)
	  continue;
      } else if(!summary){
	if(!arg1.empty() && !isname(arg1, mob_index[rnum].name))
	  continue;
      }

      // print the zone header if we haven't already
      // we do it here, so we can prevent printing headers for empty zones
      if(!header){
	buf = fmt("\n--%s\n") % zd.name;
	sb += buf;
	header=1;
      }

      count=convertTo<float>(db["count"]);

      if(!summary){
	buf = fmt("You will gain %s experience when fighting %s.\n\r") %
		trophy.getExpModDescr(count) % mob_index[rnum].short_desc;
	sb += buf;
      }

      ++mcount;
      ++zcount;

      if(mob_index[rnum].doesLoad)
	++active_zcount;

      processrow=1; // ok to get the next row
    }

    // we have some mobs for this zone, so do some tallies
    if(header){
      buf = fmt("Total mobs: %i\n\r") % zcount;
      sb += buf;

      unsigned int objnx;
      for (objnx = 0; objnx < mob_index.size(); objnx++) {
	if(mob_index[objnx].virt >= bottom &&
	   mob_index[objnx].virt <= zd.top &&
	   mob_index[objnx].doesLoad){
	  ++zcountt;
	}
      }

      buf = fmt("You have killed %1.2f%c of mobs in this zone.\n\r") %((float)((float)active_zcount/(float)zcountt)*100.0) % '%';
      sb += buf;
    }

    header=zcount=zcountt=active_zcount=0;
    bottom=zd.top+1;
  }

  int activemobcount=0;
  for (unsigned int mobnum = 0; mobnum < mob_index.size(); mobnum++) {
    for (unsigned int zone = 0; zone < zone_table.size(); zone++) {
      if(mob_index[mobnum].virt <= zone_table[zone].top &&
	 mob_index[mobnum].doesLoad){
	if(zone_table[zone].enabled)
	  activemobcount++;
	break;
      }
    }
  }

  buf = fmt("\n--\nTotal mobs: %i\n\r") % mcount;
  sb += buf;
  if(mcount>0){
    buf = fmt("You have killed %1.2f%c of all mobs.\n\r") %((float)((float)mcount/(float)activemobcount)*100.0) % '%';
    sb += buf;
  }

  if (desc)
    desc->page_string(sb, SHOWNOW_NO, ALLOWREP_YES);

  return;
}

void TTrophy::wipe(){
  db->query("select id from player where name='%s'", getMyName().c_str());

  if(db->fetchRow())
    db->query("delete from trophy where player_id=%i", convertTo<int>((*db)["id"]));

}
<|endoftext|>


<commit_before>#include "stdsneezy.h"
#include "database.h"

#include <vector>
#include <string>

#include "cgicc/Cgicc.h"
#include "cgicc/HTTPHTMLHeader.h"
#include "cgicc/HTMLClasses.h"

using namespace cgicc;

void print_form()
{
  cout << "<form method=post action=\"/low/objlog.cgi\">" << endl;
  cout << "Filter on Object Name: <input type=text name=name>
" << endl;
  cout << "Filter on Object VNum: <input type=text name=vnum>
" << endl;
  cout << "<input type=hidden name=start value=1" << ">";
  cout << "<input type=submit>
" << endl;
  cout << "Notes:
" << endl;
  cout << "1.  Leaving both fields blank will list all entries in the log.
" << endl;
  cout << "2.  The object name field should use the % wildcard character.  Example: %shield%
" << endl;
  cout << "3.  If both fields are filled in, the script ignores the VNum field.
" << endl;
}

int main(int argc, char **argv)
{
  Cgicc cgi;
  TDatabase db(DB_SNEEZYPROD);
  // TDatabase db(DB_SNEEZYBETA);
  toggleInfo.loadToggles();

  form_iterator name = cgi.getElement("name");
  form_iterator vnum = cgi.getElement("vnum");
  form_iterator start = cgi.getElement("start");

  if (start == cgi.getElements().end()) {
    cout << HTTPHTMLHeader() << endl;
    cout << html() << head(title("Object Load Logs")) << endl;
    cout << body() << endl;
    print_form();
    cout << body() << endl;
  } else {
    cout << HTTPHTMLHeader() << endl;
    cout << html() << head(title("Object Load Logs")) << endl;
    cout << body() << endl;

    print_form();
    cout << "
" << endl;
    cout << "
" << endl;
    cout << "    VNum	" << endl;
    cout << "    Object Name	" << endl;
    cout << "    Loadtime	" << endl;
    cout << "    Count	" << endl;
    cout << "
" << endl;

    if ((**vnum).empty() && (**name).empty()) {
      db.query("select l.vnum, o.name, l.loadtime::timestamp(0), l.objcount from objlog l, obj o where l.vnum = o.vnum order by l.loadtime");
    } else if ((**vnum).empty()) {
      db.query("select l.vnum, o.name, l.loadtime::timestamp(0), l.objcount from objlog l, obj o where l.vnum = o.vnum and o.name like '%s' order by l.loadtime", (**name).c_str());
    } else if ((**name).empty()) {
      db.query("select l.vnum, o.name, l.loadtime::timestamp(0), l.objcount from objlog l, obj o where l.vnum = o.vnum and l.vnum=%i order by l.loadtime", convertTo<int>(**vnum));
    }
    while(db.fetchRow()){
      cout << "
" << endl;
      cout << "    " << stripColorCodes(db["vnum"]) << "	" << endl;
      cout << "    " << stripColorCodes(db["name"]) << "	" << endl;
      cout << "    " << stripColorCodes(db["loadtime"]) << "	" << endl;
      cout << "    " << stripColorCodes(db["objcount"]) << "	" << endl;
      cout << "
" << endl;
    }
    cout << "
" << endl;
    cout << body() << endl;
  }
  cout << html() << endl;
}
<commit_msg>Improved the logic flow a bit and reduced the number of repeated lines.<commit_after>#include "stdsneezy.h"
#include "database.h"

#include <vector>
#include <string>

#include "cgicc/Cgicc.h"
#include "cgicc/HTTPHTMLHeader.h"
#include "cgicc/HTMLClasses.h"

using namespace cgicc;

void print_form()
{
  cout << "<form method=post action=\"/low/objlog.cgi\">" << endl;
  cout << "Filter on Object Name: <input type=text name=name>
" << endl;
  cout << "Filter on Object VNum: <input type=text name=vnum>
" << endl;
  cout << "<input type=hidden name=start value=1" << ">";
  cout << "<input type=submit>
" << endl;
  cout << "Notes:
" << endl;
  cout << "1.  Leaving both fields blank will list all entries in the log.
" << endl;
  cout << "2.  The object name field should use the % wildcard character.  Example: %shield%
" << endl;
  cout << "3.  If both fields are filled in, the script ignores the VNum field.
" << endl;
}

int main(int argc, char **argv)
{
  Cgicc cgi;
  string my_query;
  TDatabase db(DB_SNEEZYPROD);
  // TDatabase db(DB_SNEEZYBETA);

  toggleInfo.loadToggles();

  form_iterator name = cgi.getElement("name");
  form_iterator vnum = cgi.getElement("vnum");
  form_iterator start = cgi.getElement("start");

  if (start == cgi.getElements().end()) {
    cout << HTTPHTMLHeader() << endl;
    cout << html() << head(title("Object Load Logs")) << endl;
    cout << body() << endl;
    print_form();
    cout << body() << endl;
  } else {
    cout << HTTPHTMLHeader() << endl;
    cout << html() << head(title("Object Load Logs")) << endl;
    cout << body() << endl;

    print_form();
    cout << "
" << endl;
    cout << "
" << endl;
    cout << "    VNum	" << endl;
    cout << "    Object Name	" << endl;
    cout << "    Loadtime	" << endl;
    cout << "    Count	" << endl;
    cout << "
" << endl;

    my_query = "select l.vnum, o.name, l.loadtime::timestamp(0), l.objcount from objlog l, obj o where l.vnum = o.vnum";
    if ((**vnum).empty() && (**name).empty()) {
      my_query += " order by l.loadtime";
      db.query(my_query.c_str());
    } else if ((**name).empty()) {
      my_query += " and l.vnum=%i order by l.loadtime";
      db.query(my_query.c_str(), convertTo<int>(**vnum));
    } else {
      my_query += " and o.name like '%s' order by l.loadtime";
      db.query(my_query.c_str(), (**name).c_str());
    }
    while(db.fetchRow()){
      cout << "
" << endl;
      cout << "    " << stripColorCodes(db["vnum"]) << "	" << endl;
      cout << "    " << stripColorCodes(db["name"]) << "	" << endl;
      cout << "    " << stripColorCodes(db["loadtime"]) << "	" << endl;
      cout << "    " << stripColorCodes(db["objcount"]) << "	" << endl;
      cout << "
" << endl;
    }
    cout << "
" << endl;
    cout << body() << endl;
  }
  cout << html() << endl;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "propacc.hxx"

#include <basic/sbstar.hxx>
#include <basic/sbuno.hxx>
#include <sbunoobj.hxx>
#include <limits.h>

using com::sun::star::uno::Reference;
using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace cppu;

struct SbCompare_UString_PropertyValue_Impl
{
   bool operator() (PropertyValue const & lhs, const OUString& rhs)
   {
      return lhs.Name.compareTo(rhs) < 0;
   }
};

extern "C" int SAL_CALL SbCompare_UString_Property_Impl( const void *arg1, const void *arg2 )
{
    const OUString *pArg1 = (OUString*) arg1;
    const Property *pArg2 = (Property*) arg2;
    return pArg1->compareTo( pArg2->Name );
}

SbPropertyValues::SbPropertyValues()
{
}

SbPropertyValues::~SbPropertyValues()
{
    m_xInfo.clear();
}

Reference< XPropertySetInfo > SbPropertyValues::getPropertySetInfo(void) throw( RuntimeException, std::exception )
{
    // create on demand?
    if (!m_xInfo.is())
    {
        SbPropertySetInfo *pInfo = new SbPropertySetInfo( m_aPropVals );
        m_xInfo.set(pInfo);
    }
    return m_xInfo;
}

size_t SbPropertyValues::GetIndex_Impl( const OUString &rPropName ) const
{
    SbPropertyValueArr_Impl::const_iterator it = std::lower_bound(
          m_aPropVals.begin(), m_aPropVals.end(), rPropName,
          SbCompare_UString_PropertyValue_Impl() );
    if (it == m_aPropVals.end())
    {
        throw beans::UnknownPropertyException(
                "Property not found: " + rPropName,
                const_cast<SbPropertyValues&>(*this));
    }
    return it - m_aPropVals.begin();
}

void SbPropertyValues::setPropertyValue(
                    const OUString& aPropertyName,
                    const Any& aValue)
                    throw (::com::sun::star::beans::UnknownPropertyException,
                    ::com::sun::star::beans::PropertyVetoException,
                    ::com::sun::star::lang::IllegalArgumentException,
                    ::com::sun::star::lang::WrappedTargetException,
                    ::com::sun::star::uno::RuntimeException, std::exception)
{
    size_t const nIndex = GetIndex_Impl( aPropertyName );
    PropertyValue & rPropVal = m_aPropVals[nIndex];
    rPropVal.Value = aValue;
}

Any SbPropertyValues::getPropertyValue(
                    const OUString& aPropertyName)
                    throw(::com::sun::star::beans::UnknownPropertyException,
                    ::com::sun::star::lang::WrappedTargetException,
                    ::com::sun::star::uno::RuntimeException, std::exception)
{
    size_t const nIndex = GetIndex_Impl( aPropertyName );
    return m_aPropVals[nIndex].Value;
}

void SbPropertyValues::addPropertyChangeListener(
                    const OUString& aPropertyName,
                    const Reference< XPropertyChangeListener >& )
                    throw (std::exception)
{
    (void)aPropertyName;
}

void SbPropertyValues::removePropertyChangeListener(
                    const OUString& aPropertyName,
                    const Reference< XPropertyChangeListener >& )
                    throw (std::exception)
{
    (void)aPropertyName;
}

void SbPropertyValues::addVetoableChangeListener(
                    const OUString& aPropertyName,
                    const Reference< XVetoableChangeListener >& )
                    throw(std::exception)
{
    (void)aPropertyName;
}

void SbPropertyValues::removeVetoableChangeListener(
                    const OUString& aPropertyName,
                    const Reference< XVetoableChangeListener >& )
                    throw(std::exception)
{
    (void)aPropertyName;
}

Sequence< PropertyValue > SbPropertyValues::getPropertyValues(void) throw (::com::sun::star::uno::RuntimeException, std::exception)
{
    Sequence<PropertyValue> aRet( m_aPropVals.size() );
    for (size_t n = 0; n < m_aPropVals.size(); ++n)
        aRet.getArray()[n] = m_aPropVals[n];
    return aRet;
}

void SbPropertyValues::setPropertyValues(const Sequence< PropertyValue >& rPropertyValues )
                     throw (::com::sun::star::beans::UnknownPropertyException,
                     ::com::sun::star::beans::PropertyVetoException,
                     ::com::sun::star::lang::IllegalArgumentException,
                     ::com::sun::star::lang::WrappedTargetException,
                     ::com::sun::star::uno::RuntimeException, std::exception)
{
    if ( !m_aPropVals.empty() )
        throw PropertyExistException();

    const PropertyValue *pPropVals = rPropertyValues.getConstArray();
    for (sal_Int32 n = 0; n < rPropertyValues.getLength(); ++n)
    {
        PropertyValue *pPropVal = new PropertyValue(pPropVals[n]);
        m_aPropVals.push_back( pPropVal );
    }
}

//PropertySetInfoImpl

PropertySetInfoImpl::PropertySetInfoImpl()
{
}

sal_Int32 PropertySetInfoImpl::GetIndex_Impl( const OUString &rPropName ) const
{
    Property *pP;
    pP = (Property*)
            bsearch( &rPropName, _aProps.getConstArray(), _aProps.getLength(),
                      sizeof( Property ),
                      SbCompare_UString_Property_Impl );
    return pP ? sal::static_int_cast<sal_Int32>( pP - _aProps.getConstArray() ) : -1;
}

Sequence< Property > PropertySetInfoImpl::getProperties(void) throw()
{
    return _aProps;
}

Property PropertySetInfoImpl::getPropertyByName(const OUString& Name) throw( RuntimeException )
{
    sal_Int32 nIndex = GetIndex_Impl( Name );
    if( USHRT_MAX != nIndex )
        return _aProps.getConstArray()[ nIndex ];
    return Property();
}

bool PropertySetInfoImpl::hasPropertyByName(const OUString& Name) throw( RuntimeException )
{
    sal_Int32 nIndex = GetIndex_Impl( Name );
    return USHRT_MAX != nIndex;
}

SbPropertySetInfo::SbPropertySetInfo( const SbPropertyValueArr_Impl &rPropVals )
{
    aImpl._aProps.realloc( rPropVals.size() );
    for ( sal_uInt16 n = 0; n < rPropVals.size(); ++n )
    {
        Property &rProp = aImpl._aProps.getArray()[n];
        const PropertyValue &rPropVal = rPropVals[n];
        rProp.Name = rPropVal.Name;
        rProp.Handle = rPropVal.Handle;
        rProp.Type = getCppuVoidType();
        rProp.Attributes = 0;
    }
}

SbPropertySetInfo::~SbPropertySetInfo()
{
}

Sequence< Property > SbPropertySetInfo::getProperties(void) throw( RuntimeException, std::exception )
{
    return aImpl.getProperties();
}

Property SbPropertySetInfo::getPropertyByName(const OUString& Name)
    throw( RuntimeException, std::exception )
{
    return aImpl.getPropertyByName( Name );
}

sal_Bool SbPropertySetInfo::hasPropertyByName(const OUString& Name)
    throw( RuntimeException, std::exception )
{
    return aImpl.hasPropertyByName( Name );
}

void RTL_Impl_CreatePropertySet( StarBASIC* pBasic, SbxArray& rPar, bool bWrite )
{
    (void)pBasic;
    (void)bWrite;

    // We need at least one parameter
    // TODO: In this case < 2 is not correct ;-)
    if ( rPar.Count() < 2 )
    {
        StarBASIC::Error( SbERR_BAD_ARGUMENT );
        return;
    }

    // Get class names of struct
    OUString aServiceName( "stardiv.uno.beans.PropertySet");

    Reference< XInterface > xInterface = (OWeakObject*) new SbPropertyValues();

    SbxVariableRef refVar = rPar.Get(0);
    if( xInterface.is() )
    {
        // Set PropertyValues
        Any aArgAsAny = sbxToUnoValue( rPar.Get(1),
                getCppuType( (Sequence<PropertyValue>*)0 ) );
        Sequence<PropertyValue> *pArg =
                (Sequence<PropertyValue>*) aArgAsAny.getValue();
        Reference< XPropertyAccess > xPropAcc = Reference< XPropertyAccess >::query( xInterface );
        xPropAcc->setPropertyValues( *pArg );

        // Build a SbUnoObject and return it
        Any aAny;
        aAny <<= xInterface;
        SbUnoObjectRef xUnoObj = new SbUnoObject( aServiceName, aAny );
        if( xUnoObj->getUnoAny().getValueType().getTypeClass() != TypeClass_VOID )
        {
            // Return object
            refVar->PutObject( (SbUnoObject*)xUnoObj );
            return;
        }
    }

    // Object could not be created
    refVar->PutObject( NULL );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#706231 Uncaught exception<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "propacc.hxx"

#include <basic/sbstar.hxx>
#include <basic/sbuno.hxx>
#include <sbunoobj.hxx>
#include <limits.h>

using com::sun::star::uno::Reference;
using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace cppu;

struct SbCompare_UString_PropertyValue_Impl
{
   bool operator() (PropertyValue const & lhs, const OUString& rhs)
   {
      return lhs.Name.compareTo(rhs) < 0;
   }
};

extern "C" int SAL_CALL SbCompare_UString_Property_Impl( const void *arg1, const void *arg2 )
{
    const OUString *pArg1 = (OUString*) arg1;
    const Property *pArg2 = (Property*) arg2;
    return pArg1->compareTo( pArg2->Name );
}

SbPropertyValues::SbPropertyValues()
{
}

SbPropertyValues::~SbPropertyValues()
{
    m_xInfo.clear();
}

Reference< XPropertySetInfo > SbPropertyValues::getPropertySetInfo(void) throw( RuntimeException, std::exception )
{
    // create on demand?
    if (!m_xInfo.is())
    {
        SbPropertySetInfo *pInfo = new SbPropertySetInfo( m_aPropVals );
        m_xInfo.set(pInfo);
    }
    return m_xInfo;
}

size_t SbPropertyValues::GetIndex_Impl( const OUString &rPropName ) const
{
    SbPropertyValueArr_Impl::const_iterator it = std::lower_bound(
          m_aPropVals.begin(), m_aPropVals.end(), rPropName,
          SbCompare_UString_PropertyValue_Impl() );
    if (it == m_aPropVals.end())
    {
        throw beans::UnknownPropertyException(
                "Property not found: " + rPropName,
                const_cast<SbPropertyValues&>(*this));
    }
    return it - m_aPropVals.begin();
}

void SbPropertyValues::setPropertyValue(
                    const OUString& aPropertyName,
                    const Any& aValue)
                    throw (::com::sun::star::beans::UnknownPropertyException,
                    ::com::sun::star::beans::PropertyVetoException,
                    ::com::sun::star::lang::IllegalArgumentException,
                    ::com::sun::star::lang::WrappedTargetException,
                    ::com::sun::star::uno::RuntimeException, std::exception)
{
    size_t const nIndex = GetIndex_Impl( aPropertyName );
    PropertyValue & rPropVal = m_aPropVals[nIndex];
    rPropVal.Value = aValue;
}

Any SbPropertyValues::getPropertyValue(
                    const OUString& aPropertyName)
                    throw(::com::sun::star::beans::UnknownPropertyException,
                    ::com::sun::star::lang::WrappedTargetException,
                    ::com::sun::star::uno::RuntimeException, std::exception)
{
    size_t const nIndex = GetIndex_Impl( aPropertyName );
    return m_aPropVals[nIndex].Value;
}

void SbPropertyValues::addPropertyChangeListener(
                    const OUString& aPropertyName,
                    const Reference< XPropertyChangeListener >& )
                    throw (std::exception)
{
    (void)aPropertyName;
}

void SbPropertyValues::removePropertyChangeListener(
                    const OUString& aPropertyName,
                    const Reference< XPropertyChangeListener >& )
                    throw (std::exception)
{
    (void)aPropertyName;
}

void SbPropertyValues::addVetoableChangeListener(
                    const OUString& aPropertyName,
                    const Reference< XVetoableChangeListener >& )
                    throw(std::exception)
{
    (void)aPropertyName;
}

void SbPropertyValues::removeVetoableChangeListener(
                    const OUString& aPropertyName,
                    const Reference< XVetoableChangeListener >& )
                    throw(std::exception)
{
    (void)aPropertyName;
}

Sequence< PropertyValue > SbPropertyValues::getPropertyValues(void) throw (::com::sun::star::uno::RuntimeException, std::exception)
{
    Sequence<PropertyValue> aRet( m_aPropVals.size() );
    for (size_t n = 0; n < m_aPropVals.size(); ++n)
        aRet.getArray()[n] = m_aPropVals[n];
    return aRet;
}

void SbPropertyValues::setPropertyValues(const Sequence< PropertyValue >& rPropertyValues )
                     throw (::com::sun::star::beans::UnknownPropertyException,
                     ::com::sun::star::beans::PropertyVetoException,
                     ::com::sun::star::lang::IllegalArgumentException,
                     ::com::sun::star::lang::WrappedTargetException,
                     ::com::sun::star::uno::RuntimeException, std::exception)
{
    if ( !m_aPropVals.empty() )
        throw IllegalArgumentException();

    const PropertyValue *pPropVals = rPropertyValues.getConstArray();
    for (sal_Int32 n = 0; n < rPropertyValues.getLength(); ++n)
    {
        PropertyValue *pPropVal = new PropertyValue(pPropVals[n]);
        m_aPropVals.push_back( pPropVal );
    }
}

//PropertySetInfoImpl

PropertySetInfoImpl::PropertySetInfoImpl()
{
}

sal_Int32 PropertySetInfoImpl::GetIndex_Impl( const OUString &rPropName ) const
{
    Property *pP;
    pP = (Property*)
            bsearch( &rPropName, _aProps.getConstArray(), _aProps.getLength(),
                      sizeof( Property ),
                      SbCompare_UString_Property_Impl );
    return pP ? sal::static_int_cast<sal_Int32>( pP - _aProps.getConstArray() ) : -1;
}

Sequence< Property > PropertySetInfoImpl::getProperties(void) throw()
{
    return _aProps;
}

Property PropertySetInfoImpl::getPropertyByName(const OUString& Name) throw( RuntimeException )
{
    sal_Int32 nIndex = GetIndex_Impl( Name );
    if( USHRT_MAX != nIndex )
        return _aProps.getConstArray()[ nIndex ];
    return Property();
}

bool PropertySetInfoImpl::hasPropertyByName(const OUString& Name) throw( RuntimeException )
{
    sal_Int32 nIndex = GetIndex_Impl( Name );
    return USHRT_MAX != nIndex;
}

SbPropertySetInfo::SbPropertySetInfo( const SbPropertyValueArr_Impl &rPropVals )
{
    aImpl._aProps.realloc( rPropVals.size() );
    for ( sal_uInt16 n = 0; n < rPropVals.size(); ++n )
    {
        Property &rProp = aImpl._aProps.getArray()[n];
        const PropertyValue &rPropVal = rPropVals[n];
        rProp.Name = rPropVal.Name;
        rProp.Handle = rPropVal.Handle;
        rProp.Type = getCppuVoidType();
        rProp.Attributes = 0;
    }
}

SbPropertySetInfo::~SbPropertySetInfo()
{
}

Sequence< Property > SbPropertySetInfo::getProperties(void) throw( RuntimeException, std::exception )
{
    return aImpl.getProperties();
}

Property SbPropertySetInfo::getPropertyByName(const OUString& Name)
    throw( RuntimeException, std::exception )
{
    return aImpl.getPropertyByName( Name );
}

sal_Bool SbPropertySetInfo::hasPropertyByName(const OUString& Name)
    throw( RuntimeException, std::exception )
{
    return aImpl.hasPropertyByName( Name );
}

void RTL_Impl_CreatePropertySet( StarBASIC* pBasic, SbxArray& rPar, bool bWrite )
{
    (void)pBasic;
    (void)bWrite;

    // We need at least one parameter
    // TODO: In this case < 2 is not correct ;-)
    if ( rPar.Count() < 2 )
    {
        StarBASIC::Error( SbERR_BAD_ARGUMENT );
        return;
    }

    // Get class names of struct
    OUString aServiceName( "stardiv.uno.beans.PropertySet");

    Reference< XInterface > xInterface = (OWeakObject*) new SbPropertyValues();

    SbxVariableRef refVar = rPar.Get(0);
    if( xInterface.is() )
    {
        // Set PropertyValues
        Any aArgAsAny = sbxToUnoValue( rPar.Get(1),
                getCppuType( (Sequence<PropertyValue>*)0 ) );
        Sequence<PropertyValue> *pArg =
                (Sequence<PropertyValue>*) aArgAsAny.getValue();
        Reference< XPropertyAccess > xPropAcc = Reference< XPropertyAccess >::query( xInterface );
        xPropAcc->setPropertyValues( *pArg );

        // Build a SbUnoObject and return it
        Any aAny;
        aAny <<= xInterface;
        SbUnoObjectRef xUnoObj = new SbUnoObject( aServiceName, aAny );
        if( xUnoObj->getUnoAny().getValueType().getTypeClass() != TypeClass_VOID )
        {
            // Return object
            refVar->PutObject( (SbUnoObject*)xUnoObj );
            return;
        }
    }

    // Object could not be created
    refVar->PutObject( NULL );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2003-2009, John Wiegley.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * - Neither the name of New Artisans LLC nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <system.hh>

#include "pyinterp.h"
#include "pyutils.h"
#include "hooks.h"
#include "journal.h"
#include "xact.h"

namespace ledger {

using namespace boost::python;

namespace {

  account_t& py_account_master(journal_t& journal) {
    return *journal.master;
  }

  commodity_pool_t& py_commodity_pool(journal_t& journal) {
    return *journal.commodity_pool;
  }

  long xacts_len(journal_t& journal)
  {
    return journal.xacts.size();
  }

  xact_t& xacts_getitem(journal_t& journal, long i)
  {
    static long last_index = 0;
    static journal_t * last_journal = NULL;
    static xacts_list::iterator elem;

    long len = journal.xacts.size();

    if (labs(i) >= len) {
      PyErr_SetString(PyExc_IndexError, _("Index out of range"));
      throw_error_already_set();
    }

    if (&journal == last_journal && i == last_index + 1) {
      last_index = i;
      return **++elem;
    }

    long x = i < 0 ? len + i : i;
    elem = journal.xacts.begin();
    while (--x >= 0)
      elem++;

    last_journal = &journal;
    last_index   = i;

    return **elem;
  }

  long accounts_len(account_t& account)
  {
    return account.accounts.size();
  }

  account_t& accounts_getitem(account_t& account, long i)
  {
    static long last_index = 0;
    static account_t * last_account = NULL;
    static accounts_map::iterator elem;

    long len = account.accounts.size();

    if (labs(i) >= len) {
      PyErr_SetString(PyExc_IndexError, _("Index out of range"));
      throw_error_already_set();
    }

    if (&account == last_account && i == last_index + 1) {
      last_index = i;
      return *(*++elem).second;
    }

    long x = i < 0 ? len + i : i;
    elem = account.accounts.begin();
    while (--x >= 0)
      elem++;

    last_account = &account;
    last_index   = i;

    return *(*elem).second;
  }

  account_t * py_find_account_1(journal_t& journal, const string& name)
  {
    return journal.find_account(name);
  }

  account_t * py_find_account_2(journal_t& journal, const string& name,
				const bool auto_create)
  {
    return journal.find_account(name, auto_create);
  }

  struct py_xact_finalizer_t : public xact_finalizer_t {
    object pyobj;
    py_xact_finalizer_t() {}
    py_xact_finalizer_t(object obj) : pyobj(obj) {}
    py_xact_finalizer_t(const py_xact_finalizer_t& other)
      : pyobj(other.pyobj) {}
    virtual bool operator()(xact_t& xact, bool post) {
      return call<bool>(pyobj.ptr(), xact, post);
    }
  };

  std::list<py_xact_finalizer_t> py_finalizers;

  void py_add_xact_finalizer(journal_t& journal, object x)
  {
    py_finalizers.push_back(py_xact_finalizer_t(x));
    journal.add_xact_finalizer(&py_finalizers.back());
  }

  void py_remove_xact_finalizer(journal_t& journal, object x)
  {
    for (std::list<py_xact_finalizer_t>::iterator i = py_finalizers.begin();
	 i != py_finalizers.end();
	 i++)
      if ((*i).pyobj == x) {
	journal.remove_xact_finalizer(&(*i));
	py_finalizers.erase(i);
	return;
      }
  }

  void py_run_xact_finalizers(journal_t& journal, xact_t& xact, bool post)
  {
    journal.xact_finalize_hooks.run_hooks(xact, post);
  }

} // unnamed namespace

void export_journal()
{
  class_< journal_t::fileinfo_t > ("FileInfo")
    .def(init<path>())

    .add_property("filename",
		  make_getter(&journal_t::fileinfo_t::filename),
		  make_setter(&journal_t::fileinfo_t::filename))
    .add_property("size",
		  make_getter(&journal_t::fileinfo_t::size),
		  make_setter(&journal_t::fileinfo_t::size))
    .add_property("modtime",
		  make_getter(&journal_t::fileinfo_t::modtime),
		  make_setter(&journal_t::fileinfo_t::modtime))
    .add_property("from_stream",
		  make_getter(&journal_t::fileinfo_t::from_stream),
		  make_setter(&journal_t::fileinfo_t::from_stream))
    ;

  class_< journal_t, boost::noncopyable > ("Journal")
    .def(init<path>())
    .def(init<string>())

    .add_property("master", make_getter(&journal_t::master,
					return_internal_reference<>()))
    .add_property("bucket",
		  make_getter(&journal_t::bucket,
			      return_internal_reference<>()),
		  make_setter(&journal_t::bucket))
    .add_property("was_loaded", make_getter(&journal_t::was_loaded))
    .add_property("commodity_pool",
		  make_getter(&journal_t::commodity_pool,
			      return_internal_reference<>()))
#if 0
    .add_property("xact_finalize_hooks",
		  make_getter(&journal_t::xact_finalize_hooks),
		  make_setter(&journal_t::xact_finalize_hooks))
#endif

    .def("add_account", &journal_t::add_account)
    .def("remove_account", &journal_t::remove_account)

    .def("find_account", py_find_account_1, return_internal_reference<>())
    .def("find_account", py_find_account_2, return_internal_reference<>())
    .def("find_account_re", &journal_t::find_account_re,
	 return_internal_reference<>())

    .def("add_xact", &journal_t::add_xact)
    .def("remove_xact", &journal_t::remove_xact)

    .def("add_xact_finalizer", py_add_xact_finalizer)
    .def("remove_xact_finalizer", py_remove_xact_finalizer)
    .def("run_xact_finalizers", py_run_xact_finalizers)

    .def("__len__", xacts_len)
    .def("__getitem__", xacts_getitem, return_internal_reference<1>())

    .def("__iter__", range<return_internal_reference<> >
	 (&journal_t::xacts_begin, &journal_t::xacts_end))
    .def("xacts", range<return_internal_reference<> >
	 (&journal_t::xacts_begin, &journal_t::xacts_end))
    .def("auto_xacts", range<return_internal_reference<> >
	 (&journal_t::auto_xacts_begin, &journal_t::auto_xacts_end))
    .def("period_xacts", range<return_internal_reference<> >
	 (&journal_t::period_xacts_begin, &journal_t::period_xacts_end))
    .def("sources", range<return_internal_reference<> >
	 (&journal_t::sources_begin, &journal_t::sources_end))

    .def("clear_xdata", &journal_t::clear_xdata)

    .def("valid", &journal_t::valid)
    ;
}

} // namespace ledger
<commit_msg>Expose journal_t::read to Python<commit_after>/*
 * Copyright (c) 2003-2009, John Wiegley.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * - Neither the name of New Artisans LLC nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <system.hh>

#include "pyinterp.h"
#include "pyutils.h"
#include "hooks.h"
#include "journal.h"
#include "xact.h"

namespace ledger {

using namespace boost::python;

namespace {

  account_t& py_account_master(journal_t& journal) {
    return *journal.master;
  }

  commodity_pool_t& py_commodity_pool(journal_t& journal) {
    return *journal.commodity_pool;
  }

  long xacts_len(journal_t& journal)
  {
    return journal.xacts.size();
  }

  xact_t& xacts_getitem(journal_t& journal, long i)
  {
    static long last_index = 0;
    static journal_t * last_journal = NULL;
    static xacts_list::iterator elem;

    long len = journal.xacts.size();

    if (labs(i) >= len) {
      PyErr_SetString(PyExc_IndexError, _("Index out of range"));
      throw_error_already_set();
    }

    if (&journal == last_journal && i == last_index + 1) {
      last_index = i;
      return **++elem;
    }

    long x = i < 0 ? len + i : i;
    elem = journal.xacts.begin();
    while (--x >= 0)
      elem++;

    last_journal = &journal;
    last_index   = i;

    return **elem;
  }

  long accounts_len(account_t& account)
  {
    return account.accounts.size();
  }

  account_t& accounts_getitem(account_t& account, long i)
  {
    static long last_index = 0;
    static account_t * last_account = NULL;
    static accounts_map::iterator elem;

    long len = account.accounts.size();

    if (labs(i) >= len) {
      PyErr_SetString(PyExc_IndexError, _("Index out of range"));
      throw_error_already_set();
    }

    if (&account == last_account && i == last_index + 1) {
      last_index = i;
      return *(*++elem).second;
    }

    long x = i < 0 ? len + i : i;
    elem = account.accounts.begin();
    while (--x >= 0)
      elem++;

    last_account = &account;
    last_index   = i;

    return *(*elem).second;
  }

  account_t * py_find_account_1(journal_t& journal, const string& name)
  {
    return journal.find_account(name);
  }

  account_t * py_find_account_2(journal_t& journal, const string& name,
				const bool auto_create)
  {
    return journal.find_account(name, auto_create);
  }

  struct py_xact_finalizer_t : public xact_finalizer_t {
    object pyobj;
    py_xact_finalizer_t() {}
    py_xact_finalizer_t(object obj) : pyobj(obj) {}
    py_xact_finalizer_t(const py_xact_finalizer_t& other)
      : pyobj(other.pyobj) {}
    virtual bool operator()(xact_t& xact, bool post) {
      return call<bool>(pyobj.ptr(), xact, post);
    }
  };

  std::list<py_xact_finalizer_t> py_finalizers;

  void py_add_xact_finalizer(journal_t& journal, object x)
  {
    py_finalizers.push_back(py_xact_finalizer_t(x));
    journal.add_xact_finalizer(&py_finalizers.back());
  }

  void py_remove_xact_finalizer(journal_t& journal, object x)
  {
    for (std::list<py_xact_finalizer_t>::iterator i = py_finalizers.begin();
	 i != py_finalizers.end();
	 i++)
      if ((*i).pyobj == x) {
	journal.remove_xact_finalizer(&(*i));
	py_finalizers.erase(i);
	return;
      }
  }

  void py_run_xact_finalizers(journal_t& journal, xact_t& xact, bool post)
  {
    journal.xact_finalize_hooks.run_hooks(xact, post);
  }

  std::size_t py_read(journal_t& journal, const string& pathname)
  {
    return journal.read(pathname);
  }

} // unnamed namespace

void export_journal()
{
  class_< journal_t::fileinfo_t > ("FileInfo")
    .def(init<path>())

    .add_property("filename",
		  make_getter(&journal_t::fileinfo_t::filename),
		  make_setter(&journal_t::fileinfo_t::filename))
    .add_property("size",
		  make_getter(&journal_t::fileinfo_t::size),
		  make_setter(&journal_t::fileinfo_t::size))
    .add_property("modtime",
		  make_getter(&journal_t::fileinfo_t::modtime),
		  make_setter(&journal_t::fileinfo_t::modtime))
    .add_property("from_stream",
		  make_getter(&journal_t::fileinfo_t::from_stream),
		  make_setter(&journal_t::fileinfo_t::from_stream))
    ;

  class_< journal_t, boost::noncopyable > ("Journal")
    .def(init<path>())
    .def(init<string>())

    .add_property("master", make_getter(&journal_t::master,
					return_internal_reference<>()))
    .add_property("bucket",
		  make_getter(&journal_t::bucket,
			      return_internal_reference<>()),
		  make_setter(&journal_t::bucket))
    .add_property("was_loaded", make_getter(&journal_t::was_loaded))
    .add_property("commodity_pool",
		  make_getter(&journal_t::commodity_pool,
			      return_internal_reference<>()))
#if 0
    .add_property("xact_finalize_hooks",
		  make_getter(&journal_t::xact_finalize_hooks),
		  make_setter(&journal_t::xact_finalize_hooks))
#endif

    .def("add_account", &journal_t::add_account)
    .def("remove_account", &journal_t::remove_account)

    .def("find_account", py_find_account_1, return_internal_reference<>())
    .def("find_account", py_find_account_2, return_internal_reference<>())
    .def("find_account_re", &journal_t::find_account_re,
	 return_internal_reference<>())

    .def("add_xact", &journal_t::add_xact)
    .def("remove_xact", &journal_t::remove_xact)

    .def("add_xact_finalizer", py_add_xact_finalizer)
    .def("remove_xact_finalizer", py_remove_xact_finalizer)
    .def("run_xact_finalizers", py_run_xact_finalizers)

    .def("__len__", xacts_len)
    .def("__getitem__", xacts_getitem, return_internal_reference<1>())

    .def("__iter__", range<return_internal_reference<> >
	 (&journal_t::xacts_begin, &journal_t::xacts_end))
    .def("xacts", range<return_internal_reference<> >
	 (&journal_t::xacts_begin, &journal_t::xacts_end))
    .def("auto_xacts", range<return_internal_reference<> >
	 (&journal_t::auto_xacts_begin, &journal_t::auto_xacts_end))
    .def("period_xacts", range<return_internal_reference<> >
	 (&journal_t::period_xacts_begin, &journal_t::period_xacts_end))
    .def("sources", range<return_internal_reference<> >
	 (&journal_t::sources_begin, &journal_t::sources_end))

    .def("read", py_read)

    .def("clear_xdata", &journal_t::clear_xdata)

    .def("valid", &journal_t::valid)
    ;
}

} // namespace ledger
<|endoftext|>


<commit_before>/*
 * Race.cpp
 *
 *  Created on: 2009-09-25
 *      Author: chudy
 */

#include "Race.h"

#include <stdlib.h>

#include "Message.h"
#include "graphics/Stage.h"
#include "network/events.h"
#include "network/Client.h"

Race::Race(CL_DisplayWindow *p_window, Player *p_player, Client *p_client) :
	m_lapsNum(0),
	m_localPlayer(p_player),
	m_level(),
	m_inputLock(false),
	m_raceClient(&p_client->getRaceClient()),
	m_raceScene(this),
	m_displayWindow(p_window)
{
	// listen for local car status change
	m_slots.connect(m_localPlayer.getCar().sigStatusChange(), this, &Race::slotCarStateChangedLocal);
	// and for remote car status change
	m_slots.connect(m_raceClient->signalCarStateReceived(), this, &Race::slotCarStateChangedRemote);
	// race start countdown
	m_slots.connect(m_raceClient->signalStartCountdown(), this, &Race::slotStartCountdown);
	// countdown ends
	m_raceStartTimer.func_expired().set(this, &Race::slotCountdownEnds);
	// car lock
	m_slots.connect(m_raceClient->signalLockCar(), this, &Race::slotInputLock);
	// race state
	m_slots.connect(m_raceClient->signalRaceStateChanged(), this, &Race::slotRaceStateChanged);

	// player join
	m_slots.connect(p_client->signalPlayerConnected(), this, &Race::slotPlayerReady);
	// player leave
	m_slots.connect(p_client->signalPlayerDisconnected(), this, &Race::slotPlayerLeaving);

}

Race::~Race()
{
}

void Race::exec()
{

	m_level.addCar(&m_localPlayer.getCar());

	loadAll();

	unsigned lastTime = CL_System::get_time();

	while (true) { // FIXME: Check when race is finished

		const unsigned delta = CL_System::get_time() - lastTime;
		lastTime += delta;

		m_iterationMutex.lock();

		grabInput(delta);
		updateWorld(delta);
		drawScene(delta);

		m_iterationMutex.unlock();

		// Avoid using 100% CPU in the loop:
		static const int MS_60 = 1000 / 60;
		const int sleepTime = MS_60 - delta;

		if (sleepTime > 0) {
			CL_System::sleep(sleepTime);
		}

	}
}

void Race::loadAll()
{
	Debug::out() << "Loading race..." << std::endl;
	const unsigned start = CL_System::get_time();

	CL_GraphicContext gc = m_displayWindow->get_gc();
	m_raceScene.load(gc);

	const unsigned duration = CL_System::get_time() - start;
	Debug::out() << "Loaded in " << duration << " ms" << std::endl;
}

void Race::grabInput(unsigned delta)
{
	CL_InputDevice keyboard = m_displayWindow->get_ic().get_keyboard();
	Car &car = m_localPlayer.getCar();

	if (keyboard.get_keycode(CL_KEY_ESCAPE)) {
		exit(0); // TODO: Find better way to exit the race
	}

	if (!m_inputLock) {
		if (keyboard.get_keycode(CL_KEY_LEFT) && !keyboard.get_keycode(CL_KEY_RIGHT)) {
			car.setTurn(-1.0f);
		} else if (keyboard.get_keycode(CL_KEY_RIGHT) && !keyboard.get_keycode(CL_KEY_LEFT)) {
			car.setTurn(1.0f);
		} else {
			car.setTurn(0.0f);
		}

		if (keyboard.get_keycode(CL_KEY_UP)) {
			car.setAcceleration(true);
		} else {
			car.setAcceleration(false);
		}

		if (keyboard.get_keycode(CL_KEY_DOWN)) {
			car.setBrake(true);
		} else {
			car.setBrake(false);
		}
	}

#ifndef NDEBUG
	// viewport change
	if (keyboard.get_keycode(CL_KEY_ADD)) {
		const float scale = m_raceScene.getViewport().getScale();
		m_raceScene.getViewport().setScale(scale + scale * 0.01f);
	}

	if (keyboard.get_keycode(CL_KEY_SUBTRACT)) {
		const float scale = m_raceScene.getViewport().getScale();
		m_raceScene.getViewport().setScale(scale - scale * 0.01f);
	}

	// trigger race start
	if (keyboard.get_keycode(CL_KEY_BACKSPACE)) {
		m_raceClient->triggerRaceStart(3);
	}

#endif
}

void Race::updateWorld(unsigned p_delta)
{
	// update all cars
	m_localPlayer.getCar().update(p_delta);

	const size_t remotePlayersSize = m_remotePlayers.size();

	for (size_t i = 0; i < remotePlayersSize; ++i) {
		m_remotePlayers[i]->getCar().update(p_delta);
	}

	// update the level
	m_level.update(p_delta);

	// update race scene
	m_raceScene.update(p_delta);
}

void Race::drawScene(unsigned p_delta)
{
	CL_GraphicContext gc = m_displayWindow->get_gc();

	gc.clear(CL_Colorf::cadetblue);

	m_raceScene.draw(gc);

	Stage::getDebugLayer()->draw(gc);

	// Make the stuff visible:
	m_displayWindow->flip();

	// Read messages from the windowing system message queue,
	// if any are available:
	CL_KeepAlive::process();
}

void Race::slotCarStateChangedRemote(const CL_NetGameEvent& p_event)
{

	Debug::out() << "handling " << p_event.get_name().c_str() << std::endl;

	// first argument will be name of player
	const CL_String name = (CL_String) p_event.get_argument(0);

	if (name.size() == 0) {
		// this is about me!
		cl_log_event("event", "setting myself to start position");
		m_localPlayer.getCar().applyStatusEvent(p_event, 1);
	} else {
		// remote player state
		RacePlayer *racePlayer = findPlayer(name);

		if (racePlayer == NULL) {
			Debug::err() << "remote player '" << name.c_str() << "' not found" << std::endl;
			return;
		}

		Car &car = racePlayer->getCar();
		car.applyStatusEvent(p_event, 1);
	}
}

RacePlayer *Race::findPlayer(const CL_String& p_name)
{
	const size_t remotePlayersSize = m_remotePlayers.size();

	for (size_t i = 0; i < remotePlayersSize; ++i) {
		if (m_remotePlayers[i]->getPlayer().getName() == p_name) {
			return m_remotePlayers[i];
		}
	}

	return NULL;
}

void Race::slotCarStateChangedLocal(Car &p_car)
{
	CL_NetGameEvent event(EVENT_CAR_STATE_CHANGE, m_localPlayer.getPlayer().getName());
	p_car.prepareStatusEvent(event);

	m_raceClient->sendCarStateEvent(event);
}

void Race::slotPlayerReady(Player* p_player)
{

	Debug::out() << "Player '" << p_player->getName().c_str() << "' has arrived" << std::endl;

	RacePlayer *racePlayer = new RacePlayer(p_player);

	m_iterationMutex.lock();

	m_remotePlayers.push_back(racePlayer);
	m_level.addCar(&racePlayer->getCar());

	m_iterationMutex.unlock();
}

void Race::slotPlayerLeaving(Player* p_player)
{

	Debug::out() << "Player '" << p_player->getName().c_str() << "' is leaving" << std::endl;

	m_iterationMutex.lock();

	for (
		std::vector<RacePlayer*>::iterator itor = m_remotePlayers.begin();
		itor != m_remotePlayers.end();
		++itor
	) {
		if (&(*itor)->getPlayer() == p_player) {

			// remove car
			m_level.removeCar(&(*itor)->getCar());

			delete *itor;
			m_remotePlayers.erase(itor);
		}
	}

	m_iterationMutex.unlock();
}

void Race::slotStartCountdown()
{
	cl_log_event("race", "starting countdown...");

	static const unsigned RACE_START_COUNTDOWN_TIME = 3000;

	m_raceStartTimer.start(RACE_START_COUNTDOWN_TIME, false);
	m_raceScene.getUI().displayCountdown();
}

void Race::slotCountdownEnds()
{
	m_inputLock = false;
}

void Race::slotInputLock()
{
	m_inputLock = true;
}

void Race::slotRaceStateChanged(int p_lapsNum)
{
	m_lapsNum = p_lapsNum;
	m_localPlayer.getCar().setLap(1);
}
<commit_msg>* Added handbrake action to SPACE<commit_after>/*
 * Race.cpp
 *
 *  Created on: 2009-09-25
 *      Author: chudy
 */

#include "Race.h"

#include <stdlib.h>

#include "Message.h"
#include "graphics/Stage.h"
#include "network/events.h"
#include "network/Client.h"

Race::Race(CL_DisplayWindow *p_window, Player *p_player, Client *p_client) :
	m_lapsNum(0),
	m_localPlayer(p_player),
	m_level(),
	m_inputLock(false),
	m_raceClient(&p_client->getRaceClient()),
	m_raceScene(this),
	m_displayWindow(p_window)
{
	// listen for local car status change
	m_slots.connect(m_localPlayer.getCar().sigStatusChange(), this, &Race::slotCarStateChangedLocal);
	// and for remote car status change
	m_slots.connect(m_raceClient->signalCarStateReceived(), this, &Race::slotCarStateChangedRemote);
	// race start countdown
	m_slots.connect(m_raceClient->signalStartCountdown(), this, &Race::slotStartCountdown);
	// countdown ends
	m_raceStartTimer.func_expired().set(this, &Race::slotCountdownEnds);
	// car lock
	m_slots.connect(m_raceClient->signalLockCar(), this, &Race::slotInputLock);
	// race state
	m_slots.connect(m_raceClient->signalRaceStateChanged(), this, &Race::slotRaceStateChanged);

	// player join
	m_slots.connect(p_client->signalPlayerConnected(), this, &Race::slotPlayerReady);
	// player leave
	m_slots.connect(p_client->signalPlayerDisconnected(), this, &Race::slotPlayerLeaving);

}

Race::~Race()
{
}

void Race::exec()
{

	m_level.addCar(&m_localPlayer.getCar());

	loadAll();

	unsigned lastTime = CL_System::get_time();

	while (true) { // FIXME: Check when race is finished

		const unsigned delta = CL_System::get_time() - lastTime;
		lastTime += delta;

		m_iterationMutex.lock();

		grabInput(delta);
		updateWorld(delta);
		drawScene(delta);

		m_iterationMutex.unlock();

		// Avoid using 100% CPU in the loop:
		static const int MS_60 = 1000 / 60;
		const int sleepTime = MS_60 - delta;

		if (sleepTime > 0) {
			CL_System::sleep(sleepTime);
		}

	}
}

void Race::loadAll()
{
	Debug::out() << "Loading race..." << std::endl;
	const unsigned start = CL_System::get_time();

	CL_GraphicContext gc = m_displayWindow->get_gc();
	m_raceScene.load(gc);

	const unsigned duration = CL_System::get_time() - start;
	Debug::out() << "Loaded in " << duration << " ms" << std::endl;
}

void Race::grabInput(unsigned delta)
{
	CL_InputDevice keyboard = m_displayWindow->get_ic().get_keyboard();
	Car &car = m_localPlayer.getCar();

	if (keyboard.get_keycode(CL_KEY_ESCAPE)) {
		exit(0); // TODO: Find better way to exit the race
	}

	if (!m_inputLock) {
		if (keyboard.get_keycode(CL_KEY_LEFT) && !keyboard.get_keycode(CL_KEY_RIGHT)) {
			car.setTurn(-1.0f);
		} else if (keyboard.get_keycode(CL_KEY_RIGHT) && !keyboard.get_keycode(CL_KEY_LEFT)) {
			car.setTurn(1.0f);
		} else {
			car.setTurn(0.0f);
		}

		if (keyboard.get_keycode(CL_KEY_UP)) {
			car.setAcceleration(true);
		} else {
			car.setAcceleration(false);
		}

		if (keyboard.get_keycode(CL_KEY_DOWN)) {
			car.setBrake(true);
		} else {
			car.setBrake(false);
		}

		if (keyboard.get_keycode(CL_KEY_SPACE)) {
			car.setHandbrake(true);
		} else {
			car.setHandbrake(false);
		}
	}

#ifndef NDEBUG
	// viewport change
	if (keyboard.get_keycode(CL_KEY_ADD)) {
		const float scale = m_raceScene.getViewport().getScale();
		m_raceScene.getViewport().setScale(scale + scale * 0.01f);
	}

	if (keyboard.get_keycode(CL_KEY_SUBTRACT)) {
		const float scale = m_raceScene.getViewport().getScale();
		m_raceScene.getViewport().setScale(scale - scale * 0.01f);
	}

	// trigger race start
	if (keyboard.get_keycode(CL_KEY_BACKSPACE)) {
		m_raceClient->triggerRaceStart(3);
	}

#endif
}

void Race::updateWorld(unsigned p_delta)
{
	// update all cars
	m_localPlayer.getCar().update(p_delta);

	const size_t remotePlayersSize = m_remotePlayers.size();

	for (size_t i = 0; i < remotePlayersSize; ++i) {
		m_remotePlayers[i]->getCar().update(p_delta);
	}

	// update the level
	m_level.update(p_delta);

	// update race scene
	m_raceScene.update(p_delta);
}

void Race::drawScene(unsigned p_delta)
{
	CL_GraphicContext gc = m_displayWindow->get_gc();

	gc.clear(CL_Colorf::cadetblue);

	m_raceScene.draw(gc);

	Stage::getDebugLayer()->draw(gc);

	// Make the stuff visible:
	m_displayWindow->flip();

	// Read messages from the windowing system message queue,
	// if any are available:
	CL_KeepAlive::process();
}

void Race::slotCarStateChangedRemote(const CL_NetGameEvent& p_event)
{

	Debug::out() << "handling " << p_event.get_name().c_str() << std::endl;

	// first argument will be name of player
	const CL_String name = (CL_String) p_event.get_argument(0);

	if (name.size() == 0) {
		// this is about me!
		cl_log_event("event", "setting myself to start position");
		m_localPlayer.getCar().applyStatusEvent(p_event, 1);
	} else {
		// remote player state
		RacePlayer *racePlayer = findPlayer(name);

		if (racePlayer == NULL) {
			Debug::err() << "remote player '" << name.c_str() << "' not found" << std::endl;
			return;
		}

		Car &car = racePlayer->getCar();
		car.applyStatusEvent(p_event, 1);
	}
}

RacePlayer *Race::findPlayer(const CL_String& p_name)
{
	const size_t remotePlayersSize = m_remotePlayers.size();

	for (size_t i = 0; i < remotePlayersSize; ++i) {
		if (m_remotePlayers[i]->getPlayer().getName() == p_name) {
			return m_remotePlayers[i];
		}
	}

	return NULL;
}

void Race::slotCarStateChangedLocal(Car &p_car)
{
	CL_NetGameEvent event(EVENT_CAR_STATE_CHANGE, m_localPlayer.getPlayer().getName());
	p_car.prepareStatusEvent(event);

	m_raceClient->sendCarStateEvent(event);
}

void Race::slotPlayerReady(Player* p_player)
{

	Debug::out() << "Player '" << p_player->getName().c_str() << "' has arrived" << std::endl;

	RacePlayer *racePlayer = new RacePlayer(p_player);

	m_iterationMutex.lock();

	m_remotePlayers.push_back(racePlayer);
	m_level.addCar(&racePlayer->getCar());

	m_iterationMutex.unlock();
}

void Race::slotPlayerLeaving(Player* p_player)
{

	Debug::out() << "Player '" << p_player->getName().c_str() << "' is leaving" << std::endl;

	m_iterationMutex.lock();

	for (
		std::vector<RacePlayer*>::iterator itor = m_remotePlayers.begin();
		itor != m_remotePlayers.end();
		++itor
	) {
		if (&(*itor)->getPlayer() == p_player) {

			// remove car
			m_level.removeCar(&(*itor)->getCar());

			delete *itor;
			m_remotePlayers.erase(itor);
		}
	}

	m_iterationMutex.unlock();
}

void Race::slotStartCountdown()
{
	cl_log_event("race", "starting countdown...");

	static const unsigned RACE_START_COUNTDOWN_TIME = 3000;

	m_raceStartTimer.start(RACE_START_COUNTDOWN_TIME, false);
	m_raceScene.getUI().displayCountdown();
}

void Race::slotCountdownEnds()
{
	m_inputLock = false;
}

void Race::slotInputLock()
{
	m_inputLock = true;
}

void Race::slotRaceStateChanged(int p_lapsNum)
{
	m_lapsNum = p_lapsNum;
	m_localPlayer.getCar().setLap(1);
}
<|endoftext|>


<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <common/config.h>

#if VSNRAY_COMMON_HAVE_3DCONNEXIONCLIENT

#include <cassert>

#include <3DConnexionClient/ConnexionClient.h>
#include <3DConnexionClient/ConnexionClientAPI.h>

#include "space_mouse.h"

// Import weak so we can later check if the
// driver is loaded by checking for NULL
extern int16_t SetConnexionHandlers(
        ConnexionMessageHandlerProc messageHandler,
        ConnexionAddedHandlerProc   addedHandler,
        ConnexionRemovedHandlerProc removedHandler,
        bool useSeparateThread
        ) __attribute__((weak_import));

namespace visionaray
{
namespace space_mouse
{

static uint16_t client_id = -1;

static event_callback event_callbacks[EventTypeCount] = { nullptr };

static void message_handler(unsigned product_id, unsigned message_type, void* message_arg)
{
    switch (message_type)
    {
    case kConnexionMsgDeviceState:
    {
        ConnexionDeviceState* state = reinterpret_cast<ConnexionDeviceState*>(message_arg);

        if (state->client == client_id)
        {
            switch (state->command)
            {
            case kConnexionCmdHandleAxis:
            {
                // Call translation handler
                if (event_callbacks[Translation] != nullptr && (state->axis[0] || state->axis[1] || state->axis[2]))
                {
                    event_callbacks[Translation](
                            space_mouse_event(Translation, pos(state->axis[0], state->axis[1], state->axis[2]))
                            );
                }

                // Call rotation handler
                if (event_callbacks[Rotation] != nullptr && (state->axis[3] || state->axis[4] || state->axis[5]))
                {
                    event_callbacks[Rotation](
                            space_mouse_event(Rotation, pos(state->axis[3], state->axis[4], state->axis[5]))
                            );
                }
                break;
            }
            case kConnexionCmdHandleButtons:
                // TODO
                break;
            }
        }
    }
    default:
        break;
    }
}

bool init()
{
    if (SetConnexionHandlers == 0)
    {
        // Driver not loaded
        return false;
    }

    // Register callback
    int16_t err = SetConnexionHandlers(message_handler, 0, 0, false);

    // Take space mouse over system-wide
    client_id = RegisterConnexionClient(
            'vsnr',
            0,
            kConnexionClientModeTakeOver,
            kConnexionMaskAll
            );

    return true;
}

void register_event_callback(event_type type, event_callback cb)
{
    assert(type < EventTypeCount);

    event_callbacks[type] = cb;
}

void cleanup()
{
	if (SetConnexionHandlers != 0)
	{
        if (client_id)
        {
            UnregisterConnexionClient(client_id);
        }

        CleanupConnexionHandlers();
	}
}

} // space_mouse
} // visionaray

#else

//-------------------------------------------------------------------------------------------------
// No 3DconnexionClient API
//

namespace visionaray
{
namespace space_mouse
{

bool init() { return false; }
void register_event_callback(event_type, event_callback) {}
void cleanup() {}

} // space_mouse
} // visionaray

#endif
<commit_msg>Compile fix<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <common/config.h>

#include <cassert>

#if VSNRAY_COMMON_HAVE_3DCONNEXIONCLIENT
#include <3DConnexionClient/ConnexionClient.h>
#include <3DConnexionClient/ConnexionClientAPI.h>
#endif

#include "space_mouse.h"

#if VSNRAY_COMMON_HAVE_3DCONNEXIONCLIENT

// Import weak so we can later check if the
// driver is loaded by checking for NULL
extern int16_t SetConnexionHandlers(
        ConnexionMessageHandlerProc messageHandler,
        ConnexionAddedHandlerProc   addedHandler,
        ConnexionRemovedHandlerProc removedHandler,
        bool useSeparateThread
        ) __attribute__((weak_import));

namespace visionaray
{
namespace space_mouse
{

static uint16_t client_id = -1;

static event_callback event_callbacks[EventTypeCount] = { nullptr };

static void message_handler(unsigned product_id, unsigned message_type, void* message_arg)
{
    switch (message_type)
    {
    case kConnexionMsgDeviceState:
    {
        ConnexionDeviceState* state = reinterpret_cast<ConnexionDeviceState*>(message_arg);

        if (state->client == client_id)
        {
            switch (state->command)
            {
            case kConnexionCmdHandleAxis:
            {
                // Call translation handler
                if (event_callbacks[Translation] != nullptr && (state->axis[0] || state->axis[1] || state->axis[2]))
                {
                    event_callbacks[Translation](
                            space_mouse_event(Translation, pos(state->axis[0], state->axis[1], state->axis[2]))
                            );
                }

                // Call rotation handler
                if (event_callbacks[Rotation] != nullptr && (state->axis[3] || state->axis[4] || state->axis[5]))
                {
                    event_callbacks[Rotation](
                            space_mouse_event(Rotation, pos(state->axis[3], state->axis[4], state->axis[5]))
                            );
                }
                break;
            }
            case kConnexionCmdHandleButtons:
                // TODO
                break;
            }
        }
    }
    default:
        break;
    }
}

bool init()
{
    if (SetConnexionHandlers == 0)
    {
        // Driver not loaded
        return false;
    }

    // Register callback
    int16_t err = SetConnexionHandlers(message_handler, 0, 0, false);

    // Take space mouse over system-wide
    client_id = RegisterConnexionClient(
            'vsnr',
            0,
            kConnexionClientModeTakeOver,
            kConnexionMaskAll
            );

    return true;
}

void register_event_callback(event_type type, event_callback cb)
{
    assert(type < EventTypeCount);

    event_callbacks[type] = cb;
}

void cleanup()
{
	if (SetConnexionHandlers != 0)
	{
        if (client_id)
        {
            UnregisterConnexionClient(client_id);
        }

        CleanupConnexionHandlers();
	}
}

} // space_mouse
} // visionaray

#else

//-------------------------------------------------------------------------------------------------
// No 3DconnexionClient API
//

namespace visionaray
{
namespace space_mouse
{

bool init() { return false; }
void register_event_callback(event_type, event_callback) {}
void cleanup() {}

} // space_mouse
} // visionaray

#endif
<|endoftext|>


<commit_before><commit_msg>Add failing example from issue 41<commit_after><|endoftext|>


<commit_before>/* Copyright (C) 2012,2013 IBM Corp.
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
#include <iostream>
#include <vector>
#include <iomanip>
#include <cassert>

using namespace std;

/**
 * @class Cube
 * @brief Indexing into a hypercube
 **/
class Cube {
class Cube {
private:
   vector<int> dims;  // dims[i] is the size along the i'th diemnsion
   vector<int> prods; // prods[i] = \prod_{j=i}^{n-1} dims[i]
   vector<int> data;
   int size;

   Cube();

public:
   Cube(const vector<int>& idims) {
      dims = idims;
      int n = dims.size();
      assert(n > 0);

      prods.resize(n+1);
      prods[n] = 1;
      for (int i = n-1; i >= 0; i--) {
         assert(dims[i] > 0);
         prods[i] = dims[i]*prods[i+1];
      }

      size = prods[0];
      data.resize(size);
      for (int i = 0; i < size; i++) data[i] = 0;
   }

   bool operator==(const Cube& that) const {
      return dims == that.dims && data == that.data;
   }

   bool operator!=(const Cube& that) const {
      return !(*this == that);
   }

   const vector<int>& getDims() const { return dims; }

   int getSize() const { return size; }

   int getNumDims() const { return dims.size(); }

   int getDim(int d) const { return dims.at(d); }

   int getCoord(int i, int d) const {
      assert(i >= 0 && i < size);

      return (i % prods.at(d)) / prods.at(d+1);
   }

   int addCoord(int i, int d, int offset) const {
      assert(i >= 0 && i < size);

      offset = offset % dims.at(d);
      if (offset < 0) offset += dims.at(d);

      int i_d = getCoord(i, d);
      int i_d1 = (i_d + offset) % dims.at(d);

      int i1 = i + (i_d1 - i_d) * prods.at(d+1);

      return i1;

   }

   int& at(int i) { return data.at(i); }

   const int& at(int i) const { return data.at(i); }

};

Cube simpleRotate(const Cube& c, int offset) {

   assert(offset >= 0);
   Cube c1(c.getDims());

   int size = c.getSize();

   for (int i = 0; i < size; i++) {
      c1.at((i+offset)%size) = c.at(i);
   }

   return c1;

}

Cube rotate1D(const Cube& c, int d, int offset) {

   assert(offset >= 0);

   Cube c1(c.getDims());

   int size = c.getSize();

   for (int i = 0; i < size; i++) {
      c1.at(c.addCoord(i, d, offset)) = c.at(i);
   }

   return c1;

}

Cube operator+(const Cube& c1, const Cube& c2) {
   const vector<int>& dims1 = c1.getDims();
   const vector<int>& dims2 = c2.getDims();
   assert(dims1 == dims2);

   Cube c(dims1);
   int size = c.getSize();

   for (int i = 0; i < size; i++)
      c.at(i) = c1.at(i) + c2.at(i);

   return c;
}

Cube operator*(const Cube& c1, const Cube& c2) {
   const vector<int>& dims1 = c1.getDims();
   const vector<int>& dims2 = c2.getDims();
   assert(dims1 == dims2);

   Cube c(dims1);
   int size = c.getSize();

   for (int i = 0; i < size; i++)
      c.at(i) = c1.at(i) * c2.at(i);

   return c;
}

Cube operator!(const Cube& c1) {
   const vector<int>& dims1 = c1.getDims();

   Cube c(dims1);
   int size = c.getSize();

   for (int i = 0; i < size; i++)
      c.at(i) = c1.at(i) == 0 ? 1 : 0;

   return c;
}

Cube computeMask(const vector<int>& dims, int d, int k) {
   Cube c(dims);
   int size = c.getSize();

   for (int i = 0; i < size; i++) {
      if (c.getCoord(i, d) >= k)
         c.at(i) = 1;
   }

   return c;
}

void print3D(const Cube& c) {
   const vector<int>& dims = c.getDims();
   assert(dims.size() == 3);

   int size = c.getSize();

   for (int i = 0; i < size; i++) {
      cout << setw(3) << c.at(i);
      if ((i+1) % dims.at(2) == 0) cout << endl;
      if ((i+1) % (dims.at(1)*dims.at(2)) == 0) cout << endl;
   }
}

Cube fancyRotate(const Cube& c, int offset) {

   const vector<int>& dims = c.getDims();

   assert(offset >= 0);
   offset = offset % c.getSize();

   Cube c1 = c;
   Cube mask = !Cube(dims); // the all-1 cube

   for (int d = dims.size()-1; d >= 0; d--) {
      int k = c.getCoord(offset, d);

      c1 = (rotate1D(c1, d, k)*mask) + (rotate1D(c1, d, k+1)*(!mask));
      mask = computeMask(dims, d, k)*mask + computeMask(dims, d, k+1)*(!mask);
   }

   return c1;
}

int main()
{
   vector<int> dims(5);
   dims[0] = 5;
   dims[1] = 4;
   dims[2] = 3;
   dims[3] = 3;
   dims[4] = 4;

   Cube c(dims);
   int size = c.getSize();
   for (int i = 0; i < size; i++) c.at(i) = i;

   bool fail=false;
   for (int offset = 1; offset < size; offset++) {
      Cube c1 = simpleRotate(c, offset);
      Cube c2 = fancyRotate(c, offset);
      if (c1 != c2) {
	cout << offset << ": BOO HOO\n";
	fail = true;
      }
   }
   if (!fail) cout << "YEE HA\n";
}

<commit_msg>deleted empty lines to much overall coding style<commit_after>/* Copyright (C) 2012,2013 IBM Corp.
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
#include <iostream>
#include <vector>
#include <iomanip>
#include <cassert>

using namespace std;

/**
 * @class Cube
 * @brief Indexing into a hypercube
 **/
class Cube {
class Cube {
private:
   vector<int> dims;  // dims[i] is the size along the i'th diemnsion
   vector<int> prods; // prods[i] = \prod_{j=i}^{n-1} dims[i]
   vector<int> data;
   int size;

   Cube();

public:
   Cube(const vector<int>& idims) {
      dims = idims;
      int n = dims.size();
      assert(n > 0);

      prods.resize(n+1);
      prods[n] = 1;
      for (int i = n-1; i >= 0; i--) {
         assert(dims[i] > 0);
         prods[i] = dims[i]*prods[i+1];
      }

      size = prods[0];
      data.resize(size);
      for (int i = 0; i < size; i++) data[i] = 0;
   }

   bool operator==(const Cube& that) const {
      return dims == that.dims && data == that.data;
   }

   bool operator!=(const Cube& that) const {
      return !(*this == that);
   }

   const vector<int>& getDims() const { return dims; }

   int getSize() const { return size; }

   int getNumDims() const { return dims.size(); }

   int getDim(int d) const { return dims.at(d); }

   int getCoord(int i, int d) const {
      assert(i >= 0 && i < size);

      return (i % prods.at(d)) / prods.at(d+1);
   }

   int addCoord(int i, int d, int offset) const {
      assert(i >= 0 && i < size);

      offset = offset % dims.at(d);
      if (offset < 0) offset += dims.at(d);

      int i_d = getCoord(i, d);
      int i_d1 = (i_d + offset) % dims.at(d);

      int i1 = i + (i_d1 - i_d) * prods.at(d+1);

      return i1;

   }

   int& at(int i) { return data.at(i); }

   const int& at(int i) const { return data.at(i); }

};

Cube simpleRotate(const Cube& c, int offset) {

   assert(offset >= 0);
   Cube c1(c.getDims());

   int size = c.getSize();

   for (int i = 0; i < size; i++) {
      c1.at((i+offset)%size) = c.at(i);
   }

   return c1;
}

Cube rotate1D(const Cube& c, int d, int offset) {

   assert(offset >= 0);

   Cube c1(c.getDims());

   int size = c.getSize();

   for (int i = 0; i < size; i++) {
      c1.at(c.addCoord(i, d, offset)) = c.at(i);
   }

   return c1;
}

Cube operator+(const Cube& c1, const Cube& c2) {
   const vector<int>& dims1 = c1.getDims();
   const vector<int>& dims2 = c2.getDims();
   assert(dims1 == dims2);

   Cube c(dims1);
   int size = c.getSize();

   for (int i = 0; i < size; i++)
      c.at(i) = c1.at(i) + c2.at(i);

   return c;
}

Cube operator*(const Cube& c1, const Cube& c2) {
   const vector<int>& dims1 = c1.getDims();
   const vector<int>& dims2 = c2.getDims();
   assert(dims1 == dims2);

   Cube c(dims1);
   int size = c.getSize();

   for (int i = 0; i < size; i++)
      c.at(i) = c1.at(i) * c2.at(i);

   return c;
}

Cube operator!(const Cube& c1) {
   const vector<int>& dims1 = c1.getDims();

   Cube c(dims1);
   int size = c.getSize();

   for (int i = 0; i < size; i++)
      c.at(i) = c1.at(i) == 0 ? 1 : 0;

   return c;
}

Cube computeMask(const vector<int>& dims, int d, int k) {
   Cube c(dims);
   int size = c.getSize();

   for (int i = 0; i < size; i++) {
      if (c.getCoord(i, d) >= k)
         c.at(i) = 1;
   }

   return c;
}

void print3D(const Cube& c) {
   const vector<int>& dims = c.getDims();
   assert(dims.size() == 3);

   int size = c.getSize();

   for (int i = 0; i < size; i++) {
      cout << setw(3) << c.at(i);
      if ((i+1) % dims.at(2) == 0) cout << endl;
      if ((i+1) % (dims.at(1)*dims.at(2)) == 0) cout << endl;
   }
}

Cube fancyRotate(const Cube& c, int offset) {

   const vector<int>& dims = c.getDims();

   assert(offset >= 0);
   offset = offset % c.getSize();

   Cube c1 = c;
   Cube mask = !Cube(dims); // the all-1 cube

   for (int d = dims.size()-1; d >= 0; d--) {
      int k = c.getCoord(offset, d);

      c1 = (rotate1D(c1, d, k)*mask) + (rotate1D(c1, d, k+1)*(!mask));
      mask = computeMask(dims, d, k)*mask + computeMask(dims, d, k+1)*(!mask);
   }

   return c1;
}

int main()
{
   vector<int> dims(5);
   dims[0] = 5;
   dims[1] = 4;
   dims[2] = 3;
   dims[3] = 3;
   dims[4] = 4;

   Cube c(dims);
   int size = c.getSize();
   for (int i = 0; i < size; i++) c.at(i) = i;

   bool fail=false;
   for (int offset = 1; offset < size; offset++) {
      Cube c1 = simpleRotate(c, offset);
      Cube c2 = fancyRotate(c, offset);
      if (c1 != c2) {
	cout << offset << ": BOO HOO\n";
	fail = true;
      }
   }
   if (!fail) cout << "YEE HA\n";
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: FullScreenPane.cxx,v $
 *
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "precompiled_sd.hxx"

#include "FullScreenPane.hxx"
#include "ViewShellBase.hxx"
#include <cppcanvas/vclfactory.hxx>
#include <sfx2/dispatch.hxx>
#include <vcl/svapp.hxx>
#include <vcl/dialog.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/frame/XLayoutManager.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/util/URL.hpp>

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::drawing::framework;
using ::rtl::OUString;

#define A2S(pString) (::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(pString)))

namespace sd { namespace framework {

FullScreenPane::FullScreenPane (
    const Reference<XComponentContext>& rxComponentContext,
    const Reference<XResourceId>& rxPaneId,
    const ::Window* pViewShellWindow)
    : FrameWindowPane(rxPaneId,NULL),
      mxComponentContext(rxComponentContext),
      mpWorkWindow(NULL)
{
    ::Window* pParent = NULL;
    mpWorkWindow.reset(new WorkWindow(
        pParent,
        0));  // For debugging (non-fullscreen) use WB_BORDER | WB_MOVEABLE | WB_SIZEABLE));

    if ( ! rxPaneId.is())
        throw lang::IllegalArgumentException();

    sal_Int32 nScreenNumber = 1;
    ExtractArguments(rxPaneId, nScreenNumber);

    if (mpWorkWindow.get() == NULL)
        return;

    // Create a new top-leve window that is displayed full screen.
    mpWorkWindow->ShowFullScreenMode(TRUE, nScreenNumber);
    // For debugging (non-fullscreen) use mpWorkWindow->SetScreenNumber(nScreenNumber);
    mpWorkWindow->SetMenuBarMode(MENUBAR_MODE_HIDE);
    mpWorkWindow->SetBorderStyle(WINDOW_BORDER_REMOVEBORDER);
    mpWorkWindow->SetBackground(Wallpaper());
    // Don't show the window right now in order to allow the setting of an
    // accessibility object: accessibility objects are typically
    // requested by AT-tools when the window is shown.  Chaning it
    // afterwards may or may not work.

    // Add resize listener at the work window.
    Link aWindowEventHandler (LINK(this, FullScreenPane, WindowEventHandler));
    mpWorkWindow->AddEventListener(aWindowEventHandler);

    // Set title and icon of the new window to those of the current window
    // of the view shell.
    if (pViewShellWindow != NULL)
    {
        const SystemWindow* pSystemWindow = pViewShellWindow->GetSystemWindow();
        mpWorkWindow->SetText(pSystemWindow->GetText());
        mpWorkWindow->SetIcon(pSystemWindow->GetIcon());
    }

    // For some reason the VCL canvas can not paint into a WorkWindow.
    // Therefore a child window is created that covers the WorkWindow
    // completely.
    mpWindow = new ::Window(mpWorkWindow.get());
    mpWindow->SetPosSizePixel(Point(0,0), mpWorkWindow->GetSizePixel());
    mpWindow->SetBackground(Wallpaper());
    mxWindow = VCLUnoHelper::GetInterface(mpWindow);

    // Create the canvas.
    mxCanvas = CreateCanvas();

    mpWindow->GrabFocus();
}

FullScreenPane::~FullScreenPane (void) throw()
{
}

void SAL_CALL FullScreenPane::disposing (void)
{
    // We have created the window pointed to by mpWindow, we delete it.
    if (mpWindow != NULL)
    {
        delete mpWindow;
    }

    if (mpWorkWindow.get() != NULL)
    {
        Link aWindowEventHandler (LINK(this, FullScreenPane, WindowEventHandler));
        mpWorkWindow->RemoveEventListener(aWindowEventHandler);
        mpWorkWindow.reset();
    }

    FrameWindowPane::disposing();
}

//----- XPane -----------------------------------------------------------------

sal_Bool SAL_CALL FullScreenPane::isVisible (void)
    throw (RuntimeException)
{
    ThrowIfDisposed();

    if (mpWindow != NULL)
        return mpWindow->IsReallyVisible();
    else
        return false;
}

void SAL_CALL FullScreenPane::setVisible (const sal_Bool bIsVisible)
    throw (RuntimeException)
{
    ThrowIfDisposed();

    if (mpWindow != NULL)
        mpWindow->Show(bIsVisible);
    if (mpWorkWindow != NULL)
        mpWorkWindow->Show(bIsVisible);
}

Reference<accessibility::XAccessible> SAL_CALL FullScreenPane::getAccessible (void)
    throw (RuntimeException)
{
    ThrowIfDisposed();

    if (mpWorkWindow != NULL)
        return mpWorkWindow->GetAccessible(FALSE);
    else
        return NULL;
}

void SAL_CALL FullScreenPane::setAccessible (
    const Reference<accessibility::XAccessible>& rxAccessible)
    throw (RuntimeException)
{
    ThrowIfDisposed();

    if (mpWindow != NULL)
    {
        Reference<lang::XInitialization> xInitializable (rxAccessible, UNO_QUERY);
        if (xInitializable.is())
        {
            ::Window* pParentWindow = mpWindow->GetParent();
            Reference<accessibility::XAccessible> xAccessibleParent;
            if (pParentWindow != NULL)
                xAccessibleParent = pParentWindow->GetAccessible();
            Sequence<Any> aArguments (1);
            aArguments[0] = Any(xAccessibleParent);
            xInitializable->initialize(aArguments);
        }
        GetWindow()->SetAccessible(rxAccessible);
    }
}

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

IMPL_LINK(FullScreenPane, WindowEventHandler, VclWindowEvent*, pEvent)
{
    switch (pEvent->GetId())
    {
        case VCLEVENT_WINDOW_RESIZE:
            GetWindow()->SetPosPixel(Point(0,0));
            GetWindow()->SetSizePixel(Size(
                mpWorkWindow->GetSizePixel().Width(),
                mpWorkWindow->GetSizePixel().Height()));
            break;

        case VCLEVENT_OBJECT_DYING:
            mpWorkWindow.reset();
            break;
    }
    return 1;
}

Reference<rendering::XCanvas> FullScreenPane::CreateCanvas (void)
    throw (RuntimeException)
{
    ::Window* pWindow = VCLUnoHelper::GetWindow(mxWindow);
    if (pWindow != NULL)
    {
        Sequence<Any> aArg (5);

        // common: first any is VCL pointer to window (for VCL canvas)
        aArg[0] = makeAny(reinterpret_cast<sal_Int64>(pWindow));
        aArg[1] = Any();
        aArg[2] = makeAny(::com::sun::star::awt::Rectangle());
        aArg[3] = makeAny(sal_False);
        aArg[4] = makeAny(mxWindow);

        Reference<lang::XMultiServiceFactory> xFactory (
            mxComponentContext->getServiceManager(), UNO_QUERY_THROW);
        return Reference<rendering::XCanvas>(
            xFactory->createInstanceWithArguments(
                OUString::createFromAscii("com.sun.star.rendering.SpriteCanvas.VCL"),
                aArg),
            UNO_QUERY);
    }
    else
        throw RuntimeException();
}

void FullScreenPane::ExtractArguments (
    const Reference<XResourceId>& rxPaneId,
    sal_Int32& rnScreenNumberReturnValue)
{
    // Extract arguments from the resource URL.
    const util::URL aURL = rxPaneId->getFullResourceURL();
    sal_Int32 nIndex = 0;
    while (nIndex >= 0)
    {
        const OUString aToken = aURL.Arguments.getToken(0, '&', nIndex);
        if (aToken.getLength() > 0)
        {
            // Split at the first '='.
            const sal_Int32 nAssign = aToken.indexOf('=');
            const OUString sKey = aToken.copy(0, nAssign);
            const OUString sValue = aToken.copy(nAssign+1);

            if (sKey.compareToAscii("ScreenNumber") == 0)
            {
                rnScreenNumberReturnValue = sValue.toInt32();
            }
        }
    }
}

} } // end of namespace sd::framework
<commit_msg>#i10000#<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: FullScreenPane.cxx,v $
 *
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "precompiled_sd.hxx"

#include "FullScreenPane.hxx"
#include "ViewShellBase.hxx"
#include <cppcanvas/vclfactory.hxx>
#include <sfx2/dispatch.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/svapp.hxx>
#include <vcl/dialog.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/frame/XLayoutManager.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/util/URL.hpp>

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::drawing::framework;
using ::rtl::OUString;

#define A2S(pString) (::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(pString)))

namespace sd { namespace framework {

FullScreenPane::FullScreenPane (
    const Reference<XComponentContext>& rxComponentContext,
    const Reference<XResourceId>& rxPaneId,
    const ::Window* pViewShellWindow)
    : FrameWindowPane(rxPaneId,NULL),
      mxComponentContext(rxComponentContext),
      mpWorkWindow(NULL)
{
    ::Window* pParent = NULL;
    mpWorkWindow.reset(new WorkWindow(
        pParent,
        0));  // For debugging (non-fullscreen) use WB_BORDER | WB_MOVEABLE | WB_SIZEABLE));

    if ( ! rxPaneId.is())
        throw lang::IllegalArgumentException();

    sal_Int32 nScreenNumber = 1;
    ExtractArguments(rxPaneId, nScreenNumber);

    if (mpWorkWindow.get() == NULL)
        return;

    // Create a new top-leve window that is displayed full screen.
    mpWorkWindow->ShowFullScreenMode(TRUE, nScreenNumber);
    // For debugging (non-fullscreen) use mpWorkWindow->SetScreenNumber(nScreenNumber);
    mpWorkWindow->SetMenuBarMode(MENUBAR_MODE_HIDE);
    mpWorkWindow->SetBorderStyle(WINDOW_BORDER_REMOVEBORDER);
    mpWorkWindow->SetBackground(Wallpaper());
    // Don't show the window right now in order to allow the setting of an
    // accessibility object: accessibility objects are typically
    // requested by AT-tools when the window is shown.  Chaning it
    // afterwards may or may not work.

    // Add resize listener at the work window.
    Link aWindowEventHandler (LINK(this, FullScreenPane, WindowEventHandler));
    mpWorkWindow->AddEventListener(aWindowEventHandler);

    // Set title and icon of the new window to those of the current window
    // of the view shell.
    if (pViewShellWindow != NULL)
    {
        const SystemWindow* pSystemWindow = pViewShellWindow->GetSystemWindow();
        mpWorkWindow->SetText(pSystemWindow->GetText());
        mpWorkWindow->SetIcon(pSystemWindow->GetIcon());
    }

    // For some reason the VCL canvas can not paint into a WorkWindow.
    // Therefore a child window is created that covers the WorkWindow
    // completely.
    mpWindow = new ::Window(mpWorkWindow.get());
    mpWindow->SetPosSizePixel(Point(0,0), mpWorkWindow->GetSizePixel());
    mpWindow->SetBackground(Wallpaper());
    mxWindow = VCLUnoHelper::GetInterface(mpWindow);

    // Create the canvas.
    mxCanvas = CreateCanvas();

    mpWindow->GrabFocus();
}

FullScreenPane::~FullScreenPane (void) throw()
{
}

void SAL_CALL FullScreenPane::disposing (void)
{
    // We have created the window pointed to by mpWindow, we delete it.
    if (mpWindow != NULL)
    {
        delete mpWindow;
    }

    if (mpWorkWindow.get() != NULL)
    {
        Link aWindowEventHandler (LINK(this, FullScreenPane, WindowEventHandler));
        mpWorkWindow->RemoveEventListener(aWindowEventHandler);
        mpWorkWindow.reset();
    }

    FrameWindowPane::disposing();
}

//----- XPane -----------------------------------------------------------------

sal_Bool SAL_CALL FullScreenPane::isVisible (void)
    throw (RuntimeException)
{
    ThrowIfDisposed();

    if (mpWindow != NULL)
        return mpWindow->IsReallyVisible();
    else
        return false;
}

void SAL_CALL FullScreenPane::setVisible (const sal_Bool bIsVisible)
    throw (RuntimeException)
{
    ThrowIfDisposed();

    if (mpWindow != NULL)
        mpWindow->Show(bIsVisible);
    if (mpWorkWindow != NULL)
        mpWorkWindow->Show(bIsVisible);
}

Reference<accessibility::XAccessible> SAL_CALL FullScreenPane::getAccessible (void)
    throw (RuntimeException)
{
    ThrowIfDisposed();

    if (mpWorkWindow != NULL)
        return mpWorkWindow->GetAccessible(FALSE);
    else
        return NULL;
}

void SAL_CALL FullScreenPane::setAccessible (
    const Reference<accessibility::XAccessible>& rxAccessible)
    throw (RuntimeException)
{
    ThrowIfDisposed();

    if (mpWindow != NULL)
    {
        Reference<lang::XInitialization> xInitializable (rxAccessible, UNO_QUERY);
        if (xInitializable.is())
        {
            ::Window* pParentWindow = mpWindow->GetParent();
            Reference<accessibility::XAccessible> xAccessibleParent;
            if (pParentWindow != NULL)
                xAccessibleParent = pParentWindow->GetAccessible();
            Sequence<Any> aArguments (1);
            aArguments[0] = Any(xAccessibleParent);
            xInitializable->initialize(aArguments);
        }
        GetWindow()->SetAccessible(rxAccessible);
    }
}

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

IMPL_LINK(FullScreenPane, WindowEventHandler, VclWindowEvent*, pEvent)
{
    switch (pEvent->GetId())
    {
        case VCLEVENT_WINDOW_RESIZE:
            GetWindow()->SetPosPixel(Point(0,0));
            GetWindow()->SetSizePixel(Size(
                mpWorkWindow->GetSizePixel().Width(),
                mpWorkWindow->GetSizePixel().Height()));
            break;

        case VCLEVENT_OBJECT_DYING:
            mpWorkWindow.reset();
            break;
    }
    return 1;
}

Reference<rendering::XCanvas> FullScreenPane::CreateCanvas (void)
    throw (RuntimeException)
{
    ::Window* pWindow = VCLUnoHelper::GetWindow(mxWindow);
    if (pWindow != NULL)
    {
        Sequence<Any> aArg (5);

        // common: first any is VCL pointer to window (for VCL canvas)
        aArg[0] = makeAny(reinterpret_cast<sal_Int64>(pWindow));
        aArg[1] = Any();
        aArg[2] = makeAny(::com::sun::star::awt::Rectangle());
        aArg[3] = makeAny(sal_False);
        aArg[4] = makeAny(mxWindow);

        Reference<lang::XMultiServiceFactory> xFactory (
            mxComponentContext->getServiceManager(), UNO_QUERY_THROW);
        return Reference<rendering::XCanvas>(
            xFactory->createInstanceWithArguments(
                OUString::createFromAscii("com.sun.star.rendering.SpriteCanvas.VCL"),
                aArg),
            UNO_QUERY);
    }
    else
        throw RuntimeException();
}

void FullScreenPane::ExtractArguments (
    const Reference<XResourceId>& rxPaneId,
    sal_Int32& rnScreenNumberReturnValue)
{
    // Extract arguments from the resource URL.
    const util::URL aURL = rxPaneId->getFullResourceURL();
    sal_Int32 nIndex = 0;
    while (nIndex >= 0)
    {
        const OUString aToken = aURL.Arguments.getToken(0, '&', nIndex);
        if (aToken.getLength() > 0)
        {
            // Split at the first '='.
            const sal_Int32 nAssign = aToken.indexOf('=');
            const OUString sKey = aToken.copy(0, nAssign);
            const OUString sValue = aToken.copy(nAssign+1);

            if (sKey.compareToAscii("ScreenNumber") == 0)
            {
                rnScreenNumberReturnValue = sValue.toInt32();
            }
        }
    }
}

} } // end of namespace sd::framework
<|endoftext|>