<commit_before>#include "platform/local_country_file.hpp"
#include "platform/platform.hpp"

#include "coding/internal/file_data.hpp"
#include "coding/file_name_utils.hpp"

#include "base/logging.hpp"

#include "std/sstream.hpp"

namespace platform
{
LocalCountryFile::LocalCountryFile()
    : m_version(0), m_files(MapOptions::Nothing), m_mapSize(0), m_routingSize()
{
}

LocalCountryFile::LocalCountryFile(string const & directory, CountryFile const & countryFile,
                                   int64_t version)
    : m_directory(directory),
      m_countryFile(countryFile),
      m_version(version),
      m_files(MapOptions::Nothing),
      m_mapSize(0),
      m_routingSize(0)
{
}

void LocalCountryFile::SyncWithDisk()
{
  m_files = MapOptions::Nothing;
  m_mapSize = 0;
  m_routingSize = 0;

  Platform & platform = GetPlatform();

  if (platform.GetFileSizeByFullPath(GetPath(MapOptions::Map), m_mapSize))
    m_files = SetOptions(m_files, MapOptions::Map);

  string const routingPath = GetPath(MapOptions::CarRouting);
  if (platform.GetFileSizeByFullPath(routingPath, m_routingSize))
    m_files = SetOptions(m_files, MapOptions::CarRouting);
}

void LocalCountryFile::DeleteFromDisk(MapOptions files) const
{
  for (MapOptions file : {MapOptions::Map, MapOptions::CarRouting})
  {
    if (OnDisk(file) && HasOptions(files, file))
    {
      if (!my::DeleteFileX(GetPath(file)))
        LOG(LERROR, (file, "from", *this, "wasn't deleted from disk."));
    }
  }
}

string LocalCountryFile::GetPath(MapOptions file) const
{
  // todo(@m): Refactor with MwmTraits after merge new-search branch.
  bool singleFile = GetVersion() > 151215;
  string const & countryFilePath = singleFile ? m_countryFile.GetNameWithExt(MapOptions::Map)
                                              : m_countryFile.GetNameWithExt(file);
  return my::JoinFoldersToPath(m_directory, countryFilePath);
}

uint32_t LocalCountryFile::GetSize(MapOptions filesMask) const
{
  uint64_t size64 = 0;
  if (HasOptions(filesMask, MapOptions::Map))
    size64 += m_mapSize;
  if (HasOptions(filesMask, MapOptions::CarRouting))
    size64 += m_routingSize;
  uint32_t const size32 = static_cast<uint32_t>(size64);
  ASSERT_EQUAL(size32, size64, ());
  return size32;
}

bool LocalCountryFile::operator<(LocalCountryFile const & rhs) const
{
  if (m_countryFile != rhs.m_countryFile)
    return m_countryFile < rhs.m_countryFile;
  if (m_version != rhs.m_version)
    return m_version < rhs.m_version;
  if (m_directory != rhs.m_directory)
    return m_directory < rhs.m_directory;
  if (m_files != rhs.m_files)
    return m_files < rhs.m_files;
  return false;
}

bool LocalCountryFile::operator==(LocalCountryFile const & rhs) const
{
  return m_directory == rhs.m_directory && m_countryFile == rhs.m_countryFile &&
         m_version == rhs.m_version && m_files == rhs.m_files;
}

// static
LocalCountryFile LocalCountryFile::MakeForTesting(string const & countryFileName)
{
  CountryFile const countryFile(countryFileName);
  LocalCountryFile localFile(GetPlatform().WritableDir(), countryFile, 0 /* version */);
  localFile.SyncWithDisk();
  return localFile;
}

// static
LocalCountryFile LocalCountryFile::MakeTemporary(string const & fullPath)
{
  string name = fullPath;
  my::GetNameFromFullPath(name);
  my::GetNameWithoutExt(name);

  return LocalCountryFile(my::GetDirectory(fullPath), CountryFile(name), 0 /* version */);
}

string DebugPrint(LocalCountryFile const & file)
{
  ostringstream os;
  os << "LocalCountryFile [" << file.m_directory << ", " << DebugPrint(file.m_countryFile) << ", "
     << file.m_version << ", " << DebugPrint(file.m_files) << "]";
  return os.str();
}
}  // namespace platform
<commit_msg>[old map downloader] Fixing assert in Storage tests.<commit_after>#include "platform/local_country_file.hpp"
#include "platform/mwm_version.hpp"
#include "platform/platform.hpp"

#include "coding/internal/file_data.hpp"
#include "coding/file_name_utils.hpp"

#include "base/logging.hpp"

#include "std/sstream.hpp"

namespace platform
{
LocalCountryFile::LocalCountryFile()
    : m_version(0), m_files(MapOptions::Nothing), m_mapSize(0), m_routingSize()
{
}

LocalCountryFile::LocalCountryFile(string const & directory, CountryFile const & countryFile,
                                   int64_t version)
    : m_directory(directory),
      m_countryFile(countryFile),
      m_version(version),
      m_files(MapOptions::Nothing),
      m_mapSize(0),
      m_routingSize(0)
{
}

void LocalCountryFile::SyncWithDisk()
{
  m_files = MapOptions::Nothing;
  m_mapSize = 0;
  m_routingSize = 0;

  Platform & platform = GetPlatform();

  if (platform.GetFileSizeByFullPath(GetPath(MapOptions::Map), m_mapSize))
    m_files = SetOptions(m_files, MapOptions::Map);

  string const routingPath = GetPath(MapOptions::CarRouting);
  if (platform.GetFileSizeByFullPath(routingPath, m_routingSize))
    m_files = SetOptions(m_files, MapOptions::CarRouting);
}

void LocalCountryFile::DeleteFromDisk(MapOptions files) const
{
  vector<MapOptions> const mapOptions =
      version::IsSingleMwm(GetVersion()) ? vector<MapOptions>({MapOptions::Map})
                                         : vector<MapOptions>({MapOptions::Map, MapOptions::CarRouting});
  for (MapOptions file : mapOptions)
  {
    if (OnDisk(file) && HasOptions(files, file))
    {
      if (!my::DeleteFileX(GetPath(file)))
        LOG(LERROR, (file, "from", *this, "wasn't deleted from disk."));
    }
  }
}

string LocalCountryFile::GetPath(MapOptions file) const
{
  // todo(@m): Refactor with MwmTraits after merge new-search branch.
  bool const singleFile = version::IsSingleMwm(GetVersion());
  string const & countryFilePath = singleFile ? m_countryFile.GetNameWithExt(MapOptions::Map)
                                              : m_countryFile.GetNameWithExt(file);
  return my::JoinFoldersToPath(m_directory, countryFilePath);
}

uint32_t LocalCountryFile::GetSize(MapOptions filesMask) const
{
  uint64_t size64 = 0;
  if (HasOptions(filesMask, MapOptions::Map))
    size64 += m_mapSize;
  if (HasOptions(filesMask, MapOptions::CarRouting))
    size64 += m_routingSize;
  uint32_t const size32 = static_cast<uint32_t>(size64);
  ASSERT_EQUAL(size32, size64, ());
  return size32;
}

bool LocalCountryFile::operator<(LocalCountryFile const & rhs) const
{
  if (m_countryFile != rhs.m_countryFile)
    return m_countryFile < rhs.m_countryFile;
  if (m_version != rhs.m_version)
    return m_version < rhs.m_version;
  if (m_directory != rhs.m_directory)
    return m_directory < rhs.m_directory;
  if (m_files != rhs.m_files)
    return m_files < rhs.m_files;
  return false;
}

bool LocalCountryFile::operator==(LocalCountryFile const & rhs) const
{
  return m_directory == rhs.m_directory && m_countryFile == rhs.m_countryFile &&
         m_version == rhs.m_version && m_files == rhs.m_files;
}

// static
LocalCountryFile LocalCountryFile::MakeForTesting(string const & countryFileName)
{
  CountryFile const countryFile(countryFileName);
  LocalCountryFile localFile(GetPlatform().WritableDir(), countryFile, 0 /* version */);
  localFile.SyncWithDisk();
  return localFile;
}

// static
LocalCountryFile LocalCountryFile::MakeTemporary(string const & fullPath)
{
  string name = fullPath;
  my::GetNameFromFullPath(name);
  my::GetNameWithoutExt(name);

  return LocalCountryFile(my::GetDirectory(fullPath), CountryFile(name), 0 /* version */);
}

string DebugPrint(LocalCountryFile const & file)
{
  ostringstream os;
  os << "LocalCountryFile [" << file.m_directory << ", " << DebugPrint(file.m_countryFile) << ", "
     << file.m_version << ", " << DebugPrint(file.m_files) << "]";
  return os.str();
}
}  // namespace platform
<|endoftext|>


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

#ifndef _CONNECTIVITY_ADABAS_USERS_HXX_
#include "adabas/BUsers.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_USER_HXX_
#include "adabas/BUser.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_TABLE_HXX_
#include "adabas/BTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _CONNECTIVITY_SDBCX_IREFRESHABLE_HXX_
#include "connectivity/sdbcx/IRefreshable.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif

using namespace ::comphelper;
using namespace connectivity;
using namespace connectivity::adabas;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
//  using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
typedef connectivity::sdbcx::OCollection OCollection_TYPE;

sdbcx::ObjectType OUsers::createObject(const ::rtl::OUString& _rName)
{
    return new OAdabasUser(m_pConnection,_rName);
}
// -------------------------------------------------------------------------
void OUsers::impl_refresh() throw(RuntimeException)
{
    m_pParent->refreshUsers();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OUsers::createEmptyObject()
{
    OUserExtend* pNew = new OUserExtend(m_pConnection);
    return pNew;
}
// -------------------------------------------------------------------------
// XAppend
void OUsers::appendObject( const Reference< XPropertySet >& descriptor )
{
    ::rtl::OUString aSql    = ::rtl::OUString::createFromAscii("CREATE USER ");
    ::rtl::OUString aQuote  = m_pConnection->getMetaData()->getIdentifierQuoteString(  );

    ::rtl::OUString sUserName;
    descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)) >>= sUserName;
    sUserName = sUserName.toAsciiUpperCase();
    descriptor->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME),makeAny(sUserName));
    aSql += ::dbtools::quoteName(aQuote,sUserName)
                + ::rtl::OUString::createFromAscii(" PASSWORD ")
                + getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)));
    aSql += ::rtl::OUString::createFromAscii(" RESOURCE NOT EXCLUSIVE");

    Reference< XStatement > xStmt = m_pConnection->createStatement(  );
    if(xStmt.is())
        xStmt->execute(aSql);
    ::comphelper::disposeComponent(xStmt);
}
// -------------------------------------------------------------------------
// XDrop
void OUsers::dropObject(sal_Int32 /*_nPos*/,const ::rtl::OUString _sElementName)
{
    {
        // first we have to check if this user is live relevaant for the database
        // which means with out these users the database will miss more than one important system table
        ::rtl::OUString sUsers = ::rtl::OUString::createFromAscii("SELECT USERMODE,USERNAME FROM DOMAIN.USERS WHERE USERNAME = '");
        sUsers += _sElementName + ::rtl::OUString::createFromAscii("'");
        Reference< XStatement > xStmt = m_pConnection->createStatement();
        if(xStmt.is())
        {
            Reference<XResultSet> xRes = xStmt->executeQuery(sUsers);
            Reference<XRow> xRow(xRes,UNO_QUERY);
            if(xRes.is() && xRow.is() && xRes->next()) // there can only be one user with this name
            {
                static const ::rtl::OUString sDbaUser = ::rtl::OUString::createFromAscii("DBA");
                if(xRow->getString(1) == sDbaUser)
                {
                    ::comphelper::disposeComponent(xStmt);
                    ::dbtools::throwGenericSQLException(::rtl::OUString::createFromAscii("This user couldn't be deleted. Otherwise the database stays in a inconsistent state."),static_cast<XTypeProvider*>(this));
                }
            }
            ::comphelper::disposeComponent(xStmt);
        }
    }

    {
        ::rtl::OUString aSql    = ::rtl::OUString::createFromAscii("DROP USER ");
        ::rtl::OUString aQuote  = m_pConnection->getMetaData()->getIdentifierQuoteString(  );
        aSql += ::dbtools::quoteName(aQuote,_sElementName);

        Reference< XStatement > xStmt = m_pConnection->createStatement(  );
        if(xStmt.is())
            xStmt->execute(aSql);
        ::comphelper::disposeComponent(xStmt);
    }
}

// -------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS qiq (1.15.104); FILE MERGED 2006/06/27 14:05:40 fs 1.15.104.2: RESYNC: (1.15-1.16); FILE MERGED 2006/06/16 11:32:30 fs 1.15.104.1: during #i51143#:<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: BUsers.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: obo $ $Date: 2006-07-10 14:22:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_ADABAS_USERS_HXX_
#include "adabas/BUsers.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_USER_HXX_
#include "adabas/BUser.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_TABLE_HXX_
#include "adabas/BTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _CONNECTIVITY_SDBCX_IREFRESHABLE_HXX_
#include "connectivity/sdbcx/IRefreshable.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif

using namespace ::comphelper;
using namespace connectivity;
using namespace connectivity::adabas;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
//  using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
typedef connectivity::sdbcx::OCollection OCollection_TYPE;

sdbcx::ObjectType OUsers::createObject(const ::rtl::OUString& _rName)
{
    return new OAdabasUser(m_pConnection,_rName);
}
// -------------------------------------------------------------------------
void OUsers::impl_refresh() throw(RuntimeException)
{
    m_pParent->refreshUsers();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OUsers::createDescriptor()
{
    OUserExtend* pNew = new OUserExtend(m_pConnection);
    return pNew;
}
// -------------------------------------------------------------------------
// XAppend
sdbcx::ObjectType OUsers::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& descriptor )
{
    ::rtl::OUString aSql    = ::rtl::OUString::createFromAscii("CREATE USER ");
    ::rtl::OUString aQuote  = m_pConnection->getMetaData()->getIdentifierQuoteString(  );

    ::rtl::OUString sUserName( _rForName );
    sUserName = sUserName.toAsciiUpperCase();
    descriptor->setPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME),makeAny(sUserName));
    aSql += ::dbtools::quoteName(aQuote,sUserName)
                + ::rtl::OUString::createFromAscii(" PASSWORD ")
                + getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD)));
    aSql += ::rtl::OUString::createFromAscii(" RESOURCE NOT EXCLUSIVE");

    Reference< XStatement > xStmt = m_pConnection->createStatement(  );
    if(xStmt.is())
        xStmt->execute(aSql);
    ::comphelper::disposeComponent(xStmt);

    return createObject( _rForName );
}
// -------------------------------------------------------------------------
// XDrop
void OUsers::dropObject(sal_Int32 /*_nPos*/,const ::rtl::OUString _sElementName)
{
    {
        // first we have to check if this user is live relevaant for the database
        // which means with out these users the database will miss more than one important system table
        ::rtl::OUString sUsers = ::rtl::OUString::createFromAscii("SELECT USERMODE,USERNAME FROM DOMAIN.USERS WHERE USERNAME = '");
        sUsers += _sElementName + ::rtl::OUString::createFromAscii("'");
        Reference< XStatement > xStmt = m_pConnection->createStatement();
        if(xStmt.is())
        {
            Reference<XResultSet> xRes = xStmt->executeQuery(sUsers);
            Reference<XRow> xRow(xRes,UNO_QUERY);
            if(xRes.is() && xRow.is() && xRes->next()) // there can only be one user with this name
            {
                static const ::rtl::OUString sDbaUser = ::rtl::OUString::createFromAscii("DBA");
                if(xRow->getString(1) == sDbaUser)
                {
                    ::comphelper::disposeComponent(xStmt);
                    ::dbtools::throwGenericSQLException(::rtl::OUString::createFromAscii("This user couldn't be deleted. Otherwise the database stays in a inconsistent state."),static_cast<XTypeProvider*>(this));
                }
            }
            ::comphelper::disposeComponent(xStmt);
        }
    }

    {
        ::rtl::OUString aSql    = ::rtl::OUString::createFromAscii("DROP USER ");
        ::rtl::OUString aQuote  = m_pConnection->getMetaData()->getIdentifierQuoteString(  );
        aSql += ::dbtools::quoteName(aQuote,_sElementName);

        Reference< XStatement > xStmt = m_pConnection->createStatement(  );
        if(xStmt.is())
            xStmt->execute(aSql);
        ::comphelper::disposeComponent(xStmt);
    }
}

// -------------------------------------------------------------------------
<|endoftext|>


<commit_before>// STL
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>

// Boost
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/scoped_ptr.hpp>

// Local
#include "pyp-topics.hh"
#include "corpus.hh"
#include "contexts_corpus.hh"
#include "gzstream.hh"
#include "mt19937ar.h"

static const char *REVISION = "$Rev$";

// Namespaces
using namespace boost;
using namespace boost::program_options;
using namespace std;

int main(int argc, char **argv)
{
 cout << "Pitman Yor topic models: Copyright 2010 Phil Blunsom\n";
 cout << REVISION << '\n' <<endl;

  ////////////////////////////////////////////////////////////////////////////////////////////
  // Command line processing
  variables_map vm;

  // Command line processing
  {
    options_description cmdline_options("Allowed options");
    cmdline_options.add_options()
      ("help,h", "print help message")
      ("data,d", value<string>(), "file containing the documents and context terms")
      ("topics,t", value<int>()->default_value(50), "number of topics")
      ("document-topics-out,o", value<string>(), "file to write the document topics to")
      ("default-topics-out", value<string>(), "file to write default term topic assignments.")
      ("topic-words-out,w", value<string>(), "file to write the topic word distribution to")
      ("samples,s", value<int>()->default_value(10), "number of sampling passes through the data")
      ("backoff-type", value<string>(), "backoff type: none|simple")
      ("filter-singleton-contexts", "filter singleton contexts")
      ("hierarchical-topics", "Use a backoff hierarchical PYP as the P0 for the document topics distribution.")
      ;
    store(parse_command_line(argc, argv, cmdline_options), vm);
    notify(vm);

    if (vm.count("help")) {
      cout << cmdline_options << "\n";
      return 1;
    }
  }
  ////////////////////////////////////////////////////////////////////////////////////////////

  if (!vm.count("data")) {
    cerr << "Please specify a file containing the data." << endl;
    return 1;
  }

  // seed the random number generator
  //mt_init_genrand(time(0));

  PYPTopics model(vm["topics"].as<int>(), vm.count("hierarchical-topics"));

  // read the data
  BackoffGenerator* backoff_gen=0;
  if (vm.count("backoff-type")) {
    if (vm["backoff-type"].as<std::string>() == "none") {
      backoff_gen = 0;
    }
    else if (vm["backoff-type"].as<std::string>() == "simple") {
      backoff_gen = new SimpleBackoffGenerator();
    }
    else {
     cerr << "Backoff type (--backoff-type) must be one of none|simple." <<endl;
      return(1);
    }
  }

  ContextsCorpus contexts_corpus;
  contexts_corpus.read_contexts(vm["data"].as<string>(), backoff_gen, vm.count("filter-singleton-contexts"));
  model.set_backoff(contexts_corpus.backoff_index());

  if (backoff_gen)
    delete backoff_gen;

  // train the sampler
  model.sample(contexts_corpus, vm["samples"].as<int>());

  if (vm.count("document-topics-out")) {
    ogzstream documents_out(vm["document-topics-out"].as<string>().c_str());

    int document_id=0;
   map<int,int> all_terms;
    for (Corpus::const_iterator corpusIt=contexts_corpus.begin();
         corpusIt != contexts_corpus.end(); ++corpusIt, ++document_id) {
     vector<int> unique_terms;
      for (Document::const_iterator docIt=corpusIt->begin();
           docIt != corpusIt->end(); ++docIt) {
        if (unique_terms.empty() || *docIt != unique_terms.back())
          unique_terms.push_back(*docIt);
        // increment this terms frequency
        pair<map<int,int>::iterator,bool> insert_result = all_terms.insert(make_pair(*docIt,1));
        if (!insert_result.second)
          insert_result.first++;
      }
      documents_out << contexts_corpus.key(document_id) << '\t';
      for (std::vector<int>::const_iterator termIt=unique_terms.begin();
           termIt != unique_terms.end(); ++termIt) {
        if (termIt != unique_terms.begin())
          documents_out << " ||| ";
       vector<std::string> strings = contexts_corpus.context2string(*termIt);
       copy(strings.begin(), strings.end(),ostream_iterator<std::string>(documents_out, " "));
        documents_out << "||| C=" << model.max(document_id, *termIt);

      }
      documents_out <<endl;
    }
    documents_out.close();

   ofstream default_topics(vm["default-topics-out"].as<string>().c_str());
    default_topics << model.max_topic() <<endl;
    for (std::map<int,int>::const_iterator termIt=all_terms.begin(); termIt != all_terms.end(); ++termIt) {
     vector<std::string> strings = contexts_corpus.context2string(termIt->first);
      default_topics << model.max(-1, termIt->first) << " ||| " << termIt->second << " ||| ";
     copy(strings.begin(), strings.end(),ostream_iterator<std::string>(default_topics, " "));
      default_topics <<endl;
    }
  }

  if (vm.count("topic-words-out")) {
    ogzstream topics_out(vm["topic-words-out"].as<string>().c_str());
    model.print_topic_terms(topics_out);
    topics_out.close();
  }

 cout <<endl;

  return 0;
}
<commit_msg><commit_after>// STL
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>

// Boost
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/scoped_ptr.hpp>

// Local
#include "pyp-topics.hh"
#include "corpus.hh"
#include "contexts_corpus.hh"
#include "gzstream.hh"
#include "mt19937ar.h"

static const char *REVISION = "$Rev$";

// Namespaces
using namespace boost;
using namespace boost::program_options;
using namespace std;

int main(int argc, char **argv)
{
 cout << "Pitman Yor topic models: Copyright 2010 Phil Blunsom\n";
 cout << REVISION << '\n' <<endl;

  ////////////////////////////////////////////////////////////////////////////////////////////
  // Command line processing
  variables_map vm;

  // Command line processing
  {
    options_description cmdline_options("Allowed options");
    cmdline_options.add_options()
      ("help,h", "print help message")
      ("data,d", value<string>(), "file containing the documents and context terms")
      ("topics,t", value<int>()->default_value(50), "number of topics")
      ("document-topics-out,o", value<string>(), "file to write the document topics to")
      ("default-topics-out", value<string>(), "file to write default term topic assignments.")
      ("topic-words-out,w", value<string>(), "file to write the topic word distribution to")
      ("samples,s", value<int>()->default_value(10), "number of sampling passes through the data")
      ("backoff-type", value<string>(), "backoff type: none|simple")
      ("filter-singleton-contexts", "filter singleton contexts")
      ("hierarchical-topics", "Use a backoff hierarchical PYP as the P0 for the document topics distribution.")
      ;
    store(parse_command_line(argc, argv, cmdline_options), vm);
    notify(vm);

    if (vm.count("help")) {
      cout << cmdline_options << "\n";
      return 1;
    }
  }
  ////////////////////////////////////////////////////////////////////////////////////////////

  if (!vm.count("data")) {
    cerr << "Please specify a file containing the data." << endl;
    return 1;
  }

  // seed the random number generator
  //mt_init_genrand(time(0));

  PYPTopics model(vm["topics"].as<int>(), vm.count("hierarchical-topics"));

  // read the data
  BackoffGenerator* backoff_gen=0;
  if (vm.count("backoff-type")) {
    if (vm["backoff-type"].as<std::string>() == "none") {
      backoff_gen = 0;
    }
    else if (vm["backoff-type"].as<std::string>() == "simple") {
      backoff_gen = new SimpleBackoffGenerator();
    }
    else {
     cerr << "Backoff type (--backoff-type) must be one of none|simple." <<endl;
      return(1);
    }
  }

  ContextsCorpus contexts_corpus;
  contexts_corpus.read_contexts(vm["data"].as<string>(), backoff_gen, vm.count("filter-singleton-contexts"));
  model.set_backoff(contexts_corpus.backoff_index());

  if (backoff_gen)
    delete backoff_gen;

  // train the sampler
  model.sample(contexts_corpus, vm["samples"].as<int>());

  if (vm.count("document-topics-out")) {
    ogzstream documents_out(vm["document-topics-out"].as<string>().c_str());

    int document_id=0;
   map<int,int> all_terms;
    for (Corpus::const_iterator corpusIt=contexts_corpus.begin();
         corpusIt != contexts_corpus.end(); ++corpusIt, ++document_id) {
     vector<int> unique_terms;
      for (Document::const_iterator docIt=corpusIt->begin();
           docIt != corpusIt->end(); ++docIt) {
        if (unique_terms.empty() || *docIt != unique_terms.back())
          unique_terms.push_back(*docIt);
        // increment this terms frequency
        pair<map<int,int>::iterator,bool> insert_result = all_terms.insert(make_pair(*docIt,1));
        if (!insert_result.second)
          all_terms[*docIt] = all_terms[*docIt] + 1;
          //insert_result.first++;
      }
      documents_out << contexts_corpus.key(document_id) << '\t';
      for (std::vector<int>::const_iterator termIt=unique_terms.begin();
           termIt != unique_terms.end(); ++termIt) {
        if (termIt != unique_terms.begin())
          documents_out << " ||| ";
       vector<std::string> strings = contexts_corpus.context2string(*termIt);
       copy(strings.begin(), strings.end(),ostream_iterator<std::string>(documents_out, " "));
        documents_out << "||| C=" << model.max(document_id, *termIt);

      }
      documents_out <<endl;
    }
    documents_out.close();

   ofstream default_topics(vm["default-topics-out"].as<string>().c_str());
    default_topics << model.max_topic() <<endl;
    for (std::map<int,int>::const_iterator termIt=all_terms.begin(); termIt != all_terms.end(); ++termIt) {
     vector<std::string> strings = contexts_corpus.context2string(termIt->first);
      default_topics << model.max(-1, termIt->first) << " ||| " << termIt->second << " ||| ";
     copy(strings.begin(), strings.end(),ostream_iterator<std::string>(default_topics, " "));
      default_topics <<endl;
    }
  }

  if (vm.count("topic-words-out")) {
    ogzstream topics_out(vm["topic-words-out"].as<string>().c_str());
    model.print_topic_terms(topics_out);
    topics_out.close();
  }

 cout <<endl;

  return 0;
}
<|endoftext|>


<commit_before>/*
    Test module for atlas

    Tests functions of class Object
    by Gordon Hart, fex <who@which.net>

    29 Jan 2000

*/

#include "../Object/Object.h"
using Atlas::Object;

#include <iostream>
using std::cout;
using std::endl;

//________________________________________________________________________________
//Global
bool verbose = true;

//________________________________________________________________________________
//Helper inlines

inline void print ( const string& output ) {

    if (verbose) {
        cout << output;
        cout.flush();
    }
}

inline void println ( const string& output ) {

    if (verbose) {
        cout << endl << output << endl;
        cout.flush();
    }
}

class TestError {};

inline void check( const bool test ) {
    if (!test)
        throw TestError();
    print(".Ok");
}

//________________________________________________________________________________
//Proto
bool mapTest();

//________________________________________________________________________________
//Main

int main() {

    println("Object test - ");

    int error = 0;

    error += mapTest();

    println("Test run finished");

    if ( error )
        return -1;

    return 0;

}

//________________________________________________________________________________
//subchecks

void mapTypeCheck( const Object& anObject) {

    check(  anObject.isMap() );
    check( !anObject.isList() );
    check( !anObject.isInt() );
    check( !anObject.isFloat() );
    check( !anObject.isString() );
}

//________________________________________________________________________________
//Main checks

bool mapTest() {

    try {

        println( "Creating map" );

        Object map;

        println( "Type check 1" );
        mapTypeCheck( map );

        println( "Check has()" );
        check( !map.has( "" ) );
        check( !map.has( "map") );

        println( "Check length" );
        check ( map.length() == 0 );

        println( "Adding value" );
        map.set( "string", "Stringval" );

        println( "Consistency checks" );
        check( map.length() == 1 );
        check( map.has( "string" ) );
        check( !map.has( "" ) );

        println( "Overwriting value" );
        map.set( "string", "stringval" );

        check( map.length() == 1 );
        check( map.has( "string" ) );
        check( !map.has( "" ) );

        println( "Delete check 1" );
        map.del( "" );
        check( map.has( "string" ) );
        check( map.length() == 1 );
        map.del( "string" );
        check( !map.has( "string" ) );
        check( map.length() == 0 );

        println( "Delete check 2" );
        map.set( "1", "2" );
        map.set( "3", "4" );
        check( map.length() == 2 );
        check( map.has("1") );
        check( map.has("3") );
        check( !map.has("2" ) );
        map.del( "1" );
        check( map.length() == 1 );
        check( !map.has( "1" ) );
        map.del( "3" );
        check( map.length() == 0 );
        check( !map.has( "3" ) );

        println( "Clearing map" );
        map.set( "1", "2" );
        map.set( "3", "4" );
        map.clear();
        check( map.length() == 0 );

        println( "Integer add" );
        map.set( "int", 9191 );
        check( map.has( "int" ) );
        check( map.length() == 1 );

        println( "double add" );
        map.set( "double", 2828.2828 );
        check( map.has( "double" ) );
        check( map.length() == 2 );

        println( "string add" );
        map.set( "string", "a test String" );
        check( map.has( "string" ) );
        check( map.length() == 3 );

        println( "long add" );
        map.set( "long", 12345678L );
        check( map.has( "long" ) );
        check( map.length() == 4 );

        Object foo;
        println( "Convert to value List check" );
        foo = map.vals();
        check( foo.length() == 4 );

        println( "Convert to key List check" );
        foo = map.vals();
        check( foo.length() == 4 );

        int ival=       0;
        double dval=    0;
        long lval=      0;
        string sval=    "";

        println( "Integer true get" );
        check( map.get( "int", ival ) );
        check( ival == 9191 );
        println( "Integer get as Long" );
        check( map.get( "int", lval ) );
        check( ival == 9191L );
        println( "Bad type get" );
        check( !map.get( "int", dval ) );
        check( !map.get( "int", sval ) );

        dval = lval = ival = 0;
        sval = "";
        println( "Double true get" );
        check( map.get( "double", dval ) );
        check( dval != 0 );
        println( "Bad type get" );
        check( !map.get( "double", ival ) );
        check( !map.get( "double", sval ) );
        check( !map.get( "double", lval ) );

        dval = lval = ival = 0;
        sval = "";
        println( "Long true get" );
        check( map.get( "long", lval ) );
        check( lval == 12345678L );
        println( "Long get as integer" );
        check( map.get( "long", ival ) );
        check( ival == 12345678L );
        println( "Bad type get" );
        check( !map.get( "long", dval ) );
        check( !map.get( "long", sval ) );

        dval = lval = ival = 0;
        sval = "";
        println( "String true get" );
        check( map.get( "string", sval ) );
        check( sval == "a test String" );
        println( "Bad type get" );
        check( !map.get( "string", ival ) );
        check( !map.get( "string", dval ) );
        check( !map.get( "string", lval ) );

        println( "Embedded object test" );
        Object bar;
        Object bar2;
        bar.set( "object", map );
        check( bar.length() == 1);
        check( map.length() == 4);
        check( bar.has( "object" ) );
        check( bar.get( "object", bar2 ) );
        check( bar2.length() == 4 );

        println( "Key list check" );
        Object foobar = bar2.keys();
        check( foobar.length() == 4 );

/*
        println( "Out of bounds ndx check on key list" );
        for ( int i = -10 ; i < 10; ++i) {
            if ( ( i < 0) || ( i > 3 ) ) {
                cout << " check not there ";
                check( !foobar.get( i, sval ) );
            }
            else {
                cout << " check there ";
                check( foobar.get( i, sval ) );
                println( sval );
            }
        }
*/
        println( "Out of bounds ndx check on key list" );
        for ( int i = -10 ; i < 10; ++i) {
            sval = "";
            cout << foobar.get( i, sval);
            cout << "At map[" << i << "] is the string [" << sval << "]" << endl;
        }

        println( "Closing clear checks" );
        bar.clear();
        check( bar.length() == 0 );
        check( map.length() == 4 );
        map.clear();
        check( map.length() == 0 );

        return true;

    } catch ( TestError& e ) {

        print("...Failed\n");
        return false;
    }

}<commit_msg>*** empty log message ***<commit_after>/*
    Test module for atlas

    Tests functions of class Object
    by Gordon Hart, fex <who@which.net>

    29 Jan 2000

*/

#include "../Object/Object.h"
using Atlas::Object;

#include <iostream>
using std::cout;
using std::endl;

//________________________________________________________________________________
//Global
bool verbose = true;

//________________________________________________________________________________
//Helper inlines

inline void print ( const string& output ) {

    if (verbose) {
        cout << output;
        cout.flush();
    }
}

inline void println ( const string& output ) {

    if (verbose) {
        cout << endl << output << endl;
        cout.flush();
    }
}

class TestError {};

inline void check( const bool test ) {
    if (!test)
        throw TestError();
    print(".Ok");
}

//________________________________________________________________________________
//Proto
bool mapTest();

//________________________________________________________________________________
//Main

int main() {

    println("Object test - ");

    int error = 0;

    error += mapTest();

    println("Test run finished");

    if ( error )
        return -1;

    return 0;

}

//________________________________________________________________________________
//subchecks

void mapTypeCheck( const Object& anObject) {

    check(  anObject.isMap() );
    check( !anObject.isList() );
    check( !anObject.isInt() );
    check( !anObject.isFloat() );
    check( !anObject.isString() );
}

//________________________________________________________________________________
//Main checks

bool mapTest() {

    try {

        println( "Creating map" );

        Object map;

        println( "Type check 1" );
        mapTypeCheck( map );

        println( "Check has()" );
        check( !map.has( "" ) );
        check( !map.has( "map") );

        println( "Check length" );
        check ( map.length() == 0 );

        println( "Adding value" );
        map.set( "string", "Stringval" );

        println( "Consistency checks" );
        check( map.length() == 1 );
        check( map.has( "string" ) );
        check( !map.has( "" ) );

        println( "Overwriting value" );
        map.set( "string", "stringval" );

        check( map.length() == 1 );
        check( map.has( "string" ) );
        check( !map.has( "" ) );

        println( "Delete check 1" );
        map.del( "" );
        check( map.has( "string" ) );
        check( map.length() == 1 );
        map.del( "string" );
        check( !map.has( "string" ) );
        check( map.length() == 0 );

        println( "Delete check 2" );
        map.set( "1", "2" );
        map.set( "3", "4" );
        check( map.length() == 2 );
        check( map.has("1") );
        check( map.has("3") );
        check( !map.has("2" ) );
        map.del( "1" );
        check( map.length() == 1 );
        check( !map.has( "1" ) );
        map.del( "3" );
        check( map.length() == 0 );
        check( !map.has( "3" ) );

        println( "Clearing map" );
        map.set( "1", "2" );
        map.set( "3", "4" );
        map.clear();
        check( map.length() == 0 );

        println( "Integer add" );
        map.set( "int", 9191 );
        check( map.has( "int" ) );
        check( map.length() == 1 );

        println( "double add" );
        map.set( "double", 2828.2828 );
        check( map.has( "double" ) );
        check( map.length() == 2 );

        println( "string add" );
        map.set( "string", "a test String" );
        check( map.has( "string" ) );
        check( map.length() == 3 );

        println( "long add" );
        map.set( "long", 12345678L );
        check( map.has( "long" ) );
        check( map.length() == 4 );

        Object foo;
        println( "Convert to value List check" );
        foo = map.vals();
        check( foo.length() == 4 );

        println( "Convert to key List check" );
        foo = map.vals();
        check( foo.length() == 4 );

        int ival=       0;
        double dval=    0;
        long lval=      0;
        string sval=    "";

        println( "Integer true get" );
        check( map.get( "int", ival ) );
        check( ival == 9191 );
        println( "Integer get as Long" );
        check( map.get( "int", lval ) );
        check( ival == 9191L );
        println( "Bad type get" );
        check( !map.get( "int", dval ) );
        check( !map.get( "int", sval ) );

        dval = lval = ival = 0;
        sval = "";
        println( "Double true get" );
        check( map.get( "double", dval ) );
        check( dval != 0 );
        println( "Bad type get" );
        check( !map.get( "double", ival ) );
        check( !map.get( "double", sval ) );
        check( !map.get( "double", lval ) );

        dval = lval = ival = 0;
        sval = "";
        println( "Long true get" );
        check( map.get( "long", lval ) );
        check( lval == 12345678L );
        println( "Long get as integer" );
        check( map.get( "long", ival ) );
        check( ival == 12345678L );
        println( "Bad type get" );
        check( !map.get( "long", dval ) );
        check( !map.get( "long", sval ) );

        dval = lval = ival = 0;
        sval = "";
        println( "String true get" );
        check( map.get( "string", sval ) );
        check( sval == "a test String" );
        println( "Bad type get" );
        check( !map.get( "string", ival ) );
        check( !map.get( "string", dval ) );
        check( !map.get( "string", lval ) );

        println( "Embedded object test" );
        Object bar;
        Object bar2;
        bar.set( "object", map );
        check( bar.length() == 1);
        check( map.length() == 4);
        check( bar.has( "object" ) );
        check( bar.get( "object", bar2 ) );
        check( bar2.length() == 4 );

        println( "Key list check" );
        Object foobar = bar2.keys();
        check( foobar.length() == 4 );

        /*
        println( "Out of bounds ndx check on key list" );
        for ( int i = -10 ; i < 10; ++i) {
            if ( ( i < 0) || ( i > 3 ) ) {
                cout << " check not there ";
                check( !foobar.get( i, sval ) );
            }
            else {
                cout << " check there ";
                check( foobar.get( i, sval ) );
                println( sval );
            }
        }
        */
        // out of bound calls on list are broken,this shows it up
        // the code above is the proper check for correct behaviour
        println( "Out of bounds ndx check on key list" );
        for ( int i = -10 ; i < 10; ++i) {
            sval = "";
            cout << foobar.get( i, sval);
            cout << "At map[" << i << "] is the string [" << sval << "]" << endl;
        }

        println( "Closing clear checks" );
        bar.clear();
        check( bar.length() == 0 );
        check( map.length() == 4 );
        map.clear();
        check( map.length() == 0 );

        return true;

    } catch ( TestError& e ) {

        print("...Failed\n");
        return false;
    }

}<|endoftext|>


<commit_before>/*****************************************************************************\
 *                        ANALYSIS PERFORMANCE TOOLS                         *
 *                                  wxparaver                                *
 *              Paraver Trace Visualization and Analysis Tool                *
 *****************************************************************************
 *     ___     This library is free software; you can redistribute it and/or *
 *    /  __         modify it under the terms of the GNU LGPL as published   *
 *   /  /  _____    by the Free Software Foundation; either version 2.1      *
 *  /  /  /     \   of the License, or (at your option) any later version.   *
 * (  (  ( B S C )                                                           *
 *  \  \  \_____/   This library is distributed in 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 LGPL for more details.   *
 *                                                                           *
 * You should have received a copy of the GNU Lesser General Public License  *
 * along with this library; if not, write to the Free Software Foundation,   *
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA          *
 * The GNU LEsser General Public License is contained in the file COPYING.   *
 *                                 ---------                                 *
 *   Barcelona Supercomputing Center - Centro Nacional de Supercomputacion   *
\*****************************************************************************/

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\
 | @file: $HeadURL$
 | @last_commit: $Date$
 | @version:     $Revision$
\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

////@begin includes
////@end includes

#include "labelconstructor.h"

// Signal handling
#include <signal.h>
#include <stdio.h>

#include "wxparaverapp.h"
#include "connection.h"
#include <wx/filename.h>

////@begin XPM images
////@end XPM images

#ifndef WIN32
struct sigaction act;
#endif

/*!
 * Application instance implementation
 */

////@begin implement app
IMPLEMENT_APP( wxparaverApp )
////@end implement app

/*!
 * wxparaverApp type definition
 */

IMPLEMENT_CLASS( wxparaverApp, wxApp )

/*!
 * wxparaverApp event table definition
 */

BEGIN_EVENT_TABLE( wxparaverApp, wxApp )

////@begin wxparaverApp event table entries
////@end wxparaverApp event table entries

END_EVENT_TABLE()

/*!
 * Constructor for wxparaverApp
 */

wxparaverApp::wxparaverApp()
{
  Init();
}

/*!
 * Member initialisation
 */

void wxparaverApp::Init()
{
////@begin wxparaverApp member initialisation
	globalTiming = false;
	globalTimingBegin = 0;
	globalTimingEnd = 0;
	globalTimingCallDialog = NULL;
	globalTimingBeginIsSet = false;
	eventTypeForCode = 60000119;
////@end wxparaverApp member initialisation
  m_locale.Init();
}

/*!
 * Initialisation for wxparaverApp
 */

paraverMain* wxparaverApp::mainWindow = NULL;

#ifndef WIN32
volatile bool sig1 = false;
volatile bool sig2 = false;

void wxparaverApp::handler( int signalNumber )
{
  sigdelset( &act.sa_mask, SIGUSR1 );
  sigdelset( &act.sa_mask, SIGUSR2 );

//  wxMutexGuiEnter();
//  wxparaverApp::mainWindow->OnSignal( signalNumber );
//  wxMutexGuiLeave();
  if ( signalNumber == SIGUSR1 )
  {
    sig1 = true;
  }
  else
  {
    sig1 = false;
  }

  sig2 = !sig1;

//  wxIdleEvent event;
//  event.RequestMore();
//  wxTheApp->SendIdleEvents( mainWindow, event );
  mainWindow->Raise();

  sigaddset( &act.sa_mask, SIGUSR1 );
  sigaddset( &act.sa_mask, SIGUSR2 );
  sigaction( SIGUSR1, &act, NULL );
  sigaction( SIGUSR2, &act, NULL );
}

void wxparaverApp::presetUserSignals()
{

  act.sa_handler = &handler;
  act.sa_flags = 0;

  if ( sigemptyset( &act.sa_mask ) != 0 )
  {
    /* Handle error */
  }

  if ( sigaddset( &act.sa_mask, SIGUSR1 ))
  {
    /* Handle error */
  }

  if ( sigaddset( &act.sa_mask, SIGUSR2 ))
  {
    /* Handle error */
  }

  if ( sigaction( SIGUSR1, &act, NULL ) != 0 )
  {
    /* Handle error */
  }

  if ( sigaction( SIGUSR2, &act, NULL ) != 0 )
  {
    /* Handle error */
  }
}
#endif

bool wxparaverApp::OnInit()
{
  wxCmdLineEntryDesc argumentsParseSyntax[] =
  {
    { wxCMD_LINE_SWITCH,
      wxT("v"),
      wxT("version"),
      wxT("Show wxparaver version."),
      wxCMD_LINE_VAL_STRING },

    { wxCMD_LINE_SWITCH,
      wxT("h"),
      wxT("help"),
      wxT("Show this help."),
      wxCMD_LINE_VAL_STRING,
      wxCMD_LINE_OPTION_HELP },

    { wxCMD_LINE_OPTION,
      wxT("t"),
      wxT("type"),
      wxT("Event type to code linking."),
      wxCMD_LINE_VAL_NUMBER,
      wxCMD_LINE_PARAM_OPTIONAL },

    { wxCMD_LINE_PARAM,
      NULL,
      NULL,
      wxT( "(trace.prv | trace.prv.gz) (configuration.cfg)" ),
      wxCMD_LINE_VAL_STRING,
      wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE },

    { wxCMD_LINE_NONE }
  };

  wxCmdLineParser paraverCommandLineParser( argumentsParseSyntax, argc, argv );
  if ( paraverCommandLineParser.Parse( false ) != 0 )
  {
    paraverCommandLineParser.Usage();
    return false;
  }

  if( paraverCommandLineParser.Found( wxT("v") ))
  {
    PrintVersion();
    return false;
  }

  ParaverConfig::getInstance()->readParaverConfigFile();

  if( ParaverConfig::getInstance()->getGlobalSingleInstance() )
  {
    const wxString name = wxString::Format( _( "wxparaver-%s" ), wxGetUserId().c_str());
    m_checker = new wxSingleInstanceChecker(name);
    if ( !m_checker->IsAnotherRunning() )
    {
      m_server = new stServer;

#ifdef WIN32
      if( !m_server->Create( wxT( "wxparaver_service" ) ) )
#else
      const wxString service_name = wxString::Format( _( "/tmp/wxparaver_service-%s" ), wxGetUserId().c_str());
      if( !m_server->Create( service_name ) )
#endif
        wxLogDebug( wxT( "Failed to create an IPC service." ) );
    }
    else
    {
      wxLogNull logNull;

      stClient *client = new stClient;
      wxString hostName = wxT( "localhost" );
#ifdef WIN32
      wxConnectionBase *connection = client->MakeConnection( hostName,
                                                             wxT( "wxparaver_service" ),
                                                             wxT( "wxparaver" ) );
#else
      const wxString service_name = wxString::Format( _( "/tmp/wxparaver_service-%s" ), wxGetUserId().c_str());
      wxConnectionBase *connection = client->MakeConnection( hostName,
                                                             service_name,
                                                             wxT( "wxparaver" ) );
#endif
      if( connection )
      {
        connection->Execute( wxT( "BEGIN" ) );
        for( int i = 1; i < argc; ++i )
        {
          wxFileName tmpFile( wxT( argv[ i ] ) );
          tmpFile.Normalize();
          connection->Execute( tmpFile.GetFullPath().c_str() );
        }
        connection->Execute( wxT( "END" ) );
        connection->Disconnect();
        delete connection;
      }
      else
      {
        wxMessageBox( wxT( "Sorry, the existing instance may be too busy to respond." ),
                      wxT( "wxparaver" ), wxICON_INFORMATION|wxOK );
      }

      delete client;
      return false;
    }
  }

#if wxUSE_XPM
  wxImage::AddHandler(new wxXPMHandler);
#endif
#if wxUSE_LIBPNG
  wxImage::AddHandler(new wxPNGHandler);
#endif
#if wxUSE_LIBJPEG
  wxImage::AddHandler(new wxJPEGHandler);
#endif
#if wxUSE_GIF
  wxImage::AddHandler(new wxGIFHandler);
#endif

  wxSize mainWindowSize( ParaverConfig::getInstance()->getMainWindowWidth(),
                         ParaverConfig::getInstance()->getMainWindowHeight() );
  mainWindow = new paraverMain( NULL, SYMBOL_PARAVERMAIN_IDNAME, SYMBOL_PARAVERMAIN_TITLE, SYMBOL_PARAVERMAIN_POSITION, mainWindowSize );
  //mainWindow = new paraverMain( NULL );

  mainWindow->Show(true);

  long int tmpType;
  if( paraverCommandLineParser.Found( wxT("t"), &tmpType ) )
    eventTypeForCode = tmpType;

  mainWindow->commandLineLoadings( paraverCommandLineParser );

/*
  paraverMain *mainWindow;
  mainWindow = new paraverMain( NULL );

  mainWindow->Show(true);

  mainWindow->commandLineLoadings( paraverCommandLineParser );
*/
#ifndef WIN32
  presetUserSignals();
#endif

  return true;
}

/*!
 * Cleanup for wxparaverApp
 */

int wxparaverApp::OnExit()
{
//  double w, h;
//  wxparaverApp::mainWindow->GetAuiManager().GetDockSizeConstraint( &w, &h );
//  cout<<w<<" "<<h<<endl;
//  cout << wxparaverApp::mainWindow->GetAuiManager().SavePaneInfo(
//            wxparaverApp::mainWindow->GetAuiManager().GetPane( wxparaverApp::mainWindow->choiceWindowBrowser ) ).mb_str()<<endl;
  ParaverConfig::getInstance()->writeParaverConfigFile();

  if( m_checker != NULL )
    delete m_checker;

  if( m_server != NULL )
    delete m_server;

////@begin wxparaverApp cleanup
	return wxApp::OnExit();
////@end wxparaverApp cleanup
}

#ifdef WIN32
int wxparaverApp::FilterEvent(wxEvent& event)
{
  if ( event.GetEventType()==wxEVT_KEY_DOWN &&
       ((wxKeyEvent&)event).ControlDown() &&
       ((wxKeyEvent&)event).GetKeyCode() == (long) 'C'
     )
  {
    mainWindow->OnKeyCopy();
    return true;
  }
  else if ( event.GetEventType()==wxEVT_KEY_DOWN &&
            ((wxKeyEvent&)event).ControlDown() &&
            ((wxKeyEvent&)event).GetKeyCode() == (long) 'V'
          )
  {
    mainWindow->OnKeyPaste();
    return true;
  }

  return -1;
}
#endif

void wxparaverApp::ActivateGlobalTiming( wxDialog* whichDialog )
{
  globalTimingCallDialog = whichDialog;
  wxSetCursor( *wxCROSS_CURSOR );
  globalTiming = true;
  globalTimingBeginIsSet = false;
  globalTimingCallDialog->Enable( false );
  globalTimingCallDialog->MakeModal( false );
#ifdef WIN32
  globalTimingCallDialog->Iconize( true );
#endif
  mainWindow->Raise();
}

void wxparaverApp::DeactivateGlobalTiming()
{
cout << "DeactivateGlobalTiming" << endl;
  wxSetCursor( wxNullCursor );
  globalTiming = false;
  globalTimingBeginIsSet = false;
  globalTimingCallDialog->Enable( true );
  globalTimingCallDialog->MakeModal( true );
#ifdef WIN32
  globalTimingCallDialog->Iconize( false );
#endif
  globalTimingCallDialog->Raise();
}

void wxparaverApp::PrintVersion()
{
  cout << PACKAGE_STRING;

  bool reverseOrder = true;
  string auxDate = LabelConstructor::getDate( reverseOrder );

  if ( auxDate.compare("") != 0 )
    cout << " Build ";

  cout << auxDate << endl;
}
<commit_msg>*** empty log message ***<commit_after>/*****************************************************************************\
 *                        ANALYSIS PERFORMANCE TOOLS                         *
 *                                  wxparaver                                *
 *              Paraver Trace Visualization and Analysis Tool                *
 *****************************************************************************
 *     ___     This library is free software; you can redistribute it and/or *
 *    /  __         modify it under the terms of the GNU LGPL as published   *
 *   /  /  _____    by the Free Software Foundation; either version 2.1      *
 *  /  /  /     \   of the License, or (at your option) any later version.   *
 * (  (  ( B S C )                                                           *
 *  \  \  \_____/   This library is distributed in 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 LGPL for more details.   *
 *                                                                           *
 * You should have received a copy of the GNU Lesser General Public License  *
 * along with this library; if not, write to the Free Software Foundation,   *
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA          *
 * The GNU LEsser General Public License is contained in the file COPYING.   *
 *                                 ---------                                 *
 *   Barcelona Supercomputing Center - Centro Nacional de Supercomputacion   *
\*****************************************************************************/

/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- *\
 | @file: $HeadURL$
 | @last_commit: $Date$
 | @version:     $Revision$
\* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

////@begin includes
////@end includes

#include "labelconstructor.h"

// Signal handling
#include <signal.h>
#include <stdio.h>

#include "wxparaverapp.h"
#include "connection.h"
#include <wx/filename.h>

////@begin XPM images
////@end XPM images

#ifndef WIN32
struct sigaction act;
#endif

/*!
 * Application instance implementation
 */

////@begin implement app
IMPLEMENT_APP( wxparaverApp )
////@end implement app

/*!
 * wxparaverApp type definition
 */

IMPLEMENT_CLASS( wxparaverApp, wxApp )

/*!
 * wxparaverApp event table definition
 */

BEGIN_EVENT_TABLE( wxparaverApp, wxApp )

////@begin wxparaverApp event table entries
////@end wxparaverApp event table entries

END_EVENT_TABLE()

/*!
 * Constructor for wxparaverApp
 */

wxparaverApp::wxparaverApp()
{
  Init();
}

/*!
 * Member initialisation
 */

void wxparaverApp::Init()
{
////@begin wxparaverApp member initialisation
	globalTiming = false;
	globalTimingBegin = 0;
	globalTimingEnd = 0;
	globalTimingCallDialog = NULL;
	globalTimingBeginIsSet = false;
	eventTypeForCode = 60000119;
////@end wxparaverApp member initialisation
  m_locale.Init();
}

/*!
 * Initialisation for wxparaverApp
 */

paraverMain* wxparaverApp::mainWindow = NULL;

#ifndef WIN32
volatile bool sig1 = false;
volatile bool sig2 = false;

void wxparaverApp::handler( int signalNumber )
{
  sigdelset( &act.sa_mask, SIGUSR1 );
  sigdelset( &act.sa_mask, SIGUSR2 );

//  wxMutexGuiEnter();
//  wxparaverApp::mainWindow->OnSignal( signalNumber );
//  wxMutexGuiLeave();
  if ( signalNumber == SIGUSR1 )
  {
    sig1 = true;
  }
  else
  {
    sig1 = false;
  }

  sig2 = !sig1;

//  wxIdleEvent event;
//  event.RequestMore();
//  wxTheApp->SendIdleEvents( mainWindow, event );
  mainWindow->Raise();

  sigaddset( &act.sa_mask, SIGUSR1 );
  sigaddset( &act.sa_mask, SIGUSR2 );
  sigaction( SIGUSR1, &act, NULL );
  sigaction( SIGUSR2, &act, NULL );
}

void wxparaverApp::presetUserSignals()
{

  act.sa_handler = &handler;
  act.sa_flags = 0;

  if ( sigemptyset( &act.sa_mask ) != 0 )
  {
    /* Handle error */
  }

  if ( sigaddset( &act.sa_mask, SIGUSR1 ))
  {
    /* Handle error */
  }

  if ( sigaddset( &act.sa_mask, SIGUSR2 ))
  {
    /* Handle error */
  }

  if ( sigaction( SIGUSR1, &act, NULL ) != 0 )
  {
    /* Handle error */
  }

  if ( sigaction( SIGUSR2, &act, NULL ) != 0 )
  {
    /* Handle error */
  }
}
#endif

bool wxparaverApp::OnInit()
{
  wxCmdLineEntryDesc argumentsParseSyntax[] =
  {
    { wxCMD_LINE_SWITCH,
      wxT("v"),
      wxT("version"),
      wxT("Show wxparaver version."),
      wxCMD_LINE_VAL_STRING },

    { wxCMD_LINE_SWITCH,
      wxT("h"),
      wxT("help"),
      wxT("Show this help."),
      wxCMD_LINE_VAL_STRING,
      wxCMD_LINE_OPTION_HELP },

    { wxCMD_LINE_OPTION,
      wxT("t"),
      wxT("type"),
      wxT("Event type to code linking."),
      wxCMD_LINE_VAL_NUMBER,
      wxCMD_LINE_PARAM_OPTIONAL },

    { wxCMD_LINE_PARAM,
      NULL,
      NULL,
      wxT( "(trace.prv | trace.prv.gz) (configuration.cfg)" ),
      wxCMD_LINE_VAL_STRING,
      wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE },

    { wxCMD_LINE_NONE }
  };

  wxCmdLineParser paraverCommandLineParser( argumentsParseSyntax, argc, argv );
  if ( paraverCommandLineParser.Parse( false ) != 0 )
  {
    paraverCommandLineParser.Usage();
    return false;
  }

  if( paraverCommandLineParser.Found( wxT("v") ))
  {
    PrintVersion();
    return false;
  }

  ParaverConfig::getInstance()->readParaverConfigFile();

  if( ParaverConfig::getInstance()->getGlobalSingleInstance() )
  {
    const wxString name = wxString::Format( _( "wxparaver-%s" ), wxGetUserId().c_str());
    m_checker = new wxSingleInstanceChecker(name);
    if ( !m_checker->IsAnotherRunning() )
    {
      m_server = new stServer;

#ifdef WIN32
      if( !m_server->Create( wxT( "wxparaver_service" ) ) )
#else
      const wxString service_name = wxString::Format( _( "/tmp/wxparaver_service-%s" ), wxGetUserId().c_str());
      if( !m_server->Create( service_name ) )
#endif
        wxLogDebug( wxT( "Failed to create an IPC service." ) );
    }
    else
    {
      wxLogNull logNull;

      stClient *client = new stClient;
      wxString hostName = wxT( "localhost" );
#ifdef WIN32
      wxConnectionBase *connection = client->MakeConnection( hostName,
                                                             wxT( "wxparaver_service" ),
                                                             wxT( "wxparaver" ) );
#else
      const wxString service_name = wxString::Format( _( "/tmp/wxparaver_service-%s" ), wxGetUserId().c_str());
      wxConnectionBase *connection = client->MakeConnection( hostName,
                                                             service_name,
                                                             wxT( "wxparaver" ) );
#endif
      if( connection )
      {
        connection->Execute( wxT( "BEGIN" ) );
        for( int i = 1; i < argc; ++i )
        {
          wxFileName tmpFile( argv[ i ] );
          tmpFile.Normalize();
          connection->Execute( tmpFile.GetFullPath().c_str() );
        }
        connection->Execute( wxT( "END" ) );
        connection->Disconnect();
        delete connection;
      }
      else
      {
        wxMessageBox( wxT( "Sorry, the existing instance may be too busy to respond." ),
                      wxT( "wxparaver" ), wxICON_INFORMATION|wxOK );
      }

      delete client;
      return false;
    }
  }

#if wxUSE_XPM
  wxImage::AddHandler(new wxXPMHandler);
#endif
#if wxUSE_LIBPNG
  wxImage::AddHandler(new wxPNGHandler);
#endif
#if wxUSE_LIBJPEG
  wxImage::AddHandler(new wxJPEGHandler);
#endif
#if wxUSE_GIF
  wxImage::AddHandler(new wxGIFHandler);
#endif

  wxSize mainWindowSize( ParaverConfig::getInstance()->getMainWindowWidth(),
                         ParaverConfig::getInstance()->getMainWindowHeight() );
  mainWindow = new paraverMain( NULL, SYMBOL_PARAVERMAIN_IDNAME, SYMBOL_PARAVERMAIN_TITLE, SYMBOL_PARAVERMAIN_POSITION, mainWindowSize );
  //mainWindow = new paraverMain( NULL );

  mainWindow->Show(true);

  long int tmpType;
  if( paraverCommandLineParser.Found( wxT("t"), &tmpType ) )
    eventTypeForCode = tmpType;

  mainWindow->commandLineLoadings( paraverCommandLineParser );

/*
  paraverMain *mainWindow;
  mainWindow = new paraverMain( NULL );

  mainWindow->Show(true);

  mainWindow->commandLineLoadings( paraverCommandLineParser );
*/
#ifndef WIN32
  presetUserSignals();
#endif

  return true;
}

/*!
 * Cleanup for wxparaverApp
 */

int wxparaverApp::OnExit()
{
//  double w, h;
//  wxparaverApp::mainWindow->GetAuiManager().GetDockSizeConstraint( &w, &h );
//  cout<<w<<" "<<h<<endl;
//  cout << wxparaverApp::mainWindow->GetAuiManager().SavePaneInfo(
//            wxparaverApp::mainWindow->GetAuiManager().GetPane( wxparaverApp::mainWindow->choiceWindowBrowser ) ).mb_str()<<endl;
  ParaverConfig::getInstance()->writeParaverConfigFile();

  if( m_checker != NULL )
    delete m_checker;

  if( m_server != NULL )
    delete m_server;

////@begin wxparaverApp cleanup
	return wxApp::OnExit();
////@end wxparaverApp cleanup
}

#ifdef WIN32
int wxparaverApp::FilterEvent(wxEvent& event)
{
  if ( event.GetEventType()==wxEVT_KEY_DOWN &&
       ((wxKeyEvent&)event).ControlDown() &&
       ((wxKeyEvent&)event).GetKeyCode() == (long) 'C'
     )
  {
    mainWindow->OnKeyCopy();
    return true;
  }
  else if ( event.GetEventType()==wxEVT_KEY_DOWN &&
            ((wxKeyEvent&)event).ControlDown() &&
            ((wxKeyEvent&)event).GetKeyCode() == (long) 'V'
          )
  {
    mainWindow->OnKeyPaste();
    return true;
  }

  return -1;
}
#endif

void wxparaverApp::ActivateGlobalTiming( wxDialog* whichDialog )
{
  globalTimingCallDialog = whichDialog;
  wxSetCursor( *wxCROSS_CURSOR );
  globalTiming = true;
  globalTimingBeginIsSet = false;
  globalTimingCallDialog->Enable( false );
  globalTimingCallDialog->MakeModal( false );
#ifdef WIN32
  globalTimingCallDialog->Iconize( true );
#endif
  mainWindow->Raise();
}

void wxparaverApp::DeactivateGlobalTiming()
{
cout << "DeactivateGlobalTiming" << endl;
  wxSetCursor( wxNullCursor );
  globalTiming = false;
  globalTimingBeginIsSet = false;
  globalTimingCallDialog->Enable( true );
  globalTimingCallDialog->MakeModal( true );
#ifdef WIN32
  globalTimingCallDialog->Iconize( false );
#endif
  globalTimingCallDialog->Raise();
}

void wxparaverApp::PrintVersion()
{
  cout << PACKAGE_STRING;

  bool reverseOrder = true;
  string auxDate = LabelConstructor::getDate( reverseOrder );

  if ( auxDate.compare("") != 0 )
    cout << " Build ";

  cout << auxDate << endl;
}
<|endoftext|>


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

  Program: Visomics

  Copyright (c) Kitware, Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

// Qt includes
#include <QDebug>
#include <QList>
#include <QFile>
#include <QTextStream>

// Visomics includes
#include "voDataObject.h"
#include "voInputFileDataObject.h"
#include "voOneZoomDynView.h"
#include "voUtils.h"

// VTK includes
#include <vtkTree.h>

// --------------------------------------------------------------------------
class voOneZoomDynViewPrivate
{
public:
  voOneZoomDynViewPrivate();
};

// --------------------------------------------------------------------------
// voOneZoomDynViewPrivate methods

// --------------------------------------------------------------------------
voOneZoomDynViewPrivate::voOneZoomDynViewPrivate()
{
}

// --------------------------------------------------------------------------
// voOneZoomDynView methods

// --------------------------------------------------------------------------
voOneZoomDynView::voOneZoomDynView(QWidget * newParent):
    Superclass(newParent), d_ptr(new voOneZoomDynViewPrivate)
{
}

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

// --------------------------------------------------------------------------
QString voOneZoomDynView::stringify(const voDataObject& dataObject)
{
  vtkTree * tree = vtkTree::SafeDownCast(dataObject.dataAsVTKDataObject());
  if (!tree)
    {
    qCritical() << "voOneZoomDynView - Failed to setDataObject - vtkTree data is expected !";
    return QString();
    }

  //Ideally, a vtkNewickTreeWriter function can be used to convert a tree to a newick formated string;
  //For now, we just use the original input file to obtain the newick string.
  QString filename =  dynamic_cast<voInputFileDataObject *> (const_cast<voDataObject*>(&dataObject))->fileName();

  //read the tree file into a string
  QFile file(filename);
  QString treeString = "";
  if (file.open (QIODevice::ReadOnly | QIODevice::Text))
    {
    QTextStream stream ( &file );
    treeString = stream.readAll();
    }
  file.close(); // when your done.

  return treeString;
}
<commit_msg>make Wikipedia links from OneZoom work more reliably.<commit_after>/*=========================================================================

  Program: Visomics

  Copyright (c) Kitware, Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

// Qt includes
#include <QDebug>
#include <QList>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>

// Visomics includes
#include "voDataObject.h"
#include "voInputFileDataObject.h"
#include "voOneZoomDynView.h"
#include "voUtils.h"

// VTK includes
#include <vtkTree.h>

// --------------------------------------------------------------------------
class voOneZoomDynViewPrivate
{
public:
  voOneZoomDynViewPrivate();
};

// --------------------------------------------------------------------------
// voOneZoomDynViewPrivate methods

// --------------------------------------------------------------------------
voOneZoomDynViewPrivate::voOneZoomDynViewPrivate()
{
}

// --------------------------------------------------------------------------
// voOneZoomDynView methods

// --------------------------------------------------------------------------
voOneZoomDynView::voOneZoomDynView(QWidget * newParent):
    Superclass(newParent), d_ptr(new voOneZoomDynViewPrivate)
{
}

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

// --------------------------------------------------------------------------
QString voOneZoomDynView::stringify(const voDataObject& dataObject)
{
  vtkTree * tree = vtkTree::SafeDownCast(dataObject.dataAsVTKDataObject());
  if (!tree)
    {
    qCritical() << "voOneZoomDynView - Failed to setDataObject - vtkTree data is expected !";
    return QString();
    }

  //Ideally, a vtkNewickTreeWriter function can be used to convert a tree to a newick formated string;
  //For now, we just use the original input file to obtain the newick string.
  QString filename =  dynamic_cast<voInputFileDataObject *> (const_cast<voDataObject*>(&dataObject))->fileName();

  //read the tree file into a string
  QFile file(filename);
  QString treeString = "";
  if (file.open (QIODevice::ReadOnly | QIODevice::Text))
    {
    QTextStream stream ( &file );
    treeString = stream.readAll();
    }
  file.close(); // when your done.

  //Massage the leaf node labels so Wikipedia linking works more reliably.
  if (!treeString.contains("_"))
    {
    if (treeString.contains(" "))
      {
      treeString.replace(QString(" "), QString("_"));
      }
    else
      {
      QFileInfo fileInfo(file);
      QString nameToAppend = fileInfo.baseName();
      treeString.replace(QRegExp("([a-zA-Z]+)"), QString("%1_\\1").arg(nameToAppend));
      }
    }

  return treeString;
}
<|endoftext|>


<commit_before>/*
The MIT License

Copyright (c) 2010 by Jorrit Tyberghein

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */

#include "../apparesed.h"
#include "curvemode.h"

#include <wx/xrc/xmlres.h>

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

BEGIN_EVENT_TABLE(CurveMode::Panel, wxPanel)
  EVT_BUTTON (XRCID("rotLeftButton"), CurveMode::Panel::OnRotLeft)
  EVT_BUTTON (XRCID("rotRightButton"), CurveMode::Panel::OnRotRight)
  EVT_BUTTON (XRCID("rotResetButton"), CurveMode::Panel::OnRotReset)
  EVT_BUTTON (XRCID("flattenButton"), CurveMode::Panel::OnFlatten)
  EVT_CHECKBOX (XRCID("autoSmoothCheckBox"), CurveMode::Panel::OnAutoSmoothSelected)
END_EVENT_TABLE()

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

CurveMode::CurveMode (wxWindow* parent, AresEdit3DView* aresed3d)
  : ViewMode (aresed3d, "Curve")
{
  panel = new Panel (parent, this);
  parent->GetSizer ()->Add (panel, 1, wxALL | wxEXPAND);
  wxXmlResource::Get()->LoadPanel (panel, parent, wxT ("CurveModePanel"));

  editingCurveFactory = 0;
  autoSmooth = true;
  wxCheckBox* autoSmoothCheckBox = XRCCTRL (*panel, "autoSmoothCheckBox", wxCheckBox);
  autoSmoothCheckBox->SetValue (autoSmooth);
}

void CurveMode::UpdateMarkers ()
{
  iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
  if (editingCurveFactory->GetPointCount () != markers.GetSize ())
  {
    Stop ();
    for (size_t i = 0 ; i < editingCurveFactory->GetPointCount () ; i++)
    {
      iMarker* marker = aresed3d->GetMarkerManager ()->CreateMarker ();
      markers.Push (marker);
      marker->AttachMesh (mesh);
    }
  }

  iMarkerColor* red = aresed3d->GetMarkerManager ()->FindMarkerColor ("red");
  iMarkerColor* green = aresed3d->GetMarkerManager ()->FindMarkerColor ("green");
  iMarkerColor* yellow = aresed3d->GetMarkerManager ()->FindMarkerColor ("yellow");

  for (size_t i = 0 ; i < editingCurveFactory->GetPointCount () ; i++)
  {
    csVector3 pos = editingCurveFactory->GetPosition (i);
    csVector3 front = editingCurveFactory->GetFront (i);
    csVector3 up = editingCurveFactory->GetUp (i);
    iMarker* marker = markers[i];
    marker->Clear ();
    marker->Line (MARKER_OBJECT, pos, pos+front, green, true);
    marker->Line (MARKER_OBJECT, pos, pos+up, red, true);
    marker->ClearHitAreas ();
    iMarkerHitArea* hitArea = marker->HitArea (MARKER_OBJECT, pos, .1f, i, yellow);
    csRef<MarkerCallback> cb;
    cb.AttachNew (new MarkerCallback (this));
    hitArea->DefineDrag (0, 0, MARKER_WORLD, CONSTRAIN_MESH, cb);
    hitArea->DefineDrag (0, CSMASK_SHIFT, MARKER_WORLD, CONSTRAIN_MESH, cb);
    hitArea->DefineDrag (0, CSMASK_ALT, MARKER_WORLD, CONSTRAIN_YPLANE, cb);
    hitArea->DefineDrag (0, CSMASK_SHIFT + CSMASK_ALT, MARKER_WORLD, CONSTRAIN_YPLANE, cb);
    hitArea->DefineDrag (0, CSMASK_CTRL, MARKER_WORLD, CONSTRAIN_NONE, cb);
    hitArea->DefineDrag (0, CSMASK_SHIFT + CSMASK_CTRL, MARKER_WORLD, CONSTRAIN_NONE, cb);
  }

  UpdateMarkerSelection ();
}

void CurveMode::UpdateMarkerSelection ()
{
  for (size_t i = 0 ; i < markers.GetSize () ; i++)
    markers[i]->SetSelectionLevel (SELECTION_NONE);
  for (size_t i = 0 ; i < selectedPoints.GetSize () ; i++)
    markers[selectedPoints[i]]->SetSelectionLevel (SELECTION_SELECTED);
}

void CurveMode::Start ()
{
  ViewMode::Start ();
  if (!aresed3d->GetSelection ()->HasSelection ()) return;
  iDynamicObject* dynobj = aresed3d->GetSelection ()->GetFirst ();
  csString name = dynobj->GetFactory ()->GetName ();
  editingCurveFactory = aresed3d->GetCurvedMeshCreator ()->GetCurvedFactory (name);
  ggen = scfQueryInterface<iGeometryGenerator> (editingCurveFactory);
  selectedPoints.Empty ();
  dragPoints.Empty ();

  UpdateMarkers ();
}

void CurveMode::Stop ()
{
  ViewMode::Stop ();
  for (size_t i = 0 ; i < markers.GetSize () ; i++)
    aresed3d->GetMarkerManager ()->DestroyMarker (markers[i]);
  markers.Empty ();
}

void CurveMode::MarkerStartDragging (iMarker* marker, iMarkerHitArea* area,
    const csVector3& pos, uint button, uint32 modifiers)
{
  size_t idx = size_t (area->GetData ());

  if (modifiers & CSMASK_SHIFT)
    AddCurrentPoint (idx);
  else
    SetCurrentPoint (idx);

  csArray<size_t>::Iterator it = selectedPoints.GetIterator ();
  while (it.HasNext ())
  {
    size_t id = it.Next ();
    csVector3 wpos = GetWorldPosPoint (id);
    DragPoint dob;

    dob.kineOffset = pos - wpos;
    dob.idx = id;
    dragPoints.Push (dob);
  }
}

void CurveMode::MarkerWantsMove (iMarker* marker, iMarkerHitArea* area,
      const csVector3& pos)
{
  iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
  const csReversibleTransform& meshtrans = mesh->GetMovable ()->GetTransform ();
  for (size_t i = 0 ; i < dragPoints.GetSize () ; i++)
  {
    csVector3 np = pos - dragPoints[i].kineOffset;
    size_t idx = dragPoints[i].idx;
    csVector3 rp = meshtrans.Other2This (np);
    editingCurveFactory->ChangePoint (idx,
	  rp,
	  editingCurveFactory->GetFront (idx),
	  editingCurveFactory->GetUp (idx));
    UpdateMarkers ();
  }
  if (autoSmooth) DoAutoSmooth ();
  ggen->GenerateGeometry (mesh);
  aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
}

void CurveMode::MarkerStopDragging (iMarker* marker, iMarkerHitArea* area)
{
  StopDrag ();
}

void CurveMode::SetCurrentPoint (size_t idx)
{
  if (selectedPoints.Find (idx) != csArrayItemNotFound) return;
  selectedPoints.DeleteAll ();
  selectedPoints.Push (idx);
  UpdateMarkerSelection ();
}

void CurveMode::AddCurrentPoint (size_t idx)
{
  if (selectedPoints.Find (idx) != csArrayItemNotFound)
  {
    selectedPoints.Delete (idx);
  }
  else
  {
    selectedPoints.Push (idx);
  }
  UpdateMarkerSelection ();
}

void CurveMode::StopDrag ()
{
  dragPoints.DeleteAll ();
}

void CurveMode::FramePre()
{
  ViewMode::FramePre ();
}

void CurveMode::Frame3D()
{
  ViewMode::Frame3D ();
}

void CurveMode::Frame2D()
{
  ViewMode::Frame2D ();
}

void CurveMode::DoAutoSmooth ()
{
  if (editingCurveFactory->GetPointCount () <= 2) return;
  for (size_t i = 1 ; i < editingCurveFactory->GetPointCount ()-1 ; i++)
    SmoothPoint (i, false);
  iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
  ggen->GenerateGeometry (mesh);
  aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
}

void CurveMode::SmoothPoint (size_t idx, bool regen)
{
  if (idx == 0 || idx >= editingCurveFactory->GetPointCount ()-1)
    return;
  const csVector3& p1 = editingCurveFactory->GetPosition (idx-1);
  const csVector3& pos = editingCurveFactory->GetPosition (idx);
  const csVector3& p2 = editingCurveFactory->GetPosition (idx+1);
  csVector3 fr = ((p2 - pos).Unit () + (pos - p1).Unit ()) / 2.0;
  csVector3 up = editingCurveFactory->GetUp (idx);
  //csVector3 right = fr % up;
  //up = - (fr % right).Unit ();
  editingCurveFactory->ChangePoint (idx, pos, fr, up);
  UpdateMarkers ();
  if (regen)
  {
    iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
    ggen->GenerateGeometry (mesh);
    aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
  }
}

csVector3 CurveMode::GetWorldPosPoint (size_t idx)
{
  iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
  const csReversibleTransform& meshtrans = mesh->GetMovable ()->GetTransform ();
  const csVector3& pos = editingCurveFactory->GetPosition (idx);
  return meshtrans.This2Other (pos);
}

size_t CurveMode::FindCurvePoint (int mouseX, int mouseY)
{
  int data;
  iMarker* marker = aresed3d->GetMarkerManager ()->FindHitMarker (mouseX, mouseY, data);
  if (!marker) return csArrayItemNotFound;
  size_t idx = 0;
  while (idx < markers.GetSize ())
    if (markers[idx] == marker) return idx;
    else idx++;
  return csArrayItemNotFound;
}

void CurveMode::RotateCurrent (float baseAngle)
{
  bool slow = aresed3d->GetKeyboardDriver ()->GetKeyState (CSKEY_CTRL);
  bool fast = aresed3d->GetKeyboardDriver ()->GetKeyState (CSKEY_SHIFT);
  float angle = baseAngle;
  if (slow) angle /= 180.0;
  else if (fast) angle /= 2.0;
  else angle /= 8.0;

  csArray<size_t>::Iterator it = selectedPoints.GetIterator ();
  while (it.HasNext ())
  {
    size_t id = it.Next ();
    // @TODO: optimize!!!
    const csVector3& pos = editingCurveFactory->GetPosition (id);
    const csVector3& f = editingCurveFactory->GetFront (id);
    const csVector3& u = editingCurveFactory->GetUp (id);
    csVector3 r = f % u;
    csMatrix3 m (r.x, r.y, r.z, u.x, u.y, u.z, f.x, f.y, f.z);
    csReversibleTransform tr (m, pos);
    tr.RotateOther (u, angle);
    editingCurveFactory->ChangePoint (id, pos, tr.GetFront (), u);
    UpdateMarkers ();
  }
  iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
  ggen->GenerateGeometry (mesh);
  aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
}

void CurveMode::FlatPoint (size_t idx)
{
  float sideHeight = editingCurveFactory->GetSideHeight ();
  iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
  const csReversibleTransform& meshtrans = mesh->GetMovable ()->GetTransform ();
  csVector3 pos = editingCurveFactory->GetPosition (idx);
  pos = meshtrans.This2Other (pos);
  const csVector3& f = editingCurveFactory->GetFront (idx);
  const csVector3& u = editingCurveFactory->GetUp (idx);
  pos.y += 100.0;
  iSector* sector = aresed3d->GetCsCamera ()->GetSector ();

  csFlags oldFlags = mesh->GetFlags ();
  mesh->GetFlags ().Set (CS_ENTITY_NOHITBEAM);
  csSectorHitBeamResult result = sector->HitBeamPortals (pos, pos - csVector3 (0, 1000, 0));
  mesh->GetFlags ().SetAll (oldFlags.Get ());

  if (result.mesh)
  {
    pos = result.isect;
    pos.y += sideHeight / 2.0;
    pos = meshtrans.Other2This (pos);
    editingCurveFactory->ChangePoint (idx, pos, f, u);
    UpdateMarkers ();
    if (autoSmooth)
      DoAutoSmooth ();
    else
      ggen->GenerateGeometry (mesh);
    aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
  }
}

void CurveMode::OnFlatten ()
{
  if (selectedPoints.GetSize () == 0)
  {
    for (size_t i = 0 ; i < editingCurveFactory->GetPointCount () ; i++)
      FlatPoint (i);
  }
  else
  {
    csArray<size_t>::Iterator it = selectedPoints.GetIterator ();
    while (it.HasNext ())
    {
      size_t id = it.Next ();
      FlatPoint (id);
    }
  }
}

void CurveMode::OnRotLeft ()
{
  RotateCurrent (-PI);
}

void CurveMode::OnRotRight ()
{
  RotateCurrent (PI);
}

void CurveMode::OnRotReset ()
{
  csArray<size_t>::Iterator it = selectedPoints.GetIterator ();
  while (it.HasNext ())
  {
    size_t id = it.Next ();
    SmoothPoint (id);
  }
}

void CurveMode::OnAutoSmoothSelected ()
{
  wxCheckBox* autoSmoothCheckBox = XRCCTRL (*panel, "autoSmoothCheckBox", wxCheckBox);
  autoSmooth = autoSmoothCheckBox->IsChecked ();
}

bool CurveMode::OnKeyboard (iEvent& ev, utf32_char code)
{
  if (ViewMode::OnKeyboard (ev, code))
    return true;

  if (code == 'e')
  {
    size_t id = editingCurveFactory->GetPointCount ()-1;
    const csVector3& pos = editingCurveFactory->GetPosition (id);
    const csVector3& front = editingCurveFactory->GetFront (id);
    const csVector3& up = editingCurveFactory->GetUp (id);
    editingCurveFactory->AddPoint (pos + front, front, up);
    if (autoSmooth) DoAutoSmooth ();

    iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
    ggen->GenerateGeometry (mesh);
    aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
    UpdateMarkers ();
  }
  return false;
}

bool CurveMode::OnMouseDown (iEvent& ev, uint but, int mouseX, int mouseY)
{
  return ViewMode::OnMouseDown (ev, but, mouseX, mouseY);
}

bool CurveMode::OnMouseUp(iEvent& ev, uint but, int mouseX, int mouseY)
{
  return ViewMode::OnMouseUp (ev, but, mouseX, mouseY);
}

bool CurveMode::OnMouseMove (iEvent& ev, int mouseX, int mouseY)
{
  return ViewMode::OnMouseMove (ev, mouseX, mouseY);
}

<commit_msg>Fixed crasher in curve mode in case the selected object has no curve.<commit_after>/*
The MIT License

Copyright (c) 2010 by Jorrit Tyberghein

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */

#include "../apparesed.h"
#include "curvemode.h"

#include <wx/xrc/xmlres.h>

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

BEGIN_EVENT_TABLE(CurveMode::Panel, wxPanel)
  EVT_BUTTON (XRCID("rotLeftButton"), CurveMode::Panel::OnRotLeft)
  EVT_BUTTON (XRCID("rotRightButton"), CurveMode::Panel::OnRotRight)
  EVT_BUTTON (XRCID("rotResetButton"), CurveMode::Panel::OnRotReset)
  EVT_BUTTON (XRCID("flattenButton"), CurveMode::Panel::OnFlatten)
  EVT_CHECKBOX (XRCID("autoSmoothCheckBox"), CurveMode::Panel::OnAutoSmoothSelected)
END_EVENT_TABLE()

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

CurveMode::CurveMode (wxWindow* parent, AresEdit3DView* aresed3d)
  : ViewMode (aresed3d, "Curve")
{
  panel = new Panel (parent, this);
  parent->GetSizer ()->Add (panel, 1, wxALL | wxEXPAND);
  wxXmlResource::Get()->LoadPanel (panel, parent, wxT ("CurveModePanel"));

  editingCurveFactory = 0;
  autoSmooth = true;
  wxCheckBox* autoSmoothCheckBox = XRCCTRL (*panel, "autoSmoothCheckBox", wxCheckBox);
  autoSmoothCheckBox->SetValue (autoSmooth);
}

void CurveMode::UpdateMarkers ()
{
  if (!editingCurveFactory) return;
  iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
  if (editingCurveFactory->GetPointCount () != markers.GetSize ())
  {
    Stop ();
    for (size_t i = 0 ; i < editingCurveFactory->GetPointCount () ; i++)
    {
      iMarker* marker = aresed3d->GetMarkerManager ()->CreateMarker ();
      markers.Push (marker);
      marker->AttachMesh (mesh);
    }
  }

  iMarkerColor* red = aresed3d->GetMarkerManager ()->FindMarkerColor ("red");
  iMarkerColor* green = aresed3d->GetMarkerManager ()->FindMarkerColor ("green");
  iMarkerColor* yellow = aresed3d->GetMarkerManager ()->FindMarkerColor ("yellow");

  for (size_t i = 0 ; i < editingCurveFactory->GetPointCount () ; i++)
  {
    csVector3 pos = editingCurveFactory->GetPosition (i);
    csVector3 front = editingCurveFactory->GetFront (i);
    csVector3 up = editingCurveFactory->GetUp (i);
    iMarker* marker = markers[i];
    marker->Clear ();
    marker->Line (MARKER_OBJECT, pos, pos+front, green, true);
    marker->Line (MARKER_OBJECT, pos, pos+up, red, true);
    marker->ClearHitAreas ();
    iMarkerHitArea* hitArea = marker->HitArea (MARKER_OBJECT, pos, .1f, i, yellow);
    csRef<MarkerCallback> cb;
    cb.AttachNew (new MarkerCallback (this));
    hitArea->DefineDrag (0, 0, MARKER_WORLD, CONSTRAIN_MESH, cb);
    hitArea->DefineDrag (0, CSMASK_SHIFT, MARKER_WORLD, CONSTRAIN_MESH, cb);
    hitArea->DefineDrag (0, CSMASK_ALT, MARKER_WORLD, CONSTRAIN_YPLANE, cb);
    hitArea->DefineDrag (0, CSMASK_SHIFT + CSMASK_ALT, MARKER_WORLD, CONSTRAIN_YPLANE, cb);
    hitArea->DefineDrag (0, CSMASK_CTRL, MARKER_WORLD, CONSTRAIN_NONE, cb);
    hitArea->DefineDrag (0, CSMASK_SHIFT + CSMASK_CTRL, MARKER_WORLD, CONSTRAIN_NONE, cb);
  }

  UpdateMarkerSelection ();
}

void CurveMode::UpdateMarkerSelection ()
{
  for (size_t i = 0 ; i < markers.GetSize () ; i++)
    markers[i]->SetSelectionLevel (SELECTION_NONE);
  for (size_t i = 0 ; i < selectedPoints.GetSize () ; i++)
    markers[selectedPoints[i]]->SetSelectionLevel (SELECTION_SELECTED);
}

void CurveMode::Start ()
{
  ViewMode::Start ();
  if (!aresed3d->GetSelection ()->HasSelection ()) return;
  iDynamicObject* dynobj = aresed3d->GetSelection ()->GetFirst ();
  csString name = dynobj->GetFactory ()->GetName ();
  editingCurveFactory = aresed3d->GetCurvedMeshCreator ()->GetCurvedFactory (name);
  if (editingCurveFactory)
    ggen = scfQueryInterface<iGeometryGenerator> (editingCurveFactory);
  else
    ggen = 0;
  selectedPoints.Empty ();
  dragPoints.Empty ();

  UpdateMarkers ();
}

void CurveMode::Stop ()
{
  ViewMode::Stop ();
  for (size_t i = 0 ; i < markers.GetSize () ; i++)
    aresed3d->GetMarkerManager ()->DestroyMarker (markers[i]);
  markers.Empty ();
}

void CurveMode::MarkerStartDragging (iMarker* marker, iMarkerHitArea* area,
    const csVector3& pos, uint button, uint32 modifiers)
{
  size_t idx = size_t (area->GetData ());

  if (modifiers & CSMASK_SHIFT)
    AddCurrentPoint (idx);
  else
    SetCurrentPoint (idx);

  csArray<size_t>::Iterator it = selectedPoints.GetIterator ();
  while (it.HasNext ())
  {
    size_t id = it.Next ();
    csVector3 wpos = GetWorldPosPoint (id);
    DragPoint dob;

    dob.kineOffset = pos - wpos;
    dob.idx = id;
    dragPoints.Push (dob);
  }
}

void CurveMode::MarkerWantsMove (iMarker* marker, iMarkerHitArea* area,
      const csVector3& pos)
{
  iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
  const csReversibleTransform& meshtrans = mesh->GetMovable ()->GetTransform ();
  for (size_t i = 0 ; i < dragPoints.GetSize () ; i++)
  {
    csVector3 np = pos - dragPoints[i].kineOffset;
    size_t idx = dragPoints[i].idx;
    csVector3 rp = meshtrans.Other2This (np);
    editingCurveFactory->ChangePoint (idx,
	  rp,
	  editingCurveFactory->GetFront (idx),
	  editingCurveFactory->GetUp (idx));
    UpdateMarkers ();
  }
  if (autoSmooth) DoAutoSmooth ();
  ggen->GenerateGeometry (mesh);
  aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
}

void CurveMode::MarkerStopDragging (iMarker* marker, iMarkerHitArea* area)
{
  StopDrag ();
}

void CurveMode::SetCurrentPoint (size_t idx)
{
  if (selectedPoints.Find (idx) != csArrayItemNotFound) return;
  selectedPoints.DeleteAll ();
  selectedPoints.Push (idx);
  UpdateMarkerSelection ();
}

void CurveMode::AddCurrentPoint (size_t idx)
{
  if (selectedPoints.Find (idx) != csArrayItemNotFound)
  {
    selectedPoints.Delete (idx);
  }
  else
  {
    selectedPoints.Push (idx);
  }
  UpdateMarkerSelection ();
}

void CurveMode::StopDrag ()
{
  dragPoints.DeleteAll ();
}

void CurveMode::FramePre()
{
  ViewMode::FramePre ();
}

void CurveMode::Frame3D()
{
  ViewMode::Frame3D ();
}

void CurveMode::Frame2D()
{
  ViewMode::Frame2D ();
}

void CurveMode::DoAutoSmooth ()
{
  if (editingCurveFactory->GetPointCount () <= 2) return;
  for (size_t i = 1 ; i < editingCurveFactory->GetPointCount ()-1 ; i++)
    SmoothPoint (i, false);
  iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
  ggen->GenerateGeometry (mesh);
  aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
}

void CurveMode::SmoothPoint (size_t idx, bool regen)
{
  if (idx == 0 || idx >= editingCurveFactory->GetPointCount ()-1)
    return;
  const csVector3& p1 = editingCurveFactory->GetPosition (idx-1);
  const csVector3& pos = editingCurveFactory->GetPosition (idx);
  const csVector3& p2 = editingCurveFactory->GetPosition (idx+1);
  csVector3 fr = ((p2 - pos).Unit () + (pos - p1).Unit ()) / 2.0;
  csVector3 up = editingCurveFactory->GetUp (idx);
  //csVector3 right = fr % up;
  //up = - (fr % right).Unit ();
  editingCurveFactory->ChangePoint (idx, pos, fr, up);
  UpdateMarkers ();
  if (regen)
  {
    iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
    ggen->GenerateGeometry (mesh);
    aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
  }
}

csVector3 CurveMode::GetWorldPosPoint (size_t idx)
{
  iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
  const csReversibleTransform& meshtrans = mesh->GetMovable ()->GetTransform ();
  const csVector3& pos = editingCurveFactory->GetPosition (idx);
  return meshtrans.This2Other (pos);
}

size_t CurveMode::FindCurvePoint (int mouseX, int mouseY)
{
  int data;
  iMarker* marker = aresed3d->GetMarkerManager ()->FindHitMarker (mouseX, mouseY, data);
  if (!marker) return csArrayItemNotFound;
  size_t idx = 0;
  while (idx < markers.GetSize ())
    if (markers[idx] == marker) return idx;
    else idx++;
  return csArrayItemNotFound;
}

void CurveMode::RotateCurrent (float baseAngle)
{
  bool slow = aresed3d->GetKeyboardDriver ()->GetKeyState (CSKEY_CTRL);
  bool fast = aresed3d->GetKeyboardDriver ()->GetKeyState (CSKEY_SHIFT);
  float angle = baseAngle;
  if (slow) angle /= 180.0;
  else if (fast) angle /= 2.0;
  else angle /= 8.0;

  csArray<size_t>::Iterator it = selectedPoints.GetIterator ();
  while (it.HasNext ())
  {
    size_t id = it.Next ();
    // @TODO: optimize!!!
    const csVector3& pos = editingCurveFactory->GetPosition (id);
    const csVector3& f = editingCurveFactory->GetFront (id);
    const csVector3& u = editingCurveFactory->GetUp (id);
    csVector3 r = f % u;
    csMatrix3 m (r.x, r.y, r.z, u.x, u.y, u.z, f.x, f.y, f.z);
    csReversibleTransform tr (m, pos);
    tr.RotateOther (u, angle);
    editingCurveFactory->ChangePoint (id, pos, tr.GetFront (), u);
    UpdateMarkers ();
  }
  iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
  ggen->GenerateGeometry (mesh);
  aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
}

void CurveMode::FlatPoint (size_t idx)
{
  float sideHeight = editingCurveFactory->GetSideHeight ();
  iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
  const csReversibleTransform& meshtrans = mesh->GetMovable ()->GetTransform ();
  csVector3 pos = editingCurveFactory->GetPosition (idx);
  pos = meshtrans.This2Other (pos);
  const csVector3& f = editingCurveFactory->GetFront (idx);
  const csVector3& u = editingCurveFactory->GetUp (idx);
  pos.y += 100.0;
  iSector* sector = aresed3d->GetCsCamera ()->GetSector ();

  csFlags oldFlags = mesh->GetFlags ();
  mesh->GetFlags ().Set (CS_ENTITY_NOHITBEAM);
  csSectorHitBeamResult result = sector->HitBeamPortals (pos, pos - csVector3 (0, 1000, 0));
  mesh->GetFlags ().SetAll (oldFlags.Get ());

  if (result.mesh)
  {
    pos = result.isect;
    pos.y += sideHeight / 2.0;
    pos = meshtrans.Other2This (pos);
    editingCurveFactory->ChangePoint (idx, pos, f, u);
    UpdateMarkers ();
    if (autoSmooth)
      DoAutoSmooth ();
    else
      ggen->GenerateGeometry (mesh);
    aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
  }
}

void CurveMode::OnFlatten ()
{
  if (selectedPoints.GetSize () == 0)
  {
    for (size_t i = 0 ; i < editingCurveFactory->GetPointCount () ; i++)
      FlatPoint (i);
  }
  else
  {
    csArray<size_t>::Iterator it = selectedPoints.GetIterator ();
    while (it.HasNext ())
    {
      size_t id = it.Next ();
      FlatPoint (id);
    }
  }
}

void CurveMode::OnRotLeft ()
{
  RotateCurrent (-PI);
}

void CurveMode::OnRotRight ()
{
  RotateCurrent (PI);
}

void CurveMode::OnRotReset ()
{
  csArray<size_t>::Iterator it = selectedPoints.GetIterator ();
  while (it.HasNext ())
  {
    size_t id = it.Next ();
    SmoothPoint (id);
  }
}

void CurveMode::OnAutoSmoothSelected ()
{
  wxCheckBox* autoSmoothCheckBox = XRCCTRL (*panel, "autoSmoothCheckBox", wxCheckBox);
  autoSmooth = autoSmoothCheckBox->IsChecked ();
}

bool CurveMode::OnKeyboard (iEvent& ev, utf32_char code)
{
  if (ViewMode::OnKeyboard (ev, code))
    return true;

  if (editingCurveFactory && code == 'e')
  {
    size_t id = editingCurveFactory->GetPointCount ()-1;
    const csVector3& pos = editingCurveFactory->GetPosition (id);
    const csVector3& front = editingCurveFactory->GetFront (id);
    const csVector3& up = editingCurveFactory->GetUp (id);
    editingCurveFactory->AddPoint (pos + front, front, up);
    if (autoSmooth) DoAutoSmooth ();

    iMeshWrapper* mesh = aresed3d->GetSelection ()->GetFirst ()->GetMesh ();
    ggen->GenerateGeometry (mesh);
    aresed3d->GetSelection ()->GetFirst ()->RefreshColliders ();
    UpdateMarkers ();
  }
  return false;
}

bool CurveMode::OnMouseDown (iEvent& ev, uint but, int mouseX, int mouseY)
{
  return ViewMode::OnMouseDown (ev, but, mouseX, mouseY);
}

bool CurveMode::OnMouseUp(iEvent& ev, uint but, int mouseX, int mouseY)
{
  return ViewMode::OnMouseUp (ev, but, mouseX, mouseY);
}

bool CurveMode::OnMouseMove (iEvent& ev, int mouseX, int mouseY)
{
  return ViewMode::OnMouseMove (ev, mouseX, mouseY);
}

<|endoftext|>