<commit_before>/*
  This file is part of Kontact.

  Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>
  adapted for karm 2005 by Thorsten Staerk <kde@staerk.de>
  karm renamed to ktimetracker 2007-2008

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

#include "ktimetracker_plugin.h"
#include "ktimetrackerinterface.h"

#include <karm_part.h>

#include <kontactinterfaces/core.h>
#include <kontactinterfaces/plugin.h>

#include <kactioncollection.h>
#include <kcmdlineargs.h>
#include <kgenericfactory.h>
#include <kicon.h>
#include <kparts/componentfactory.h>

EXPORT_KONTACT_PLUGIN( KarmPlugin, ktimetracker )

KarmPlugin::KarmPlugin( Kontact::Core *core, const QVariantList & )
  : Kontact::Plugin( core, core, "ktimetracker" ), mInterface( 0 )
{
  setComponentData( KontactPluginFactory::componentData() );

  KAction *action  = new KAction( KIcon( "ktimetracker" ), i18n( "New Task" ), this );
  actionCollection()->addAction( "new_task", action );
  action->setShortcut( QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_W ) );
  connect( action, SIGNAL(triggered(bool)), SLOT(newTask()) );
  insertNewAction( action );

  mUniqueAppWatcher = new Kontact::UniqueAppWatcher(
    new Kontact::UniqueAppHandlerFactory<KarmUniqueAppHandler>(), this );
}

KarmPlugin::~KarmPlugin()
{
}

bool KarmPlugin::isRunningStandalone()
{
  return mUniqueAppWatcher->isRunningStandalone();
}

QStringList KarmPlugin::invisibleToolbarActions() const
{
  return QStringList() << "new_task" << "new_sub_task" ;
}

KParts::ReadOnlyPart *KarmPlugin::createPart()
{
  KParts::ReadOnlyPart *part = loadPart();
  if ( !part ) {
    return 0;
  }

  mInterface = new OrgKdeKtimetrackerKtimetrackerInterface(
    "org.kde.ktimetracker", "/KTimeTracker", QDBusConnection::sessionBus() );

  return part;
}

OrgKdeKtimetrackerKtimetrackerInterface *KarmPlugin::interface()
{
  if ( !mInterface ) {
    part();
  }
  Q_ASSERT( mInterface );
  return mInterface;
}

QString KarmPlugin::tipFile() const
{
  // TODO: tips file
  //QString file = KStandardDirs::locate("data", "karm/tips");
  QString file;
  return file;
}

QStringList KarmPlugin::configModules() const
{
  QStringList modules;
  modules << "PIM/ktimetrackerconfig.desktop";
  return modules;
}

void KarmPlugin::newTask()
{
  core()->selectPlugin( this );
  interface()->newTask();
}

void KarmUniqueAppHandler::loadCommandLineOptions()
{
  // TODO: handle command line options
  KCmdLineArgs::addCmdLineOptions( KCmdLineOptions() );
}

int KarmUniqueAppHandler::newInstance()
{
  kDebug();
  // Ensure part is loaded
  (void)plugin()->part();
  return Kontact::UniqueAppHandler::newInstance();
}

#include "ktimetracker_plugin.moc"

<commit_msg>Fix compile<commit_after>/*
  This file is part of Kontact.

  Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>
  adapted for karm 2005 by Thorsten Staerk <kde@staerk.de>
  karm renamed to ktimetracker 2007-2008

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

  As a special exception, permission is given to link this program
  with any edition of Qt, and distribute the resulting executable,
  without including the source code for Qt in the source distribution.
*/

#include "ktimetracker_plugin.h"
#include "ktimetrackerinterface.h"

#include <ktimetrackerpart.h>

#include <kontactinterfaces/core.h>
#include <kontactinterfaces/plugin.h>

#include <kactioncollection.h>
#include <kcmdlineargs.h>
#include <kgenericfactory.h>
#include <kicon.h>
#include <kparts/componentfactory.h>

EXPORT_KONTACT_PLUGIN( KarmPlugin, ktimetracker )

KarmPlugin::KarmPlugin( Kontact::Core *core, const QVariantList & )
  : Kontact::Plugin( core, core, "ktimetracker" ), mInterface( 0 )
{
  setComponentData( KontactPluginFactory::componentData() );

  KAction *action  = new KAction( KIcon( "ktimetracker" ), i18n( "New Task" ), this );
  actionCollection()->addAction( "new_task", action );
  action->setShortcut( QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_W ) );
  connect( action, SIGNAL(triggered(bool)), SLOT(newTask()) );
  insertNewAction( action );

  mUniqueAppWatcher = new Kontact::UniqueAppWatcher(
    new Kontact::UniqueAppHandlerFactory<KarmUniqueAppHandler>(), this );
}

KarmPlugin::~KarmPlugin()
{
}

bool KarmPlugin::isRunningStandalone()
{
  return mUniqueAppWatcher->isRunningStandalone();
}

QStringList KarmPlugin::invisibleToolbarActions() const
{
  return QStringList() << "new_task" << "new_sub_task" ;
}

KParts::ReadOnlyPart *KarmPlugin::createPart()
{
  KParts::ReadOnlyPart *part = loadPart();
  if ( !part ) {
    return 0;
  }

  mInterface = new OrgKdeKtimetrackerKtimetrackerInterface(
    "org.kde.ktimetracker", "/KTimeTracker", QDBusConnection::sessionBus() );

  return part;
}

OrgKdeKtimetrackerKtimetrackerInterface *KarmPlugin::interface()
{
  if ( !mInterface ) {
    part();
  }
  Q_ASSERT( mInterface );
  return mInterface;
}

QString KarmPlugin::tipFile() const
{
  // TODO: tips file
  //QString file = KStandardDirs::locate("data", "karm/tips");
  QString file;
  return file;
}

QStringList KarmPlugin::configModules() const
{
  QStringList modules;
  modules << "PIM/ktimetrackerconfig.desktop";
  return modules;
}

void KarmPlugin::newTask()
{
  core()->selectPlugin( this );
  interface()->newTask();
}

void KarmUniqueAppHandler::loadCommandLineOptions()
{
  // TODO: handle command line options
  KCmdLineArgs::addCmdLineOptions( KCmdLineOptions() );
}

int KarmUniqueAppHandler::newInstance()
{
  kDebug();
  // Ensure part is loaded
  (void)plugin()->part();
  return Kontact::UniqueAppHandler::newInstance();
}

#include "ktimetracker_plugin.moc"

<|endoftext|>


<commit_before>#include <iostream>

constexpr int MAX_N = 1000;
constexpr int MAX_K = 100;

int N, K;
int dp[MAX_N][MAX_K];

void solve();

int main(){
    solve();
}

void solve(){
    dp[1][1] = 1;
    for(int i = 1; i <= MAX_N; ++i){
        for(int j = 1; j <= i; ++j){
            if(i == 1 && j == 1){
                continue;
            }

        }
    }
}
<commit_msg>2016.12.27<commit_after>#include <cstdio>
#include <algorithm>

#define MAX_N 1000
#define MAX_K 100
#define MOD 100000000000000000

int N, K;
unsigned long long dp[MAX_K + 1][MAX_N + 1][2];

void solve();

int main(){
	scanf("%d %d", &N, &K);
    solve();
	return 0;
}

void solve(){
	dp[0][0][1] = 1;

	for(int i = 1; i <= K; ++i){
		for(int j = 0; j <= N; ++j){
			dp[i][j][0] += dp[i - 1][j][0];
			dp[i][j][1] += dp[i - 1][j][1];
			dp[i][j][0] += dp[i][j][1] / MOD;
			dp[i][j][1] = dp[i][j][1] % MOD;
			if(j >= i){
				dp[i][j][0] += dp[i][j - i][0];
				dp[i][j][1] += dp[i][j - i][1];
				dp[i][j][0] += dp[i][j][1] / MOD;
				dp[i][j][1] = dp[i][j][1] % MOD;
			}
		}
	}

	if(dp[K][N][0] != 0){
		printf("%llu", dp[K][N][0]);
	}
	printf("%llu\n", dp[K][N][1]);
}
<|endoftext|>


<commit_before>/*
   Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   SPDX-License-Identifier: Apache-2.0
*/

/**
 * Before running this C++ code example, set up your development environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 * https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/getting-started.html.
 *
 * For information on the structure of the code examples and how to build and run the examples, see
 * https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/getting-started-code-examples.html.
 *
 * Purpose
 *
 * Demonstrates creating an IAM user.
 *
 */

//snippet-start:[iam.cpp.create_user.inc]
#include <aws/core/Aws.h>
#include <aws/iam/IAMClient.h>
#include <aws/iam/model/CreateUserRequest.h>
#include <aws/iam/model/GetUserRequest.h>
#include <aws/iam/model/GetUserResult.h>
#include <iostream>
#include "iam_samples.h"
//snippet-end:[iam.cpp.create_user.inc]

//! Creates an IAM user.
/*!
  \sa createUser()
  \param userName: The user name.
  \param clientConfig: Aws client configuration.
  \return bool: Successful completion.
*/
bool AwsDoc::IAM::createUser(const Aws::String &userName,
                             const Aws::Client::ClientConfiguration &clientConfig) {
    // snippet-start:[iam.cpp.create_user01.code]
    Aws::IAM::IAMClient iam(clientConfig);
    // snippet-end:[iam.cpp.create_user01.code]
    // snippet-start:[iam.cpp.get_user.code]
    Aws::IAM::Model::GetUserRequest get_request;
    get_request.SetUserName(userName);

    auto get_outcome = iam.GetUser(get_request);
    if (get_outcome.IsSuccess()) {
        std::cout << "IAM user " << userName << " already exists" << std::endl;
        return true;
    }
    else if (get_outcome.GetError().GetErrorType() !=
             Aws::IAM::IAMErrors::NO_SUCH_ENTITY) {
        std::cerr << "Error checking existence of IAM user " << userName << ":"
                  << get_outcome.GetError().GetMessage() << std::endl;
        return false;
    }
    // snippet-end:[iam.cpp.get_user.code]

    // snippet-start:[iam.cpp.create_user02.code]
    Aws::IAM::Model::CreateUserRequest create_request;
    create_request.SetUserName(userName);

    auto create_outcome = iam.CreateUser(create_request);
    if (!create_outcome.IsSuccess()) {
        std::cerr << "Error creating IAM user " << userName << ":" <<
                  create_outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Successfully created IAM user " << userName << std::endl;
    }

    return create_outcome.IsSuccess();
    // snippet-end:[iam.cpp.create_user02.code]
}

/*
 *
 *  main function
 *
 * Usage: 'run_create_user <user_name>'
 *
 */

#ifndef TESTING_BUILD

int main(int argc, char **argv) {
    if (argc != 2) {
        std::cout << "Usage: run_create_user <user_name>" << std::endl;
        return 1;
    }

    Aws::SDKOptions options;
    Aws::InitAPI(options);
    {
        Aws::String userName(argv[1]);

        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";
        AwsDoc::IAM::createUser(userName, clientConfig);
    }

    Aws::ShutdownAPI(options);
    return 0;
}

#endif  // TESTING_BUILD
<commit_msg>Update create_user.cpp<commit_after>/*
   Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   SPDX-License-Identifier: Apache-2.0
*/

/**
 * Before running this C++ code example, set up your development environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 * https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/getting-started.html.
 *
 * For information on the structure of the code examples and how to build and run the examples, see
 * https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/getting-started-code-examples.html.
 *
 * Purpose
 *
 * Demonstrates creating an IAM user.
 *
 */

//snippet-start:[iam.cpp.create_user.inc]
#include <aws/core/Aws.h>
#include <aws/iam/IAMClient.h>
#include <aws/iam/model/CreateUserRequest.h>
//snippet-start:[iam.cpp.get_user.inc]
#include <aws/iam/model/GetUserRequest.h>
#include <aws/iam/model/GetUserResult.h>
//snippet-end:[iam.cpp.get_user.inc]
#include <iostream>
#include "iam_samples.h"
//snippet-end:[iam.cpp.create_user.inc]

//! Creates an IAM user.
/*!
  \sa createUser()
  \param userName: The user name.
  \param clientConfig: Aws client configuration.
  \return bool: Successful completion.
*/
bool AwsDoc::IAM::createUser(const Aws::String &userName,
                             const Aws::Client::ClientConfiguration &clientConfig) {
    // snippet-start:[iam.cpp.create_user01.code]
    Aws::IAM::IAMClient iam(clientConfig);
    // snippet-end:[iam.cpp.create_user01.code]
    // snippet-start:[iam.cpp.get_user.code]
    Aws::IAM::Model::GetUserRequest get_request;
    get_request.SetUserName(userName);

    auto get_outcome = iam.GetUser(get_request);
    if (get_outcome.IsSuccess()) {
        std::cout << "IAM user " << userName << " already exists" << std::endl;
        return true;
    }
    else if (get_outcome.GetError().GetErrorType() !=
             Aws::IAM::IAMErrors::NO_SUCH_ENTITY) {
        std::cerr << "Error checking existence of IAM user " << userName << ":"
                  << get_outcome.GetError().GetMessage() << std::endl;
        return false;
    }
    // snippet-end:[iam.cpp.get_user.code]

    // snippet-start:[iam.cpp.create_user02.code]
    Aws::IAM::Model::CreateUserRequest create_request;
    create_request.SetUserName(userName);

    auto create_outcome = iam.CreateUser(create_request);
    if (!create_outcome.IsSuccess()) {
        std::cerr << "Error creating IAM user " << userName << ":" <<
                  create_outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Successfully created IAM user " << userName << std::endl;
    }

    return create_outcome.IsSuccess();
    // snippet-end:[iam.cpp.create_user02.code]
}

/*
 *
 *  main function
 *
 * Usage: 'run_create_user <user_name>'
 *
 */

#ifndef TESTING_BUILD

int main(int argc, char **argv) {
    if (argc != 2) {
        std::cout << "Usage: run_create_user <user_name>" << std::endl;
        return 1;
    }

    Aws::SDKOptions options;
    Aws::InitAPI(options);
    {
        Aws::String userName(argv[1]);

        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";
        AwsDoc::IAM::createUser(userName, clientConfig);
    }

    Aws::ShutdownAPI(options);
    return 0;
}

#endif  // TESTING_BUILD
<|endoftext|>


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

#ifndef _SLIDESHOW_ATTRIBUTABLESHAPE_HXX
#define _SLIDESHOW_ATTRIBUTABLESHAPE_HXX

#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif

#include <animatableshape.hxx>
#include <shapeattributelayer.hxx>
#include <doctreenodesupplier.hxx>

namespace presentation
{
    namespace internal
    {
        // forward declaration necessary, because methods use AttributableShapeSharedPtr
        class AttributableShape;

        typedef ::boost::shared_ptr< AttributableShape > AttributableShapeSharedPtr;

        /** Represents an animatable shape, that can have its
            attributes changed.

            Over an animatable shape, this interface adds attribute
            modification methods. Furthermore, the shape can be
            queried for sub items, which in turn can be separated out
            into own AttributableShapes.
         */
        class AttributableShape : public AnimatableShape
        {
        public:
            // Attribute layer methods
            //------------------------------------------------------------------

            /** Create a new shape attribute layer.

                This method creates a new layer for shape attributes,
                which lies atop of all previous attribute layers. That
                is most typically used when a new SMIL animation
                starts (which according to the spec always lies atop
                of all previous animations). Thus, subsequent calls to
                this method generate a sandwich of attribute layers,
                which in total define the shape's attributes.

                Please note that the attribute layers do not
                contain the underlying XShape's attributes as
                default. Instead, attributes not explicitely set by
                animations remain in invalid state, allowing the
                shape's paint method to determine whether they have to
                override the underlying graphical shape
                representation. XShape attributes must be passed
                explicitely to animations which need them (e.g. 'by'
                animations).

                @return the new layer
             */
            virtual ShapeAttributeLayerSharedPtr createAttributeLayer() = 0;

            /** Revoke a previously generated attribute layer.

                This method revokes a previously generated attribute
                layer, and removes the effect of that layer from this
                shape. The layer need not be the current toplevel
                layer, it can also be revoked from in between.

                @param rLayer
                Layer to revoke. Must have been generated by
                createAttributeLayer() at the same Shape.

                @return true, if layer was successfully removed, false
                otherwise (e.g. if the given layer was not generated
                for this shape).
             */
            virtual bool revokeAttributeLayer( const ShapeAttributeLayerSharedPtr& rLayer ) = 0;

            /** Change shape visibility

                This method hides or unhides a shape. Note that every
                attribute layer generated for this shape will override
                the setting given here, until it is revoked.

                @param bVisible
                When true, shape will be visible, when false,
                invisible (modulo attribute layer overrides).
             */
            virtual void setVisibility( bool bVisible ) = 0;

            // Sub-item handling
            //------------------------------------------------------------------

            /** Retrieve interface for DocTreeNode creation.

                This method provides the caller with a reference to
                the DocTreeNodeSupplier interface, which can be used
                to request specific tree nodes for this shape.
             */
            virtual const DocTreeNodeSupplier& getTreeNodeSupplier() const = 0;
            virtual DocTreeNodeSupplier&       getTreeNodeSupplier() = 0;

            /** Query the subset this shape displays.

                This method returns a tree node denoting the subset
                displayed by this shape. If this shape is not a subset
                shape, an empty tree node should be returned. If this
                shape is a subset, and itself has subsetted children,
                this method might return more than the shape is
                actually displaying (because a single DocTreeNode is
                not able to model holes in the range).
             */
            virtual DocTreeNode getSubsetNode() const = 0;

            /** Query a subset Shape, if already existent at this
                object

                This method returns a clone of this Shape, which
                renders only the selected subset of itself, but only
                if such a subset has been explicitely created before.

                @param rTreeNode
                A DocTreeNode instance queried from this Shape, which
                specifies the subset of the Shape to render.

                @return a NULL Shape pointer, if no subset exists for
                the given DocTreeNode.
            */
            virtual AttributableShapeSharedPtr getSubset( const DocTreeNode& rTreeNode ) const = 0;

            /** Create a subset Shape

                This method creates a clone of this Shape, which
                renders only the selected subset of itself. Multiple
                createSubset() calls for the same DocTreeNode will all
                share the same subset shape.

                The original shape (i.e. the one this method is called
                on) will cease to display the selected subset
                part. That is, together the shapes will display the
                original content, but the content of all subset shapes
                and their original shape will always be mutually
                disjunct.

                After deregistering the subset shape a matching number
                of times via revokeSubset(), the original shape will
                resume displaying the subsetted part.

                @attention To maintain view integrity, this method
                should only be called from the LayerManager

                @param o_rSubset
                The requested Shape

                @param rTreeNode
                A DocTreeNode instance queried from this Shape, which
                specifies the subset of the Shape to render

                @return true, if the shape was newly created, and
                false, if an already existing subset is returned.
            */
            virtual bool createSubset( AttributableShapeSharedPtr&  o_rSubset,
                                       const DocTreeNode&           rTreeNode ) = 0;

            /** Revoke a previously generated shape subset.

                After revoking a subset shape, the corresponding
                subset part will become visible again on the original
                shape.

                @attention To maintain view integrity, this method
                should only be called from the LayerManager

                @param rShape
                The subset to revoke

                @return true, if the last client called
                revokeSubset().
             */
            virtual bool revokeSubset( const AttributableShapeSharedPtr& rShape ) = 0;
        };

        typedef ::boost::shared_ptr< AttributableShape > AttributableShapeSharedPtr;

    }
}

#endif /* _SLIDESHOW_ATTRIBUTABLESHAPE_HXX */
<commit_msg>INTEGRATION: CWS presfixes03 (1.3.2); FILE MERGED 2005/04/14 17:40:58 thb 1.3.2.1: #i47428# Temporary fix to handle vanishing text after effect, still shows intermittent timing problems (first characters seem to blink). Proper fix should go with i47472.<commit_after>/*************************************************************************
 *
 *  $RCSfile: attributableshape.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2005-04-18 09:51:27 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SLIDESHOW_ATTRIBUTABLESHAPE_HXX
#define _SLIDESHOW_ATTRIBUTABLESHAPE_HXX

#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif

#include <animatableshape.hxx>
#include <shapeattributelayer.hxx>
#include <doctreenodesupplier.hxx>

namespace presentation
{
    namespace internal
    {
        // forward declaration necessary, because methods use AttributableShapeSharedPtr
        class AttributableShape;

        typedef ::boost::shared_ptr< AttributableShape > AttributableShapeSharedPtr;

        /** Represents an animatable shape, that can have its
            attributes changed.

            Over an animatable shape, this interface adds attribute
            modification methods. Furthermore, the shape can be
            queried for sub items, which in turn can be separated out
            into own AttributableShapes.
         */
        class AttributableShape : public AnimatableShape
        {
        public:
            // Attribute layer methods
            //------------------------------------------------------------------

            /** Create a new shape attribute layer.

                This method creates a new layer for shape attributes,
                which lies atop of all previous attribute layers. That
                is most typically used when a new SMIL animation
                starts (which according to the spec always lies atop
                of all previous animations). Thus, subsequent calls to
                this method generate a sandwich of attribute layers,
                which in total define the shape's attributes.

                Please note that the attribute layers do not
                contain the underlying XShape's attributes as
                default. Instead, attributes not explicitely set by
                animations remain in invalid state, allowing the
                shape's paint method to determine whether they have to
                override the underlying graphical shape
                representation. XShape attributes must be passed
                explicitely to animations which need them (e.g. 'by'
                animations).

                @return the new layer
             */
            virtual ShapeAttributeLayerSharedPtr createAttributeLayer() = 0;

            /** Revoke a previously generated attribute layer.

                This method revokes a previously generated attribute
                layer, and removes the effect of that layer from this
                shape. The layer need not be the current toplevel
                layer, it can also be revoked from in between.

                @param rLayer
                Layer to revoke. Must have been generated by
                createAttributeLayer() at the same Shape.

                @return true, if layer was successfully removed, false
                otherwise (e.g. if the given layer was not generated
                for this shape).
             */
            virtual bool revokeAttributeLayer( const ShapeAttributeLayerSharedPtr& rLayer ) = 0;

            /** Get the topmost shape attribute layer (if any).

                This method returns the topmost layer for shape
                attributes, i.e. the one which ultimately determines
                the shape's look.

                Please note that the attribute layers do not
                contain the underlying XShape's attributes as
                default. Instead, attributes not explicitely set by
                animations remain in invalid state, allowing the
                shape's paint method to determine whether they have to
                override the underlying graphical shape
                representation. XShape attributes must be passed
                explicitely to animations which need them (e.g. 'by'
                animations).

                @return the topmost layer
             */
            virtual ShapeAttributeLayerSharedPtr getTopmostAttributeLayer() const = 0;

            /** Change default shape visibility

                This method hides or unhides a shape. Note that every
                attribute layer generated for this shape is able to
                override the setting given here, until it is revoked.

                @param bVisible
                When true, shape will be visible, when false,
                invisible (modulo attribute layer overrides).
             */
            virtual void setVisibility( bool bVisible ) = 0;

            // Sub-item handling
            //------------------------------------------------------------------

            /** Retrieve interface for DocTreeNode creation.

                This method provides the caller with a reference to
                the DocTreeNodeSupplier interface, which can be used
                to request specific tree nodes for this shape.
             */
            virtual const DocTreeNodeSupplier& getTreeNodeSupplier() const = 0;
            virtual DocTreeNodeSupplier&       getTreeNodeSupplier() = 0;

            /** Query the subset this shape displays.

                This method returns a tree node denoting the subset
                displayed by this shape. If this shape is not a subset
                shape, an empty tree node should be returned. If this
                shape is a subset, and itself has subsetted children,
                this method might return more than the shape is
                actually displaying (because a single DocTreeNode is
                not able to model holes in the range).
             */
            virtual DocTreeNode getSubsetNode() const = 0;

            /** Query a subset Shape, if already existent at this
                object

                This method returns a clone of this Shape, which
                renders only the selected subset of itself, but only
                if such a subset has been explicitely created before.

                @param rTreeNode
                A DocTreeNode instance queried from this Shape, which
                specifies the subset of the Shape to render.

                @return a NULL Shape pointer, if no subset exists for
                the given DocTreeNode.
            */
            virtual AttributableShapeSharedPtr getSubset( const DocTreeNode& rTreeNode ) const = 0;

            /** Create a subset Shape

                This method creates a clone of this Shape, which
                renders only the selected subset of itself. Multiple
                createSubset() calls for the same DocTreeNode will all
                share the same subset shape.

                The original shape (i.e. the one this method is called
                on) will cease to display the selected subset
                part. That is, together the shapes will display the
                original content, but the content of all subset shapes
                and their original shape will always be mutually
                disjunct.

                After deregistering the subset shape a matching number
                of times via revokeSubset(), the original shape will
                resume displaying the subsetted part.

                @attention To maintain view integrity, this method
                should only be called from the LayerManager

                @param o_rSubset
                The requested Shape

                @param rTreeNode
                A DocTreeNode instance queried from this Shape, which
                specifies the subset of the Shape to render

                @return true, if the shape was newly created, and
                false, if an already existing subset is returned.
            */
            virtual bool createSubset( AttributableShapeSharedPtr&  o_rSubset,
                                       const DocTreeNode&           rTreeNode ) = 0;

            /** Revoke a previously generated shape subset.

                After revoking a subset shape, the corresponding
                subset part will become visible again on the original
                shape.

                @attention To maintain view integrity, this method
                should only be called from the LayerManager

                @param rShape
                The subset to revoke

                @return true, if the last client called
                revokeSubset().
             */
            virtual bool revokeSubset( const AttributableShapeSharedPtr& rShape ) = 0;
        };

        typedef ::boost::shared_ptr< AttributableShape > AttributableShapeSharedPtr;

    }
}

#endif /* _SLIDESHOW_ATTRIBUTABLESHAPE_HXX */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: mouseeventhandler.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 21:15:46 $
 *
 *  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 _SLIDESHOW_MOUSEEVENTHANDLER_HXX
#define _SLIDESHOW_MOUSEEVENTHANDLER_HXX

#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif

#include <disposable.hxx>

namespace com { namespace sun { namespace star { namespace awt
{
    struct MouseEvent;
} } } }

/* Definition of MouseEventHandler interface */

namespace presentation
{
    namespace internal
    {

        /** Interface for handling mouse events.

            Classes implementing this interface can be added to an
            EventMultiplexer object, and are called from there to
            handle mouse events.
         */
        class MouseEventHandler : public Disposable
        {
        public:
            /** Handle a mouse button pressed event.

                @param e
                The mouse event that occurred. The x,y coordinates of
                the event are already transformed back to user
                coordinate space, taking the inverse transform of the
                view in which the event occurred.

                @return true, if this handler has successfully
                processed the mouse event. When this method returns
                false, possibly other, less prioritized handlers can be
                called, too.
             */
            virtual bool handleMousePressed( const ::com::sun::star::awt::MouseEvent& e ) = 0;

            /** Handle a mouse button released event.

                @param e
                The mouse event that occurred. The x,y coordinates of
                the event are already transformed back to user
                coordinate space, taking the inverse transform of the
                view in which the event occurred.

                @return true, if this handler has successfully
                processed the pause event. When this method returns
                false, possibly other, less prioritized handlers are
                called, too.
             */
            virtual bool handleMouseReleased( const ::com::sun::star::awt::MouseEvent& e ) = 0;

            /** Handle a mouse entered the view event.

                @param e
                The mouse event that occurred. The x,y coordinates of
                the event are already transformed back to user
                coordinate space, taking the inverse transform of the
                view in which the event occurred.

                @return true, if this handler has successfully
                processed the pause event. When this method returns
                false, possibly other, less prioritized handlers are
                called, too.
             */
            virtual bool handleMouseEntered( const ::com::sun::star::awt::MouseEvent& e ) = 0;

            /** Handle a mouse exited the view event.

                @param e
                The mouse event that occurred. The x,y coordinates of
                the event are already transformed back to user
                coordinate space, taking the inverse transform of the
                view in which the event occurred.

                @return true, if this handler has successfully
                processed the pause event. When this method returns
                false, possibly other, less prioritized handlers are
                called, too.
             */
            virtual bool handleMouseExited( const ::com::sun::star::awt::MouseEvent& e ) = 0;

            /** Handle a mouse was moved with a pressed button event.

                @param e
                The mouse event that occurred. The x,y coordinates of
                the event are already transformed back to user
                coordinate space, taking the inverse transform of the
                view in which the event occurred.

                @return true, if this handler has successfully
                processed the pause event. When this method returns
                false, possibly other, less prioritized handlers are
                called, too.
             */
            virtual bool handleMouseDragged( const ::com::sun::star::awt::MouseEvent& e ) = 0;

            /** Handle a mouse was moved event.

                @param e
                The mouse event that occurred. The x,y coordinates of
                the event are already transformed back to user
                coordinate space, taking the inverse transform of the
                view in which the event occurred.

                @return true, if this handler has successfully
                processed the pause event. When this method returns
                false, possibly other, less prioritized handlers are
                called, too.
             */
            virtual bool handleMouseMoved( const ::com::sun::star::awt::MouseEvent& e ) = 0;
        };

        typedef ::boost::shared_ptr< MouseEventHandler > MouseEventHandlerSharedPtr;

    }
}

#endif /* _SLIDESHOW_MOUSEEVENTHANDLER_HXX */
<commit_msg>INTEGRATION: CWS presfixes09 (1.3.18); FILE MERGED 2006/03/24 18:23:35 thb 1.3.18.2: #i37778# Moved whole slideshow engine from namespace presentation (which conflicts with one of the UNO subnamespaces) to slideshow 2006/03/06 22:14:35 thb 1.3.18.1: #i53194# #i55294# #i59324# Overhauled IntrinsicAnimationActivity; fixes GIF animation import; corrected rehearse timings sprite size; several cosmetic changes (removed external header guards); prepared scene for sprite prio<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: mouseeventhandler.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-13 16:00:05 $
 *
 *  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 _SLIDESHOW_MOUSEEVENTHANDLER_HXX
#define _SLIDESHOW_MOUSEEVENTHANDLER_HXX

#include <boost/shared_ptr.hpp>

#include <disposable.hxx>

namespace com { namespace sun { namespace star { namespace awt
{
    struct MouseEvent;
} } } }

/* Definition of MouseEventHandler interface */

namespace slideshow
{
    namespace internal
    {

        /** Interface for handling mouse events.

            Classes implementing this interface can be added to an
            EventMultiplexer object, and are called from there to
            handle mouse events.
         */
        class MouseEventHandler : public Disposable
        {
        public:
            /** Handle a mouse button pressed event.

                @param e
                The mouse event that occurred. The x,y coordinates of
                the event are already transformed back to user
                coordinate space, taking the inverse transform of the
                view in which the event occurred.

                @return true, if this handler has successfully
                processed the mouse event. When this method returns
                false, possibly other, less prioritized handlers can be
                called, too.
             */
            virtual bool handleMousePressed( const ::com::sun::star::awt::MouseEvent& e ) = 0;

            /** Handle a mouse button released event.

                @param e
                The mouse event that occurred. The x,y coordinates of
                the event are already transformed back to user
                coordinate space, taking the inverse transform of the
                view in which the event occurred.

                @return true, if this handler has successfully
                processed the pause event. When this method returns
                false, possibly other, less prioritized handlers are
                called, too.
             */
            virtual bool handleMouseReleased( const ::com::sun::star::awt::MouseEvent& e ) = 0;

            /** Handle a mouse entered the view event.

                @param e
                The mouse event that occurred. The x,y coordinates of
                the event are already transformed back to user
                coordinate space, taking the inverse transform of the
                view in which the event occurred.

                @return true, if this handler has successfully
                processed the pause event. When this method returns
                false, possibly other, less prioritized handlers are
                called, too.
             */
            virtual bool handleMouseEntered( const ::com::sun::star::awt::MouseEvent& e ) = 0;

            /** Handle a mouse exited the view event.

                @param e
                The mouse event that occurred. The x,y coordinates of
                the event are already transformed back to user
                coordinate space, taking the inverse transform of the
                view in which the event occurred.

                @return true, if this handler has successfully
                processed the pause event. When this method returns
                false, possibly other, less prioritized handlers are
                called, too.
             */
            virtual bool handleMouseExited( const ::com::sun::star::awt::MouseEvent& e ) = 0;

            /** Handle a mouse was moved with a pressed button event.

                @param e
                The mouse event that occurred. The x,y coordinates of
                the event are already transformed back to user
                coordinate space, taking the inverse transform of the
                view in which the event occurred.

                @return true, if this handler has successfully
                processed the pause event. When this method returns
                false, possibly other, less prioritized handlers are
                called, too.
             */
            virtual bool handleMouseDragged( const ::com::sun::star::awt::MouseEvent& e ) = 0;

            /** Handle a mouse was moved event.

                @param e
                The mouse event that occurred. The x,y coordinates of
                the event are already transformed back to user
                coordinate space, taking the inverse transform of the
                view in which the event occurred.

                @return true, if this handler has successfully
                processed the pause event. When this method returns
                false, possibly other, less prioritized handlers are
                called, too.
             */
            virtual bool handleMouseMoved( const ::com::sun::star::awt::MouseEvent& e ) = 0;
        };

        typedef ::boost::shared_ptr< MouseEventHandler > MouseEventHandlerSharedPtr;

    }
}

#endif /* _SLIDESHOW_MOUSEEVENTHANDLER_HXX */
<|endoftext|>


<commit_before>#include "includes.hpp"

#pragma once

template <typename T>
constexpr typename std::enable_if<std::is_integral<T>::value, T>::type
inf() {
  return std::numeric_limits::max() / 2 - 1000;
}

template <typename T>
constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type
inf() {
  return 1e30;
}

template <typename T>
constexpr typename std::enable_if<std::is_arithmetic<T>::value, T>::type
zero() {
  return T(0);
}

const long double pi = acos(-1.0);
<commit_msg>Fix and docs<commit_after>#include "includes.hpp"

#pragma once

/// @return Returns a large finite value representable by the numeric type T.
/// @note It is guaranteed that the return values is strictly less than std::numeric_limits<T>::max() / 2.
template <typename T>
constexpr typename std::enable_if<std::is_integral<T>::value, T>::type inf() {
  return std::numeric_limits<T>::max() / 2 - 1000;
}

/// @return Returns a large finite value representable by the numeric type T.
/// @note It is guaranteed that the return values is strictly less than std::numeric_limits<T>::max() / 2.
template <typename T>
constexpr typename std::enable_if<std::is_floating_point<T>::value, T>::type
inf() {
  return std::min(std::numeric_limits<T>::max() / 2 - 1000, T(1e50));
}

/// @return Returns the zero value representable by the numeric type T.
template <typename T>
constexpr typename std::enable_if<std::is_arithmetic<T>::value, T>::type
zero() {
  return T(0);
}

const long double pi = acos(-1.0);
<|endoftext|>


<commit_before>#include "libxtreemfs/object_cache.h"

#include <stdint.h>

#include <boost/optional.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/mutex.hpp>
#include <gtest/gtest_prod.h>
#include <list>
#include <map>
#include <string>

#include "xtreemfs/OSD.pb.h"
#include "rpc/sync_callback.h"

namespace xtreemfs {

static uint64_t Now() {
  return time(NULL);
}

CachedObject::CachedObject(int object_no, int object_size)
    : object_no_(object_no), object_size_(object_size),
      data_(NULL), actual_size_(0), is_dirty_(false),
      last_access_(Now()) {}
CachedObject::~CachedObject() {
  delete [] data_;
}

// Flush data and free memory
void CachedObject::Erase(ObjectWriter* writer) {
  boost::unique_lock<boost::mutex> lock(mutex_);
  if (is_dirty_) {
    WriteObjectToOSD(writer);
    is_dirty_ = false;
    delete [] data_;
    data_ = NULL;
    lock.unlock();
  }
}

int CachedObject::Read(int offset_in_object, char* buffer, int bytes_to_read,
                       ObjectReader* reader) {
  boost::unique_lock<boost::mutex> lock(mutex_);
  ReadInternal(lock, reader);
  int actual_bytes = std::min(bytes_to_read, actual_size_ - offset_in_object);
  memcpy(buffer, &data_[offset_in_object], actual_bytes);
  return actual_bytes;
}

void CachedObject::Write(int offset_in_object, const char* buffer,
                         int bytes_to_write, ObjectReader* reader) {
  boost::unique_lock<boost::mutex> lock(mutex_);
  ReadInternal(lock, reader);
  assert(bytes_to_write + offset_in_object < object_size_);
  memcpy(data_, &buffer[offset_in_object], bytes_to_write);
  actual_size_ = std::max(actual_size_, offset_in_object + bytes_to_write);
  is_dirty_ = true;
}

void CachedObject::Flush(ObjectWriter* writer) {
  boost::unique_lock<boost::mutex> lock(mutex_);
  if (is_dirty_) {
    // Write out a copy of the data asynchronously.
    WriteObjectToOSD(writer);
    is_dirty_ = false;
    // Other threads can continue to work with the buffer.
    // Another flush can happen in the meantime.
  }
  lock.unlock();
}

void CachedObject::Truncate(int new_object_size) {
  // TODO: fill up with zeros if extending?
  actual_size_ = new_object_size;
}

uint64_t CachedObject::last_access() const {
  return last_access_;
}

bool CachedObject::is_dirty() const {
  return is_dirty_;
}

void CachedObject::ReadInternal(boost::unique_lock<boost::mutex>& lock,
                               ObjectReader* reader) {
  if (ReadPending()) {
    if (read_queue_.size() == 0) {
      // Initial read
      ReadObjectFromOSD(lock, reader);  // unlocked synchronous read.
    } else {
      // Read already initiated
      boost::condition_variable* v = new boost::condition_variable();
      read_queue_.push_back(v);
      v->wait(lock);  // unlocks mutex
      delete v;  // has been dequeued already by our predecessor
    }
  }

  // We are done, next in line please.
  // It will enter when we release the lock, and wake up its successor.
  if (read_queue_.size() > 0) {
    boost::condition_variable* v = read_queue_.front();
    read_queue_.pop_front();
    v->notify_one();
  }
  last_access_ = Now();
}

void CachedObject::ReadObjectFromOSD(boost::unique_lock<boost::mutex>& lock,
                                     ObjectReader* reader) {
  lock.unlock();
  char* data = new char[object_size_];
  int read = (*reader)(object_no_, data);
  lock.lock();

  data_ = data;
  actual_size_ = read;
}

void CachedObject::WriteObjectToOSD(ObjectWriter* writer) {
  (*writer)(object_no_, data_, actual_size_);
}

bool CachedObject::ReadPending() {
  return data_ == NULL;
}

ObjectCache::ObjectCache(size_t max_objects, int object_size)
  : max_objects_(max_objects), object_size_(object_size) {
}
ObjectCache::~ObjectCache() {
  for (Cache::iterator i = cache_.begin(); i != cache_.end(); ++i) {
    delete i->second;
  }
}

int ObjectCache::Read(int object_no, int offset_in_object,
                      char* buffer, int bytes_to_read,
                      ObjectReader* reader) {
  CachedObject* object = LookupObject(object_no);
  return object->Read(offset_in_object, buffer, bytes_to_read, reader);
}

void ObjectCache::Write(int object_no, int offset_in_object,
                        const char* buffer, int bytes_to_write,
                        ObjectReader* reader) {
  CachedObject* object = LookupObject(object_no);
  object->Write(offset_in_object, buffer, bytes_to_write, reader);
}

void ObjectCache::Flush(ObjectWriter* writer) {
  while (true) {
    boost::unique_lock<boost::mutex> lock(mutex_);
    Cache::iterator i;
    for (i = cache_.begin(); i != cache_.end(); ++i) {
      if (i->second->is_dirty()) {
        CachedObject* object = i->second;
        lock.unlock();
        object->Flush(writer);
        break;  // start from beginning
      }
    }
    if (i == cache_.end()) {
      break;
    }
  }
}

void ObjectCache::Truncate(int new_size) {
  boost::unique_lock<boost::mutex> lock(mutex_);
  int object_to_cut = new_size / object_size_;
  for (Cache::iterator i = cache_.begin(); i != cache_.end(); ) {
    if (i->first == object_to_cut) {
      i->second->Truncate(new_size % object_size_);
    } else if (i->first > object_to_cut) {
      delete i->second;
      i = cache_.erase(i);
      continue;
    }
    ++i;
  }
}

CachedObject* ObjectCache::LookupObject(int object_no) {
  boost::unique_lock<boost::mutex> lock(mutex_);
  Cache::iterator i = cache_.find(object_no);
  if (i == cache_.end()) {
    cache_[object_no] = new CachedObject(object_no, object_size_);

    if (cache_.size() > max_objects_) {
      CollectLeasedObject();
    }
  }
  return cache_[object_no];
}

void ObjectCache::CollectLeasedObject() {
}

int ObjectCache::object_size() const {
  return object_size_;
}

}  // namespace xtreemfs<commit_msg>Minor fixes.<commit_after>#include "libxtreemfs/object_cache.h"

#include <stdint.h>

#include <boost/optional.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/mutex.hpp>
#include <gtest/gtest_prod.h>
#include <list>
#include <map>
#include <string>

#include "xtreemfs/OSD.pb.h"
#include "rpc/sync_callback.h"

namespace xtreemfs {

static uint64_t Now() {
  return time(NULL);
}

CachedObject::CachedObject(int object_no, int object_size)
    : object_no_(object_no), object_size_(object_size),
      data_(NULL), actual_size_(0), is_dirty_(false),
      last_access_(Now()) {}
CachedObject::~CachedObject() {
  delete [] data_;
}

// Flush data and free memory
void CachedObject::Erase(ObjectWriter* writer) {
  boost::unique_lock<boost::mutex> lock(mutex_);
  if (is_dirty_) {
    WriteObjectToOSD(writer);
    is_dirty_ = false;
    actual_size_ = 0;
    delete [] data_;
    data_ = NULL;
    lock.unlock();
  }
}

int CachedObject::Read(int offset_in_object, char* buffer, int bytes_to_read,
                       ObjectReader* reader) {
  boost::unique_lock<boost::mutex> lock(mutex_);
  ReadInternal(lock, reader);
  int actual_bytes = std::min(bytes_to_read, actual_size_ - offset_in_object);
  memcpy(buffer, &data_[offset_in_object], actual_bytes);
  last_access_ = Now();
  return actual_bytes;
}

void CachedObject::Write(int offset_in_object, const char* buffer,
                         int bytes_to_write, ObjectReader* reader) {
  boost::unique_lock<boost::mutex> lock(mutex_);
  ReadInternal(lock, reader);
  assert(bytes_to_write + offset_in_object < object_size_);
  memcpy(data_, &buffer[offset_in_object], bytes_to_write);
  actual_size_ = std::max(actual_size_, offset_in_object + bytes_to_write);
  is_dirty_ = true;
  last_access_ = Now();
}

void CachedObject::Flush(ObjectWriter* writer) {
  boost::unique_lock<boost::mutex> lock(mutex_);
  if (is_dirty_) {
    // Write out a copy of the data asynchronously.
    WriteObjectToOSD(writer);
    is_dirty_ = false;
    // Other threads can continue to work with the buffer.
    // Another flush can happen in the meantime.
  }
  lock.unlock();
}

void CachedObject::Truncate(int new_object_size) {
  // TODO: fill up with zeros if extending?
  actual_size_ = new_object_size;
}

uint64_t CachedObject::last_access() const {
  return last_access_;
}

bool CachedObject::is_dirty() const {
  return is_dirty_;
}

void CachedObject::ReadInternal(boost::unique_lock<boost::mutex>& lock,
                               ObjectReader* reader) {
  if (ReadPending()) {
    if (read_queue_.size() == 0) {
      // Initial read
      ReadObjectFromOSD(lock, reader);  // unlocked synchronous read.
    } else {
      // Read already initiated
      boost::condition_variable* v = new boost::condition_variable();
      read_queue_.push_back(v);
      v->wait(lock);  // unlocks mutex
      delete v;  // has been dequeued already by our predecessor
    }
  }

  // We are done, next in line please.
  // It will enter when we release the lock, and wake up its successor.
  if (read_queue_.size() > 0) {
    boost::condition_variable* v = read_queue_.front();
    read_queue_.pop_front();
    v->notify_one();
  }
}

void CachedObject::ReadObjectFromOSD(boost::unique_lock<boost::mutex>& lock,
                                     ObjectReader* reader) {
  lock.unlock();
  char* data = new char[object_size_];
  int read = (*reader)(object_no_, data);
  lock.lock();

  data_ = data;
  actual_size_ = read;
}

void CachedObject::WriteObjectToOSD(ObjectWriter* writer) {
  (*writer)(object_no_, data_, actual_size_);
}

bool CachedObject::ReadPending() {
  return data_ == NULL;
}

ObjectCache::ObjectCache(size_t max_objects, int object_size)
  : max_objects_(max_objects), object_size_(object_size) {
}
ObjectCache::~ObjectCache() {
  for (Cache::iterator i = cache_.begin(); i != cache_.end(); ++i) {
    delete i->second;
  }
}

int ObjectCache::Read(int object_no, int offset_in_object,
                      char* buffer, int bytes_to_read,
                      ObjectReader* reader) {
  CachedObject* object = LookupObject(object_no);
  return object->Read(offset_in_object, buffer, bytes_to_read, reader);
}

void ObjectCache::Write(int object_no, int offset_in_object,
                        const char* buffer, int bytes_to_write,
                        ObjectReader* reader) {
  CachedObject* object = LookupObject(object_no);
  object->Write(offset_in_object, buffer, bytes_to_write, reader);
}

void ObjectCache::Flush(ObjectWriter* writer) {
  while (true) {
    boost::unique_lock<boost::mutex> lock(mutex_);
    Cache::iterator i;
    for (i = cache_.begin(); i != cache_.end(); ++i) {
      if (i->second->is_dirty()) {
        CachedObject* object = i->second;
        lock.unlock();
        object->Flush(writer);
        break;  // start from beginning
      }
    }
    if (i == cache_.end()) {
      break;
    }
  }
}

void ObjectCache::Truncate(int new_size) {
  boost::unique_lock<boost::mutex> lock(mutex_);
  int object_to_cut = new_size / object_size_;
  for (Cache::iterator i = cache_.begin(); i != cache_.end(); ) {
    if (i->first == object_to_cut) {
      i->second->Truncate(new_size % object_size_);
    } else if (i->first > object_to_cut) {
      delete i->second;
      i = cache_.erase(i);
      continue;
    }
    ++i;
  }
}

CachedObject* ObjectCache::LookupObject(int object_no) {
  boost::unique_lock<boost::mutex> lock(mutex_);
  Cache::iterator i = cache_.find(object_no);
  if (i == cache_.end()) {
    cache_[object_no] = new CachedObject(object_no, object_size_);

    if (cache_.size() > max_objects_) {
      CollectLeasedObject();
    }
  }
  return cache_[object_no];
}

void ObjectCache::CollectLeasedObject() {
}

int ObjectCache::object_size() const {
  return object_size_;
}

}  // namespace xtreemfs<|endoftext|>


<commit_before>#include "rewritingexception.h"

using namespace QmlDesigner;

RewritingException::RewritingException(int line,
                                       const QString &function,
                                       const QString &file, const QString &description):
        Exception(line, function, file), m_description(description)
{
}

QString RewritingException::type() const
{
    return "RewritingException";
}

QString RewritingException::description() const
{
    return QLatin1String("Rewriting: ") + m_description;
}
<commit_msg>QmlDesigner: cleaning up description of rewritingexception<commit_after>#include "rewritingexception.h"

using namespace QmlDesigner;

RewritingException::RewritingException(int line,
                                       const QString &function,
                                       const QString &file, const QString &description):
        Exception(line, function, file), m_description(description)
{
}

QString RewritingException::type() const
{
    return "RewritingException";
}

QString RewritingException::description() const
{
    return m_description;
}
<|endoftext|>


<commit_before>/**
 * @file lltransientfloatermgr.cpp
 * @brief LLFocusMgr base class
 *
 * $LicenseInfo:firstyear=2002&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "lltransientfloatermgr.h"
#include "llfocusmgr.h"
#include "llrootview.h"
#include "llviewerwindow.h"
#include "lldockablefloater.h"
#include "llmenugl.h"

LLTransientFloaterMgr::LLTransientFloaterMgr()
{
	if(gViewerWindow)
	{
		gViewerWindow->getRootView()->getChild<LLUICtrl>("popup_holder")->setMouseDownCallback(boost::bind(
			&LLTransientFloaterMgr::leftMouseClickCallback, this, _2, _3, _4));
	}

	mGroupControls.insert(std::pair<ETransientGroup, controls_set_t >(GLOBAL, controls_set_t()));
	mGroupControls.insert(std::pair<ETransientGroup, controls_set_t >(DOCKED, controls_set_t()));
	mGroupControls.insert(std::pair<ETransientGroup, controls_set_t >(IM, controls_set_t()));
}

void LLTransientFloaterMgr::registerTransientFloater(LLTransientFloater* floater)
{
	mTransSet.insert(floater);
}

void LLTransientFloaterMgr::unregisterTransientFloater(LLTransientFloater* floater)
{
	mTransSet.erase(floater);
}

void LLTransientFloaterMgr::addControlView(ETransientGroup group, LLView* view)
{
	if (!view) return;

	mGroupControls.find(group)->second.insert(view->getHandle());
}

void LLTransientFloaterMgr::removeControlView(ETransientGroup group, LLView* view)
{
	if (!view) return;

	mGroupControls.find(group)->second.erase(view->getHandle());
}

void LLTransientFloaterMgr::addControlView(LLView* view)
{
	addControlView(GLOBAL, view);
}

void LLTransientFloaterMgr::removeControlView(LLView* view)
{
	// we will still get focus lost callbacks on this view, but that's ok
	// since we run sanity checking logic every time
	removeControlView(GLOBAL, view);
}

void LLTransientFloaterMgr::hideTransientFloaters(S32 x, S32 y)
{
	for (std::set<LLTransientFloater*>::iterator it = mTransSet.begin(); it
			!= mTransSet.end(); it++)
	{
		LLTransientFloater* floater = *it;
		if (floater->isTransientDocked())
		{
			ETransientGroup group = floater->getGroup();

			bool hide = isControlClicked(group, mGroupControls.find(group)->second, x, y);
			if (hide)
			{
				floater->setTransientVisible(FALSE);
			}
		}
	}
}

bool LLTransientFloaterMgr::isControlClicked(ETransientGroup group, controls_set_t& set, S32 x, S32 y)
{
	bool res = true;
	for (controls_set_t::iterator it = set.begin(); it
			!= set.end(); it++)
	{
		LLView* control_view = NULL;

		LLHandle<LLView> handle = *it;
		if (handle.isDead())
		{
			mGroupControls.find(group)->second.erase(handle);
			continue;
		}

		control_view = handle.get();

		if (!control_view->getVisible())
		{
			continue;
		}

		LLRect rect = control_view->calcScreenRect();
		// if click inside view rect
		if (rect.pointInRect(x, y))
		{
			res = false;
			break;
		}
	}
	return res;
}

void LLTransientFloaterMgr::leftMouseClickCallback(S32 x, S32 y,
		MASK mask)
{
	// don't hide transient floater if any context menu opened
	if (LLMenuGL::sMenuContainer->getVisibleMenu() != NULL)
	{
		return;
	}

	bool hide = isControlClicked(DOCKED, mGroupControls.find(DOCKED)->second, x, y)
			&& isControlClicked(GLOBAL, mGroupControls.find(GLOBAL)->second, x, y);
	if (hide)
	{
		hideTransientFloaters(x, y);
	}
}

void LLTransientFloater::init(LLFloater* thiz)
{
	// used since LLTransientFloater(this) can't be used in descendant constructor parameter initialization.
	mFloater = thiz;
}

<commit_msg>EXP-1462 FIX -- Moving speak button or voice settings button between toolbars can cause viewer to crash on Mac<commit_after>/**
 * @file lltransientfloatermgr.cpp
 * @brief LLFocusMgr base class
 *
 * $LicenseInfo:firstyear=2002&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "llviewerprecompiledheaders.h"

#include "lltransientfloatermgr.h"
#include "llfocusmgr.h"
#include "llrootview.h"
#include "llviewerwindow.h"
#include "lldockablefloater.h"
#include "llmenugl.h"

LLTransientFloaterMgr::LLTransientFloaterMgr()
{
	if(gViewerWindow)
	{
		gViewerWindow->getRootView()->getChild<LLUICtrl>("popup_holder")->setMouseDownCallback(boost::bind(
			&LLTransientFloaterMgr::leftMouseClickCallback, this, _2, _3, _4));
	}

	mGroupControls.insert(std::pair<ETransientGroup, controls_set_t >(GLOBAL, controls_set_t()));
	mGroupControls.insert(std::pair<ETransientGroup, controls_set_t >(DOCKED, controls_set_t()));
	mGroupControls.insert(std::pair<ETransientGroup, controls_set_t >(IM, controls_set_t()));
}

void LLTransientFloaterMgr::registerTransientFloater(LLTransientFloater* floater)
{
	mTransSet.insert(floater);
}

void LLTransientFloaterMgr::unregisterTransientFloater(LLTransientFloater* floater)
{
	mTransSet.erase(floater);
}

void LLTransientFloaterMgr::addControlView(ETransientGroup group, LLView* view)
{
	if (!view) return;

	mGroupControls.find(group)->second.insert(view->getHandle());
}

void LLTransientFloaterMgr::removeControlView(ETransientGroup group, LLView* view)
{
	if (!view) return;

	mGroupControls.find(group)->second.erase(view->getHandle());
}

void LLTransientFloaterMgr::addControlView(LLView* view)
{
	addControlView(GLOBAL, view);
}

void LLTransientFloaterMgr::removeControlView(LLView* view)
{
	// we will still get focus lost callbacks on this view, but that's ok
	// since we run sanity checking logic every time
	removeControlView(GLOBAL, view);
}

void LLTransientFloaterMgr::hideTransientFloaters(S32 x, S32 y)
{
	for (std::set<LLTransientFloater*>::iterator it = mTransSet.begin(); it
			!= mTransSet.end(); it++)
	{
		LLTransientFloater* floater = *it;
		if (floater->isTransientDocked())
		{
			ETransientGroup group = floater->getGroup();

			bool hide = isControlClicked(group, mGroupControls.find(group)->second, x, y);
			if (hide)
			{
				floater->setTransientVisible(FALSE);
			}
		}
	}
}

bool LLTransientFloaterMgr::isControlClicked(ETransientGroup group, controls_set_t& set, S32 x, S32 y)
{
	std::list< LLHandle<LLView> > dead_handles;

	bool res = true;
	for (controls_set_t::iterator it = set.begin(); it
			!= set.end(); it++)
	{
		LLView* control_view = NULL;

		LLHandle<LLView> handle = *it;
		if (handle.isDead())
		{
			dead_handles.push_back(handle);
			continue;
		}

		control_view = handle.get();

		if (!control_view->getVisible())
		{
			continue;
		}

		LLRect rect = control_view->calcScreenRect();
		// if click inside view rect
		if (rect.pointInRect(x, y))
		{
			res = false;
			break;
		}
	}

	for (std::list< LLHandle<LLView> >::iterator it = dead_handles.begin(); it != dead_handles.end(); ++it)
	{
		LLHandle<LLView> handle = *it;
		mGroupControls.find(group)->second.erase(handle);
	}

	return res;
}

void LLTransientFloaterMgr::leftMouseClickCallback(S32 x, S32 y,
		MASK mask)
{
	// don't hide transient floater if any context menu opened
	if (LLMenuGL::sMenuContainer->getVisibleMenu() != NULL)
	{
		return;
	}

	bool hide = isControlClicked(DOCKED, mGroupControls.find(DOCKED)->second, x, y)
			&& isControlClicked(GLOBAL, mGroupControls.find(GLOBAL)->second, x, y);
	if (hide)
	{
		hideTransientFloaters(x, y);
	}
}

void LLTransientFloater::init(LLFloater* thiz)
{
	// used since LLTransientFloater(this) can't be used in descendant constructor parameter initialization.
	mFloater = thiz;
}

<|endoftext|>


<commit_before>//===-- OptionValueFileSpec.cpp ---------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Interpreter/OptionValueFileSpec.h"

// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Core/FormatManager.h"
#include "lldb/Core/State.h"
#include "lldb/Interpreter/Args.h"
#include "lldb/Interpreter/CommandCompletions.h"

using namespace lldb;
using namespace lldb_private;

OptionValueFileSpec::OptionValueFileSpec () :
    OptionValue(),
    m_current_value (),
    m_default_value (),
    m_data_sp(),
    m_completion_mask (CommandCompletions::eDiskFileCompletion)
{
}

OptionValueFileSpec::OptionValueFileSpec (const FileSpec &value) :
    OptionValue(),
    m_current_value (value),
    m_default_value (value),
    m_data_sp(),
    m_completion_mask (CommandCompletions::eDiskFileCompletion)
{
}

OptionValueFileSpec::OptionValueFileSpec (const FileSpec &current_value,
                                          const FileSpec &default_value) :
    OptionValue(),
    m_current_value (current_value),
    m_default_value (default_value),
    m_data_sp(),
    m_completion_mask (CommandCompletions::eDiskFileCompletion)
{
}

void
OptionValueFileSpec::DumpValue (const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask)
{
    if (dump_mask & eDumpOptionType)
        strm.Printf ("(%s)", GetTypeAsCString ());
    if (dump_mask & eDumpOptionValue)
    {
        if (dump_mask & eDumpOptionType)
            strm.PutCString (" = ");

        if (m_current_value)
        {
            if (m_current_value.GetDirectory())
            {
                strm << '"' << m_current_value.GetDirectory();
                if (m_current_value.GetFilename())
                    strm << '/' << m_current_value.GetFilename();
                strm << '"';
            }
            else
            {
                strm << '"' << m_current_value.GetFilename() << '"';
            }
        }
    }
}

Error
OptionValueFileSpec::SetValueFromCString (const char *value_cstr,
                                          VarSetOperationType op)
{
    Error error;
    switch (op)
    {
    case eVarSetOperationClear:
        Clear ();
        break;

    case eVarSetOperationReplace:
    case eVarSetOperationAssign:
        if (value_cstr && value_cstr[0])
        {
            m_value_was_set = true;
            m_current_value.SetFile(value_cstr, false);
        }
        else
        {
            error.SetErrorString("invalid value string");
        }
        break;

    case eVarSetOperationInsertBefore:
    case eVarSetOperationInsertAfter:
    case eVarSetOperationRemove:
    case eVarSetOperationAppend:
    case eVarSetOperationInvalid:
        error = OptionValue::SetValueFromCString (value_cstr, op);
        break;
    }
    return error;
}

lldb::OptionValueSP
OptionValueFileSpec::DeepCopy () const
{
    return OptionValueSP(new OptionValueFileSpec(*this));
}

size_t
OptionValueFileSpec::AutoComplete (CommandInterpreter &interpreter,
                                   const char *s,
                                   int match_start_point,
                                   int max_return_elements,
                                   bool &word_complete,
                                   StringList &matches)
{
    word_complete = false;
    matches.Clear();
    CommandCompletions::InvokeCommonCompletionCallbacks (interpreter,
                                                         m_completion_mask,
                                                         s,
                                                         match_start_point,
                                                         max_return_elements,
                                                         NULL,
                                                         word_complete,
                                                         matches);
    return matches.GetSize();
}

const lldb::DataBufferSP &
OptionValueFileSpec::GetFileContents(bool null_terminate)
{
    if (!m_data_sp && m_current_value)
    {
        if (null_terminate)
            m_data_sp = m_current_value.ReadFileContentsAsCString();
        else
            m_data_sp = m_current_value.ReadFileContents();
    }
    return m_data_sp;
}

<commit_msg>When OptionValueFileSpec is given a filename starting with ~, we need to realpath it.  Fixes the case where<commit_after>//===-- OptionValueFileSpec.cpp ---------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Interpreter/OptionValueFileSpec.h"

// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Core/FormatManager.h"
#include "lldb/Core/State.h"
#include "lldb/Interpreter/Args.h"
#include "lldb/Interpreter/CommandCompletions.h"

using namespace lldb;
using namespace lldb_private;

OptionValueFileSpec::OptionValueFileSpec () :
    OptionValue(),
    m_current_value (),
    m_default_value (),
    m_data_sp(),
    m_completion_mask (CommandCompletions::eDiskFileCompletion)
{
}

OptionValueFileSpec::OptionValueFileSpec (const FileSpec &value) :
    OptionValue(),
    m_current_value (value),
    m_default_value (value),
    m_data_sp(),
    m_completion_mask (CommandCompletions::eDiskFileCompletion)
{
}

OptionValueFileSpec::OptionValueFileSpec (const FileSpec &current_value,
                                          const FileSpec &default_value) :
    OptionValue(),
    m_current_value (current_value),
    m_default_value (default_value),
    m_data_sp(),
    m_completion_mask (CommandCompletions::eDiskFileCompletion)
{
}

void
OptionValueFileSpec::DumpValue (const ExecutionContext *exe_ctx, Stream &strm, uint32_t dump_mask)
{
    if (dump_mask & eDumpOptionType)
        strm.Printf ("(%s)", GetTypeAsCString ());
    if (dump_mask & eDumpOptionValue)
    {
        if (dump_mask & eDumpOptionType)
            strm.PutCString (" = ");

        if (m_current_value)
        {
            if (m_current_value.GetDirectory())
            {
                strm << '"' << m_current_value.GetDirectory();
                if (m_current_value.GetFilename())
                    strm << '/' << m_current_value.GetFilename();
                strm << '"';
            }
            else
            {
                strm << '"' << m_current_value.GetFilename() << '"';
            }
        }
    }
}

Error
OptionValueFileSpec::SetValueFromCString (const char *value_cstr,
                                          VarSetOperationType op)
{
    Error error;
    switch (op)
    {
    case eVarSetOperationClear:
        Clear ();
        break;

    case eVarSetOperationReplace:
    case eVarSetOperationAssign:
        if (value_cstr && value_cstr[0])
        {
            m_value_was_set = true;
            m_current_value.SetFile(value_cstr, value_cstr[0] == '~');
        }
        else
        {
            error.SetErrorString("invalid value string");
        }
        break;

    case eVarSetOperationInsertBefore:
    case eVarSetOperationInsertAfter:
    case eVarSetOperationRemove:
    case eVarSetOperationAppend:
    case eVarSetOperationInvalid:
        error = OptionValue::SetValueFromCString (value_cstr, op);
        break;
    }
    return error;
}

lldb::OptionValueSP
OptionValueFileSpec::DeepCopy () const
{
    return OptionValueSP(new OptionValueFileSpec(*this));
}

size_t
OptionValueFileSpec::AutoComplete (CommandInterpreter &interpreter,
                                   const char *s,
                                   int match_start_point,
                                   int max_return_elements,
                                   bool &word_complete,
                                   StringList &matches)
{
    word_complete = false;
    matches.Clear();
    CommandCompletions::InvokeCommonCompletionCallbacks (interpreter,
                                                         m_completion_mask,
                                                         s,
                                                         match_start_point,
                                                         max_return_elements,
                                                         NULL,
                                                         word_complete,
                                                         matches);
    return matches.GetSize();
}

const lldb::DataBufferSP &
OptionValueFileSpec::GetFileContents(bool null_terminate)
{
    if (!m_data_sp && m_current_value)
    {
        if (null_terminate)
            m_data_sp = m_current_value.ReadFileContentsAsCString();
        else
            m_data_sp = m_current_value.ReadFileContents();
    }
    return m_data_sp;
}

<|endoftext|>