<commit_before>/*
 * CompilationDatabase.cpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "CompilationDatabase.hpp"

#include <algorithm>

#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/trim_all.hpp>

#include <core/Error.hpp>
#include <core/PerformanceTimer.hpp>
#include <core/FileSerializer.hpp>

#include <core/r_util/RToolsInfo.hpp>

#include <core/system/Process.hpp>
#include <core/system/Environment.hpp>

#include "LibClang.hpp"
#include "SourceIndex.hpp"

#include <session/projects/SessionProjects.hpp>
#include <session/SessionModuleContext.hpp>

using namespace core ;

namespace session {
namespace modules {
namespace clang {
namespace libclang {

namespace {

std::string readDependencyAttributes(const core::FilePath& cppPath)
{
   // read file
   std::string contents;
   Error error = core::readStringFromFile(cppPath, &contents);
   if (error)
   {
      LOG_ERROR(error);
      return std::string();
   }

   // find dependency attributes
   std::string attributes;
   boost::regex re(
     "^\\s*//\\s*\\[\\[Rcpp::(\\w+)(\\(.*?\\))?\\]\\]\\s*$");
   boost::sregex_token_iterator it(contents.begin(), contents.end(), re, 0);
   boost::sregex_token_iterator end;
   for ( ; it != end; ++it)
   {
      std::string attrib = *it;
      boost::algorithm::trim_all(attrib);
      attributes.append(attrib);
   }

   // return them
   return attributes;
}

std::vector<std::string> argsForSourceCpp(const core::FilePath& cppPath)
{
   // get path to R script
   FilePath rScriptPath;
   Error error = module_context::rScriptPath(&rScriptPath);
   if (error)
   {
      LOG_ERROR(error);
      return std::vector<std::string>();
   }

   // setup args and options
   std::vector<std::string> args;
   core::system::ProcessOptions options;

   // always run as a slave
   args.push_back("--slave");

   // setup environment to force make into --dry-run mode
   core::system::Options env;
   core::system::environment(&env);
   core::system::setenv(&env, "MAKE", "make --dry-run");
   core::system::setenv(&env, "R_MAKEVARS_USER", "");
   core::system::setenv(&env, "R_MAKEVARS_SITE", "");

   // for packrat projects we execute the profile and set the working
   // directory to the project directory; for other contexts we just
   // propagate the R_LIBS
   if (module_context::packratContext().modeOn)
   {
      options.workingDir = projects::projectContext().directory();
      args.push_back("--no-save");
      args.push_back("--no-restore");
   }
   else
   {
      args.push_back("--vanilla");
      std::string libPaths = module_context::libPathsString();
      if (!libPaths.empty())
         core::system::setenv(&env, "R_LIBS", libPaths);
   }

   // add rtools to path if we need to
   std::string warning;
   module_context::addRtoolsToPathIfNecessary(&env, &warning);

   // set environment into options
   options.environment = env;

   // add command to arguments
   args.push_back("-e");
   boost::format fmt("Rcpp::sourceCpp('%1%', showOutput = TRUE)");
   args.push_back(boost::str(fmt % cppPath.absolutePath()));

   // execute and capture output
   core::system::ProcessResult result;
   error = core::system::runProgram(
            core::string_utils::utf8ToSystem(rScriptPath.absolutePath()),
            args,
            "",
            options,
            &result);
   if (error)
   {
      LOG_ERROR(error);
      return std::vector<std::string>();
   }

   // break into lines
   std::vector<std::string> lines;
   boost::algorithm::split(lines, result.stdOut,
                           boost::algorithm::is_any_of("\r\n"));

   // find the line with the compilation and add it's args
   std::vector<std::string> compileArgs;
   std::string compile = "-c " + cppPath.filename() + " -o " + cppPath.stem();
   BOOST_FOREACH(const std::string& line, lines)
   {
      if (line.find(compile) != std::string::npos)
      {
         // find arguments libclang might care about
         boost::regex re("-[I|D|i|f|s](?:\\\"[^\\\"]+\\\"|[^ ]+)");
         boost::sregex_token_iterator it(line.begin(), line.end(), re, 0);
         boost::sregex_token_iterator end;
         for ( ; it != end; ++it)
         {
            // remove quotes and add it to the compile args
            std::string arg = *it;
            boost::algorithm::replace_all(arg, "\"", "");
            compileArgs.push_back(arg);
         }
         break;
      }
   }

   // return the args
   return compileArgs;
}

} // anonymous namespace

CompilationDatabase::~CompilationDatabase()
{
   try
   {

   }
   catch(...)
   {
   }
}

void CompilationDatabase::updateForPackageCppAddition(
                                          const core::FilePath& cppPath)
{
   // if we don't have this source file already then fully update
   if (argsMap_.find(cppPath.absolutePath()) == argsMap_.end())
      updateForCurrentPackage();
}

void CompilationDatabase::updateForCurrentPackage()
{

}

void CompilationDatabase::updateForStandaloneCpp(const core::FilePath& cppPath)
{
   TIME_FUNCTION

   // if we don't have Rcpp attributes then forget it
   if (!module_context::haveRcppAttributes())
      return;

   // read the dependency attributes within the cpp file to compare to
   // previous sets of attributes we've used to generate compilation args.
   // bail if we've already generated based on these attributes
   std::string attributes = readDependencyAttributes(cppPath);
   AttribsMap::const_iterator it = attribsMap_.find(cppPath.absolutePath());
   if (it != attribsMap_.end() && it->second == attributes)
      return;

   // baseline arguments
   std::vector<std::string> args;
   std::string builtinHeaders = "-I" + clang().builtinHeaders();
   args.push_back(builtinHeaders);
#if defined(_WIN32)
   std::vector<std::string> rtoolsArgs = rToolsArgs();
   std::copy(rtoolsArgs.begin(), rtoolsArgs.end(), std::back_inserter(args));
#elif defined(__APPLE__)
   args.push_back("-stdlib=libstdc++");
#endif

   // arguments for this translation unit
   std::vector<std::string> fileArgs = argsForSourceCpp(cppPath);

   // if we got args then update
   if (!fileArgs.empty())
   {
      // combine them
      std::copy(fileArgs.begin(), fileArgs.end(), std::back_inserter(args));

      // update if necessary
      updateIfNecessary(cppPath.absolutePath(), args);

      // save attributes to prevent recomputation
      attribsMap_[cppPath.absolutePath()] = attributes;
   }
}

std::vector<std::string> CompilationDatabase::argsForFile(
                                       const std::string& cppPath) const
{
   ArgsMap::const_iterator it = argsMap_.find(cppPath);
   if (it != argsMap_.end())
      return it->second;
   else
      return std::vector<std::string>();
}

std::vector<std::string> CompilationDatabase::rToolsArgs() const
{

#ifdef _WIN32
   if (rToolsArgs_.empty())
   {
      // scan for Rtools
      std::vector<core::r_util::RToolsInfo> rTools;
      Error error = core::r_util::scanRegistryForRTools(&rTools);
      if (error)
         LOG_ERROR(error);

      // enumerate them to see if we have a compatible version
      // (go in reverse order for most recent first)
      std::vector<r_util::RToolsInfo>::const_reverse_iterator it = rTools.rbegin();
      for ( ; it != rTools.rend(); ++it)
      {
         if (module_context::isRtoolsCompatible(*it))
         {
            FilePath rtoolsPath = it->installPath();

            rToolsArgs_.push_back("-I" + rtoolsPath.childPath(
               "gcc-4.6.3/i686-w64-mingw32/include").absolutePath());

            rToolsArgs_.push_back("-I" + rtoolsPath.childPath(
               "gcc-4.6.3/include/c++/4.6.3").absolutePath());

            std::string bits = "-I" + rtoolsPath.childPath(
               "gcc-4.6.3/include/c++/4.6.3/i686-w64-mingw32").absolutePath();
#ifdef _WIN64
            bits += "/64";
#endif
            rToolsArgs_.push_back(bits);

            break;
         }
      }
   }
#endif

   return rToolsArgs_;
}

void CompilationDatabase::updateIfNecessary(
                                    const std::string& cppPath,
                                    const std::vector<std::string>& args)
{
   // get existing args
   std::vector<std::string> existingArgs = argsForFile(cppPath);
   if (args != existingArgs)
   {
      // invalidate the source index
      sourceIndex().removeTranslationUnit(cppPath);

      // update
      argsMap_[cppPath] = args;
   }
}

CompilationDatabase& compilationDatabase()
{
   static CompilationDatabase instance;
   return instance;
}

} // namespace libclang
} // namespace clang
} // namespace modules
} // namesapce session

<commit_msg>use dryRun for sourcecpp<commit_after>/*
 * CompilationDatabase.cpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "CompilationDatabase.hpp"

#include <algorithm>

#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/trim_all.hpp>

#include <core/Error.hpp>
#include <core/PerformanceTimer.hpp>
#include <core/FileSerializer.hpp>

#include <core/r_util/RToolsInfo.hpp>

#include <core/system/Process.hpp>
#include <core/system/Environment.hpp>

#include "LibClang.hpp"
#include "SourceIndex.hpp"

#include <session/projects/SessionProjects.hpp>
#include <session/SessionModuleContext.hpp>

using namespace core ;

namespace session {
namespace modules {
namespace clang {
namespace libclang {

namespace {

std::string readDependencyAttributes(const core::FilePath& cppPath)
{
   // read file
   std::string contents;
   Error error = core::readStringFromFile(cppPath, &contents);
   if (error)
   {
      LOG_ERROR(error);
      return std::string();
   }

   // find dependency attributes
   std::string attributes;
   boost::regex re(
     "^\\s*//\\s*\\[\\[Rcpp::(\\w+)(\\(.*?\\))?\\]\\]\\s*$");
   boost::sregex_token_iterator it(contents.begin(), contents.end(), re, 0);
   boost::sregex_token_iterator end;
   for ( ; it != end; ++it)
   {
      std::string attrib = *it;
      boost::algorithm::trim_all(attrib);
      attributes.append(attrib);
   }

   // return them
   return attributes;
}

std::vector<std::string> argsForSourceCpp(const core::FilePath& cppPath)
{
   // get path to R script
   FilePath rScriptPath;
   Error error = module_context::rScriptPath(&rScriptPath);
   if (error)
   {
      LOG_ERROR(error);
      return std::vector<std::string>();
   }

   // setup args and options
   std::vector<std::string> args;
   core::system::ProcessOptions options;

   // always run as a slave
   args.push_back("--slave");

   // setup environment to force make into --dry-run mode
   core::system::Options env;
   core::system::environment(&env);
   core::system::setenv(&env, "MAKE", "make --dry-run");
   core::system::setenv(&env, "R_MAKEVARS_USER", "");
   core::system::setenv(&env, "R_MAKEVARS_SITE", "");

   // for packrat projects we execute the profile and set the working
   // directory to the project directory; for other contexts we just
   // propagate the R_LIBS
   if (module_context::packratContext().modeOn)
   {
      options.workingDir = projects::projectContext().directory();
      args.push_back("--no-save");
      args.push_back("--no-restore");
   }
   else
   {
      args.push_back("--vanilla");
      std::string libPaths = module_context::libPathsString();
      if (!libPaths.empty())
         core::system::setenv(&env, "R_LIBS", libPaths);
   }

   // add rtools to path if we need to
   std::string warning;
   module_context::addRtoolsToPathIfNecessary(&env, &warning);

   // set environment into options
   options.environment = env;

   // add command to arguments
   args.push_back("-e");
   boost::format fmt("Rcpp::sourceCpp('%1%', showOutput = TRUE, dryRun = TRUE)");
   args.push_back(boost::str(fmt % cppPath.absolutePath()));

   // execute and capture output
   core::system::ProcessResult result;
   error = core::system::runProgram(
            core::string_utils::utf8ToSystem(rScriptPath.absolutePath()),
            args,
            "",
            options,
            &result);
   if (error)
   {
      LOG_ERROR(error);
      return std::vector<std::string>();
   }

   // break into lines
   std::vector<std::string> lines;
   boost::algorithm::split(lines, result.stdOut,
                           boost::algorithm::is_any_of("\r\n"));

   // find the line with the compilation and add it's args
   std::vector<std::string> compileArgs;
   std::string compile = "-c " + cppPath.filename() + " -o " + cppPath.stem();
   BOOST_FOREACH(const std::string& line, lines)
   {
      if (line.find(compile) != std::string::npos)
      {
         // find arguments libclang might care about
         boost::regex re("-[I|D|i|f|s](?:\\\"[^\\\"]+\\\"|[^ ]+)");
         boost::sregex_token_iterator it(line.begin(), line.end(), re, 0);
         boost::sregex_token_iterator end;
         for ( ; it != end; ++it)
         {
            // remove quotes and add it to the compile args
            std::string arg = *it;
            boost::algorithm::replace_all(arg, "\"", "");
            compileArgs.push_back(arg);
         }
         break;
      }
   }

   // return the args
   return compileArgs;
}

} // anonymous namespace

CompilationDatabase::~CompilationDatabase()
{
   try
   {

   }
   catch(...)
   {
   }
}

void CompilationDatabase::updateForPackageCppAddition(
                                          const core::FilePath& cppPath)
{
   // if we don't have this source file already then fully update
   if (argsMap_.find(cppPath.absolutePath()) == argsMap_.end())
      updateForCurrentPackage();
}

void CompilationDatabase::updateForCurrentPackage()
{

}

void CompilationDatabase::updateForStandaloneCpp(const core::FilePath& cppPath)
{
   TIME_FUNCTION

   // if we don't have a recent version of Rcpp (that can do dryRun with
   // sourceCpp) then forget it
   if (!module_context::isPackageVersionInstalled("Rcpp", "0.11.2.7"))
      return;

   // read the dependency attributes within the cpp file to compare to
   // previous sets of attributes we've used to generate compilation args.
   // bail if we've already generated based on these attributes
   std::string attributes = readDependencyAttributes(cppPath);
   AttribsMap::const_iterator it = attribsMap_.find(cppPath.absolutePath());
   if (it != attribsMap_.end() && it->second == attributes)
      return;

   // baseline arguments
   std::vector<std::string> args;
   std::string builtinHeaders = "-I" + clang().builtinHeaders();
   args.push_back(builtinHeaders);
#if defined(_WIN32)
   std::vector<std::string> rtoolsArgs = rToolsArgs();
   std::copy(rtoolsArgs.begin(), rtoolsArgs.end(), std::back_inserter(args));
#elif defined(__APPLE__)
   args.push_back("-stdlib=libstdc++");
#endif

   // arguments for this translation unit
   std::vector<std::string> fileArgs = argsForSourceCpp(cppPath);

   // if we got args then update
   if (!fileArgs.empty())
   {
      // combine them
      std::copy(fileArgs.begin(), fileArgs.end(), std::back_inserter(args));

      // update if necessary
      updateIfNecessary(cppPath.absolutePath(), args);

      // save attributes to prevent recomputation
      attribsMap_[cppPath.absolutePath()] = attributes;
   }
}

std::vector<std::string> CompilationDatabase::argsForFile(
                                       const std::string& cppPath) const
{
   ArgsMap::const_iterator it = argsMap_.find(cppPath);
   if (it != argsMap_.end())
      return it->second;
   else
      return std::vector<std::string>();
}

std::vector<std::string> CompilationDatabase::rToolsArgs() const
{

#ifdef _WIN32
   if (rToolsArgs_.empty())
   {
      // scan for Rtools
      std::vector<core::r_util::RToolsInfo> rTools;
      Error error = core::r_util::scanRegistryForRTools(&rTools);
      if (error)
         LOG_ERROR(error);

      // enumerate them to see if we have a compatible version
      // (go in reverse order for most recent first)
      std::vector<r_util::RToolsInfo>::const_reverse_iterator it = rTools.rbegin();
      for ( ; it != rTools.rend(); ++it)
      {
         if (module_context::isRtoolsCompatible(*it))
         {
            FilePath rtoolsPath = it->installPath();

            rToolsArgs_.push_back("-I" + rtoolsPath.childPath(
               "gcc-4.6.3/i686-w64-mingw32/include").absolutePath());

            rToolsArgs_.push_back("-I" + rtoolsPath.childPath(
               "gcc-4.6.3/include/c++/4.6.3").absolutePath());

            std::string bits = "-I" + rtoolsPath.childPath(
               "gcc-4.6.3/include/c++/4.6.3/i686-w64-mingw32").absolutePath();
#ifdef _WIN64
            bits += "/64";
#endif
            rToolsArgs_.push_back(bits);

            break;
         }
      }
   }
#endif

   return rToolsArgs_;
}

void CompilationDatabase::updateIfNecessary(
                                    const std::string& cppPath,
                                    const std::vector<std::string>& args)
{
   // get existing args
   std::vector<std::string> existingArgs = argsForFile(cppPath);
   if (args != existingArgs)
   {
      // invalidate the source index
      sourceIndex().removeTranslationUnit(cppPath);

      // update
      argsMap_[cppPath] = args;
   }
}

CompilationDatabase& compilationDatabase()
{
   static CompilationDatabase instance;
   return instance;
}

} // namespace libclang
} // namespace clang
} // namespace modules
} // namesapce session

<|endoftext|>


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

#ifndef DBAUI_ADABASSTATDLG_HXX
#include "AdabasStatDlg.hxx"
#endif
#ifndef DBAUI_ADABASSTATDLG_HRC
#include "AdabasStatDlg.hrc"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef DBAUI_DRIVERSETTINGS_HXX
#include "DriverSettings.hxx"
#endif
#ifndef _DBAUI_DBADMINIMPL_HXX_
#include "DbAdminImpl.hxx"
#endif
#ifndef _DBAUI_PROPERTYSETITEM_HXX_
#include "propertysetitem.hxx"
#endif
#ifndef _DBAUI_ADMINPAGES_HXX_
#include "adminpages.hxx"
#endif
#ifndef DBAUI_ADABASPAGE_HXX
#include "AdabasPage.hxx"
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::sdbc;

    //========================================================================
    //= OAdabasStatPageDlg
    //========================================================================
    OAdabasStatPageDlg::OAdabasStatPageDlg(Window* _pParent
                                            , SfxItemSet* _pItems
                                            ,const Reference< XMultiServiceFactory >& _rxORB
                                            ,const ::com::sun::star::uno::Any& _aDataSourceName)
        :SfxTabDialog(_pParent, ModuleRes(DLG_DATABASE_ADABASADMIN), _pItems)
    {
        m_pImpl = ::std::auto_ptr<ODbDataSourceAdministrationHelper>(new ODbDataSourceAdministrationHelper(_rxORB,_pParent,this));
        m_pImpl->setCurrentDataSourceName(_aDataSourceName);
        Reference< XPropertySet > xDatasource = m_pImpl->getCurrentDataSource();
        m_pImpl->translateProperties(xDatasource, *GetInputSetImpl());
        SetInputSet(GetInputSetImpl());
        // propagate this set as our new input set and reset the example set
        delete pExampleSet;
        pExampleSet = new SfxItemSet(*GetInputSetImpl());

        DATASOURCE_TYPE eType = m_pImpl->getDatasourceType(*GetInputSetImpl());

        switch ( eType )
        {
            case DST_ADABAS:
                AddTabPage(TAB_PAG_ADABAS_SETTINGS, String(ResId(STR_PAGETITLE_ADABAS_STATISTIC)), ODriversSettings::CreateAdabas,0, sal_False, 1);
                break;
            case DST_DBASE:
            case DST_FLAT:
            case DST_MSACCESS:
            case DST_ADO:
            case DST_ODBC:
            case DST_MYSQL_ODBC:
            case DST_MYSQL_JDBC:
            case DST_LDAP:
            case DST_CALC:
            case DST_MOZILLA:
            case DST_THUNDERBIRD:
            case DST_EVOLUTION:
            case DST_OUTLOOK    :
            case DST_OUTLOOKEXP:
            case DST_JDBC:
            case DST_ORACLE_JDBC:
            case DST_USERDEFINE1:   /// first user defined driver
            case DST_USERDEFINE2:
            case DST_USERDEFINE3:
            case DST_USERDEFINE4:
            case DST_USERDEFINE5:
            case DST_USERDEFINE6:
            case DST_USERDEFINE7:
            case DST_USERDEFINE8:
            case DST_USERDEFINE9:
            case DST_USERDEFINE10:
            default:
                OSL_ENSURE(0,"Not supported for other types thasn adabas!");
                break;
        }

        // remove the reset button - it's meaning is much too ambiguous in this dialog
        RemoveResetButton();
        FreeResource();
    }

    // -----------------------------------------------------------------------
    OAdabasStatPageDlg::~OAdabasStatPageDlg()
    {
        SetInputSet(NULL);
        DELETEZ(pExampleSet);
    }
    // -----------------------------------------------------------------------
    short OAdabasStatPageDlg::Execute()
    {
        short nRet = SfxTabDialog::Execute();
        if ( nRet == RET_OK )
        {
            pExampleSet->Put(*GetOutputItemSet());
            m_pImpl->saveChanges(*pExampleSet);
        }
        return nRet;
    }
    //-------------------------------------------------------------------------
    void OAdabasStatPageDlg::PageCreated(USHORT _nId, SfxTabPage& _rPage)
    {
        // register ourself as modified listener
        static_cast<OGenericAdministrationPage&>(_rPage).SetServiceFactory(m_pImpl->getORB());
        static_cast<OGenericAdministrationPage&>(_rPage).SetAdminDialog(this,this);

        AdjustLayout();
        Window *pWin = GetViewWindow();
        if(pWin)
            pWin->Invalidate();

        SfxTabDialog::PageCreated(_nId, _rPage);
    }
    // -----------------------------------------------------------------------------
    const SfxItemSet* OAdabasStatPageDlg::getOutputSet() const
    {
        return GetExampleSet();
    }
    // -----------------------------------------------------------------------------
    SfxItemSet* OAdabasStatPageDlg::getWriteOutputSet()
    {
        return pExampleSet;
    }
    // -----------------------------------------------------------------------------
    ::std::pair< Reference<XConnection>,sal_Bool> OAdabasStatPageDlg::createConnection()
    {
        return m_pImpl->createConnection();
    }
    // -----------------------------------------------------------------------------
    Reference< XMultiServiceFactory > OAdabasStatPageDlg::getORB()
    {
        return m_pImpl->getORB();
    }
    // -----------------------------------------------------------------------------
    Reference< XDriver > OAdabasStatPageDlg::getDriver()
    {
        return m_pImpl->getDriver();
    }
    // -----------------------------------------------------------------------------
    DATASOURCE_TYPE OAdabasStatPageDlg::getDatasourceType(const SfxItemSet& _rSet) const
    {
        return m_pImpl->getDatasourceType(_rSet);
    }
    // -----------------------------------------------------------------------------
    void OAdabasStatPageDlg::clearPassword()
    {
        m_pImpl->clearPassword();
    }
    // -----------------------------------------------------------------------------
    void OAdabasStatPageDlg::setTitle(const ::rtl::OUString& _sTitle)
    {
        SetText(_sTitle);
    }
    //-------------------------------------------------------------------------
    sal_Bool OAdabasStatPageDlg::saveDatasource()
    {
        return PrepareLeaveCurrentPage();
    }
//.........................................................................
}   // namespace dbaui
//.........................................................................
<commit_msg>INTEGRATION: CWS wizopendb (1.4.60); FILE MERGED 2005/06/06 10:40:38 fs 1.4.60.1: #i42477# allow the 'New Database' wizard to load existing documents<commit_after>/*************************************************************************
 *
 *  $RCSfile: AdabasStatDlg.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2005-06-30 16:30:03 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Ocke Janssen
 *
 *
 ************************************************************************/

#ifndef DBAUI_ADABASSTATDLG_HXX
#include "AdabasStatDlg.hxx"
#endif
#ifndef DBAUI_ADABASSTATDLG_HRC
#include "AdabasStatDlg.hrc"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef DBAUI_DRIVERSETTINGS_HXX
#include "DriverSettings.hxx"
#endif
#ifndef _DBAUI_DBADMINIMPL_HXX_
#include "DbAdminImpl.hxx"
#endif
#ifndef _DBAUI_PROPERTYSETITEM_HXX_
#include "propertysetitem.hxx"
#endif
#ifndef _DBAUI_ADMINPAGES_HXX_
#include "adminpages.hxx"
#endif
#ifndef DBAUI_ADABASPAGE_HXX
#include "AdabasPage.hxx"
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::sdbc;

    //========================================================================
    //= OAdabasStatPageDlg
    //========================================================================
    OAdabasStatPageDlg::OAdabasStatPageDlg(Window* _pParent
                                            , SfxItemSet* _pItems
                                            ,const Reference< XMultiServiceFactory >& _rxORB
                                            ,const ::com::sun::star::uno::Any& _aDataSourceName)
        :SfxTabDialog(_pParent, ModuleRes(DLG_DATABASE_ADABASADMIN), _pItems)
    {
        m_pImpl = ::std::auto_ptr<ODbDataSourceAdministrationHelper>(new ODbDataSourceAdministrationHelper(_rxORB,_pParent,this));
        m_pImpl->setDataSourceOrName(_aDataSourceName);
        Reference< XPropertySet > xDatasource = m_pImpl->getCurrentDataSource();
        m_pImpl->translateProperties(xDatasource, *GetInputSetImpl());
        SetInputSet(GetInputSetImpl());
        // propagate this set as our new input set and reset the example set
        delete pExampleSet;
        pExampleSet = new SfxItemSet(*GetInputSetImpl());

        DATASOURCE_TYPE eType = m_pImpl->getDatasourceType(*GetInputSetImpl());

        switch ( eType )
        {
            case DST_ADABAS:
                AddTabPage(TAB_PAG_ADABAS_SETTINGS, String(ResId(STR_PAGETITLE_ADABAS_STATISTIC)), ODriversSettings::CreateAdabas,0, sal_False, 1);
                break;
            case DST_DBASE:
            case DST_FLAT:
            case DST_MSACCESS:
            case DST_ADO:
            case DST_ODBC:
            case DST_MYSQL_ODBC:
            case DST_MYSQL_JDBC:
            case DST_LDAP:
            case DST_CALC:
            case DST_MOZILLA:
            case DST_THUNDERBIRD:
            case DST_EVOLUTION:
            case DST_OUTLOOK    :
            case DST_OUTLOOKEXP:
            case DST_JDBC:
            case DST_ORACLE_JDBC:
            case DST_USERDEFINE1:   /// first user defined driver
            case DST_USERDEFINE2:
            case DST_USERDEFINE3:
            case DST_USERDEFINE4:
            case DST_USERDEFINE5:
            case DST_USERDEFINE6:
            case DST_USERDEFINE7:
            case DST_USERDEFINE8:
            case DST_USERDEFINE9:
            case DST_USERDEFINE10:
            default:
                OSL_ENSURE(0,"Not supported for other types thasn adabas!");
                break;
        }

        // remove the reset button - it's meaning is much too ambiguous in this dialog
        RemoveResetButton();
        FreeResource();
    }

    // -----------------------------------------------------------------------
    OAdabasStatPageDlg::~OAdabasStatPageDlg()
    {
        SetInputSet(NULL);
        DELETEZ(pExampleSet);
    }
    // -----------------------------------------------------------------------
    short OAdabasStatPageDlg::Execute()
    {
        short nRet = SfxTabDialog::Execute();
        if ( nRet == RET_OK )
        {
            pExampleSet->Put(*GetOutputItemSet());
            m_pImpl->saveChanges(*pExampleSet);
        }
        return nRet;
    }
    //-------------------------------------------------------------------------
    void OAdabasStatPageDlg::PageCreated(USHORT _nId, SfxTabPage& _rPage)
    {
        // register ourself as modified listener
        static_cast<OGenericAdministrationPage&>(_rPage).SetServiceFactory(m_pImpl->getORB());
        static_cast<OGenericAdministrationPage&>(_rPage).SetAdminDialog(this,this);

        AdjustLayout();
        Window *pWin = GetViewWindow();
        if(pWin)
            pWin->Invalidate();

        SfxTabDialog::PageCreated(_nId, _rPage);
    }
    // -----------------------------------------------------------------------------
    const SfxItemSet* OAdabasStatPageDlg::getOutputSet() const
    {
        return GetExampleSet();
    }
    // -----------------------------------------------------------------------------
    SfxItemSet* OAdabasStatPageDlg::getWriteOutputSet()
    {
        return pExampleSet;
    }
    // -----------------------------------------------------------------------------
    ::std::pair< Reference<XConnection>,sal_Bool> OAdabasStatPageDlg::createConnection()
    {
        return m_pImpl->createConnection();
    }
    // -----------------------------------------------------------------------------
    Reference< XMultiServiceFactory > OAdabasStatPageDlg::getORB()
    {
        return m_pImpl->getORB();
    }
    // -----------------------------------------------------------------------------
    Reference< XDriver > OAdabasStatPageDlg::getDriver()
    {
        return m_pImpl->getDriver();
    }
    // -----------------------------------------------------------------------------
    DATASOURCE_TYPE OAdabasStatPageDlg::getDatasourceType(const SfxItemSet& _rSet) const
    {
        return m_pImpl->getDatasourceType(_rSet);
    }
    // -----------------------------------------------------------------------------
    void OAdabasStatPageDlg::clearPassword()
    {
        m_pImpl->clearPassword();
    }
    // -----------------------------------------------------------------------------
    void OAdabasStatPageDlg::setTitle(const ::rtl::OUString& _sTitle)
    {
        SetText(_sTitle);
    }
    //-------------------------------------------------------------------------
    sal_Bool OAdabasStatPageDlg::saveDatasource()
    {
        return PrepareLeaveCurrentPage();
    }
//.........................................................................
}   // namespace dbaui
//.........................................................................
<|endoftext|>


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

#ifndef _SV_SPLIT_HXX
#include <vcl/split.hxx>
#endif

namespace dbaui
{
    //==================================================================
    class OSplitterView : public Window
    {
        Splitter*                           m_pSplitter;
        Window*                             m_pLeft;
        Window*                             m_pRight;
        sal_Bool                            m_bVertical;

        void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );
        DECL_LINK( SplitHdl, Splitter* );
    protected:
        virtual void DataChanged(const DataChangedEvent& rDCEvt);
    public:
        OSplitterView(Window* _pParent,sal_Bool _bVertical = sal_True);
        virtual ~OSplitterView();
        // window overloads
        virtual void GetFocus();

        void setSplitter(Splitter* _pSplitter);
        void set(Window* _pRight,Window* _pLeft = NULL);
        virtual void Resize();
    };
}
#endif // DBAUI_VERTSPLITVIEW_HXX

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.104); FILE MERGED 2005/09/05 17:34:32 rt 1.3.104.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: VertSplitView.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 15:41:29 $
 *
 *  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 DBAUI_VERTSPLITVIEW_HXX
#define DBAUI_VERTSPLITVIEW_HXX

#ifndef _SV_SPLIT_HXX
#include <vcl/split.hxx>
#endif

namespace dbaui
{
    //==================================================================
    class OSplitterView : public Window
    {
        Splitter*                           m_pSplitter;
        Window*                             m_pLeft;
        Window*                             m_pRight;
        sal_Bool                            m_bVertical;

        void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );
        DECL_LINK( SplitHdl, Splitter* );
    protected:
        virtual void DataChanged(const DataChangedEvent& rDCEvt);
    public:
        OSplitterView(Window* _pParent,sal_Bool _bVertical = sal_True);
        virtual ~OSplitterView();
        // window overloads
        virtual void GetFocus();

        void setSplitter(Splitter* _pSplitter);
        void set(Window* _pRight,Window* _pLeft = NULL);
        virtual void Resize();
    };
}
#endif // DBAUI_VERTSPLITVIEW_HXX

<|endoftext|>


<commit_before>/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2003 - 2007 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#include "push/FSocket.h"
#include "base/SymbianLog.h"
#include "base/util/stringUtils.h"
#include "base/util/symbianUtils.h"
#include "base/FConnection.h"
#include "base/globalsdef.h"

USE_NAMESPACE

StringBuffer FSocket::lIP;

FSocket* FSocket::createSocket(const StringBuffer& peer, int32_t port)
{
    return FSocket::NewL(peer, port);
}

FSocket* FSocket::NewL(const StringBuffer& peer, int32_t port)
{
    FSocket* self = FSocket::NewLC(peer, port);
    CleanupStack::Pop( self );
    return self;
}

FSocket* FSocket::NewLC(const StringBuffer& peer, int32_t port)
{
    FSocket* self = new ( ELeave ) FSocket();
    CleanupStack::PushL( self );
    self->ConstructL(peer, port);

    if (self->getLastStatus() != KErrNone) {
        // Something wrong.
        delete self;
        return NULL;
    }

    return self;
}

void FSocket::ConstructL(const StringBuffer& peer, int32_t port)
{
    //LOG.debug("FSocket::ConstructL");

    StringBuffer  errorMsg;
    RHostResolver resolver;
    RBuf          serverName;
    TNameEntry    hostAddress;
    TInetAddr     address;

    serverName.Assign(stringBufferToNewBuf(peer));

    //
    // Get the connection manager instance
    //
    FConnection* connection = FConnection::getInstance();
    if (!connection) {
        iStatus = -1;
        errorMsg = "Error opening connection";
        goto error;
    }
    // Session is owned by FConnection!
    RSocketServ* session = connection->getSession();

    //
    // Open the Client Socket tcp/ip
    //
#ifdef __WINSCW__
    // WINSCW: simply open the socket
    TInt res = iSocket.Open(*session, KAfInet, KSockStream, KProtocolInetTcp);
#else
    // GCCE: use the existing connection
    // If first time, connect to gprs
    if (!connection->isConnected()) {
        LOG.debug("Starting connection");
        // TODO: remove the iap name: it's already set inside FConnection
        connection->startConnection("Ask");
    }
    RConnection* conn = connection->getConnection();

    LOG.debug("Opening socket and associate with existing connection");
    TInt res = iSocket.Open(*session, KAfInet, KSockStream, KProtocolInetTcp, *conn);
    LOG.debug("Socket opened (err = %d)", res);
#endif
    if (res != KErrNone) {
        iStatus = -1;
        errorMsg = "Error opening socket";
        goto error;
    }

    // This works if serverName is the ip address, like "x.y.z.w"
    res = address.Input(serverName);

    if (res != KErrNone) {
        // Try to resolve the host address
        LOG.debug("resolve IP address...");
        res = resolver.Open(*session, KAfInet, KProtocolInetTcp);
        if (res != KErrNone) {
            iStatus = -2;
            errorMsg = "Host resolver open failed";
            goto error;
        }

        resolver.GetByName(serverName, hostAddress, iStatus);
        User::WaitForRequest(iStatus);
        resolver.Close();
        if (iStatus != KErrNone) {
            errorMsg = "DNS lookup failed";
            goto error;
        }

        // Set the socket server address/port
        address = hostAddress().iAddr;
    }

    address.SetPort(port);

    // --- Connect to host ---
    LOG.debug("Socket connect...");
    iSocket.Connect(address, iStatus);
    User::WaitForRequest(iStatus);
    if (iStatus != KErrNone) {
        errorMsg = "Failed to connect to Server";
        goto error;
    }

    return;

error:
    LOG.error(errorMsg.c_str());
    return;
}

FSocket::FSocket()
{
    iStatus = 0;
}

FSocket::~FSocket()
{
    close();
}

int32_t FSocket::writeBuffer(const int8_t* buffer, int32_t len)
{
    // This doesn't copy the buffer in memory.
    TPtr8 data((TUint8*)buffer, len);
    data.SetLength(len);

    // Sends data to the remote host.
    iSocket.Write(data, iStatus);
    User::WaitForRequest(iStatus);

    if (iStatus == KErrNone) {
        return len;
    }
    else {
        LOG.error("FSocket: error writing on socket (status = %d)", iStatus.Int());
        return -1;
    }
}

int32_t FSocket::readBuffer(int8_t* buffer, int32_t maxLen)
{
    RBuf8 data;
    data.CreateL(maxLen);

    // Receives data from a remote host and completes when data is available.
    TSockXfrLength len;
    iSocket.RecvOneOrMore(data, 0, iStatus, len);
    User::WaitForRequest(iStatus);

    TInt msgLen = len();

    if (iStatus == KErrNone) {
        if (msgLen <= maxLen) {
            // OK. Copy the message into the preallocated buffer.
            memcpy(buffer, data.Ptr(), msgLen);
            return msgLen;
        }
        else {
            LOG.error("FSocket: error reading, message too big (%d > %d) -> rejected.", msgLen, maxLen);
            iStatus = -1;
            return -1;
        }
    }
    else if (iStatus == KErrEof) {
        // Either the remote connection is closed, or the socket has been shutdown.
        LOG.info("FSocket: read interrupted (connection closed)");
        buffer = NULL;
        return -1;
    }
    else {
        LOG.error("FSocket: error reading on socket (status = %d)", iStatus.Int());
        buffer = NULL;
        return -1;
    }
}

void FSocket::close()
{
    //LOG.debug("FSocket::close");

    // TODO: shutdown if I/O in progress?
    //iSocket.Shutdown(RSocket::EImmediate, iStatus);

    iSocket.CancelAll();
    iSocket.Close();
}

const StringBuffer& FSocket::address() const {
    return lAddress;
}

const StringBuffer& FSocket::peerAddress() const {
    return pAddress;
}

const StringBuffer& FSocket::localIP() {
    return lIP;
}
<commit_msg>Starts connection (if not connected) using the default IAP. It can be set previously in FConnection class.<commit_after>/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2003 - 2007 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#include "push/FSocket.h"
#include "base/SymbianLog.h"
#include "base/util/stringUtils.h"
#include "base/util/symbianUtils.h"
#include "base/FConnection.h"
#include "base/globalsdef.h"

USE_NAMESPACE

StringBuffer FSocket::lIP;

FSocket* FSocket::createSocket(const StringBuffer& peer, int32_t port)
{
    return FSocket::NewL(peer, port);
}

FSocket* FSocket::NewL(const StringBuffer& peer, int32_t port)
{
    FSocket* self = FSocket::NewLC(peer, port);
    CleanupStack::Pop( self );
    return self;
}

FSocket* FSocket::NewLC(const StringBuffer& peer, int32_t port)
{
    FSocket* self = new ( ELeave ) FSocket();
    CleanupStack::PushL( self );
    self->ConstructL(peer, port);

    if (self->getLastStatus() != KErrNone) {
        // Something wrong.
        delete self;
        return NULL;
    }

    return self;
}

void FSocket::ConstructL(const StringBuffer& peer, int32_t port)
{
    //LOG.debug("FSocket::ConstructL");

    StringBuffer  errorMsg;
    RHostResolver resolver;
    RBuf          serverName;
    TNameEntry    hostAddress;
    TInetAddr     address;

    serverName.Assign(stringBufferToNewBuf(peer));

    //
    // Get the connection manager instance
    //
    FConnection* connection = FConnection::getInstance();
    if (!connection) {
        iStatus = -1;
        errorMsg = "Error opening connection";
        goto error;
    }
    // Session is owned by FConnection!
    RSocketServ* session = connection->getSession();

    //
    // Open the Client Socket tcp/ip
    //
#ifdef __WINSCW__
    // WINSCW: simply open the socket
    TInt res = iSocket.Open(*session, KAfInet, KSockStream, KProtocolInetTcp);
#else
    // GCCE: use the existing connection
    // If first time, connect to gprs
    if (!connection->isConnected()) {
        LOG.debug("Starting connection");
        connection->startConnection();
    }
    RConnection* conn = connection->getConnection();

    LOG.debug("Opening socket and associate with existing connection");
    TInt res = iSocket.Open(*session, KAfInet, KSockStream, KProtocolInetTcp, *conn);
    //LOG.debug("Socket opened (err = %d)", res);
#endif
    if (res != KErrNone) {
        iStatus = -1;
        errorMsg = "Error opening socket";
        goto error;
    }

    // This works if serverName is the ip address, like "x.y.z.w"
    res = address.Input(serverName);

    if (res != KErrNone) {
        // Try to resolve the host address
        LOG.debug("resolve IP address...");
        res = resolver.Open(*session, KAfInet, KProtocolInetTcp);
        if (res != KErrNone) {
            iStatus = -2;
            errorMsg = "Host resolver open failed";
            goto error;
        }

        resolver.GetByName(serverName, hostAddress, iStatus);
        User::WaitForRequest(iStatus);
        resolver.Close();
        if (iStatus != KErrNone) {
            errorMsg = "DNS lookup failed";
            goto error;
        }

        // Set the socket server address/port
        address = hostAddress().iAddr;
    }

    address.SetPort(port);

    // --- Connect to host ---
    LOG.debug("Socket connect...");
    iSocket.Connect(address, iStatus);
    User::WaitForRequest(iStatus);
    if (iStatus != KErrNone) {
        errorMsg = "Failed to connect to Server";
        goto error;
    }

    return;

error:
    LOG.error(errorMsg.c_str());
    return;
}

FSocket::FSocket()
{
    iStatus = 0;
}

FSocket::~FSocket()
{
    close();
}

int32_t FSocket::writeBuffer(const int8_t* buffer, int32_t len)
{
    // This doesn't copy the buffer in memory.
    TPtr8 data((TUint8*)buffer, len);
    data.SetLength(len);

    // Sends data to the remote host.
    iSocket.Write(data, iStatus);
    User::WaitForRequest(iStatus);

    if (iStatus == KErrNone) {
        return len;
    }
    else {
        LOG.error("FSocket: error writing on socket (status = %d)", iStatus.Int());
        return -1;
    }
}

int32_t FSocket::readBuffer(int8_t* buffer, int32_t maxLen)
{
    StringBuffer errorMsg;

    RBuf8 data;
    data.CreateL(maxLen);

    // Receives data from a remote host and completes when data is available.
    TSockXfrLength len;
    iSocket.RecvOneOrMore(data, 0, iStatus, len);
    User::WaitForRequest(iStatus);

    TInt msgLen = len();

    if (iStatus == KErrNone) {
        if (msgLen <= maxLen) {
            // OK. Copy the message into the preallocated buffer.
            memcpy(buffer, data.Ptr(), msgLen);
            return msgLen;
        }
        else {
            errorMsg.sprintf("FSocket: error reading, message too big (%d > %d) -> rejected.", msgLen, maxLen);
            goto error;
        }
    }
    else if (iStatus == KErrEof) {
        // Either the remote connection is closed, or the socket has been shutdown.
        errorMsg = "FSocket: read interrupted (connection closed)";
        goto error;
    }
    else {
        errorMsg.sprintf("FSocket: error reading on socket (status = %d)", iStatus.Int());
        goto error;
    }

error:
    LOG.error(errorMsg.c_str());
    buffer = NULL;
    return -1;
}

void FSocket::close()
{
    //LOG.debug("FSocket::close");

    // TODO: shutdown if I/O in progress?
    //iSocket.Shutdown(RSocket::EImmediate, iStatus);

    iSocket.CancelAll();
    iSocket.Close();
}

const StringBuffer& FSocket::address() const {
    return lAddress;
}

const StringBuffer& FSocket::peerAddress() const {
    return pAddress;
}

const StringBuffer& FSocket::localIP() {
    return lIP;
}
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2006 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "common.h"

// implementation header
#include "BZDBLocal.h"

// system headers
#include <stdio.h>
#include <string.h>
#include <string>

// common headers
#include "StateDatabase.h"
#include "ParseColor.h"

/******************************************************************************/
//
// BZDBbool
//

BZDBbool::BZDBbool(const std::string& _name, bool defVal, bool save)
                   : BZDBLocal(_name, save), data(defVal)
{
  BZDBLocalManager::manager.addEntry(this);
  DEBUG3("Added BZDBbool(%s) callback\n", name.c_str());
  return;
}

BZDBbool::~BZDBbool()
{
  return;
}

void BZDBbool::callback()
{
  data = BZDB.isTrue(name);
  DEBUG4("BZDBbool(%s) = %s\n", name.c_str(), data ? "true" : "false");
  return;
}

void BZDBbool::staticCallback(const std::string& /*name*/, void* data)
{
  ((BZDBbool*)data)->callback();
  return;
}

void BZDBbool::addCallbacks()
{
  if (BZDB.isSet(name)) {
    fprintf(stderr, "BZDBbool duplicate \"%s\".\n", name.c_str());
    exit(1);
  }
  BZDB.setBool(name, data);
  BZDB.setDefault(name, BZDB.get(name));
  BZDB.setPersistent(name, saveOnExit);
  BZDB.addCallback(name, staticCallback, this);
  return;
}

void BZDBbool::removeCallbacks()
{
  BZDB.removeCallback(name, staticCallback, this);
  return;
}

/******************************************************************************/
//
// BZDBint
//

BZDBint::BZDBint(const std::string& _name, int defVal,
                 int _min, int _max, bool _neverZero, bool save)
                 : BZDBLocal(_name, save), data(defVal),
                   min(_min), max(_max), neverZero(_neverZero)
{
  BZDBLocalManager::manager.addEntry(this);
  DEBUG3("Added BZDBint(%s) callback\n", name.c_str());
  return;
}

BZDBint::~BZDBint()
{
  return;
}

void BZDBint::callback()
{
  int tmp = BZDB.evalInt(name);

  if ((min != INT_MIN) && (tmp < min)) {
    DEBUG3("BZDBint(%s) min: %f < %f\n", name.c_str(), tmp, min);
    tmp = min; // clamp to min
  }

  if ((max != INT_MAX) && (tmp > max)) {
    DEBUG3("BZDBint(%s) max: %f > %f\n", name.c_str(), tmp, max);
    tmp = max; // clamp to max
  }

  if (neverZero && (tmp == 0)) {
    DEBUG3("BZDBint(%s) neverZero\n", name.c_str());
    return; // bail out
  }

  data = tmp; // set the new value

  DEBUG4("BZDBint(%s) = %i\n", name.c_str(), data);

  return;
}

void BZDBint::staticCallback(const std::string& /*name*/, void* data)
{
  ((BZDBint*)data)->callback();
  return;
}

void BZDBint::addCallbacks()
{
  if (BZDB.isSet(name)) {
    fprintf(stderr, "BZDBint duplicate \"%s\".\n", name.c_str());
    exit(1);
  }
  BZDB.setInt(name, data);
  BZDB.setDefault(name, BZDB.get(name));
  BZDB.setPersistent(name, saveOnExit);
  BZDB.addCallback(name, staticCallback, this);
  return;
}

void BZDBint::removeCallbacks()
{
  BZDB.removeCallback(name, staticCallback, this);
  return;
}

/******************************************************************************/
//
// BZDBfloat
//

BZDBfloat::BZDBfloat(const std::string& _name, float defVal,
                     float _min, float _max,
                     bool _neverZero, bool save)
                     : BZDBLocal(_name, save), data(defVal),
                       min(_min), max(_max), neverZero(_neverZero)
{
  BZDBLocalManager::manager.addEntry(this);
  DEBUG3("Added BZDBfloat(%s) callback\n", name.c_str());
  return;
}

BZDBfloat::~BZDBfloat()
{
  return;
}

void BZDBfloat::callback()
{
  float tmp = BZDB.eval(name);

  if ((min != -MAXFLOAT) && (tmp < min)) {
    DEBUG3("BZDBfloat(%s) min: %f < %f\n", name.c_str(), tmp, min);
    tmp = min; // clamp to min
  }

  if ((max != +MAXFLOAT) && (tmp > max)) {
    DEBUG3("BZDBfloat(%s) max: %f > %f\n", name.c_str(), tmp, max);
    tmp = max; // clamp to max
  }

  if (neverZero && (tmp == 0.0f)) {
    DEBUG3("BZDBfloat(%s) neverZero\n", name.c_str());
    return; // bail out
  }

  data = tmp; // set the new value

  DEBUG4("BZDBfloat(%s) = %f\n", name.c_str(), data);

  return;
}

void BZDBfloat::staticCallback(const std::string& /*name*/, void* data)
{
  ((BZDBfloat*)data)->callback();
  return;
}

void BZDBfloat::addCallbacks()
{
  if (BZDB.isSet(name)) {
    fprintf(stderr, "BZDBfloat duplicate \"%s\".\n", name.c_str());
    exit(1);
  }
  BZDB.setFloat(name, data);
  BZDB.setDefault(name, BZDB.get(name));
  BZDB.setPersistent(name, saveOnExit);
  BZDB.addCallback(name, staticCallback, this);
  return;
}

void BZDBfloat::removeCallbacks()
{
  BZDB.removeCallback(name, staticCallback, this);
  return;
}

/******************************************************************************/
//
// BZDBcolor
//

BZDBcolor::BZDBcolor(const std::string& _name,
                     float r, float g, float b, float a,
                     bool _neverAlpha, bool save)
                     : BZDBLocal(_name, save), neverAlpha(_neverAlpha)
{
  data[0] = r;
  data[1] = g;
  data[2] = b;
  data[3] = a;
  BZDBLocalManager::manager.addEntry(this);
  DEBUG3("Added BZDBcolor(%s) callback\n", name.c_str());
  return;
}

BZDBcolor::~BZDBcolor()
{
  return;
}

void BZDBcolor::callback()
{
  const std::string& expr = BZDB.get(name);
  float color[4];

  if (!parseColorString(expr, color)) {
    DEBUG3("BZDBcolor(%s) bad string: %s\n", name.c_str(), expr.c_str());
    return;
  }

  if (neverAlpha && (color[3] < 1.0f)) {
    DEBUG3("BZDBcolor(%s) made opaque: %f\n", name.c_str(), color[3]);
    color[3] = 1.0f;
  }

  // set the new value
  memcpy(data, color, sizeof(float[4]));

  DEBUG4("BZDBcolor(%s) = %f, %f, %f, %f\n", name.c_str(),
         data[0], data[1], data[2], data[3]);

  return;
}

void BZDBcolor::staticCallback(const std::string& /*name*/, void* data)
{
  ((BZDBcolor*)data)->callback();
  return;
}

void BZDBcolor::addCallbacks()
{
  if (BZDB.isSet(name)) {
    fprintf(stderr, "BZDBcolor duplicate \"%s\".\n", name.c_str());
    exit(1);
  }

  char buf[256];
  snprintf(buf, 256, " %f %f %f %f", data[0], data[1], data[2], data[3]);
  BZDB.set(name, buf);
  BZDB.setDefault(name, BZDB.get(name));
  BZDB.setPersistent(name, saveOnExit);
  BZDB.addCallback(name, staticCallback, this);
  return;
}

void BZDBcolor::removeCallbacks()
{
  BZDB.removeCallback(name, staticCallback, this);
  return;
}

/******************************************************************************/
//
// BZDBstring
//

BZDBstring::BZDBstring(const std::string& _name, const std::string& defVal,
                       bool _neverEmpty, bool save)
                       : BZDBLocal(_name, save),
                         data(defVal), neverEmpty(_neverEmpty)
{
  BZDBLocalManager::manager.addEntry(this);
  DEBUG3("Added BZDBstring(%s) callback\n", name.c_str());
  return;
}

BZDBstring::~BZDBstring()
{
  return;
}

void BZDBstring::callback()
{
  const std::string& tmp = BZDB.get(name);

  if (neverEmpty && (tmp.size() <= 0)) {
    DEBUG3("BZDBstring(%s) empty string: %s\n", name.c_str(), tmp.c_str());
    return;
  }

  data = tmp; // set the new value

  DEBUG4("BZDBstring(%s) = %s\n", name.c_str(), data.c_str());

  return;
}

void BZDBstring::staticCallback(const std::string& /*name*/, void* data)
{
  ((BZDBstring*)data)->callback();
  return;
}

void BZDBstring::addCallbacks()
{
  if (BZDB.isSet(name)) {
    fprintf(stderr, "BZDBstring duplicate \"%s\".\n", name.c_str());
    exit(1);
  }

  BZDB.set(name, data);
  BZDB.setDefault(name, BZDB.get(name));
  BZDB.setPersistent(name, saveOnExit);
  BZDB.addCallback(name, staticCallback, this);
  return;
}

void BZDBstring::removeCallbacks()
{
  BZDB.removeCallback(name, staticCallback, this);
  return;
}

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

BZDBLocalManager::BZDBLocalManager BZDBLocalManager::manager;

static std::vector<BZDBLocal*>& getEntryVector()
{
  static std::vector<BZDBLocal*> vec;
  return vec;
}

BZDBLocalManager::BZDBLocalManager()
{
  return;
}

BZDBLocalManager::~BZDBLocalManager()
{
  return;
}

bool BZDBLocalManager::addEntry(BZDBLocal* entry)
{
  std::vector<BZDBLocal*>& vec = getEntryVector();
  vec.push_back(entry);
  return true;
}

void BZDBLocalManager::init()
{
  std::vector<BZDBLocal*>& entries = getEntryVector();
  for (unsigned int i = 0; i < entries.size(); i++) {
    entries[i]->addCallbacks();
  }
  return;
}

void BZDBLocalManager::kill()
{
  std::vector<BZDBLocal*>& entries = getEntryVector();
  for (unsigned int i = 0; i < entries.size(); i++) {
    entries[i]->removeCallbacks();
  }
  return;
}

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

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>class type already known<commit_after>/* bzflag
 * Copyright (c) 1993 - 2006 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "common.h"

// implementation header
#include "BZDBLocal.h"

// system headers
#include <stdio.h>
#include <string.h>
#include <string>

// common headers
#include "StateDatabase.h"
#include "ParseColor.h"

// Function Prototypes
// -------------------
static void safeSetInt(const std::string& name, int value);
static void safeSetFloat(const std::string& name, float value);
static void safeSetString(const std::string& name, const std::string&value);

/******************************************************************************/
//
// BZDBbool
//

BZDBbool::BZDBbool(const std::string& _name, bool defVal, bool save)
                   : BZDBLocal(_name, save), data(defVal)
{
  BZDBLocalManager::manager.addEntry(this);
  DEBUG3("Added BZDBbool(%s) callback\n", name.c_str());
  return;
}

BZDBbool::~BZDBbool()
{
  return;
}

void BZDBbool::callback()
{
  data = BZDB.isTrue(name);
  DEBUG4("BZDBbool(%s) = %s\n", name.c_str(), data ? "true" : "false");
  return;
}

void BZDBbool::staticCallback(const std::string& /*name*/, void* data)
{
  ((BZDBbool*)data)->callback();
  return;
}

void BZDBbool::addCallbacks()
{
  if (BZDB.isSet(name)) {
    fprintf(stderr, "BZDBbool duplicate \"%s\".\n", name.c_str());
    exit(1);
  }
  BZDB.setBool(name, data);
  BZDB.setDefault(name, BZDB.get(name));
  BZDB.setPersistent(name, saveOnExit);
  BZDB.addCallback(name, staticCallback, this);
  return;
}

void BZDBbool::removeCallbacks()
{
  BZDB.removeCallback(name, staticCallback, this);
  return;
}

/******************************************************************************/
//
// BZDBint
//

BZDBint::BZDBint(const std::string& _name, int defVal,
                 int _min, int _max, bool _neverZero, bool save)
                 : BZDBLocal(_name, save), data(defVal),
                   min(_min), max(_max), neverZero(_neverZero)
{
  BZDBLocalManager::manager.addEntry(this);
  DEBUG3("Added BZDBint(%s) callback\n", name.c_str());
  return;
}

BZDBint::~BZDBint()
{
  return;
}

void BZDBint::callback()
{
  int tmp = BZDB.evalInt(name);

  if (tmp < min) {
    DEBUG3("BZDBint(%s) min: %f < %f\n", name.c_str(), tmp, min);
    tmp = min; // clamp to min
    safeSetInt(name, tmp);
  }

  if (tmp > max) {
    DEBUG3("BZDBint(%s) max: %f > %f\n", name.c_str(), tmp, max);
    tmp = max; // clamp to max
    safeSetInt(name, tmp);
  }

  if (neverZero && (tmp == 0)) {
    DEBUG3("BZDBint(%s) neverZero\n", name.c_str());
    return; // bail out
  }

  data = tmp; // set the new value

  DEBUG4("BZDBint(%s) = %i\n", name.c_str(), data);

  return;
}

void BZDBint::staticCallback(const std::string& /*name*/, void* data)
{
  ((BZDBint*)data)->callback();
  return;
}

void BZDBint::addCallbacks()
{
  if (BZDB.isSet(name)) {
    fprintf(stderr, "BZDBint duplicate \"%s\".\n", name.c_str());
    exit(1);
  }
  BZDB.setInt(name, data);
  BZDB.setDefault(name, BZDB.get(name));
  BZDB.setPersistent(name, saveOnExit);
  BZDB.addCallback(name, staticCallback, this);
  return;
}

void BZDBint::removeCallbacks()
{
  BZDB.removeCallback(name, staticCallback, this);
  return;
}

/******************************************************************************/
//
// BZDBfloat
//

BZDBfloat::BZDBfloat(const std::string& _name, float defVal,
                     float _min, float _max,
                     bool _neverZero, bool save)
                     : BZDBLocal(_name, save), data(defVal),
                       min(_min), max(_max), neverZero(_neverZero)
{
  BZDBLocalManager::manager.addEntry(this);
  DEBUG3("Added BZDBfloat(%s) callback\n", name.c_str());
  return;
}

BZDBfloat::~BZDBfloat()
{
  return;
}

void BZDBfloat::callback()
{
  float tmp = BZDB.eval(name);

  if (tmp < min) {
    DEBUG3("BZDBfloat(%s) min: %f < %f\n", name.c_str(), tmp, min);
    tmp = min; // clamp to min
    safeSetFloat(name, tmp);
  }

  if (tmp > max) {
    DEBUG3("BZDBfloat(%s) max: %f > %f\n", name.c_str(), tmp, max);
    tmp = max; // clamp to max
    safeSetFloat(name, tmp);
  }

  if (neverZero && (tmp == 0.0f)) {
    DEBUG3("BZDBfloat(%s) neverZero\n", name.c_str());
    return; // bail out
  }

  data = tmp; // set the new value

  DEBUG4("BZDBfloat(%s) = %f\n", name.c_str(), data);

  return;
}

void BZDBfloat::staticCallback(const std::string& /*name*/, void* data)
{
  ((BZDBfloat*)data)->callback();
  return;
}

void BZDBfloat::addCallbacks()
{
  if (BZDB.isSet(name)) {
    fprintf(stderr, "BZDBfloat duplicate \"%s\".\n", name.c_str());
    exit(1);
  }
  BZDB.setFloat(name, data);
  BZDB.setDefault(name, BZDB.get(name));
  BZDB.setPersistent(name, saveOnExit);
  BZDB.addCallback(name, staticCallback, this);
  return;
}

void BZDBfloat::removeCallbacks()
{
  BZDB.removeCallback(name, staticCallback, this);
  return;
}

/******************************************************************************/
//
// BZDBcolor
//

BZDBcolor::BZDBcolor(const std::string& _name,
                     float r, float g, float b, float a,
                     bool _neverAlpha, bool save)
                     : BZDBLocal(_name, save), neverAlpha(_neverAlpha)
{
  data[0] = r;
  data[1] = g;
  data[2] = b;
  data[3] = a;
  BZDBLocalManager::manager.addEntry(this);
  DEBUG3("Added BZDBcolor(%s) callback\n", name.c_str());
  return;
}

BZDBcolor::~BZDBcolor()
{
  return;
}

void BZDBcolor::callback()
{
  const std::string& expr = BZDB.get(name);
  float color[4];

  if (!parseColorString(expr, color)) {
    DEBUG3("BZDBcolor(%s) bad string: %s\n", name.c_str(), expr.c_str());
    return;
  }

  if (neverAlpha && (color[3] < 1.0f)) {
    DEBUG3("BZDBcolor(%s) made opaque: %f\n", name.c_str(), color[3]);
    color[3] = 1.0f;
    char buf[256];
    snprintf(buf, 256, " %f %f %f %f", color[0], color[1], color[2], color[3]);
    safeSetString(name, buf);
  }

  // set the new value
  memcpy(data, color, sizeof(float[4]));

  DEBUG4("BZDBcolor(%s) = %f, %f, %f, %f\n", name.c_str(),
         data[0], data[1], data[2], data[3]);

  return;
}

void BZDBcolor::staticCallback(const std::string& /*name*/, void* data)
{
  ((BZDBcolor*)data)->callback();
  return;
}

void BZDBcolor::addCallbacks()
{
  if (BZDB.isSet(name)) {
    fprintf(stderr, "BZDBcolor duplicate \"%s\".\n", name.c_str());
    exit(1);
  }

  char buf[256];
  snprintf(buf, 256, " %f %f %f %f", data[0], data[1], data[2], data[3]);
  BZDB.set(name, buf);
  BZDB.setDefault(name, BZDB.get(name));
  BZDB.setPersistent(name, saveOnExit);
  BZDB.addCallback(name, staticCallback, this);
  return;
}

void BZDBcolor::removeCallbacks()
{
  BZDB.removeCallback(name, staticCallback, this);
  return;
}

/******************************************************************************/
//
// BZDBstring
//

BZDBstring::BZDBstring(const std::string& _name, const std::string& defVal,
                       bool _neverEmpty, bool save)
                       : BZDBLocal(_name, save),
                         data(defVal), neverEmpty(_neverEmpty)
{
  BZDBLocalManager::manager.addEntry(this);
  DEBUG3("Added BZDBstring(%s) callback\n", name.c_str());
  return;
}

BZDBstring::~BZDBstring()
{
  return;
}

void BZDBstring::callback()
{
  const std::string& tmp = BZDB.get(name);

  if (neverEmpty && (tmp.size() <= 0)) {
    DEBUG3("BZDBstring(%s) empty string: %s\n", name.c_str(), tmp.c_str());
    safeSetString(name, tmp);
    return;
  }

  data = tmp; // set the new value

  DEBUG4("BZDBstring(%s) = %s\n", name.c_str(), data.c_str());

  return;
}

void BZDBstring::staticCallback(const std::string& /*name*/, void* data)
{
  ((BZDBstring*)data)->callback();
  return;
}

void BZDBstring::addCallbacks()
{
  if (BZDB.isSet(name)) {
    fprintf(stderr, "BZDBstring duplicate \"%s\".\n", name.c_str());
    exit(1);
  }

  BZDB.set(name, data);
  BZDB.setDefault(name, BZDB.get(name));
  BZDB.setPersistent(name, saveOnExit);
  BZDB.addCallback(name, staticCallback, this);
  return;
}

void BZDBstring::removeCallbacks()
{
  BZDB.removeCallback(name, staticCallback, this);
  return;
}

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

BZDBLocalManager BZDBLocalManager::manager;

static std::vector<BZDBLocal*>& getEntryVector()
{
  static std::vector<BZDBLocal*> vec;
  return vec;
}

BZDBLocalManager::BZDBLocalManager()
{
  return;
}

BZDBLocalManager::~BZDBLocalManager()
{
  return;
}

bool BZDBLocalManager::addEntry(BZDBLocal* entry)
{
  std::vector<BZDBLocal*>& vec = getEntryVector();
  vec.push_back(entry);
  return true;
}

void BZDBLocalManager::init()
{
  std::vector<BZDBLocal*>& entries = getEntryVector();
  for (unsigned int i = 0; i < entries.size(); i++) {
    entries[i]->addCallbacks();
  }
  return;
}

void BZDBLocalManager::kill()
{
  std::vector<BZDBLocal*>& entries = getEntryVector();
  for (unsigned int i = 0; i < entries.size(); i++) {
    entries[i]->removeCallbacks();
  }
  return;
}

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

static bool Inside = false;

static void safeSetInt(const std::string& name, int value)
{
  if (!Inside) {
    Inside = true;
    BZDB.setInt(name, value);
    Inside = false;
  }
  return;
}

static void safeSetFloat(const std::string& name, float value)
{
  if (!Inside) {
    Inside = true;
    BZDB.setFloat(name, value);
    Inside = false;
  }
  return;
}

static void safeSetString(const std::string& name, const std::string&value)
{
  if (!Inside) {
    Inside = true;
    BZDB.set(name, value);
    Inside = false;
  }
  return;
}

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

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>//____________________________________________________
void AliTRDmakeRecoParam()
{
  AliCDBMetaData *metaData= new AliCDBMetaData();
  metaData->SetObjectClassName("TObjArray");
  metaData->SetResponsible("Alexandru Bercuci");
  metaData->SetBeamPeriod(1);
  metaData->SetAliRootVersion("05-21-01"); //root version
  metaData->SetComment("Ideal reconstruction parameters for low, high and cosmic runs");

  AliCDBId id("TRD/Calib/RecoParam", 0, AliCDBRunRange::Infinity());
  AliCDBManager *man = AliCDBManager::Instance();
  AliCDBStorage *gStorLoc = man->GetStorage("local://$ALICE_ROOT/OCDB");
  if (!gStorLoc) {
    return;
  }
  gStorLoc->Put(CreateRecoParamObject(), id, metaData);

  return;
}

//____________________________________________________
TObjArray* CreateRecoParamObject()
{
  TObjArray *recos = new TObjArray(4);

  AliTRDrecoParam *rec = 0x0;
  recos->AddLast(rec = AliTRDrecoParam::GetLowFluxParam());
  rec->SetAsDefault();
  rec->SetNameTitle("Default", "TRD Default Reco Param");
  // further settings for low flux reco param
  // reco->SetThisAndThat()

  recos->AddLast(rec = AliTRDrecoParam::GetLowFluxParam());
  rec->SetEventSpecie(AliRecoParam::kLowMult);
  rec->SetNameTitle("LOW", "TRD Low Flux Reco Param");

  recos->AddLast(rec = AliTRDrecoParam::GetHighFluxParam());
  rec->SetEventSpecie(AliRecoParam::kHighMult);
  rec->SetNameTitle("HIGH", "TRD High Flux Reco Param");

  recos->AddLast(rec = AliTRDrecoParam::GetCosmicTestParam());
  rec->SetEventSpecie(AliRecoParam::kCosmic);
  rec->SetNameTitle("COSMIC", "TRD Cosmic Reco Param");
  rec->SetRawStreamVersion("FAST");

  recos->AddLast(rec = AliTRDrecoParam::GetCosmicTestParam());
  rec->SetEventSpecie(AliRecoParam::kCalib);
  rec->SetNameTitle("CALIBRATION", "TRD Calibration Reco Param");
  rec->SetRawStreamVersion("FAST");

//  recos->AddLast(rec = AliTRDrecoParam::GetLowFluxParam());
//  rec->SetNameTitle("HLT", "TRD HLT Reco Param");
//  rec->SetChi2Y(.1);
//  rec->SetChi2Z(5.);

  return recos;
}
<commit_msg>Update reco param object (Markus)<commit_after>//____________________________________________________
void AliTRDmakeRecoParam()
{
  AliCDBMetaData *metaData= new AliCDBMetaData();
  metaData->SetObjectClassName("TObjArray");
  metaData->SetResponsible("Alexandru Bercuci");
  metaData->SetBeamPeriod(1);
  metaData->SetAliRootVersion("05-21-01"); //root version
  metaData->SetComment("Ideal reconstruction parameters for low, high and cosmic runs");

  AliCDBId id("TRD/Calib/RecoParam", 0, AliCDBRunRange::Infinity());
  AliCDBManager *man = AliCDBManager::Instance();
  AliCDBStorage *gStorLoc = man->GetStorage("local://$ALICE_ROOT/OCDB");
  if (!gStorLoc) {
    return;
  }
  gStorLoc->Put(CreateRecoParamObject(), id, metaData);

  return;
}

//____________________________________________________
TObjArray* CreateRecoParamObject()
{
  TObjArray *recos = new TObjArray(4);

  AliTRDrecoParam *rec = 0x0;
  recos->AddLast(rec = AliTRDrecoParam::GetLowFluxParam());
  rec->SetAsDefault();
  rec->SetEventSpecie(AliRecoParam::kLowMult);
  rec->SetNameTitle("LOW", "TRD Low Flux Reco Param");
  rec->SetStreamLevel(AliTRDrecoParam::kTracker, 1);
  // further settings for low flux reco param
  // reco->SetThisAndThat()

  recos->AddLast(rec = AliTRDrecoParam::GetHighFluxParam());
  rec->SetEventSpecie(AliRecoParam::kHighMult);
  rec->SetNameTitle("HIGH", "TRD High Flux Reco Param");
  rec->SetStreamLevel(AliTRDrecoParam::kTracker, 1);

  recos->AddLast(rec = AliTRDrecoParam::GetCosmicTestParam());
  rec->SetEventSpecie(AliRecoParam::kCosmic);
  rec->SetNameTitle("COSMIC", "TRD Cosmic Reco Param");
  rec->SetStreamLevel(AliTRDrecoParam::kTracker, 1);
  rec->SetRawStreamVersion("FAST");

  recos->AddLast(rec = AliTRDrecoParam::GetCosmicTestParam());
  rec->SetEventSpecie(AliRecoParam::kCalib);
  rec->SetNameTitle("CALIBRATION", "TRD Calibration Reco Param");
  rec->SetStreamLevel(AliTRDrecoParam::kTracker, 1);
  rec->SetRawStreamVersion("FAST");

//  recos->AddLast(rec = AliTRDrecoParam::GetLowFluxParam());
//  rec->SetNameTitle("HLT", "TRD HLT Reco Param");
//  rec->SetChi2Y(.1);
//  rec->SetChi2Z(5.);

  return recos;
}
<|endoftext|>


<commit_before>/**
 *  Purity in C++17
 *  ===============
 *
 *  Very naive attempt.
 *
 *  Note: Compile with -std=c++17.
 */

#include <tuple>

template <typename T, typename ...Args>
class pure_io {
public:
	template <T F()>
	static constexpr T
	fapply() noexcept
	{
		static_assert(noexcept(F()), "constant function required");
		constexpr auto ret = F();
		return ret;
	}

	template <typename F, typename G>
	static constexpr T
	lapply(F f, G g) noexcept
	{
		constexpr auto ret = f(g());
		return ret;
	}
};

template <auto N>
constexpr auto
foo()
{
	return N * 2;
}

template <auto X, auto Y>
constexpr auto
bar()
{
	return foo<X + Y>();
}

template <auto N>
constexpr auto
baz()
{
	return N + 1;
}

int
main()
{
	constexpr auto n0 = pure_io<int>::fapply<bar<0, 42>>();
	static_assert(n0 == 84, "foo bar oops");
	static_assert(pure_io<int>::fapply<baz<n0>>() == 85, "baz oops");

	auto f_vals = [] {
		return std::make_tuple(0, 42);
	};
	auto f_swap = [](auto args) {
		return std::make_tuple(std::get<1>(args),
							   std::get<0>(args));
	};
	constexpr auto n1 = pure_io<std::tuple<int, int>>::lapply(f_swap, f_vals);
	static_assert(std::get<0>(n1) == 42 && std::get<1>(n1) == 0,
				  "lambda oops");

	return 0;
}
<commit_msg>updated purity1z: static_assert args gen lambda<commit_after>/**
 *  Purity in C++17
 *  ===============
 *
 *  Very naive attempt.
 *
 *  Note: Compile with -std=c++17.
 */

#include <tuple>

class pure_io {
public:
	template <auto F()>
	static constexpr auto
	fapply() noexcept
	{
		static_assert(noexcept(F()), "constant function required");
		constexpr auto ret = F();
		return ret;
	}

	template <typename F, typename G>
	static constexpr auto
	lapply(F f, G g) noexcept
	{
		static_assert(noexcept(g()), "no-param lambda required at arg#1");
		constexpr auto ret = f(g());
		return ret;
	}
};

template <auto N>
constexpr auto
foo()
{
	return N * 2;
}

template <auto X, auto Y>
constexpr auto
bar()
{
	return foo<X + Y>();
}

template <auto N>
constexpr auto
baz()
{
	return N + 1;
}

int
main()
{
	constexpr auto n0 = pure_io::fapply<bar<0, 42>>();
	static_assert(n0 == 84, "foo bar oops");
	static_assert(pure_io::fapply<baz<n0>>() == 85, "baz oops");

	auto f_vals = [] {
		return std::make_tuple(0, 42);
	};
	auto f_swap = [](auto args) {
		return std::make_tuple(std::get<1>(args),
							   std::get<0>(args));
	};
	constexpr auto n1 = pure_io::lapply(f_swap, f_vals);
	static_assert(std::get<0>(n1) == 42 && std::get<1>(n1) == 0,
				  "lambda oops");

	return 0;
}
<|endoftext|>