<commit_before>// bsls_timeinterval.cpp                                              -*-C++-*-
#include <bsls_timeinterval.h>

#include <bsls_ident.h>
BSLS_IDENT_RCSID(bsls_timeinterval_cpp,"$Id$ $CSID$")

#include <bsls_assert.h>
#include <bsls_asserttest.h>   // for testing only
#include <bsls_bsltestutil.h>  // for testing only

#include <bsls_platform.h>

#include <limits.h>

// BDE_VERIFY pragma: push
// BDE_VERIFY pragma: -FABC01

namespace BloombergLP {
namespace bsls {

namespace {

struct bsls_TimeInterval_Assertions {
    char assertion1[-3 / 2 == -1];  // Ensure that the compiler maintains the
    char assertion2[-5 % 4 == -1];  // sign of the remainder (the resulting
                                    // sign is compiler implementation defined,
                                    // though our current production compilers
                                    // maintain the sign).
};

}  // close unnamed namespace

                        // ------------------
                        // class TimeInterval
                        // ------------------

// PRIVATE CLASS METHODS
bool TimeInterval::isSumValidInt64(bsls::Types::Int64 lhs,
                                   bsls::Types::Int64 rhs)
{
    if (lhs > 0 && (LLONG_MAX - lhs) < rhs) {
        return false;                                                 // RETURN
    }

    if (lhs < 0 && (LLONG_MIN - lhs) > rhs) {
        return false;                                                 // RETURN
    }
    return true;
}

// CREATORS
TimeInterval::TimeInterval(double seconds)
{
    if (seconds < 0) {
        d_seconds = -bsls::Types::Int64(-seconds);

        // The use of a volatile storage classifier is necessary on x86 builds
        // with gcc.

#if defined(BSLS_PLATFORM_CPU_X86)                                            \
 && (defined(BSLS_PLATFORM_CMP_GNU) || defined(BSLS_PLATFORM_CMP_CLANG))
        const volatile double nanoseconds =
#else
        const double nanoseconds =
#endif
             (static_cast<double>(d_seconds) - seconds) * k_NANOSECS_PER_SEC;
        d_nanoseconds = -static_cast<int>(nanoseconds + 0.5);
        if (d_nanoseconds == -k_NANOSECS_PER_SEC) {
            --d_seconds;
            d_nanoseconds = 0;
        }
    }
    else {
        d_seconds = static_cast<bsls::Types::Int64>(seconds);

        // The use of a volatile storage classifier is necessary on x86 builds
        // with gcc.

#if defined(BSLS_PLATFORM_CPU_X86)                                            \
 && (defined(BSLS_PLATFORM_CMP_GNU) || defined(BSLS_PLATFORM_CMP_CLANG))
        const volatile double nanoseconds =
#else
        const double nanoseconds =
#endif
               (seconds - static_cast<double>(d_seconds)) * k_NANOSECS_PER_SEC;
        d_nanoseconds = static_cast<int>(nanoseconds + 0.5);
        if (d_nanoseconds == k_NANOSECS_PER_SEC) {
            ++d_seconds;
            d_nanoseconds = 0;
        }
    }
}

// MANIPULATORS
TimeInterval& TimeInterval::addSeconds(bsls::Types::Int64 seconds)
{
    BSLS_ASSERT_SAFE(isSumValidInt64(seconds, d_seconds));

    d_seconds += seconds;
    if (d_seconds > 0 && d_nanoseconds < 0) {
        --d_seconds;
        d_nanoseconds += k_NANOSECS_PER_SEC;
    }
    else if (d_seconds < 0 && d_nanoseconds > 0) {
        ++d_seconds;
        d_nanoseconds -= k_NANOSECS_PER_SEC;
    }

    return *this;
}

void TimeInterval::addInterval(bsls::Types::Int64 seconds,
                               int                nanoseconds)
{
    BSLS_ASSERT(isSumValidInt64(d_seconds, seconds));
    BSLS_ASSERT(isSumValidInt64(
       d_seconds + seconds,
       (static_cast<bsls::Types::Int64>(d_nanoseconds) + nanoseconds) /
                                                          k_NANOSECS_PER_SEC));

    d_seconds += seconds;
    bsls::Types::Int64 nanosecs = static_cast<bsls::Types::Int64>(nanoseconds)
                                + d_nanoseconds;

    if (nanosecs >=  k_NANOSECS_PER_SEC
     || nanosecs <= -k_NANOSECS_PER_SEC) {
        d_seconds     +=                  nanosecs / k_NANOSECS_PER_SEC;
        d_nanoseconds  = static_cast<int>(nanosecs % k_NANOSECS_PER_SEC);
    }
    else {
        d_nanoseconds = static_cast<int>(nanosecs);
    }

    if (d_seconds > 0 && d_nanoseconds < 0) {
        --d_seconds;
        d_nanoseconds += k_NANOSECS_PER_SEC;
    }
    else if (d_seconds < 0 && d_nanoseconds > 0) {
        ++d_seconds;
        d_nanoseconds -= k_NANOSECS_PER_SEC;
    }
}

void TimeInterval::setInterval(bsls::Types::Int64 seconds,
                               int                nanoseconds)
{
    BSLS_ASSERT(isValid(seconds, nanoseconds));

    d_seconds = seconds;
    if (nanoseconds >= k_NANOSECS_PER_SEC
     || nanoseconds <= -k_NANOSECS_PER_SEC) {
        d_seconds += nanoseconds / k_NANOSECS_PER_SEC;
        d_nanoseconds = static_cast<int>(nanoseconds % k_NANOSECS_PER_SEC);
    }
    else {
        d_nanoseconds = static_cast<int>(nanoseconds);
    }

    if (d_seconds > 0 && d_nanoseconds < 0) {
        --d_seconds;
        d_nanoseconds += k_NANOSECS_PER_SEC;
    }
    else if (d_seconds < 0 && d_nanoseconds > 0) {
        ++d_seconds;
        d_nanoseconds -= k_NANOSECS_PER_SEC;
    }
}

}  // close package namespace
}  // close enterprise namespace

// BDE_VERIFY pragma: pop

// ----------------------------------------------------------------------------
// Copyright 2014 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>Fix assertion in bsls that will never fire with GCC.<commit_after>// bsls_timeinterval.cpp                                              -*-C++-*-
#include <bsls_timeinterval.h>

#include <bsls_ident.h>
BSLS_IDENT_RCSID(bsls_timeinterval_cpp,"$Id$ $CSID$")

#include <bsls_assert.h>
#include <bsls_asserttest.h>   // for testing only
#include <bsls_bsltestutil.h>  // for testing only

#include <bsls_platform.h>

#include <limits.h>

// BDE_VERIFY pragma: push
// BDE_VERIFY pragma: -FABC01

namespace BloombergLP {
namespace bsls {

namespace {

struct bsls_TimeInterval_Assertions {
    char assertion1[-3 / 2 == -1 ? 1 : -1];
    char assertion2[-5 % 4 == -1 ? 1 : -1];
        // Ensure that the compiler maintains the sign of the remainder (the
        // resulting sign is compiler implementation defined, though our
        // current production compilers maintain the sign).
};

}  // close unnamed namespace

                        // ------------------
                        // class TimeInterval
                        // ------------------

// PRIVATE CLASS METHODS
bool TimeInterval::isSumValidInt64(bsls::Types::Int64 lhs,
                                   bsls::Types::Int64 rhs)
{
    if (lhs > 0 && (LLONG_MAX - lhs) < rhs) {
        return false;                                                 // RETURN
    }

    if (lhs < 0 && (LLONG_MIN - lhs) > rhs) {
        return false;                                                 // RETURN
    }
    return true;
}

// CREATORS
TimeInterval::TimeInterval(double seconds)
{
    if (seconds < 0) {
        d_seconds = -bsls::Types::Int64(-seconds);

        // The use of a volatile storage classifier is necessary on x86 builds
        // with gcc.

#if defined(BSLS_PLATFORM_CPU_X86)                                            \
 && (defined(BSLS_PLATFORM_CMP_GNU) || defined(BSLS_PLATFORM_CMP_CLANG))
        const volatile double nanoseconds =
#else
        const double nanoseconds =
#endif
             (static_cast<double>(d_seconds) - seconds) * k_NANOSECS_PER_SEC;
        d_nanoseconds = -static_cast<int>(nanoseconds + 0.5);
        if (d_nanoseconds == -k_NANOSECS_PER_SEC) {
            --d_seconds;
            d_nanoseconds = 0;
        }
    }
    else {
        d_seconds = static_cast<bsls::Types::Int64>(seconds);

        // The use of a volatile storage classifier is necessary on x86 builds
        // with gcc.

#if defined(BSLS_PLATFORM_CPU_X86)                                            \
 && (defined(BSLS_PLATFORM_CMP_GNU) || defined(BSLS_PLATFORM_CMP_CLANG))
        const volatile double nanoseconds =
#else
        const double nanoseconds =
#endif
               (seconds - static_cast<double>(d_seconds)) * k_NANOSECS_PER_SEC;
        d_nanoseconds = static_cast<int>(nanoseconds + 0.5);
        if (d_nanoseconds == k_NANOSECS_PER_SEC) {
            ++d_seconds;
            d_nanoseconds = 0;
        }
    }
}

// MANIPULATORS
TimeInterval& TimeInterval::addSeconds(bsls::Types::Int64 seconds)
{
    BSLS_ASSERT_SAFE(isSumValidInt64(seconds, d_seconds));

    d_seconds += seconds;
    if (d_seconds > 0 && d_nanoseconds < 0) {
        --d_seconds;
        d_nanoseconds += k_NANOSECS_PER_SEC;
    }
    else if (d_seconds < 0 && d_nanoseconds > 0) {
        ++d_seconds;
        d_nanoseconds -= k_NANOSECS_PER_SEC;
    }

    return *this;
}

void TimeInterval::addInterval(bsls::Types::Int64 seconds,
                               int                nanoseconds)
{
    BSLS_ASSERT(isSumValidInt64(d_seconds, seconds));
    BSLS_ASSERT(isSumValidInt64(
       d_seconds + seconds,
       (static_cast<bsls::Types::Int64>(d_nanoseconds) + nanoseconds) /
                                                          k_NANOSECS_PER_SEC));

    d_seconds += seconds;
    bsls::Types::Int64 nanosecs = static_cast<bsls::Types::Int64>(nanoseconds)
                                + d_nanoseconds;

    if (nanosecs >=  k_NANOSECS_PER_SEC
     || nanosecs <= -k_NANOSECS_PER_SEC) {
        d_seconds     +=                  nanosecs / k_NANOSECS_PER_SEC;
        d_nanoseconds  = static_cast<int>(nanosecs % k_NANOSECS_PER_SEC);
    }
    else {
        d_nanoseconds = static_cast<int>(nanosecs);
    }

    if (d_seconds > 0 && d_nanoseconds < 0) {
        --d_seconds;
        d_nanoseconds += k_NANOSECS_PER_SEC;
    }
    else if (d_seconds < 0 && d_nanoseconds > 0) {
        ++d_seconds;
        d_nanoseconds -= k_NANOSECS_PER_SEC;
    }
}

void TimeInterval::setInterval(bsls::Types::Int64 seconds,
                               int                nanoseconds)
{
    BSLS_ASSERT(isValid(seconds, nanoseconds));

    d_seconds = seconds;
    if (nanoseconds >= k_NANOSECS_PER_SEC
     || nanoseconds <= -k_NANOSECS_PER_SEC) {
        d_seconds += nanoseconds / k_NANOSECS_PER_SEC;
        d_nanoseconds = static_cast<int>(nanoseconds % k_NANOSECS_PER_SEC);
    }
    else {
        d_nanoseconds = static_cast<int>(nanoseconds);
    }

    if (d_seconds > 0 && d_nanoseconds < 0) {
        --d_seconds;
        d_nanoseconds += k_NANOSECS_PER_SEC;
    }
    else if (d_seconds < 0 && d_nanoseconds > 0) {
        ++d_seconds;
        d_nanoseconds -= k_NANOSECS_PER_SEC;
    }
}

}  // close package namespace
}  // close enterprise namespace

// BDE_VERIFY pragma: pop

// ----------------------------------------------------------------------------
// Copyright 2014 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|>


<commit_before>
#pragma once

#include "numerics/legendre.hpp"

#include <tuple>

#include "base/macros.hpp"
#include "numerics/combinatorics.hpp"

namespace principia {
namespace numerics {
namespace internal_legendre {

template<int degree, typename>
struct LegendreCoefficientsGenerator;

template<int degree, std::size_t... indices>
struct LegendreCoefficientsGenerator<degree, std::index_sequence<indices...>> {
  // This computation follows
  // https://en.wikipedia.org/wiki/Legendre_polynomials, fourth formula in the
  // "Explicit representations" section.  The formula has been rewritten to
  // eliminate references to the Γ function.
  // TODO(phl): Document the derivation of this formula.
  static constexpr auto coefficients =
      std::make_tuple((degree - indices) % 2 == 0
                          ? ((degree - indices) % 4 == 0 ? 1 : -1) *
                                DoubleFactorial(degree + indices - 1) *
                                DoubleFactorial(degree - indices - 1) /
                                static_cast<double>(Factorial(indices) *
                                                    Factorial(degree - indices))
                          : 0 ...);
};

// Apparently, FORCE_INLINE has to be on the definition for it to work on
// namespace-level functions.
template<int degree_, template<typename, typename, int> class Evaluator>
FORCE_INLINE(constexpr)
PolynomialInMonomialBasis<double, double, degree_, Evaluator>
LegendrePolynomial() {
  auto c = LegendreCoefficientsGenerator<
          degree_,
          std::make_index_sequence<degree_ + 1>>::coefficients;
  return PolynomialInMonomialBasis<double, double, degree_, Evaluator>(
      LegendreCoefficientsGenerator<
          degree_,
          std::make_index_sequence<degree_ + 1>>::coefficients);
}

}  // namespace internal_legendre
}  // namespace numerics
}  // namespace principia
<commit_msg>Remove comment.<commit_after>
#pragma once

#include "numerics/legendre.hpp"

#include <tuple>

#include "base/macros.hpp"
#include "numerics/combinatorics.hpp"

namespace principia {
namespace numerics {
namespace internal_legendre {

template<int degree, typename>
struct LegendreCoefficientsGenerator;

template<int degree, std::size_t... indices>
struct LegendreCoefficientsGenerator<degree, std::index_sequence<indices...>> {
  // This computation follows
  // https://en.wikipedia.org/wiki/Legendre_polynomials, fourth formula in the
  // "Explicit representations" section.  The formula has been rewritten to
  // eliminate references to the Γ function.
  static constexpr auto coefficients =
      std::make_tuple((degree - indices) % 2 == 0
                          ? ((degree - indices) % 4 == 0 ? 1 : -1) *
                                DoubleFactorial(degree + indices - 1) *
                                DoubleFactorial(degree - indices - 1) /
                                static_cast<double>(Factorial(indices) *
                                                    Factorial(degree - indices))
                          : 0 ...);
};

// Apparently, FORCE_INLINE has to be on the definition for it to work on
// namespace-level functions.
template<int degree_, template<typename, typename, int> class Evaluator>
FORCE_INLINE(constexpr)
PolynomialInMonomialBasis<double, double, degree_, Evaluator>
LegendrePolynomial() {
  auto c = LegendreCoefficientsGenerator<
          degree_,
          std::make_index_sequence<degree_ + 1>>::coefficients;
  return PolynomialInMonomialBasis<double, double, degree_, Evaluator>(
      LegendreCoefficientsGenerator<
          degree_,
          std::make_index_sequence<degree_ + 1>>::coefficients);
}

}  // namespace internal_legendre
}  // namespace numerics
}  // namespace principia
<|endoftext|>


<commit_before><commit_msg>Agregando una bandera a karel.cpp para desplegar el mundo final<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: sessionlistener.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-03-29 14:55:20 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

//_______________________________________________
// my own includes

#ifndef __FRAMEWORK_SERVICES_TYPEDETECTION_HXX_
#include <services/sessionlistener.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif

#ifndef __FRAMEWORK_PROTOCOLS_H_
#include <protocols.h>
#endif

#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif

#include <osl/thread.h>

#include <vcl/svapp.hxx>
#include <tools/urlobj.hxx>
#include <tools/tempfile.hxx>
#include <unotools/tempfile.hxx>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/PropertyState.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/frame/XFramesSupplier.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <com/sun/star/frame/XDispatch.hpp>
#include <com/sun/star/util/XModifiable.hpp>
#include <com/sun/star/util/XChangesBatch.hpp>
#include <com/sun/star/util/XURLTransformer.hpp>
#include <com/sun/star/util/URL.hpp>
#include <osl/time.h>
#include <comphelper/processfactory.hxx>
#include <svtools/pathoptions.hxx>
#include <svtools/internaloptions.hxx>
#include <stdio.h>
//_______________________________________________
// interface includes

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

#include <com/sun/star/uno/Sequence.hxx>
//_______________________________________________
// includes of other projects

//_______________________________________________
// namespace

using namespace com::sun::star::uno;
using namespace com::sun::star::util;
using namespace com::sun::star::frame;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::container;

using namespace rtl;

namespace framework{

//_______________________________________________
// non exported const

//_______________________________________________
// non exported definitions

//_______________________________________________
// declarations

//***********************************************
// XInterface, XTypeProvider, XServiceInfo

DEFINE_XINTERFACE_5(
        SessionListener,
        OWeakObject,
        DIRECT_INTERFACE(css::lang::XTypeProvider),
        DIRECT_INTERFACE(css::lang::XInitialization),
        DIRECT_INTERFACE(css::frame::XSessionManagerListener),
        DIRECT_INTERFACE(css::frame::XStatusListener),
        DIRECT_INTERFACE(css::lang::XServiceInfo))

DEFINE_XTYPEPROVIDER_5(
        SessionListener,
        css::lang::XTypeProvider,
        css::lang::XInitialization,
        css::frame::XSessionManagerListener,
        css::frame::XStatusListener,
        css::lang::XServiceInfo)

DEFINE_XSERVICEINFO_ONEINSTANCESERVICE(
       SessionListener,
       cppu::OWeakObject,
       SERVICENAME_SESSIONLISTENER,
       IMPLEMENTATIONNAME_SESSIONLISTENER)

DEFINE_INIT_SERVICE(SessionListener,
                    {
                        /* Add special code for initialization here, if you have to use your own instance
                           during your ctor is still in progress! */
                    }
                   )

SessionListener::SessionListener(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR )
        : ThreadHelpBase      (&Application::GetSolarMutex())
        , OWeakObject         (                             )
        , m_xSMGR             (xSMGR                        )
        , m_cRestoreDone(osl_createCondition())
{
}

SessionListener::~SessionListener()
{
    if (m_rSessionManager.is())
    {
        css::uno::Reference< XSessionManagerListener> me(this);
        m_rSessionManager->removeSessionManagerListener(me);
    }
}

void SAL_CALL SessionListener::disposing(const com::sun::star::lang::EventObject&) throw (RuntimeException)
{
}

void SAL_CALL SessionListener::initialize(const Sequence< Any  >& args)
    throw (RuntimeException)
{

    OUString aSMgr = OUString::createFromAscii("com.sun.star.frame.SessionManagerClient");
    if (args.getLength() > 0)
    {
        NamedValue v;
        for (int i = 0; i < args.getLength(); i++)
        {
            if (args[i] >>= v)
            {
                if (v.Name.equalsAscii("SessionManagerName"))
                    v.Value >>= aSMgr;
                else if (v.Name.equalsAscii("SessionManager"))
                    v.Value >>= m_rSessionManager;
            }
        }
    }
    if (!m_rSessionManager.is())
        m_rSessionManager = Reference< XSessionManagerClient >
            (m_xSMGR->createInstance(aSMgr), UNO_QUERY);

    if (m_rSessionManager.is())
    {
        m_rSessionManager->addSessionManagerListener(this);
    }
    // configuration provider
    m_cfgProv = Reference< XMultiServiceFactory > (
            m_xSMGR->createInstance(OUString::createFromAscii(
            "com.sun.star.configuration.ConfigurationProvider")),
            UNO_QUERY_THROW);
}

void SAL_CALL SessionListener::statusChanged(const FeatureStateEvent& event)
    throw (css::uno::RuntimeException)
{
   if (event.FeatureURL.Complete.equalsAscii("vnd.sun.star.autorecovery:/doSessionRestore"))
    {
        if (event.FeatureDescriptor.compareToAscii("update")==0)
            m_bRestored = sal_True; // a document was restored
        // if (event.FeatureDescriptor.compareToAscii("stop")==0)

    }
    else if (event.FeatureURL.Complete.equalsAscii("vnd.sun.star.autorecovery:/doSessionSave"))
    {
        if (event.FeatureDescriptor.compareToAscii("stop")==0)
        {
            if (m_rSessionManager.is())
                m_rSessionManager->saveDone(this); // done with save
        }
    }
}

sal_Bool SAL_CALL SessionListener::doRestore()
    throw (RuntimeException)
{
    ResetableGuard aGuard(m_aLock);
    m_bRestored = sal_False;
    osl_resetCondition(m_cRestoreDone);
    try {
        Reference< XDispatch > xDispatch(m_xSMGR->createInstance(SERVICENAME_AUTORECOVERY), UNO_QUERY_THROW);
        // check whether there is anything to restore
        Reference< XPropertySet > xPropSet(xDispatch, UNO_QUERY_THROW);
        sal_Bool bCrash = sal_False;
        sal_Bool bRecovery = sal_False;
        xPropSet->getPropertyValue(OUString::createFromAscii("Crashed")) >>= bCrash;
        xPropSet->getPropertyValue(OUString::createFromAscii("ExistsRecoveryData")) >>= bRecovery;
        if (!bCrash && bRecovery)
        {
            URL aURL;
            aURL.Complete = OUString::createFromAscii("vnd.sun.star.autorecovery:/doSessionRestore");
            Reference< XURLTransformer > xURLTransformer(m_xSMGR->createInstance(SERVICENAME_URLTRANSFORMER), UNO_QUERY_THROW);
            xURLTransformer->parseStrict(aURL);
            Sequence< PropertyValue > args;
            xDispatch->addStatusListener(this, aURL);
            xDispatch->dispatch(aURL, args);
            m_bRestored = sal_True;
        }
    } catch (com::sun::star::uno::Exception& e) {
        OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8);
        OSL_ENSURE(sal_False, aMsg.getStr());
    }

    return m_bRestored;
}

void SAL_CALL SessionListener::doSave( sal_Bool bShutdown, sal_Bool bCancelable )
    throw (RuntimeException)
{
    if (bShutdown)
    {
        sal_Bool bDispatched = sal_False;
        ResetableGuard aGuard(m_aLock);
        try
        {
            // xd create SERVICENAME_AUTORECOVERY -> XDispatch
            // xd->dispatch("vnd.sun.star.autorecovery:/doSessionSave, async=true
            // on stop event m_rSessionManager->saveDone(this);

            Reference< XDispatch > xDispatch(m_xSMGR->createInstance(SERVICENAME_AUTORECOVERY), UNO_QUERY_THROW);
            Reference< XURLTransformer > xURLTransformer(m_xSMGR->createInstance(SERVICENAME_URLTRANSFORMER), UNO_QUERY_THROW);
            URL aURL;
            aURL.Complete = OUString::createFromAscii("vnd.sun.star.autorecovery:/doSessionSave");
            xURLTransformer->parseStrict(aURL);
            xDispatch->addStatusListener(this, aURL);
            Sequence< PropertyValue > args(1);
            args[0] = PropertyValue(OUString::createFromAscii("DispatchAsynchron"),-1,makeAny(sal_True),PropertyState_DIRECT_VALUE);
            xDispatch->dispatch(aURL, args);
            bDispatched = sal_True;
            // on stop event set call m_rSessionManager->saveDone(this);
        } catch (com::sun::star::uno::Exception& e) {
            OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8);
            OSL_ENSURE(sal_False, aMsg.getStr());
            // save failed, but tell manager to go on if we havent yet dispatched the request
            if (m_rSessionManager.is() && !bDispatched)
                m_rSessionManager->saveDone(this);
        }
    }
}

void SAL_CALL SessionListener::approveInteraction( sal_Bool bInteractionGranted )
    throw (RuntimeException)
{
    if (_pcInteract != NULL)
        osl_setCondition(*_pcInteract);
}

void SessionListener::shutdownCanceled()
    throw (RuntimeException)
{
    if (_pcCancelShutdown != NULL)
        osl_setCondition(*_pcCancelShutdown);
}

void SessionListener::_doInteraction(
        const OUString& title, const OUString& url, sal_Bool bCanceable, sal_Bool* save, sal_Bool* cancel)
{
}

sal_Bool SessionListener::_cancelShutdown()
{
    oslCondition c = osl_createCondition();
    _pcCancelShutdown = &c;
    TimeValue t;
    t.Seconds = 5;
    t.Nanosec = 0;
    m_rSessionManager->cancelShutdown();
    sal_Bool b = osl_waitCondition(c, &t);
    _pcCancelShutdown = NULL;
    osl_destroyCondition(c);
    return b;
}

sal_Bool SessionListener::_requestInteraction()
{
    oslCondition c = osl_createCondition();
    _pcInteract = &c;
    TimeValue t;
    t.Seconds = 5;
    t.Nanosec = 0;
    m_rSessionManager->queryInteraction(Reference<XSessionManagerListener>(this));
    sal_Bool b = osl_waitCondition(c, &t);
    _pcInteract = NULL;
    osl_destroyCondition(c);
    return b;
}

void SessionListener::_finishInteraction()
{
    m_rSessionManager->interactionDone(Reference< XSessionManagerListener >(this));
}

}
<commit_msg>INTEGRATION: CWS vclshowstop02 (1.3.8); FILE MERGED 2005/04/07 17:48:06 pl 1.3.8.1: #i46947# answer to session manager in any case<commit_after>/*************************************************************************
 *
 *  $RCSfile: sessionlistener.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2005-04-11 14:12:55 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
//_______________________________________________
// my own includes

#ifndef __FRAMEWORK_SERVICES_TYPEDETECTION_HXX_
#include <services/sessionlistener.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif

#ifndef __FRAMEWORK_PROTOCOLS_H_
#include <protocols.h>
#endif

#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif

#include <osl/thread.h>

#include <vcl/svapp.hxx>
#include <tools/urlobj.hxx>
#include <tools/tempfile.hxx>
#include <unotools/tempfile.hxx>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/PropertyState.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/frame/XFramesSupplier.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <com/sun/star/frame/XDispatch.hpp>
#include <com/sun/star/util/XModifiable.hpp>
#include <com/sun/star/util/XChangesBatch.hpp>
#include <com/sun/star/util/XURLTransformer.hpp>
#include <com/sun/star/util/URL.hpp>
#include <osl/time.h>
#include <comphelper/processfactory.hxx>
#include <svtools/pathoptions.hxx>
#include <svtools/internaloptions.hxx>
#include <stdio.h>
//_______________________________________________
// interface includes

#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif

#include <com/sun/star/uno/Sequence.hxx>
//_______________________________________________
// includes of other projects

//_______________________________________________
// namespace

using namespace com::sun::star::uno;
using namespace com::sun::star::util;
using namespace com::sun::star::frame;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::container;

using namespace rtl;

namespace framework{

//_______________________________________________
// non exported const

//_______________________________________________
// non exported definitions

//_______________________________________________
// declarations

//***********************************************
// XInterface, XTypeProvider, XServiceInfo

DEFINE_XINTERFACE_5(
        SessionListener,
        OWeakObject,
        DIRECT_INTERFACE(css::lang::XTypeProvider),
        DIRECT_INTERFACE(css::lang::XInitialization),
        DIRECT_INTERFACE(css::frame::XSessionManagerListener),
        DIRECT_INTERFACE(css::frame::XStatusListener),
        DIRECT_INTERFACE(css::lang::XServiceInfo))

DEFINE_XTYPEPROVIDER_5(
        SessionListener,
        css::lang::XTypeProvider,
        css::lang::XInitialization,
        css::frame::XSessionManagerListener,
        css::frame::XStatusListener,
        css::lang::XServiceInfo)

DEFINE_XSERVICEINFO_ONEINSTANCESERVICE(
       SessionListener,
       cppu::OWeakObject,
       SERVICENAME_SESSIONLISTENER,
       IMPLEMENTATIONNAME_SESSIONLISTENER)

DEFINE_INIT_SERVICE(SessionListener,
                    {
                        /* Add special code for initialization here, if you have to use your own instance
                           during your ctor is still in progress! */
                    }
                   )

SessionListener::SessionListener(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR )
        : ThreadHelpBase      (&Application::GetSolarMutex())
        , OWeakObject         (                             )
        , m_xSMGR             (xSMGR                        )
        , m_cRestoreDone(osl_createCondition())
{
}

SessionListener::~SessionListener()
{
    if (m_rSessionManager.is())
    {
        css::uno::Reference< XSessionManagerListener> me(this);
        m_rSessionManager->removeSessionManagerListener(me);
    }
}

void SAL_CALL SessionListener::disposing(const com::sun::star::lang::EventObject&) throw (RuntimeException)
{
}

void SAL_CALL SessionListener::initialize(const Sequence< Any  >& args)
    throw (RuntimeException)
{

    OUString aSMgr = OUString::createFromAscii("com.sun.star.frame.SessionManagerClient");
    if (args.getLength() > 0)
    {
        NamedValue v;
        for (int i = 0; i < args.getLength(); i++)
        {
            if (args[i] >>= v)
            {
                if (v.Name.equalsAscii("SessionManagerName"))
                    v.Value >>= aSMgr;
                else if (v.Name.equalsAscii("SessionManager"))
                    v.Value >>= m_rSessionManager;
            }
        }
    }
    if (!m_rSessionManager.is())
        m_rSessionManager = Reference< XSessionManagerClient >
            (m_xSMGR->createInstance(aSMgr), UNO_QUERY);

    if (m_rSessionManager.is())
    {
        m_rSessionManager->addSessionManagerListener(this);
    }
    // configuration provider
    m_cfgProv = Reference< XMultiServiceFactory > (
            m_xSMGR->createInstance(OUString::createFromAscii(
            "com.sun.star.configuration.ConfigurationProvider")),
            UNO_QUERY_THROW);
}

void SAL_CALL SessionListener::statusChanged(const FeatureStateEvent& event)
    throw (css::uno::RuntimeException)
{
   if (event.FeatureURL.Complete.equalsAscii("vnd.sun.star.autorecovery:/doSessionRestore"))
    {
        if (event.FeatureDescriptor.compareToAscii("update")==0)
            m_bRestored = sal_True; // a document was restored
        // if (event.FeatureDescriptor.compareToAscii("stop")==0)

    }
    else if (event.FeatureURL.Complete.equalsAscii("vnd.sun.star.autorecovery:/doSessionSave"))
    {
        if (event.FeatureDescriptor.compareToAscii("stop")==0)
        {
            if (m_rSessionManager.is())
                m_rSessionManager->saveDone(this); // done with save
        }
    }
}

sal_Bool SAL_CALL SessionListener::doRestore()
    throw (RuntimeException)
{
    ResetableGuard aGuard(m_aLock);
    m_bRestored = sal_False;
    osl_resetCondition(m_cRestoreDone);
    try {
        Reference< XDispatch > xDispatch(m_xSMGR->createInstance(SERVICENAME_AUTORECOVERY), UNO_QUERY_THROW);
        // check whether there is anything to restore
        Reference< XPropertySet > xPropSet(xDispatch, UNO_QUERY_THROW);
        sal_Bool bCrash = sal_False;
        sal_Bool bRecovery = sal_False;
        xPropSet->getPropertyValue(OUString::createFromAscii("Crashed")) >>= bCrash;
        xPropSet->getPropertyValue(OUString::createFromAscii("ExistsRecoveryData")) >>= bRecovery;
        if (!bCrash && bRecovery)
        {
            URL aURL;
            aURL.Complete = OUString::createFromAscii("vnd.sun.star.autorecovery:/doSessionRestore");
            Reference< XURLTransformer > xURLTransformer(m_xSMGR->createInstance(SERVICENAME_URLTRANSFORMER), UNO_QUERY_THROW);
            xURLTransformer->parseStrict(aURL);
            Sequence< PropertyValue > args;
            xDispatch->addStatusListener(this, aURL);
            xDispatch->dispatch(aURL, args);
            m_bRestored = sal_True;
        }
    } catch (com::sun::star::uno::Exception& e) {
        OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8);
        OSL_ENSURE(sal_False, aMsg.getStr());
    }

    return m_bRestored;
}

void SAL_CALL SessionListener::doSave( sal_Bool bShutdown, sal_Bool bCancelable )
    throw (RuntimeException)
{
    if (bShutdown)
    {
        sal_Bool bDispatched = sal_False;
        ResetableGuard aGuard(m_aLock);
        try
        {
            // xd create SERVICENAME_AUTORECOVERY -> XDispatch
            // xd->dispatch("vnd.sun.star.autorecovery:/doSessionSave, async=true
            // on stop event m_rSessionManager->saveDone(this);

            Reference< XDispatch > xDispatch(m_xSMGR->createInstance(SERVICENAME_AUTORECOVERY), UNO_QUERY_THROW);
            Reference< XURLTransformer > xURLTransformer(m_xSMGR->createInstance(SERVICENAME_URLTRANSFORMER), UNO_QUERY_THROW);
            URL aURL;
            aURL.Complete = OUString::createFromAscii("vnd.sun.star.autorecovery:/doSessionSave");
            xURLTransformer->parseStrict(aURL);
            xDispatch->addStatusListener(this, aURL);
            Sequence< PropertyValue > args(1);
            args[0] = PropertyValue(OUString::createFromAscii("DispatchAsynchron"),-1,makeAny(sal_True),PropertyState_DIRECT_VALUE);
            xDispatch->dispatch(aURL, args);
            bDispatched = sal_True;
            // on stop event set call m_rSessionManager->saveDone(this);
        } catch (com::sun::star::uno::Exception& e) {
            OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8);
            OSL_ENSURE(sal_False, aMsg.getStr());
            // save failed, but tell manager to go on if we havent yet dispatched the request
            if (m_rSessionManager.is() && !bDispatched)
                m_rSessionManager->saveDone(this);
        }
    }
    // we don't have anything to do so tell the session manager we're done
    else if( m_rSessionManager.is() )
        m_rSessionManager->saveDone( this );
}

void SAL_CALL SessionListener::approveInteraction( sal_Bool bInteractionGranted )
    throw (RuntimeException)
{
    if (_pcInteract != NULL)
        osl_setCondition(*_pcInteract);
}

void SessionListener::shutdownCanceled()
    throw (RuntimeException)
{
    if (_pcCancelShutdown != NULL)
        osl_setCondition(*_pcCancelShutdown);
}

void SessionListener::_doInteraction(
        const OUString& title, const OUString& url, sal_Bool bCanceable, sal_Bool* save, sal_Bool* cancel)
{
}

sal_Bool SessionListener::_cancelShutdown()
{
    oslCondition c = osl_createCondition();
    _pcCancelShutdown = &c;
    TimeValue t;
    t.Seconds = 5;
    t.Nanosec = 0;
    m_rSessionManager->cancelShutdown();
    sal_Bool b = osl_waitCondition(c, &t);
    _pcCancelShutdown = NULL;
    osl_destroyCondition(c);
    return b;
}

sal_Bool SessionListener::_requestInteraction()
{
    oslCondition c = osl_createCondition();
    _pcInteract = &c;
    TimeValue t;
    t.Seconds = 5;
    t.Nanosec = 0;
    m_rSessionManager->queryInteraction(Reference<XSessionManagerListener>(this));
    sal_Bool b = osl_waitCondition(c, &t);
    _pcInteract = NULL;
    osl_destroyCondition(c);
    return b;
}

void SessionListener::_finishInteraction()
{
    m_rSessionManager->interactionDone(Reference< XSessionManagerListener >(this));
}

}
<|endoftext|>


<commit_before>/*
 * socials.cpp
 *   Functions for social(s)
 *   ____            _
 *  |  _ \ ___  __ _| |_ __ ___  ___
 *  | |_) / _ \/ _` | | '_ ` _ \/ __|
 *  |  _ <  __/ (_| | | | | | | \__ \
 *  |_| \_\___|\__,_|_|_| |_| |_|___/
 *
 * Permission to use, modify and distribute is granted via the
 *  GNU Affero General Public License v3 or later
 *
 *  Copyright (C) 2007-2021 Jason Mitchell, Randi Mitchell
 *     Contributions by Tim Callahan, Jonathan Hseu
 *  Based on Mordor (C) Brooke Paul, Brett J. Vickers, John P. Freeman
 *
 */

#include <boost/algorithm/string/replace.hpp>  // for replace_all
#include <boost/iterator/iterator_traits.hpp>  // for iterator_value<>::type
#include <cassert>                             // for assert
#include <deque>                               // for _Deque_iterator
#include <functional>                          // for function
#include <set>                                 // for operator==, _Rb_tree_c...
#include <string>                              // for string, allocator, ope...
#include <string_view>                         // for string_view

#include "cmd.hpp"                             // for cmd
#include "commands.hpp"                        // for orderPet, cmdSocial
#include "config.hpp"                          // for Config, SocialSet
#include "creatureStreams.hpp"                 // for Streamable
#include "flags.hpp"                           // for P_AFK, P_SLEEPING
#include "global.hpp"                          // for CAP
#include "mudObjects/container.hpp"            // for Container, PlayerSet
#include "mudObjects/creatures.hpp"            // for Creature
#include "mudObjects/players.hpp"              // for Player
#include "proto.hpp"                           // for socialHooks, actionShow
#include "socials.hpp"                         // for SocialCommand
#include "structs.hpp"                         // for Command

void Config::clearSocials() {
    socials.clear();
}

bool SocialCommand::getWakeTarget() const {
    return(wakeTarget);
}
bool SocialCommand::getRudeWakeTarget() const {
    return(rudeWakeTarget);
}
bool SocialCommand::getWakeRoom() const {
    return(wakeRoom);
}

std::string_view SocialCommand::getSelfNoTarget() const  {
    return(selfNoTarget);
}
std::string_view SocialCommand::getRoomNoTarget() const {
    return(roomNoTarget);
}

std::string_view SocialCommand::getSelfOnTarget() const {
    return(selfOnTarget);
}
std::string_view SocialCommand::getRoomOnTarget() const {
    return(roomOnTarget);
}
std::string_view SocialCommand::getVictimOnTarget() const {
    return(victimOnTarget);
}

std::string_view SocialCommand::getSelfOnSelf() const {
    return(selfOnSelf);
}
std::string_view SocialCommand::getRoomOnSelf() const {
    return(roomOnSelf);
}

int cmdSocial(Creature* creature, cmd* cmnd) {
    Container* parent = creature->getParent();

    assert(parent);

    Player  *player=nullptr, *pTarget=nullptr;
    Creature* target=nullptr;

    player = creature->getAsPlayer();
    if(!creature->ableToDoCommand(cmnd))
        return(0);

    std::string str = cmnd->myCommand->getName();
    auto* social = dynamic_cast<const SocialCommand*>(cmnd->myCommand);

    if(!social)
        return(0);

    if(player) {
        creature->clearFlag(P_AFK);

        if(str != "sleep")
            player->unhide();

        // if they have a pet, they use orderPet instead
        if(str == "pet" && player->hasPet()) {
            return(orderPet(player, cmnd));
        }
    }

    if(cmnd->num == 2) {
        target = parent->findCreature(creature, cmnd->str[1], cmnd->val[1], true, true);
        if(target)
            pTarget = target->getAsPlayer();
        if( (!target || target == creature) )
        {
            *creature << "That is not here.\n";
            return(player ? 0 : 1);
        }
    }

    if(pTarget && pTarget->flagIsSet(P_SLEEPING)) {
        if(social->getRudeWakeTarget())
            pTarget->wake("You awaken suddenly!");
        else if(social->getWakeTarget())
            pTarget->wake("You wake up.");
    }
    if(social->getWakeRoom())
        parent->wake("You awaken suddenly!", true);

    if(target && !social->getSelfOnTarget().empty()) {
        // Social on Target

        std::string toSelf = std::string(social->getSelfOnTarget());
        boost::replace_all(toSelf,"*TARGET*", target->getCrtStr(creature));
        boost::replace_all(toSelf,"*VICTIM*", target->getCrtStr(creature));
        *creature << toSelf << "\n";

        if(actionShow(pTarget, creature)) {
            std::string toTarget = std::string(social->getVictimOnTarget());
            boost::replace_all(toTarget, "*A-HISHER*", creature->hisHer());
            boost::replace_all(toTarget, "*A-HIMHER*", creature->himHer());
            boost::replace_all(toTarget, "*A-HESHE*", creature->heShe());
            boost::replace_all(toTarget, "*ACTOR*", creature->getCrtStr(target, CAP));

            *target << toTarget << "\n";
        }

        std::string toRoom = std::string(social->getRoomOnTarget());
        parent->doSocialEcho(toRoom, creature, target);

        socialHooks(creature, target, str);
    } else {
        // Social no target

        *creature << social->getSelfNoTarget() << "\n";

        std::string toRoom = std::string(social->getRoomNoTarget());

        if(!toRoom.empty() && parent) {
            parent->doSocialEcho(toRoom, creature, target);
            socialHooks(creature, str);
        }

    }

    return(0);
}

void Container::doSocialEcho(std::string str, const Creature* actor, const Creature* target) {
    if(str.empty() || !actor)
        return;
    boost::replace_all(str, "*A-HISHER*", actor->hisHer());
    boost::replace_all(str, "*A-HIMHER*", actor->himHer());
    boost::replace_all(str, "*A-HESHE*", actor->heShe());

    for(Player* ply : players) {
        if(ply == actor || ply == target) continue;

        std::string out = str;
        boost::replace_all(out, "*ACTOR*", actor->getCrtStr(ply, CAP));
        if(target) {
            boost::replace_all(out, "*TARGET*", target->getCrtStr(ply));
            boost::replace_all(out, "*VICTIM*", target->getCrtStr(ply));
        }
        *ply << out << "\n";
    }

}

int SocialCommand::execute(Creature* player, cmd* cmnd) const {
    return((fn)(player, cmnd));
}
<commit_msg>add *A-UPHESHE* to socials (#101)<commit_after>/*
 * socials.cpp
 *   Functions for social(s)
 *   ____            _
 *  |  _ \ ___  __ _| |_ __ ___  ___
 *  | |_) / _ \/ _` | | '_ ` _ \/ __|
 *  |  _ <  __/ (_| | | | | | | \__ \
 *  |_| \_\___|\__,_|_|_| |_| |_|___/
 *
 * Permission to use, modify and distribute is granted via the
 *  GNU Affero General Public License v3 or later
 *
 *  Copyright (C) 2007-2021 Jason Mitchell, Randi Mitchell
 *     Contributions by Tim Callahan, Jonathan Hseu
 *  Based on Mordor (C) Brooke Paul, Brett J. Vickers, John P. Freeman
 *
 */

#include <boost/algorithm/string/replace.hpp>  // for replace_all
#include <boost/iterator/iterator_traits.hpp>  // for iterator_value<>::type
#include <cassert>                             // for assert
#include <deque>                               // for _Deque_iterator
#include <functional>                          // for function
#include <set>                                 // for operator==, _Rb_tree_c...
#include <string>                              // for string, allocator, ope...
#include <string_view>                         // for string_view

#include "cmd.hpp"                             // for cmd
#include "commands.hpp"                        // for orderPet, cmdSocial
#include "config.hpp"                          // for Config, SocialSet
#include "creatureStreams.hpp"                 // for Streamable
#include "flags.hpp"                           // for P_AFK, P_SLEEPING
#include "global.hpp"                          // for CAP
#include "mudObjects/container.hpp"            // for Container, PlayerSet
#include "mudObjects/creatures.hpp"            // for Creature
#include "mudObjects/players.hpp"              // for Player
#include "proto.hpp"                           // for socialHooks, actionShow
#include "socials.hpp"                         // for SocialCommand
#include "structs.hpp"                         // for Command

void Config::clearSocials() {
    socials.clear();
}

bool SocialCommand::getWakeTarget() const {
    return(wakeTarget);
}
bool SocialCommand::getRudeWakeTarget() const {
    return(rudeWakeTarget);
}
bool SocialCommand::getWakeRoom() const {
    return(wakeRoom);
}

std::string_view SocialCommand::getSelfNoTarget() const  {
    return(selfNoTarget);
}
std::string_view SocialCommand::getRoomNoTarget() const {
    return(roomNoTarget);
}

std::string_view SocialCommand::getSelfOnTarget() const {
    return(selfOnTarget);
}
std::string_view SocialCommand::getRoomOnTarget() const {
    return(roomOnTarget);
}
std::string_view SocialCommand::getVictimOnTarget() const {
    return(victimOnTarget);
}

std::string_view SocialCommand::getSelfOnSelf() const {
    return(selfOnSelf);
}
std::string_view SocialCommand::getRoomOnSelf() const {
    return(roomOnSelf);
}

int cmdSocial(Creature* creature, cmd* cmnd) {
    Container* parent = creature->getParent();

    assert(parent);

    Player  *player=nullptr, *pTarget=nullptr;
    Creature* target=nullptr;

    player = creature->getAsPlayer();
    if(!creature->ableToDoCommand(cmnd))
        return(0);

    std::string str = cmnd->myCommand->getName();
    auto* social = dynamic_cast<const SocialCommand*>(cmnd->myCommand);

    if(!social)
        return(0);

    if(player) {
        creature->clearFlag(P_AFK);

        if(str != "sleep")
            player->unhide();

        // if they have a pet, they use orderPet instead
        if(str == "pet" && player->hasPet()) {
            return(orderPet(player, cmnd));
        }
    }

    if(cmnd->num == 2) {
        target = parent->findCreature(creature, cmnd->str[1], cmnd->val[1], true, true);
        if(target)
            pTarget = target->getAsPlayer();
        if( (!target || target == creature) )
        {
            *creature << "That is not here.\n";
            return(player ? 0 : 1);
        }
    }

    if(pTarget && pTarget->flagIsSet(P_SLEEPING)) {
        if(social->getRudeWakeTarget())
            pTarget->wake("You awaken suddenly!");
        else if(social->getWakeTarget())
            pTarget->wake("You wake up.");
    }
    if(social->getWakeRoom())
        parent->wake("You awaken suddenly!", true);

    if(target && !social->getSelfOnTarget().empty()) {
        // Social on Target

        std::string toSelf = std::string(social->getSelfOnTarget());
        boost::replace_all(toSelf,"*TARGET*", target->getCrtStr(creature));
        boost::replace_all(toSelf,"*VICTIM*", target->getCrtStr(creature));
        *creature << toSelf << "\n";

        if(actionShow(pTarget, creature)) {
            std::string toTarget = std::string(social->getVictimOnTarget());
            boost::replace_all(toTarget, "*A-HISHER*", creature->hisHer());
            boost::replace_all(toTarget, "*A-HIMHER*", creature->himHer());
            boost::replace_all(toTarget, "*A-HESHE*", creature->heShe());
            boost::replace_all(toTarget, "*A-UPHESHE*", creature->upHeShe());
            boost::replace_all(toTarget, "*ACTOR*", creature->getCrtStr(target, CAP));

            *target << toTarget << "\n";
        }

        std::string toRoom = std::string(social->getRoomOnTarget());
        parent->doSocialEcho(toRoom, creature, target);

        socialHooks(creature, target, str);
    } else {
        // Social no target

        *creature << social->getSelfNoTarget() << "\n";

        std::string toRoom = std::string(social->getRoomNoTarget());

        if(!toRoom.empty() && parent) {
            parent->doSocialEcho(toRoom, creature, target);
            socialHooks(creature, str);
        }

    }

    return(0);
}

void Container::doSocialEcho(std::string str, const Creature* actor, const Creature* target) {
    if(str.empty() || !actor)
        return;
    boost::replace_all(str, "*A-HISHER*", actor->hisHer());
    boost::replace_all(str, "*A-HIMHER*", actor->himHer());
    boost::replace_all(str, "*A-HESHE*", actor->heShe());
    boost::replace_all(str, "*A-UPHESHE*", actor->upHeShe());

    for(Player* ply : players) {
        if(ply == actor || ply == target) continue;

        std::string out = str;
        boost::replace_all(out, "*ACTOR*", actor->getCrtStr(ply, CAP));
        if(target) {
            boost::replace_all(out, "*TARGET*", target->getCrtStr(ply));
            boost::replace_all(out, "*VICTIM*", target->getCrtStr(ply));
        }
        *ply << out << "\n";
    }

}

int SocialCommand::execute(Creature* player, cmd* cmnd) const {
    return((fn)(player, cmnd));
}
<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file JPetTaskIO.cpp
 */

#include "JPetTaskIO.h"
#include <cassert>
#include "../JPetReader/JPetReader.h"
#include "../JPetTreeHeader/JPetTreeHeader.h"
#include "../JPetTask/JPetTask.h"
#include "../JPetHLDReader/JPetHLDReader.h"
#include "../JPetCommonTools/JPetCommonTools.h"

#include "../JPetLoggerInclude.h"

JPetTaskIO::JPetTaskIO():
  fTask(0),
  fEventNb(-1),
  fWriter(0),
  fReader(0),
  fHeader(0),
  fStatistics(0),
  fParamManager(0)
{
}

void JPetTaskIO::init(const JPetOptions::Options& opts)
{
  setOptions(JPetOptions(opts));
  auto inputFilename = fOptions.getInputFile();
  auto outputFilename = fOptions.getOutputFile();
  createInputObjects(inputFilename);
  createOutputObjects(outputFilename);
}

void JPetTaskIO::exec()
{
  assert(fTask);
  assert(fReader);
  assert(fParamManager);
  fTask->setParamManager(fParamManager);
  JPetTaskInterface::Options emptyOpts;
  fTask->init(emptyOpts); //prepare current task for file
  auto totalEvents = 0ll;
  if (fReader) {
    totalEvents = fReader->getNbOfAllEvents();
  } else {
    WARNING("no JPETReader set totalEvents set to -1");
    totalEvents = -1;
  }
  auto firstEvent = 0ll;
  auto lastEvent = 0ll;
  setUserLimits(fOptions, totalEvents,  firstEvent, lastEvent);
  assert(lastEvent >= 0);
  for (auto i = firstEvent; i <= lastEvent; i++) {
    fTask->setEvent(&(static_cast<TNamed&>(fReader->getCurrentEvent())));
    if (fOptions.isProgressBar()) {
      manageProgressBar(i, lastEvent);
    }
    fTask->exec();
    fReader->nextEvent();
  }
  fTask->terminate();
}

void JPetTaskIO::terminate()
{
  assert(fReader);
  assert(fWriter);
  assert(fHeader);
  assert(fStatistics);

  fWriter->writeHeader(fHeader);

  fWriter->writeObject(fStatistics->getHistogramsTable(), "Stats");

  // store the parametric objects in the ouptut ROOT file
  getParamManager().saveParametersToFile(
    fWriter);
  getParamManager().clearParameters();

  fWriter->closeFile();
  fReader->closeFile();

}
void JPetTaskIO::addSubTask(JPetTaskInterface* subtask) {
	fTask = dynamic_cast<JPetTask*>(subtask);
}
JPetTask* JPetTaskIO::getSubTask() const {
	return fTask;
}

void JPetTaskIO::setOptions(const JPetOptions& opts) {
	fOptions = opts;
}
void JPetTaskIO::setParamManager(JPetParamManager* paramManager) {
	fParamManager = paramManager;
}
JPetParamManager& JPetTaskIO::getParamManager() {
	return *fParamManager;
}

void JPetTaskIO::createInputObjects(const char* inputFilename)
{
  auto treeName = "";
  if (fOptions.getInputFileType() == JPetOptions::kHld ) {
    fReader = new JPetHLDReader;
    treeName = "T";
  } else {
    fReader = new JPetReader;
    treeName = "tree";
  }
  if ( fReader->openFileAndLoadData( inputFilename, treeName )) {
    if (fOptions.getInputFileType() == JPetOptions::kHld ) {
      // create a header to be stored along with the output tree
      fHeader = new JPetTreeHeader(fOptions.getRunNumber());

      // add general info to the Tree header
      fHeader->setBaseFileName(fOptions.getInputFile());

    } else {
      assert(fParamManager);
      fParamManager->readParametersFromFile(dynamic_cast<JPetReader*> (fReader));
      // read the header from the previous analysis stage
      //
      fHeader = dynamic_cast<JPetReader*>(fReader)->getHeaderClone();
      //fParamManager.readParametersFromFile( fReader );
    }
    // create an object for storing histograms and counters during processing
    fStatistics = new JPetStatistics();

    // add info about this module to the processing stages' history in Tree header
    fHeader->addStageInfo(fTask->GetName(), fTask->GetTitle(), 0,
			  JPetCommonTools::getTimeString());

  } else {
    ERROR(inputFilename + std::string(": Unable to open the input file or load the tree"));
    exit(-1);
  }
}

void JPetTaskIO::createOutputObjects(const char* outputFilename)
{
  fWriter = new JPetWriter( outputFilename );
  assert(fWriter);
  if (fTask) {
    fTask->setWriter(fWriter);
    fTask->setStatistics(fStatistics);
  } else {
    WARNING("the subTask does not exist, so Write was not passed to it");
  }
}

void JPetTaskIO::manageProgressBar(long long done, long long end)
{
  printf("\r[%6.4f%% %%]", setProgressBar(done, end));
}

float JPetTaskIO::setProgressBar(int currentEventNumber, int numberOfEvents)
{
  return ( ((float)currentEventNumber) / numberOfEvents ) * 100;
}

const JPetParamBank& JPetTaskIO::getParamBank()
{
  return fParamManager->getParamBank();
}

JPetTaskIO::~JPetTaskIO()
{
  if (fTask) delete fTask;
  if (fWriter) delete fWriter;
  if (fReader) delete fReader;
}

/// Sets values of firstEvent and lastEvent based on user options opts and total number of events from JPetReader
// if the totEventsFromReader is less than 0, than first and last are set to -1.
void JPetTaskIO::setUserLimits(const JPetOptions& opts, const long long kTotEventsFromReader, long long& first, long long& last) const
{
  const auto kLastEvent = opts.getLastEvent();
  const auto kFirstEvent = opts.getFirstEvent();
  if ( kTotEventsFromReader < 1) {
    WARNING("kTotEvetnsFromReader < 1, first and last set to -1");
    first = last = -1;
  } else {
    if ( kFirstEvent < 0) {
      first = 0;
    } else {
      first = kFirstEvent < kTotEventsFromReader ? kFirstEvent : kTotEventsFromReader - 1;
    }
    if (kLastEvent < 0)  {
      last = kTotEventsFromReader - 1;
    } else {
      last = kLastEvent < kTotEventsFromReader ? kLastEvent : kTotEventsFromReader - 1;
    }
  }
  assert(first >= 0);
  assert(last >= 0);
  assert(first <= last);
}
<commit_msg>GetParamManager() method checks now if JPetParamManager is created, if it is not a case returns reference to  JPetParamManager NullObject<commit_after>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file JPetTaskIO.cpp
 */

#include "JPetTaskIO.h"
#include <cassert>
#include "../JPetReader/JPetReader.h"
#include "../JPetTreeHeader/JPetTreeHeader.h"
#include "../JPetTask/JPetTask.h"
#include "../JPetHLDReader/JPetHLDReader.h"
#include "../JPetCommonTools/JPetCommonTools.h"

#include "../JPetLoggerInclude.h"

JPetTaskIO::JPetTaskIO():
  fTask(0),
  fEventNb(-1),
  fWriter(0),
  fReader(0),
  fHeader(0),
  fStatistics(0),
  fParamManager(0)
{
}

void JPetTaskIO::init(const JPetOptions::Options& opts)
{
  setOptions(JPetOptions(opts));
  auto inputFilename = fOptions.getInputFile();
  auto outputFilename = fOptions.getOutputFile();
  createInputObjects(inputFilename);
  createOutputObjects(outputFilename);
}

void JPetTaskIO::exec()
{
  assert(fTask);
  assert(fReader);
  assert(fParamManager);
  fTask->setParamManager(fParamManager);
  JPetTaskInterface::Options emptyOpts;
  fTask->init(emptyOpts); //prepare current task for file
  auto totalEvents = 0ll;
  if (fReader) {
    totalEvents = fReader->getNbOfAllEvents();
  } else {
    WARNING("no JPETReader set totalEvents set to -1");
    totalEvents = -1;
  }
  auto firstEvent = 0ll;
  auto lastEvent = 0ll;
  setUserLimits(fOptions, totalEvents,  firstEvent, lastEvent);
  assert(lastEvent >= 0);
  for (auto i = firstEvent; i <= lastEvent; i++) {
    fTask->setEvent(&(static_cast<TNamed&>(fReader->getCurrentEvent())));
    if (fOptions.isProgressBar()) {
      manageProgressBar(i, lastEvent);
    }
    fTask->exec();
    fReader->nextEvent();
  }
  fTask->terminate();
}

void JPetTaskIO::terminate()
{
  assert(fReader);
  assert(fWriter);
  assert(fHeader);
  assert(fStatistics);

  fWriter->writeHeader(fHeader);

  fWriter->writeObject(fStatistics->getHistogramsTable(), "Stats");

  // store the parametric objects in the ouptut ROOT file
  getParamManager().saveParametersToFile(
    fWriter);
  getParamManager().clearParameters();

  fWriter->closeFile();
  fReader->closeFile();

}
void JPetTaskIO::addSubTask(JPetTaskInterface* subtask) {
	fTask = dynamic_cast<JPetTask*>(subtask);
}
JPetTask* JPetTaskIO::getSubTask() const {
	return fTask;
}

void JPetTaskIO::setOptions(const JPetOptions& opts) {
	fOptions = opts;
}
void JPetTaskIO::setParamManager(JPetParamManager* paramManager) {
	fParamManager = paramManager;
}

JPetParamManager& JPetTaskIO::getParamManager() {
  static JPetParamManager NullManager(true);
  if (fParamManager) return *fParamManager;
  else return NullManager;
}

void JPetTaskIO::createInputObjects(const char* inputFilename)
{
  auto treeName = "";
  if (fOptions.getInputFileType() == JPetOptions::kHld ) {
    fReader = new JPetHLDReader;
    treeName = "T";
  } else {
    fReader = new JPetReader;
    treeName = "tree";
  }
  if ( fReader->openFileAndLoadData( inputFilename, treeName )) {
    if (fOptions.getInputFileType() == JPetOptions::kHld ) {
      // create a header to be stored along with the output tree
      fHeader = new JPetTreeHeader(fOptions.getRunNumber());

      // add general info to the Tree header
      fHeader->setBaseFileName(fOptions.getInputFile());

    } else {
      assert(fParamManager);
      fParamManager->readParametersFromFile(dynamic_cast<JPetReader*> (fReader));
      // read the header from the previous analysis stage
      //
      fHeader = dynamic_cast<JPetReader*>(fReader)->getHeaderClone();
      //fParamManager.readParametersFromFile( fReader );
    }
    // create an object for storing histograms and counters during processing
    fStatistics = new JPetStatistics();

    // add info about this module to the processing stages' history in Tree header
    fHeader->addStageInfo(fTask->GetName(), fTask->GetTitle(), 0,
			  JPetCommonTools::getTimeString());

  } else {
    ERROR(inputFilename + std::string(": Unable to open the input file or load the tree"));
    exit(-1);
  }
}

void JPetTaskIO::createOutputObjects(const char* outputFilename)
{
  fWriter = new JPetWriter( outputFilename );
  assert(fWriter);
  if (fTask) {
    fTask->setWriter(fWriter);
    fTask->setStatistics(fStatistics);
  } else {
    WARNING("the subTask does not exist, so Write was not passed to it");
  }
}

void JPetTaskIO::manageProgressBar(long long done, long long end)
{
  printf("\r[%6.4f%% %%]", setProgressBar(done, end));
}

float JPetTaskIO::setProgressBar(int currentEventNumber, int numberOfEvents)
{
  return ( ((float)currentEventNumber) / numberOfEvents ) * 100;
}

const JPetParamBank& JPetTaskIO::getParamBank()
{
  return fParamManager->getParamBank();
}

JPetTaskIO::~JPetTaskIO()
{
  if (fTask) delete fTask;
  if (fWriter) delete fWriter;
  if (fReader) delete fReader;
}

/// Sets values of firstEvent and lastEvent based on user options opts and total number of events from JPetReader
// if the totEventsFromReader is less than 0, than first and last are set to -1.
void JPetTaskIO::setUserLimits(const JPetOptions& opts, const long long kTotEventsFromReader, long long& first, long long& last) const
{
  const auto kLastEvent = opts.getLastEvent();
  const auto kFirstEvent = opts.getFirstEvent();
  if ( kTotEventsFromReader < 1) {
    WARNING("kTotEvetnsFromReader < 1, first and last set to -1");
    first = last = -1;
  } else {
    if ( kFirstEvent < 0) {
      first = 0;
    } else {
      first = kFirstEvent < kTotEventsFromReader ? kFirstEvent : kTotEventsFromReader - 1;
    }
    if (kLastEvent < 0)  {
      last = kTotEventsFromReader - 1;
    } else {
      last = kLastEvent < kTotEventsFromReader ? kLastEvent : kTotEventsFromReader - 1;
    }
  }
  assert(first >= 0);
  assert(last >= 0);
  assert(first <= last);
}
<|endoftext|>


<commit_before>/*
 * jcom.hub - internals
 * manage internal objects that are hosted within the hub for a module
 * By Tim Place, Copyright  2007
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#include "jcom.hub.h"

class hubInternalObject {
	private:
	t_object	*theObject;

	public:
	method		action;

	hubInternalObject(char *classname, char *subscribername, char *subscribertype, char *ramptype, char *description)
	{
		t_atom		a[7];

		theObject = NULL;
		atom_setsym(a+0, gensym(subscribername));
		atom_setsym(a+1, gensym("@type"));
		atom_setsym(a+2, gensym(subscribertype));
		atom_setsym(a+3, gensym("@ramp/drive"));
		atom_setsym(a+4, gensym(ramptype));
		atom_setsym(a+5, gensym("@description"));
		atom_setsym(a+6, gensym(description));
		jcom_core_loadextern(gensym(classname), 7, a, &theObject);
	}

	~hubInternalObject()
	{
		object_free(theObject);
	}
};

void hub_internals_create(t_hub *x)
{
	hubInternalObject	*anObject;

	x->hash_internals = hashtab_new(0);

	anObject = new hubInternalObject("jcom.message", 	"init",						"msg_none",		"none",	"Initialize a module completely to the original state.");
	anObject->action = (method)hub_init;
	hashtab_store(x->hash_internals, gensym("init"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"documentation/generate",	"msg_none",		"none",	"Generate a documentation page for this module and save it to disk.");
	anObject->action = (method)hub_autodoc;
	hashtab_store(x->hash_internals, gensym("documentation/generate"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"module/view_internals",	"msg_none",		"none",	"Attempts to open the internal algorithm for viewing.  This works for most modules.  Some modules may choose to cloak the algorithms - preventing this message from functioning.");
	anObject->action = (method)hub_module_view_alg;
	hashtab_store(x->hash_internals, gensym("module/view_internals"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/read",				"msg_symbol",	"none",	"Open an xml-preset file and recall the first preset in that file.  An optional argument defines the file to open.");
	anObject->action = (method)hub_preset_read;
	hashtab_store(x->hash_internals, gensym("preset/read"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/write",				"msg_symbol",	"none",	"Write an xml-preset file to disk.  An optional argument defines the file to open.");
	anObject->action = (method)hub_preset_write;
	hashtab_store(x->hash_internals, gensym("preset/write"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/recall",			"msg_generic",	"none",	"Recall a preset by number - you can also choose presets from the module menu.");
	anObject->action = (method)hub_preset_recall;
	hashtab_store(x->hash_internals, gensym("preset/recall"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/copy",				"msg_list",		"none",	"Create a new preset (2nd argument) by copying the contents of another preset (1st argument)");
	anObject->action = (method)hub_preset_copy;
	hashtab_store(x->hash_internals, gensym("preset/copy"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/store",				"msg_list",		"none",	"Store a preset by number in memory.  All presets present in memory will be written to disk when you send a save_settings message to the module.");
	anObject->action = (method)hub_preset_store;
	hashtab_store(x->hash_internals, gensym("preset/store"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/storenext",			"msg_list",		"none",	"Store a preset in the next preset slot.  Handy so that you do not need to specify a preset number manually.");
	anObject->action = (method)hub_preset_store_next;
	hashtab_store(x->hash_internals, gensym("preset/storenext"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/interpolate",		"msg_list",		"none",	"Interpolate between two named presets (argument 1 and 2) using a ratio (float in the range [0.0, 1.0]) specified as the third argument.");
	anObject->action = (method)hub_preset_interpolate;
	hashtab_store(x->hash_internals, gensym("preset/interpolate"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/default",			"msg_none",		"none",	"Open the default preset file and recall the first preset in that file.");
	anObject->action = (method)hub_preset_default;
	hashtab_store(x->hash_internals, gensym("preset/default"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/clear",				"msg_none",		"none",	"Clears all presets, providing a blank slate for saving new presets.");
	anObject->action = (method)hub_presets_clear;
	hashtab_store(x->hash_internals, gensym("preset/clear"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/post",				"msg_none",		"none",	"Post all presets to the Max window.");
	anObject->action = (method)hub_presets_dump;
	hashtab_store(x->hash_internals, gensym("preset/post"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.parameter",	"ui/freeze",				"msg_toggle",	"none",	"Turn off the updating of user interface elements when parameters change.  This may be done to conserve CPU resources.");
	anObject->action = (method)hub_ui_freeze;
	hashtab_store(x->hash_internals, gensym("ui/freeze"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"ui/refresh",				"msg_none",		"none",	"Update displayed values for module to reflect current state.");
	anObject->action = (method)hub_ui_refresh;
	hashtab_store(x->hash_internals, gensym("ui/refresh"), (t_object*)anObject);
}

void hub_internals_destroy(t_hub *x)
{
	long				i;
	long				numKeys = 0;
	t_symbol			**keys = NULL;
	hubInternalObject	*anObject;
	t_max_err			err;

	hashtab_getkeys(x->hash_internals, &numKeys, &keys);
	for(i=0; i<numKeys; i++){
		err = hashtab_lookup(x->hash_internals, keys[i], (t_object**)&anObject);
		if(!err)
			delete anObject;
	}
	/* XXX Should we free keys here since it's memory must have been alloced in hashtab_getkeys()?? */
	//if(keys)
	//	sysmem_freeptr(keys);

	hashtab_chuck(x->hash_internals);
}

void hub_internals_dispatch(t_hub *x, t_symbol *osc_name, long argc, t_atom *argv)
{
	hubInternalObject	*theObject;
	t_max_err			err;

	err = hashtab_lookup(x->hash_internals, osc_name, (t_object**)&theObject);
	if(!err)
		theObject->action(x, osc_name, argc, argv);
}

<commit_msg>free alloced hashtab keys<commit_after>/*
 * jcom.hub - internals
 * manage internal objects that are hosted within the hub for a module
 * By Tim Place, Copyright  2007
 *
 * License: This code is licensed under the terms of the GNU LGPL
 * http://www.gnu.org/licenses/lgpl.html
 */

#include "jcom.hub.h"

class hubInternalObject {
	private:
	t_object	*theObject;

	public:
	method		action;

	hubInternalObject(char *classname, char *subscribername, char *subscribertype, char *ramptype, char *description)
	{
		t_atom		a[7];

		theObject = NULL;
		atom_setsym(a+0, gensym(subscribername));
		atom_setsym(a+1, gensym("@type"));
		atom_setsym(a+2, gensym(subscribertype));
		atom_setsym(a+3, gensym("@ramp/drive"));
		atom_setsym(a+4, gensym(ramptype));
		atom_setsym(a+5, gensym("@description"));
		atom_setsym(a+6, gensym(description));
		jcom_core_loadextern(gensym(classname), 7, a, &theObject);
	}

	~hubInternalObject()
	{
		object_free(theObject);
	}
};

void hub_internals_create(t_hub *x)
{
	hubInternalObject	*anObject;

	x->hash_internals = hashtab_new(0);

	anObject = new hubInternalObject("jcom.message", 	"init",						"msg_none",		"none",	"Initialize a module completely to the original state.");
	anObject->action = (method)hub_init;
	hashtab_store(x->hash_internals, gensym("init"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"documentation/generate",	"msg_none",		"none",	"Generate a documentation page for this module and save it to disk.");
	anObject->action = (method)hub_autodoc;
	hashtab_store(x->hash_internals, gensym("documentation/generate"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"module/view_internals",	"msg_none",		"none",	"Attempts to open the internal algorithm for viewing.  This works for most modules.  Some modules may choose to cloak the algorithms - preventing this message from functioning.");
	anObject->action = (method)hub_module_view_alg;
	hashtab_store(x->hash_internals, gensym("module/view_internals"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/read",				"msg_symbol",	"none",	"Open an xml-preset file and recall the first preset in that file.  An optional argument defines the file to open.");
	anObject->action = (method)hub_preset_read;
	hashtab_store(x->hash_internals, gensym("preset/read"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/write",				"msg_symbol",	"none",	"Write an xml-preset file to disk.  An optional argument defines the file to open.");
	anObject->action = (method)hub_preset_write;
	hashtab_store(x->hash_internals, gensym("preset/write"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/recall",			"msg_generic",	"none",	"Recall a preset by number - you can also choose presets from the module menu.");
	anObject->action = (method)hub_preset_recall;
	hashtab_store(x->hash_internals, gensym("preset/recall"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/copy",				"msg_list",		"none",	"Create a new preset (2nd argument) by copying the contents of another preset (1st argument)");
	anObject->action = (method)hub_preset_copy;
	hashtab_store(x->hash_internals, gensym("preset/copy"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/store",				"msg_list",		"none",	"Store a preset by number in memory.  All presets present in memory will be written to disk when you send a save_settings message to the module.");
	anObject->action = (method)hub_preset_store;
	hashtab_store(x->hash_internals, gensym("preset/store"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/storenext",			"msg_list",		"none",	"Store a preset in the next preset slot.  Handy so that you do not need to specify a preset number manually.");
	anObject->action = (method)hub_preset_store_next;
	hashtab_store(x->hash_internals, gensym("preset/storenext"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/interpolate",		"msg_list",		"none",	"Interpolate between two named presets (argument 1 and 2) using a ratio (float in the range [0.0, 1.0]) specified as the third argument.");
	anObject->action = (method)hub_preset_interpolate;
	hashtab_store(x->hash_internals, gensym("preset/interpolate"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/default",			"msg_none",		"none",	"Open the default preset file and recall the first preset in that file.");
	anObject->action = (method)hub_preset_default;
	hashtab_store(x->hash_internals, gensym("preset/default"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/clear",				"msg_none",		"none",	"Clears all presets, providing a blank slate for saving new presets.");
	anObject->action = (method)hub_presets_clear;
	hashtab_store(x->hash_internals, gensym("preset/clear"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"preset/post",				"msg_none",		"none",	"Post all presets to the Max window.");
	anObject->action = (method)hub_presets_dump;
	hashtab_store(x->hash_internals, gensym("preset/post"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.parameter",	"ui/freeze",				"msg_toggle",	"none",	"Turn off the updating of user interface elements when parameters change.  This may be done to conserve CPU resources.");
	anObject->action = (method)hub_ui_freeze;
	hashtab_store(x->hash_internals, gensym("ui/freeze"), (t_object*)anObject);

	anObject = new hubInternalObject("jcom.message", 	"ui/refresh",				"msg_none",		"none",	"Update displayed values for module to reflect current state.");
	anObject->action = (method)hub_ui_refresh;
	hashtab_store(x->hash_internals, gensym("ui/refresh"), (t_object*)anObject);
}

void hub_internals_destroy(t_hub *x)
{
	long				i;
	long				numKeys = 0;
	t_symbol			**keys = NULL;
	hubInternalObject	*anObject;
	t_max_err			err;

	hashtab_getkeys(x->hash_internals, &numKeys, &keys);
	for(i=0; i<numKeys; i++){
		err = hashtab_lookup(x->hash_internals, keys[i], (t_object**)&anObject);
		if(!err)
			delete anObject;
	}

	if(keys)
		sysmem_freeptr(keys);

	hashtab_chuck(x->hash_internals);
}

void hub_internals_dispatch(t_hub *x, t_symbol *osc_name, long argc, t_atom *argv)
{
	hubInternalObject	*theObject;
	t_max_err			err;

	err = hashtab_lookup(x->hash_internals, osc_name, (t_object**)&theObject);
	if(!err)
		theObject->action(x, osc_name, argc, argv);
}

<|endoftext|>


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

#include "services/uriabbreviation.hxx"
#include "services.h"

#include "sal/config.h"
#include "cppuhelper/factory.hxx"
#include "cppuhelper/implementationentry.hxx"

#include "tools/urlobj.hxx"

// component helper namespace
namespace css = ::com::sun::star;

// framework namespace
namespace framework
{

namespace css = ::com::sun::star;

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

//*****************************************************************************************************************
//  XInterface, XTypeProvider, XServiceInfo
//*****************************************************************************************************************
DEFINE_XINTERFACE_3                (    UriAbbreviation                                                         ,
                                        cppu::OWeakObject                                                       ,
                                        DIRECT_INTERFACE(css::lang::XTypeProvider                               ),
                                        DIRECT_INTERFACE(css::lang::XServiceInfo                                ),
                                        DIRECT_INTERFACE(css::util::XStringAbbreviation                         )
                                    )

DEFINE_XTYPEPROVIDER_3              (   UriAbbreviation                                                         ,
                                        css::lang::XTypeProvider                                                ,
                                        css::lang::XServiceInfo                                                 ,
                                        css::util::XStringAbbreviation
                                    )

DEFINE_XSERVICEINFO_MULTISERVICE_2 (    UriAbbreviation                                                         ,
                                        ::cppu::OWeakObject                                                     ,
                                        SERVICENAME_STRINGABBREVIATION                                          ,
                                        IMPLEMENTATIONNAME_URIABBREVIATION
                                    )

DEFINE_INIT_SERVICE                 (   UriAbbreviation,
                                        {
                                        }
                                    )

UriAbbreviation::UriAbbreviation(css::uno::Reference< css::uno::XComponentContext > const & context) :
    m_xContext(context)
{
}

// ::com::sun::star::util::XStringAbbreviation:
::rtl::OUString SAL_CALL UriAbbreviation::abbreviateString(const css::uno::Reference< css::util::XStringWidth > & xStringWidth, ::sal_Int32 nWidth, const ::rtl::OUString & aString) throw (css::uno::RuntimeException)
{
    ::rtl::OUString aResult( aString );
    if ( xStringWidth.is() )
    {
        // Use INetURLObject to abbreviate URLs
        INetURLObject aURL( aString );
        aResult = aURL.getAbbreviated( xStringWidth, nWidth, INetURLObject::DECODE_UNAMBIGUOUS );
    }

    return aResult;
}

} // namespace framework<commit_msg>#i10000# EOL missing<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: uriabbreviation.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2007-01-26 09:17:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"

#include "services/uriabbreviation.hxx"
#include "services.h"

#include "sal/config.h"
#include "cppuhelper/factory.hxx"
#include "cppuhelper/implementationentry.hxx"

#include "tools/urlobj.hxx"

// component helper namespace
namespace css = ::com::sun::star;

// framework namespace
namespace framework
{

namespace css = ::com::sun::star;

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

//*****************************************************************************************************************
//  XInterface, XTypeProvider, XServiceInfo
//*****************************************************************************************************************
DEFINE_XINTERFACE_3                (    UriAbbreviation                                                         ,
                                        cppu::OWeakObject                                                       ,
                                        DIRECT_INTERFACE(css::lang::XTypeProvider                               ),
                                        DIRECT_INTERFACE(css::lang::XServiceInfo                                ),
                                        DIRECT_INTERFACE(css::util::XStringAbbreviation                         )
                                    )

DEFINE_XTYPEPROVIDER_3              (   UriAbbreviation                                                         ,
                                        css::lang::XTypeProvider                                                ,
                                        css::lang::XServiceInfo                                                 ,
                                        css::util::XStringAbbreviation
                                    )

DEFINE_XSERVICEINFO_MULTISERVICE_2 (    UriAbbreviation                                                         ,
                                        ::cppu::OWeakObject                                                     ,
                                        SERVICENAME_STRINGABBREVIATION                                          ,
                                        IMPLEMENTATIONNAME_URIABBREVIATION
                                    )

DEFINE_INIT_SERVICE                 (   UriAbbreviation,
                                        {
                                        }
                                    )

UriAbbreviation::UriAbbreviation(css::uno::Reference< css::uno::XComponentContext > const & context) :
    m_xContext(context)
{
}

// ::com::sun::star::util::XStringAbbreviation:
::rtl::OUString SAL_CALL UriAbbreviation::abbreviateString(const css::uno::Reference< css::util::XStringWidth > & xStringWidth, ::sal_Int32 nWidth, const ::rtl::OUString & aString) throw (css::uno::RuntimeException)
{
    ::rtl::OUString aResult( aString );
    if ( xStringWidth.is() )
    {
        // Use INetURLObject to abbreviate URLs
        INetURLObject aURL( aString );
        aResult = aURL.getAbbreviated( xStringWidth, nWidth, INetURLObject::DECODE_UNAMBIGUOUS );
    }

    return aResult;
}

} // namespace framework

<|endoftext|>