<commit_before>/*************************************************************************
 *
 *  $RCSfile: interactionhandler.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-13 19:03:25 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#include <jni.h>

//#include <iostream>
#include <stdio.h>
#include <sal/main.h>
#include <rtl/process.h>

#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/weak.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <osl/thread.h>

#include <com/sun/star/registry/XSimpleRegistry.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/java/XJavaVM.hpp>
#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/java/XJavaThreadRegister_11.hpp>

#include <com/sun/star/uno/XCurrentContext.hpp>
#include <com/sun/star/task/XInteractionHandler.hpp>
#include <com/sun/star/task/XInteractionRequest.hpp>
#include <com/sun/star/task/XInteractionContinuation.hpp>
#include <com/sun/star/task/XInteractionAbort.hpp>
#include <com/sun/star/task/XInteractionRetry.hpp>
#include <com/sun/star/java/JavaNotConfiguredException.hpp>
#include <com/sun/star/java/MissingJavaRuntimeException.hpp>
#include <com/sun/star/java/JavaDisabledException.hpp>
#include <com/sun/star/java/JavaVMCreationFailureException.hpp>
#include <cppuhelper/implbase1.hxx>
#include <uno/current_context.hxx>
using namespace std;
using namespace rtl;
using namespace cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
//using namespace com::sun::star::reflection;
using namespace com::sun::star::lang;
using namespace com::sun::star::registry;
using namespace com::sun::star::java;
using namespace com::sun::star::task;

#define OUSTR( x ) OUString(RTL_CONSTASCII_USTRINGPARAM( x ))
#define INTERACTION_HANDLER_NAME "java-vm.interaction-handler"

class Context: public WeakImplHelper1<XCurrentContext>
{
    virtual Any SAL_CALL getValueByName( const OUString& Name ) throw (RuntimeException);
};

class InteractionHandler: public WeakImplHelper1<XInteractionHandler>
{
    virtual void SAL_CALL handle( const Reference< XInteractionRequest >& Request )
        throw (RuntimeException);
};

Any SAL_CALL Context::getValueByName( const OUString& Name) throw (RuntimeException)
{
    Any retVal;
    if( Name.equals( OUSTR(INTERACTION_HANDLER_NAME)))
    {
        Reference<XInteractionHandler> handler( static_cast<XWeak*>(new InteractionHandler()),
                                                UNO_QUERY);
        retVal <<= handler;
    }
    return retVal;
}

void SAL_CALL InteractionHandler::handle( const Reference< XInteractionRequest >& Request )
        throw (RuntimeException)
{
    Any anyExc= Request->getRequest();
    Sequence<Reference< XInteractionContinuation> >seqCont= Request->getContinuations();

    Reference<XInteractionAbort> abort;
    Reference<XInteractionRetry> retry;

    for (sal_Int32 i= 0; i < seqCont.getLength(); i++)
    {
        abort= Reference<XInteractionAbort>::query( seqCont[i]);
        if(abort.is())
            break;
    }
    for (sal_Int32 i= 0; i < seqCont.getLength(); i++)
    {
        retry= Reference<XInteractionRetry>::query( seqCont[i]);
        if(retry.is())
            break;
    }

//     if( abort.is())
//         abort->select();

    static int cRetry= 0;

    if( cRetry++ == 5)
    {
        if( abort.is())
            abort->select();
        return;
    }
    if( retry.is())
         retry->select();
}

sal_Bool test1(const Reference< XMultiServiceFactory > & xMgr )
{
    sal_Bool retVal= sal_True;
    setCurrentContext( Reference<XCurrentContext>( static_cast<XWeak*>(new Context()), UNO_QUERY));

      OUString sVMService( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.java.JavaVirtualMachine"));
    Reference<XInterface> xXInt= xMgr->createInstance(sVMService);
    if( ! xXInt.is())
        return sal_False;
    Reference<XJavaVM> xVM( xXInt, UNO_QUERY);
    if( ! xVM.is())
        return sal_False;

    sal_Int8 arId[16];
    rtl_getGlobalProcessId((sal_uInt8*) arId);

    Any anyVM;
    try
    {
        anyVM = xVM->getJavaVM( Sequence<sal_Int8>(arId, 16));
    }
    catch (JavaNotConfiguredException& e)
    {
        OString msg= OUStringToOString(e.Message, osl_getThreadTextEncoding());
        printf("JavaNotConfiguredException: %s\n", msg.getStr());
    }
    catch (JavaVMCreationFailureException& e)
    {
        OString msg= OUStringToOString(e.Message, osl_getThreadTextEncoding());
        printf("JavaVMCreationFailureException: %s\n", msg.getStr());
    }
    catch (MissingJavaRuntimeException& e)
    {
        OString msg= OUStringToOString(e.Message, osl_getThreadTextEncoding());
        printf("MissingJavaRuntimeException: %s\n", msg.getStr());
    }
    catch (JavaDisabledException& e)
    {
        OString msg= OUStringToOString(e.Message, osl_getThreadTextEncoding());
        printf("JavaDisabledException: %s\n", msg.getStr());
    }
    catch (RuntimeException & e)
    {
        OString msg= OUStringToOString(e.Message, osl_getThreadTextEncoding());
        printf("###RuntimeException: %s\n", msg.getStr());
        retVal= sal_False;
    }
    return retVal;
}

SAL_IMPLEMENT_MAIN()
{
    Reference<XSimpleRegistry> xreg= createSimpleRegistry();
    xreg->open( OUString( RTL_CONSTASCII_USTRINGPARAM("applicat.rdb")),
                               sal_False, sal_False );

    Reference< XComponentContext > context= bootstrap_InitialComponentContext(xreg);
    Reference<XMultiComponentFactory> fac= context->getServiceManager();
    Reference<XMultiServiceFactory> xMgr( fac, UNO_QUERY);

    sal_Bool bSucc = sal_False;
    bSucc= test1(xMgr);
    Reference< XComponent > xCompContext( context, UNO_QUERY );
    xCompContext->dispose();
    return (bSucc ? 0 : -1);
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.4.28); FILE MERGED 2005/09/05 17:11:37 rt 1.4.28.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: interactionhandler.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 08:28:53 $
 *
 *  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
 *
 ************************************************************************/

#include <jni.h>

//#include <iostream>
#include <stdio.h>
#include <sal/main.h>
#include <rtl/process.h>

#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/weak.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <osl/thread.h>

#include <com/sun/star/registry/XSimpleRegistry.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/java/XJavaVM.hpp>
#include <com/sun/star/registry/XImplementationRegistration.hpp>
#include <com/sun/star/java/XJavaThreadRegister_11.hpp>

#include <com/sun/star/uno/XCurrentContext.hpp>
#include <com/sun/star/task/XInteractionHandler.hpp>
#include <com/sun/star/task/XInteractionRequest.hpp>
#include <com/sun/star/task/XInteractionContinuation.hpp>
#include <com/sun/star/task/XInteractionAbort.hpp>
#include <com/sun/star/task/XInteractionRetry.hpp>
#include <com/sun/star/java/JavaNotConfiguredException.hpp>
#include <com/sun/star/java/MissingJavaRuntimeException.hpp>
#include <com/sun/star/java/JavaDisabledException.hpp>
#include <com/sun/star/java/JavaVMCreationFailureException.hpp>
#include <cppuhelper/implbase1.hxx>
#include <uno/current_context.hxx>
using namespace std;
using namespace rtl;
using namespace cppu;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
//using namespace com::sun::star::reflection;
using namespace com::sun::star::lang;
using namespace com::sun::star::registry;
using namespace com::sun::star::java;
using namespace com::sun::star::task;

#define OUSTR( x ) OUString(RTL_CONSTASCII_USTRINGPARAM( x ))
#define INTERACTION_HANDLER_NAME "java-vm.interaction-handler"

class Context: public WeakImplHelper1<XCurrentContext>
{
    virtual Any SAL_CALL getValueByName( const OUString& Name ) throw (RuntimeException);
};

class InteractionHandler: public WeakImplHelper1<XInteractionHandler>
{
    virtual void SAL_CALL handle( const Reference< XInteractionRequest >& Request )
        throw (RuntimeException);
};

Any SAL_CALL Context::getValueByName( const OUString& Name) throw (RuntimeException)
{
    Any retVal;
    if( Name.equals( OUSTR(INTERACTION_HANDLER_NAME)))
    {
        Reference<XInteractionHandler> handler( static_cast<XWeak*>(new InteractionHandler()),
                                                UNO_QUERY);
        retVal <<= handler;
    }
    return retVal;
}

void SAL_CALL InteractionHandler::handle( const Reference< XInteractionRequest >& Request )
        throw (RuntimeException)
{
    Any anyExc= Request->getRequest();
    Sequence<Reference< XInteractionContinuation> >seqCont= Request->getContinuations();

    Reference<XInteractionAbort> abort;
    Reference<XInteractionRetry> retry;

    for (sal_Int32 i= 0; i < seqCont.getLength(); i++)
    {
        abort= Reference<XInteractionAbort>::query( seqCont[i]);
        if(abort.is())
            break;
    }
    for (sal_Int32 i= 0; i < seqCont.getLength(); i++)
    {
        retry= Reference<XInteractionRetry>::query( seqCont[i]);
        if(retry.is())
            break;
    }

//     if( abort.is())
//         abort->select();

    static int cRetry= 0;

    if( cRetry++ == 5)
    {
        if( abort.is())
            abort->select();
        return;
    }
    if( retry.is())
         retry->select();
}

sal_Bool test1(const Reference< XMultiServiceFactory > & xMgr )
{
    sal_Bool retVal= sal_True;
    setCurrentContext( Reference<XCurrentContext>( static_cast<XWeak*>(new Context()), UNO_QUERY));

      OUString sVMService( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.java.JavaVirtualMachine"));
    Reference<XInterface> xXInt= xMgr->createInstance(sVMService);
    if( ! xXInt.is())
        return sal_False;
    Reference<XJavaVM> xVM( xXInt, UNO_QUERY);
    if( ! xVM.is())
        return sal_False;

    sal_Int8 arId[16];
    rtl_getGlobalProcessId((sal_uInt8*) arId);

    Any anyVM;
    try
    {
        anyVM = xVM->getJavaVM( Sequence<sal_Int8>(arId, 16));
    }
    catch (JavaNotConfiguredException& e)
    {
        OString msg= OUStringToOString(e.Message, osl_getThreadTextEncoding());
        printf("JavaNotConfiguredException: %s\n", msg.getStr());
    }
    catch (JavaVMCreationFailureException& e)
    {
        OString msg= OUStringToOString(e.Message, osl_getThreadTextEncoding());
        printf("JavaVMCreationFailureException: %s\n", msg.getStr());
    }
    catch (MissingJavaRuntimeException& e)
    {
        OString msg= OUStringToOString(e.Message, osl_getThreadTextEncoding());
        printf("MissingJavaRuntimeException: %s\n", msg.getStr());
    }
    catch (JavaDisabledException& e)
    {
        OString msg= OUStringToOString(e.Message, osl_getThreadTextEncoding());
        printf("JavaDisabledException: %s\n", msg.getStr());
    }
    catch (RuntimeException & e)
    {
        OString msg= OUStringToOString(e.Message, osl_getThreadTextEncoding());
        printf("###RuntimeException: %s\n", msg.getStr());
        retVal= sal_False;
    }
    return retVal;
}

SAL_IMPLEMENT_MAIN()
{
    Reference<XSimpleRegistry> xreg= createSimpleRegistry();
    xreg->open( OUString( RTL_CONSTASCII_USTRINGPARAM("applicat.rdb")),
                               sal_False, sal_False );

    Reference< XComponentContext > context= bootstrap_InitialComponentContext(xreg);
    Reference<XMultiComponentFactory> fac= context->getServiceManager();
    Reference<XMultiServiceFactory> xMgr( fac, UNO_QUERY);

    sal_Bool bSucc = sal_False;
    bSucc= test1(xMgr);
    Reference< XComponent > xCompContext( context, UNO_QUERY );
    xCompContext->dispose();
    return (bSucc ? 0 : -1);
}

<|endoftext|>


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

#define DEFAULT_LINE_SPACING  200
#define FIX_DIST_DEF          283
#define LINESPACE_1           100
#define LINESPACE_15          150
#define LINESPACE_2           200
#define LINESPACE_115         115

// values of the mpLineDist listbox
#define LLINESPACE_1          0
#define LLINESPACE_15         1
#define LLINESPACE_2          2
#define LLINESPACE_PROP       3
#define LLINESPACE_MIN        4
#define LLINESPACE_DURCH      5
#define LLINESPACE_FIX        6

// special case; should not conflict with the mpLinDist values
#define LLINESPACE_115        7

#define MIN_FIXED_DISTANCE    28

using namespace svx;
using namespace svx::sidebar;

ParaLineSpacingControl::ParaLineSpacingControl(sal_uInt16 nId)
    : SfxPopupWindow(nId, "ParaLineSpacingControl", "svx/ui/paralinespacingcontrol.ui")
{
    mpSpacing1Button = get<PushButton>("spacing_1");
    mpSpacing115Button = get<PushButton>("spacing_115");
    mpSpacing15Button = get<PushButton>("spacing_15");
    mpSpacing2Button = get<PushButton>("spacing_2");

    mpLineDist = get<ListBox>("line_dist");

    mpLineDistLabel = get<FixedText>("value_label");
    mpLineDistAtPercentBox = get<MetricField>("percent_box");
    mpLineDistAtMetricBox = get<MetricField>("metric_box");

    mpActLineDistFld = mpLineDistAtPercentBox;

    meLNSpaceUnit = SFX_MAPUNIT_100TH_MM;

    Link aLink = LINK(this, ParaLineSpacingControl, PredefinedValuesHandler);
    mpSpacing1Button->SetClickHdl(aLink);
    mpSpacing115Button->SetClickHdl(aLink);
    mpSpacing15Button->SetClickHdl(aLink);
    mpSpacing2Button->SetClickHdl(aLink);

    aLink = LINK( this, ParaLineSpacingControl, LineSPDistHdl_Impl );
    mpLineDist->SetSelectHdl(aLink);
    SelectEntryPos(LLINESPACE_1);

    aLink = LINK( this, ParaLineSpacingControl, LineSPDistAtHdl_Impl );
    mpLineDistAtPercentBox->SetModifyHdl( aLink );
    mpLineDistAtMetricBox->SetModifyHdl( aLink );
    SetFieldUnit(*mpLineDistAtMetricBox, SfxModule::GetCurrentFieldUnit());

    initialize();
}

ParaLineSpacingControl::~ParaLineSpacingControl()
{
}

void ParaLineSpacingControl::initialize()
{
    const SfxPoolItem* pItem;
    SfxItemState eState = SfxViewFrame::Current()->GetBindings().GetDispatcher()->QueryState(SID_ATTR_PARA_LINESPACE, pItem);

    const SvxLineSpacingItem* currSPItem = static_cast<const SvxLineSpacingItem*>(pItem);

    mpLineDist->Enable();

    if( eState >= SfxItemState::DEFAULT )
    {
    //  SfxMapUnit eUnit = maLNSpaceControl.GetCoreMetric();
        SfxMapUnit eUnit = SFX_MAPUNIT_100TH_MM;
        meLNSpaceUnit = eUnit;

        switch( currSPItem->GetLineSpaceRule() )
        {
        case SVX_LINE_SPACE_AUTO:
            {
                SvxInterLineSpace eInter = currSPItem->GetInterLineSpaceRule();

                switch( eInter )
                {
                case SVX_INTER_LINE_SPACE_OFF:
                    SelectEntryPos(LLINESPACE_1);
                    break;

                case SVX_INTER_LINE_SPACE_PROP:
                    {
                        if ( LINESPACE_1 == currSPItem->GetPropLineSpace() )
                        {
                            SelectEntryPos(LLINESPACE_1);
                        }
                        else if ( LINESPACE_15 == currSPItem->GetPropLineSpace() )
                        {
                            SelectEntryPos(LLINESPACE_15);
                        }
                        else if ( LINESPACE_2 == currSPItem->GetPropLineSpace() )
                        {
                            SelectEntryPos(LLINESPACE_2);
                        }
                        else
                        {
                            SelectEntryPos(LLINESPACE_PROP);
                            mpLineDistAtPercentBox->SetValue(mpLineDistAtPercentBox->Normalize(currSPItem->GetPropLineSpace()));
                        }
                    }
                    break;

                case SVX_INTER_LINE_SPACE_FIX:
                    {
                        SelectEntryPos(LLINESPACE_DURCH);
                        SetMetricValue(*mpLineDistAtMetricBox, currSPItem->GetInterLineSpace(), eUnit);
                    }
                    break;
                default:
                    break;
                }
            }
            break;
        case SVX_LINE_SPACE_FIX:
            {
                SelectEntryPos(LLINESPACE_FIX);
                SetMetricValue(*mpLineDistAtMetricBox, currSPItem->GetLineHeight(), eUnit);
            }
            break;

        case SVX_LINE_SPACE_MIN:
            {
                SelectEntryPos(LLINESPACE_MIN);
                SetMetricValue(*mpLineDistAtMetricBox, currSPItem->GetLineHeight(), eUnit);
            }
            break;
        default:
            break;
        }
    }
    else if( eState == SfxItemState::DISABLED )
    {
        mpLineDist->Disable();
        mpLineDistLabel->Disable();
        mpActLineDistFld->Disable();
        mpActLineDistFld->SetText("");

    }
    else
    {
        mpLineDistLabel->Disable();
        mpActLineDistFld->Disable();
        mpActLineDistFld->SetText("");
        mpLineDist->SetNoSelection();
    }

    mpLineDist->SaveValue();

    /* TODO
    const sal_uInt16 uCount = mpLineDist->GetEntryCount();
    if( uCount == LLINESPACE_FIX + 1 )
    {
        switch (currentContext.GetCombinedContext_DI())
        {
        case CombinedEnumContext(Application_DrawImpress, Context_Table):
        case CombinedEnumContext(Application_DrawImpress, Context_DrawText):
        case CombinedEnumContext(Application_DrawImpress, Context_Draw):
        case CombinedEnumContext(Application_DrawImpress, Context_TextObject):
        case CombinedEnumContext(Application_DrawImpress, Context_Graphic):
        case CombinedEnumContext(Application_Calc, Context_DrawText):
        case CombinedEnumContext(Application_WriterVariants, Context_DrawText):
        case CombinedEnumContext(Application_WriterVariants, Context_Annotation):
            {
                mpLineDist->RemoveEntry(LLINESPACE_FIX);
            }
        }
    }
    else if( uCount == LLINESPACE_FIX)
    {
        switch (currentContext.GetCombinedContext_DI())
        {
            case CombinedEnumContext(Application_WriterVariants, Context_Default):
            case CombinedEnumContext(Application_WriterVariants, Context_Text):
            case CombinedEnumContext(Application_WriterVariants, Context_Table):
            {
                mpLineDist->InsertEntry(OUString("Fixed"), LLINESPACE_FIX);
            }
        }
    }
    */
}

void ParaLineSpacingControl::UpdateMetricFields()
{
    switch (mpLineDist->GetSelectEntryPos())
    {
        case LLINESPACE_1:
        case LLINESPACE_15:
        case LLINESPACE_2:
            if (mpActLineDistFld == mpLineDistAtPercentBox)
                mpLineDistAtMetricBox->Hide();
            else
                mpLineDistAtPercentBox->Hide();

            mpLineDistLabel->Disable();
            mpActLineDistFld->Show();
            mpActLineDistFld->Disable();
            mpActLineDistFld->SetText("");
            break;

        case LLINESPACE_DURCH:
            mpLineDistAtPercentBox->Hide();

            mpActLineDistFld = mpLineDistAtMetricBox;
            mpLineDistAtMetricBox->SetMin(0);

            if (mpLineDistAtMetricBox->GetText().isEmpty())
                mpLineDistAtMetricBox->SetValue(mpLineDistAtMetricBox->Normalize(0));

            mpLineDistLabel->Enable();
            mpActLineDistFld->Show();
            mpActLineDistFld->Enable();
            break;

        case LLINESPACE_MIN:
            mpLineDistAtPercentBox->Hide();

            mpActLineDistFld = mpLineDistAtMetricBox;
            mpLineDistAtMetricBox->SetMin(0);

            if (mpLineDistAtMetricBox->GetText().isEmpty())
                mpLineDistAtMetricBox->SetValue(mpLineDistAtMetricBox->Normalize(0), FUNIT_TWIP);

            mpLineDistLabel->Enable();
            mpActLineDistFld->Show();
            mpActLineDistFld->Enable();
            break;

        case LLINESPACE_PROP:
            mpLineDistAtMetricBox->Hide();

            mpActLineDistFld = mpLineDistAtPercentBox;

            if (mpLineDistAtPercentBox->GetText().isEmpty())
                mpLineDistAtPercentBox->SetValue(mpLineDistAtPercentBox->Normalize(100), FUNIT_TWIP);

            mpLineDistLabel->Enable();
            mpActLineDistFld->Show();
            mpActLineDistFld->Enable();
            break;
        case LLINESPACE_FIX:
        {
            mpLineDistAtPercentBox->Hide();

            mpActLineDistFld = mpLineDistAtMetricBox;
            sal_Int64 nTemp = mpLineDistAtMetricBox->GetValue();
            mpLineDistAtMetricBox->SetMin(mpLineDistAtMetricBox->Normalize(MIN_FIXED_DISTANCE), FUNIT_TWIP);

            if (mpLineDistAtMetricBox->GetValue() != nTemp)
                SetMetricValue(*mpLineDistAtMetricBox, FIX_DIST_DEF, SFX_MAPUNIT_TWIP);

            mpLineDistLabel->Enable();
            mpActLineDistFld->Show();
            mpActLineDistFld->Enable();
        }
        break;
    }
}

void ParaLineSpacingControl::SelectEntryPos(sal_Int32 nPos)
{
    mpLineDist->SelectEntryPos(nPos);
    UpdateMetricFields();
}

IMPL_LINK(ParaLineSpacingControl, LineSPDistHdl_Impl, ListBox*, /*pBox*/)
{
    UpdateMetricFields();
    ExecuteLineSpace();
    return 0;
}

IMPL_LINK_NOARG( ParaLineSpacingControl, LineSPDistAtHdl_Impl )
{
    ExecuteLineSpace();
    return (0L);
}

void ParaLineSpacingControl::ExecuteLineSpace()
{
    mpLineDist->SaveValue();

    SvxLineSpacingItem aSpacing(DEFAULT_LINE_SPACING, SID_ATTR_PARA_LINESPACE);
    sal_uInt16 nPos = mpLineDist->GetSelectEntryPos();

    switch ( nPos )
    {
        case LLINESPACE_1:
        case LLINESPACE_15:
        case LLINESPACE_2:
            SetLineSpace(aSpacing, nPos);
            break;

        case LLINESPACE_PROP:
            SetLineSpace(aSpacing, nPos, mpLineDistAtPercentBox->Denormalize((long)mpLineDistAtPercentBox->GetValue()));
            break;

        case LLINESPACE_MIN:
        case LLINESPACE_DURCH:
        case LLINESPACE_FIX:
            SetLineSpace(aSpacing, nPos, GetCoreValue(*mpLineDistAtMetricBox, meLNSpaceUnit));
        break;

        default:
            OSL_ENSURE(false, "error!!");
            break;
    }

    SfxViewFrame::Current()->GetBindings().GetDispatcher()->Execute(
            SID_ATTR_PARA_LINESPACE, SfxCallMode::RECORD, &aSpacing, 0L);
}

void ParaLineSpacingControl::SetLineSpace(SvxLineSpacingItem& rLineSpace, int eSpace, long lValue)
{
    switch ( eSpace )
    {
        case LLINESPACE_1:
            rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_AUTO;
            rLineSpace.GetInterLineSpaceRule() = SVX_INTER_LINE_SPACE_OFF;
            break;

        case LLINESPACE_15:
            rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_AUTO;
            rLineSpace.SetPropLineSpace( LINESPACE_15 );
            break;

        case LLINESPACE_2:
            rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_AUTO;
            rLineSpace.SetPropLineSpace( LINESPACE_2 );
            break;

        case LLINESPACE_PROP:
            rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_AUTO;
            rLineSpace.SetPropLineSpace( (sal_uInt8)lValue );
            break;

        case LLINESPACE_MIN:
            rLineSpace.SetLineHeight( (sal_uInt16)lValue );
            rLineSpace.GetInterLineSpaceRule() = SVX_INTER_LINE_SPACE_OFF;
            break;

        case LLINESPACE_DURCH:
            rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_AUTO;
            rLineSpace.SetInterLineSpace( (sal_uInt16)lValue );
            break;

        case LLINESPACE_FIX:
            rLineSpace.SetLineHeight((sal_uInt16)lValue);
            rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_FIX;
            rLineSpace.GetInterLineSpaceRule() = SVX_INTER_LINE_SPACE_OFF;
        break;
    }
}

IMPL_LINK(ParaLineSpacingControl, PredefinedValuesHandler, void *, pControl)
{
    if (pControl == mpSpacing1Button)
    {
        ExecuteLineSpacing(LLINESPACE_1);
    }
    else if (pControl == mpSpacing115Button)
    {
        ExecuteLineSpacing(LLINESPACE_115);
    }
    else if (pControl == mpSpacing15Button)
    {
        ExecuteLineSpacing(LLINESPACE_15);
    }
    else if (pControl == mpSpacing2Button)
    {
        ExecuteLineSpacing(LLINESPACE_2);
    }

    return 0;
}

void ParaLineSpacingControl::ExecuteLineSpacing(sal_uInt16 nEntry)
{
    SvxLineSpacingItem aSpacing(DEFAULT_LINE_SPACING, SID_ATTR_PARA_LINESPACE);

    // special-case the 1.15 line spacing
    if (nEntry == LLINESPACE_115)
        SetLineSpace(aSpacing, LLINESPACE_PROP, mpLineDistAtPercentBox->Denormalize(LINESPACE_115));
    else
        SetLineSpace(aSpacing, nEntry);

    SfxViewFrame::Current()->GetBindings().GetDispatcher()->Execute(
            SID_ATTR_PARA_LINESPACE, SfxCallMode::RECORD, &aSpacing, 0L);

    // close when the user used the buttons
    EndPopupMode();
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>line spacing: Correct way of detecting the currently used units.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */
#include "ParaLineSpacingControl.hxx"
#include "ParaPropertyPanel.hrc"
#include <sfx2/sidebar/ResourceDefinitions.hrc>
#include <svx/dialogs.hrc>
#include <svx/dialmgr.hxx>
#include <unotools/viewoptions.hxx>
#include <editeng/kernitem.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/sidebar/Theme.hxx>
#include <sfx2/viewfrm.hxx>
#include <svtools/unitconv.hxx>
#include <vcl/settings.hxx>

#define DEFAULT_LINE_SPACING  200
#define FIX_DIST_DEF          283
#define LINESPACE_1           100
#define LINESPACE_15          150
#define LINESPACE_2           200
#define LINESPACE_115         115

// values of the mpLineDist listbox
#define LLINESPACE_1          0
#define LLINESPACE_15         1
#define LLINESPACE_2          2
#define LLINESPACE_PROP       3
#define LLINESPACE_MIN        4
#define LLINESPACE_DURCH      5
#define LLINESPACE_FIX        6

// special case; should not conflict with the mpLinDist values
#define LLINESPACE_115        7

#define MIN_FIXED_DISTANCE    28

using namespace svx;
using namespace svx::sidebar;

ParaLineSpacingControl::ParaLineSpacingControl(sal_uInt16 nId)
    : SfxPopupWindow(nId, "ParaLineSpacingControl", "svx/ui/paralinespacingcontrol.ui")
{
    mpSpacing1Button = get<PushButton>("spacing_1");
    mpSpacing115Button = get<PushButton>("spacing_115");
    mpSpacing15Button = get<PushButton>("spacing_15");
    mpSpacing2Button = get<PushButton>("spacing_2");

    mpLineDist = get<ListBox>("line_dist");

    mpLineDistLabel = get<FixedText>("value_label");
    mpLineDistAtPercentBox = get<MetricField>("percent_box");
    mpLineDistAtMetricBox = get<MetricField>("metric_box");

    mpActLineDistFld = mpLineDistAtPercentBox;

    meLNSpaceUnit = SFX_MAPUNIT_100TH_MM;

    Link aLink = LINK(this, ParaLineSpacingControl, PredefinedValuesHandler);
    mpSpacing1Button->SetClickHdl(aLink);
    mpSpacing115Button->SetClickHdl(aLink);
    mpSpacing15Button->SetClickHdl(aLink);
    mpSpacing2Button->SetClickHdl(aLink);

    aLink = LINK( this, ParaLineSpacingControl, LineSPDistHdl_Impl );
    mpLineDist->SetSelectHdl(aLink);
    SelectEntryPos(LLINESPACE_1);

    aLink = LINK( this, ParaLineSpacingControl, LineSPDistAtHdl_Impl );
    mpLineDistAtPercentBox->SetModifyHdl( aLink );
    mpLineDistAtMetricBox->SetModifyHdl( aLink );

    FieldUnit eUnit = FUNIT_INCH;
    const SfxPoolItem* pItem = NULL;
    if (SfxViewFrame::Current()->GetBindings().GetDispatcher()->QueryState(SID_ATTR_METRIC, pItem) >= SfxItemState::DEFAULT)
        eUnit = static_cast<FieldUnit>(static_cast<const SfxUInt16Item*>(pItem)->GetValue());
    else
        eUnit = SfxModule::GetCurrentFieldUnit();

    SetFieldUnit(*mpLineDistAtMetricBox, eUnit);

    initialize();
}

ParaLineSpacingControl::~ParaLineSpacingControl()
{
}

void ParaLineSpacingControl::initialize()
{
    const SfxPoolItem* pItem;
    SfxItemState eState = SfxViewFrame::Current()->GetBindings().GetDispatcher()->QueryState(SID_ATTR_PARA_LINESPACE, pItem);

    const SvxLineSpacingItem* currSPItem = static_cast<const SvxLineSpacingItem*>(pItem);

    mpLineDist->Enable();

    if( eState >= SfxItemState::DEFAULT )
    {
        SfxMapUnit eUnit = SFX_MAPUNIT_100TH_MM;
        meLNSpaceUnit = eUnit;

        switch( currSPItem->GetLineSpaceRule() )
        {
        case SVX_LINE_SPACE_AUTO:
            {
                SvxInterLineSpace eInter = currSPItem->GetInterLineSpaceRule();

                switch( eInter )
                {
                case SVX_INTER_LINE_SPACE_OFF:
                    SelectEntryPos(LLINESPACE_1);
                    break;

                case SVX_INTER_LINE_SPACE_PROP:
                    {
                        if ( LINESPACE_1 == currSPItem->GetPropLineSpace() )
                        {
                            SelectEntryPos(LLINESPACE_1);
                        }
                        else if ( LINESPACE_15 == currSPItem->GetPropLineSpace() )
                        {
                            SelectEntryPos(LLINESPACE_15);
                        }
                        else if ( LINESPACE_2 == currSPItem->GetPropLineSpace() )
                        {
                            SelectEntryPos(LLINESPACE_2);
                        }
                        else
                        {
                            SelectEntryPos(LLINESPACE_PROP);
                            mpLineDistAtPercentBox->SetValue(mpLineDistAtPercentBox->Normalize(currSPItem->GetPropLineSpace()));
                        }
                    }
                    break;

                case SVX_INTER_LINE_SPACE_FIX:
                    {
                        SelectEntryPos(LLINESPACE_DURCH);
                        SetMetricValue(*mpLineDistAtMetricBox, currSPItem->GetInterLineSpace(), eUnit);
                    }
                    break;
                default:
                    break;
                }
            }
            break;
        case SVX_LINE_SPACE_FIX:
            {
                SelectEntryPos(LLINESPACE_FIX);
                SetMetricValue(*mpLineDistAtMetricBox, currSPItem->GetLineHeight(), eUnit);
            }
            break;

        case SVX_LINE_SPACE_MIN:
            {
                SelectEntryPos(LLINESPACE_MIN);
                SetMetricValue(*mpLineDistAtMetricBox, currSPItem->GetLineHeight(), eUnit);
            }
            break;
        default:
            break;
        }
    }
    else if( eState == SfxItemState::DISABLED )
    {
        mpLineDist->Disable();
        mpLineDistLabel->Disable();
        mpActLineDistFld->Disable();
        mpActLineDistFld->SetText("");

    }
    else
    {
        mpLineDistLabel->Disable();
        mpActLineDistFld->Disable();
        mpActLineDistFld->SetText("");
        mpLineDist->SetNoSelection();
    }

    mpLineDist->SaveValue();

    /* TODO
    const sal_uInt16 uCount = mpLineDist->GetEntryCount();
    if( uCount == LLINESPACE_FIX + 1 )
    {
        switch (currentContext.GetCombinedContext_DI())
        {
        case CombinedEnumContext(Application_DrawImpress, Context_Table):
        case CombinedEnumContext(Application_DrawImpress, Context_DrawText):
        case CombinedEnumContext(Application_DrawImpress, Context_Draw):
        case CombinedEnumContext(Application_DrawImpress, Context_TextObject):
        case CombinedEnumContext(Application_DrawImpress, Context_Graphic):
        case CombinedEnumContext(Application_Calc, Context_DrawText):
        case CombinedEnumContext(Application_WriterVariants, Context_DrawText):
        case CombinedEnumContext(Application_WriterVariants, Context_Annotation):
            {
                mpLineDist->RemoveEntry(LLINESPACE_FIX);
            }
        }
    }
    else if( uCount == LLINESPACE_FIX)
    {
        switch (currentContext.GetCombinedContext_DI())
        {
            case CombinedEnumContext(Application_WriterVariants, Context_Default):
            case CombinedEnumContext(Application_WriterVariants, Context_Text):
            case CombinedEnumContext(Application_WriterVariants, Context_Table):
            {
                mpLineDist->InsertEntry(OUString("Fixed"), LLINESPACE_FIX);
            }
        }
    }
    */
}

void ParaLineSpacingControl::UpdateMetricFields()
{
    switch (mpLineDist->GetSelectEntryPos())
    {
        case LLINESPACE_1:
        case LLINESPACE_15:
        case LLINESPACE_2:
            if (mpActLineDistFld == mpLineDistAtPercentBox)
                mpLineDistAtMetricBox->Hide();
            else
                mpLineDistAtPercentBox->Hide();

            mpLineDistLabel->Disable();
            mpActLineDistFld->Show();
            mpActLineDistFld->Disable();
            mpActLineDistFld->SetText("");
            break;

        case LLINESPACE_DURCH:
            mpLineDistAtPercentBox->Hide();

            mpActLineDistFld = mpLineDistAtMetricBox;
            mpLineDistAtMetricBox->SetMin(0);

            if (mpLineDistAtMetricBox->GetText().isEmpty())
                mpLineDistAtMetricBox->SetValue(mpLineDistAtMetricBox->Normalize(0));

            mpLineDistLabel->Enable();
            mpActLineDistFld->Show();
            mpActLineDistFld->Enable();
            break;

        case LLINESPACE_MIN:
            mpLineDistAtPercentBox->Hide();

            mpActLineDistFld = mpLineDistAtMetricBox;
            mpLineDistAtMetricBox->SetMin(0);

            if (mpLineDistAtMetricBox->GetText().isEmpty())
                mpLineDistAtMetricBox->SetValue(mpLineDistAtMetricBox->Normalize(0), FUNIT_TWIP);

            mpLineDistLabel->Enable();
            mpActLineDistFld->Show();
            mpActLineDistFld->Enable();
            break;

        case LLINESPACE_PROP:
            mpLineDistAtMetricBox->Hide();

            mpActLineDistFld = mpLineDistAtPercentBox;

            if (mpLineDistAtPercentBox->GetText().isEmpty())
                mpLineDistAtPercentBox->SetValue(mpLineDistAtPercentBox->Normalize(100), FUNIT_TWIP);

            mpLineDistLabel->Enable();
            mpActLineDistFld->Show();
            mpActLineDistFld->Enable();
            break;
        case LLINESPACE_FIX:
        {
            mpLineDistAtPercentBox->Hide();

            mpActLineDistFld = mpLineDistAtMetricBox;
            sal_Int64 nTemp = mpLineDistAtMetricBox->GetValue();
            mpLineDistAtMetricBox->SetMin(mpLineDistAtMetricBox->Normalize(MIN_FIXED_DISTANCE), FUNIT_TWIP);

            if (mpLineDistAtMetricBox->GetValue() != nTemp)
                SetMetricValue(*mpLineDistAtMetricBox, FIX_DIST_DEF, SFX_MAPUNIT_TWIP);

            mpLineDistLabel->Enable();
            mpActLineDistFld->Show();
            mpActLineDistFld->Enable();
        }
        break;
    }
}

void ParaLineSpacingControl::SelectEntryPos(sal_Int32 nPos)
{
    mpLineDist->SelectEntryPos(nPos);
    UpdateMetricFields();
}

IMPL_LINK(ParaLineSpacingControl, LineSPDistHdl_Impl, ListBox*, /*pBox*/)
{
    UpdateMetricFields();
    ExecuteLineSpace();
    return 0;
}

IMPL_LINK_NOARG( ParaLineSpacingControl, LineSPDistAtHdl_Impl )
{
    ExecuteLineSpace();
    return (0L);
}

void ParaLineSpacingControl::ExecuteLineSpace()
{
    mpLineDist->SaveValue();

    SvxLineSpacingItem aSpacing(DEFAULT_LINE_SPACING, SID_ATTR_PARA_LINESPACE);
    sal_uInt16 nPos = mpLineDist->GetSelectEntryPos();

    switch ( nPos )
    {
        case LLINESPACE_1:
        case LLINESPACE_15:
        case LLINESPACE_2:
            SetLineSpace(aSpacing, nPos);
            break;

        case LLINESPACE_PROP:
            SetLineSpace(aSpacing, nPos, mpLineDistAtPercentBox->Denormalize((long)mpLineDistAtPercentBox->GetValue()));
            break;

        case LLINESPACE_MIN:
        case LLINESPACE_DURCH:
        case LLINESPACE_FIX:
            SetLineSpace(aSpacing, nPos, GetCoreValue(*mpLineDistAtMetricBox, meLNSpaceUnit));
        break;

        default:
            OSL_ENSURE(false, "error!!");
            break;
    }

    SfxViewFrame::Current()->GetBindings().GetDispatcher()->Execute(
            SID_ATTR_PARA_LINESPACE, SfxCallMode::RECORD, &aSpacing, 0L);
}

void ParaLineSpacingControl::SetLineSpace(SvxLineSpacingItem& rLineSpace, int eSpace, long lValue)
{
    switch ( eSpace )
    {
        case LLINESPACE_1:
            rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_AUTO;
            rLineSpace.GetInterLineSpaceRule() = SVX_INTER_LINE_SPACE_OFF;
            break;

        case LLINESPACE_15:
            rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_AUTO;
            rLineSpace.SetPropLineSpace( LINESPACE_15 );
            break;

        case LLINESPACE_2:
            rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_AUTO;
            rLineSpace.SetPropLineSpace( LINESPACE_2 );
            break;

        case LLINESPACE_PROP:
            rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_AUTO;
            rLineSpace.SetPropLineSpace( (sal_uInt8)lValue );
            break;

        case LLINESPACE_MIN:
            rLineSpace.SetLineHeight( (sal_uInt16)lValue );
            rLineSpace.GetInterLineSpaceRule() = SVX_INTER_LINE_SPACE_OFF;
            break;

        case LLINESPACE_DURCH:
            rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_AUTO;
            rLineSpace.SetInterLineSpace( (sal_uInt16)lValue );
            break;

        case LLINESPACE_FIX:
            rLineSpace.SetLineHeight((sal_uInt16)lValue);
            rLineSpace.GetLineSpaceRule() = SVX_LINE_SPACE_FIX;
            rLineSpace.GetInterLineSpaceRule() = SVX_INTER_LINE_SPACE_OFF;
        break;
    }
}

IMPL_LINK(ParaLineSpacingControl, PredefinedValuesHandler, void *, pControl)
{
    if (pControl == mpSpacing1Button)
    {
        ExecuteLineSpacing(LLINESPACE_1);
    }
    else if (pControl == mpSpacing115Button)
    {
        ExecuteLineSpacing(LLINESPACE_115);
    }
    else if (pControl == mpSpacing15Button)
    {
        ExecuteLineSpacing(LLINESPACE_15);
    }
    else if (pControl == mpSpacing2Button)
    {
        ExecuteLineSpacing(LLINESPACE_2);
    }

    return 0;
}

void ParaLineSpacingControl::ExecuteLineSpacing(sal_uInt16 nEntry)
{
    SvxLineSpacingItem aSpacing(DEFAULT_LINE_SPACING, SID_ATTR_PARA_LINESPACE);

    // special-case the 1.15 line spacing
    if (nEntry == LLINESPACE_115)
        SetLineSpace(aSpacing, LLINESPACE_PROP, mpLineDistAtPercentBox->Denormalize(LINESPACE_115));
    else
        SetLineSpace(aSpacing, nEntry);

    SfxViewFrame::Current()->GetBindings().GetDispatcher()->Execute(
            SID_ATTR_PARA_LINESPACE, SfxCallMode::RECORD, &aSpacing, 0L);

    // close when the user used the buttons
    EndPopupMode();
}

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


<commit_before>/* Copyright 2016 The TensorFlow 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 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.
==============================================================================*/

#include "tensorflow/core/common_runtime/optimization_registry.h"
#include "tensorflow/core/util/dump_graph.h"

namespace tensorflow {

// static
OptimizationPassRegistry* OptimizationPassRegistry::Global() {
  static OptimizationPassRegistry* global_optimization_registry =
      new OptimizationPassRegistry;
  return global_optimization_registry;
}

void OptimizationPassRegistry::Register(
    Grouping grouping, int phase, std::unique_ptr<GraphOptimizationPass> pass) {
  groups_[grouping][phase].push_back(std::move(pass));
}

Status OptimizationPassRegistry::RunGrouping(
    Grouping grouping, const GraphOptimizationPassOptions& options) {
  auto group = groups_.find(grouping);
  if (group != groups_.end()) {
    for (auto& phase : group->second) {
      VLOG(1) << "Running optimization phase " << phase.first;
      for (auto& pass : phase.second) {
        VLOG(1) << "Running optimization pass: " << pass->name();
        Status s = pass->Run(options);
        if (!s.ok()) return s;
        if (VLOG_IS_ON(1)) {
          if (options.graph) {
            DumpGraphToFile(
                strings::StrCat(
                    "after_phase_", phase.first, "_", pass->name(), "_",
                    reinterpret_cast<uintptr_t>((*options.graph).get())),
                **options.graph, options.flib_def);
          }
          if (options.partition_graphs) {
            for (auto& part : *options.partition_graphs) {
              DumpGraphToFile(
                  strings::StrCat(
                      "after_phase_", phase.first, "_", pass->name(),
                      "_partition_", part.first, "_",
                      reinterpret_cast<uintptr_t>(part.second.get())),
                  *part.second, options.flib_def);
            }
          }
        }
      }
    }
  }
  return Status::OK();
}

void OptimizationPassRegistry::LogGrouping(Grouping grouping, int vlog_level) {
  auto group = groups_.find(grouping);
  if (group != groups_.end()) {
    for (auto& phase : group->second) {
      for (auto& pass : phase.second) {
        VLOG(vlog_level) << "Registered optimization pass grouping " << grouping
                         << " phase " << phase.first << ": " << pass->name();
      }
    }
  }
}

void OptimizationPassRegistry::LogAllGroupings(int vlog_level) {
  for (auto group = groups_.begin(); group != groups_.end(); ++group) {
    LogGrouping(group->first, vlog_level);
  }
}

}  // namespace tensorflow
<commit_msg>Add a log message to inform user when graph optimization passes are being executed too many times and possible solution.<commit_after>/* Copyright 2016 The TensorFlow 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 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.
==============================================================================*/

#include "tensorflow/core/common_runtime/optimization_registry.h"
#include "tensorflow/core/util/dump_graph.h"

namespace tensorflow {

// static
OptimizationPassRegistry* OptimizationPassRegistry::Global() {
  static OptimizationPassRegistry* global_optimization_registry =
      new OptimizationPassRegistry;
  return global_optimization_registry;
}

void OptimizationPassRegistry::Register(
    Grouping grouping, int phase, std::unique_ptr<GraphOptimizationPass> pass) {
  groups_[grouping][phase].push_back(std::move(pass));
}

Status OptimizationPassRegistry::RunGrouping(
    Grouping grouping, const GraphOptimizationPassOptions& options) {
  LOG(INFO)
      << "Running all optimization passes in grouping " << grouping
      << ". If you see this a lot, you might be extending the graph too many "
         "times (which means you modify the graph many times before "
         "execution). Try reducing graph modifications or using SavedModel to "
         "avoid any graph modification";
  auto group = groups_.find(grouping);
  if (group != groups_.end()) {
    for (auto& phase : group->second) {
      VLOG(1) << "Running optimization phase " << phase.first;
      for (auto& pass : phase.second) {
        VLOG(1) << "Running optimization pass: " << pass->name();
        Status s = pass->Run(options);
        if (!s.ok()) return s;
        if (VLOG_IS_ON(1)) {
          if (options.graph) {
            DumpGraphToFile(
                strings::StrCat(
                    "after_phase_", phase.first, "_", pass->name(), "_",
                    reinterpret_cast<uintptr_t>((*options.graph).get())),
                **options.graph, options.flib_def);
          }
          if (options.partition_graphs) {
            for (auto& part : *options.partition_graphs) {
              DumpGraphToFile(
                  strings::StrCat(
                      "after_phase_", phase.first, "_", pass->name(),
                      "_partition_", part.first, "_",
                      reinterpret_cast<uintptr_t>(part.second.get())),
                  *part.second, options.flib_def);
            }
          }
        }
      }
    }
  }
  return Status::OK();
}

void OptimizationPassRegistry::LogGrouping(Grouping grouping, int vlog_level) {
  auto group = groups_.find(grouping);
  if (group != groups_.end()) {
    for (auto& phase : group->second) {
      for (auto& pass : phase.second) {
        VLOG(vlog_level) << "Registered optimization pass grouping " << grouping
                         << " phase " << phase.first << ": " << pass->name();
      }
    }
  }
}

void OptimizationPassRegistry::LogAllGroupings(int vlog_level) {
  for (auto group = groups_.begin(); group != groups_.end(); ++group) {
    LogGrouping(group->first, vlog_level);
  }
}

}  // namespace tensorflow
<|endoftext|>


<commit_before>/* Copyright 2018 The TensorFlow 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 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.
==============================================================================*/

#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/c_api_internal.h"
#include "tensorflow/lite/experimental/micro/kernels/all_ops_resolver.h"
#include "tensorflow/lite/experimental/micro/testing/micro_test.h"
#include "tensorflow/lite/experimental/micro/testing/test_utils.h"

namespace tflite {
namespace testing {
namespace {

void TestCeil(std::initializer_list<int> input_dims_data,
              std::initializer_list<float> input_data,
              std::initializer_list<float> expected_output_data,
              float* output_data) {
  TfLiteIntArray* input_dims = IntArrayFromInitializer(input_dims_data);
  TfLiteIntArray* output_dims = IntArrayFromInitializer(input_dims_data);
  const int output_dims_count = ElementCount(*output_dims);
  constexpr int inputs_size = 1;
  constexpr int outputs_size = 1;
  constexpr int tensors_size = inputs_size + outputs_size;
  TfLiteTensor tensors[tensors_size] = {
      CreateFloatTensor(input_data, input_dims, "input_tensor"),
      CreateFloatTensor(output_data, output_dims, "output_tensor"),
  };
  TfLiteContext context;
  PopulateContext(tensors, tensors_size, &context);
  ::tflite::ops::micro::AllOpsResolver resolver;
  const TfLiteRegistration* registration =
      resolver.FindOp(tflite::BuiltinOperator_CEIL, 1);
  TF_LITE_MICRO_EXPECT_NE(nullptr, registration);

  int inputs_array_data[] = {1, 0};
  TfLiteIntArray* inputs_array = IntArrayFromInts(inputs_array_data);
  int outputs_array_data[] = {1, 1};
  TfLiteIntArray* outputs_array = IntArrayFromInts(outputs_array_data);
  TfLiteIntArray* temporaries_array = IntArrayFromInitializer({0});
  TfLiteNode node;
  node.inputs = inputs_array;
  node.outputs = outputs_array;
  node.temporaries = temporaries_array;
  node.user_data = nullptr;
  node.builtin_data = nullptr;
  node.custom_initial_data = nullptr;
  node.custom_initial_data_size = 0;
  node.delegate = nullptr;
  TF_LITE_MICRO_EXPECT_NE(nullptr, registration->invoke);
  TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->invoke(&context, &node));
  for (int i = 0; i < output_dims_count; ++i) {
    TF_LITE_MICRO_EXPECT_NEAR(expected_output_data.begin()[i], output_data[i],
                              1e-5f);
  }
}

}  // namespace
}  // namespace testing
}  // namespace tflite

TF_LITE_MICRO_TESTS_BEGIN

TF_LITE_MICRO_TEST(SingleDim) {
  float output_data[2];
  tflite::testing::TestCeil({1, 2},      // input_dims_data
                            {8.5, 0.0},  // input_data
                            {9, 0},      // expected_output_data
                            output_data);
}

TF_LITE_MICRO_TEST(MultiDims) {
  float output_data[10];
  tflite::testing::TestCeil(
      {4, 2, 1, 1, 5},  // input_dims_data
      {
          0.0001,
          8.0001,
          0.9999,
          9.9999,
          0.5,
          -0.0001,
          -8.0001,
          -0.9999,
          -9.9999,
          -0.5,
      },                                  // input_data
      {1, 9, 1, 10, 1, 0, -8, 0, -9, 0},  // expected_output_data
      output_data);
}

TF_LITE_MICRO_TESTS_END
<commit_msg>Refactor micro ceil test.<commit_after>/* Copyright 2018 The TensorFlow 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 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.
==============================================================================*/

#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/c_api_internal.h"
#include "tensorflow/lite/experimental/micro/kernels/all_ops_resolver.h"
#include "tensorflow/lite/experimental/micro/testing/micro_test.h"
#include "tensorflow/lite/experimental/micro/testing/test_utils.h"

namespace tflite {
namespace testing {
namespace {

void TestCeil(const int* input_dims_data, const float* input_data,
              const float* expected_output_data, float* output_data) {
  TfLiteIntArray* input_dims = IntArrayFromInts(input_dims_data);
  TfLiteIntArray* output_dims = IntArrayFromInts(input_dims_data);
  const int output_dims_count = ElementCount(*output_dims);
  constexpr int inputs_size = 1;
  constexpr int outputs_size = 1;
  constexpr int tensors_size = inputs_size + outputs_size;
  TfLiteTensor tensors[tensors_size] = {
      CreateFloatTensor(input_data, input_dims, "input_tensor"),
      CreateFloatTensor(output_data, output_dims, "output_tensor"),
  };
  TfLiteContext context;
  PopulateContext(tensors, tensors_size, &context);
  ::tflite::ops::micro::AllOpsResolver resolver;
  const TfLiteRegistration* registration =
      resolver.FindOp(tflite::BuiltinOperator_CEIL, 1);
  TF_LITE_MICRO_EXPECT_NE(nullptr, registration);

  int inputs_array_data[] = {1, 0};
  TfLiteIntArray* inputs_array = IntArrayFromInts(inputs_array_data);
  int outputs_array_data[] = {1, 1};
  TfLiteIntArray* outputs_array = IntArrayFromInts(outputs_array_data);
  int temporaries_array_data[] = {0};
  TfLiteIntArray* temporaries_array = IntArrayFromInts(temporaries_array_data);
  TfLiteNode node;
  node.inputs = inputs_array;
  node.outputs = outputs_array;
  node.temporaries = temporaries_array;
  node.user_data = nullptr;
  node.builtin_data = nullptr;
  node.custom_initial_data = nullptr;
  node.custom_initial_data_size = 0;
  node.delegate = nullptr;
  TF_LITE_MICRO_EXPECT_NE(nullptr, registration->invoke);
  TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->invoke(&context, &node));
  for (int i = 0; i < output_dims_count; ++i) {
    TF_LITE_MICRO_EXPECT_NEAR(expected_output_data[i], output_data[i], 1e-5f);
  }
}

}  // namespace
}  // namespace testing
}  // namespace tflite

TF_LITE_MICRO_TESTS_BEGIN

TF_LITE_MICRO_TEST(SingleDim) {
  float output_data[2];
  const int input_dims[] = {1, 2};
  const float input_values[] = {8.5, 0.0};
  const float golden[] = {9, 0};
  tflite::testing::TestCeil(input_dims, input_values, golden, output_data);
}

TF_LITE_MICRO_TEST(MultiDims) {
  float output_data[10];
  const int input_dims[] = {4, 2, 1, 1, 5};
  const float input_values[] = {
      0.0001,  8.0001,  0.9999,  9.9999,  0.5,
      -0.0001, -8.0001, -0.9999, -9.9999, -0.5,
  };
  const float golden[] = {1, 9, 1, 10, 1, 0, -8, 0, -9, 0};
  tflite::testing::TestCeil(input_dims, input_values, golden, output_data);
}

TF_LITE_MICRO_TESTS_END
<|endoftext|>


<commit_before>#include "test/common/integration/base_client_integration_test.h"

#include <string>

#include "test/common/http/common.h"

#include "gtest/gtest.h"
#include "library/cc/bridge_utility.h"
#include "library/common/config/internal.h"
#include "library/common/http/header_utility.h"

namespace Envoy {
namespace {

void validateStreamIntel(const envoy_final_stream_intel& final_intel, bool expect_dns,
                         bool upstream_tls, bool is_first_request) {
  if (expect_dns) {
    EXPECT_NE(-1, final_intel.dns_start_ms);
    EXPECT_NE(-1, final_intel.dns_end_ms);
  }

  if (upstream_tls) {
    EXPECT_GT(final_intel.ssl_start_ms, 0);
    EXPECT_GT(final_intel.ssl_end_ms, 0);
  } else {
    EXPECT_EQ(-1, final_intel.ssl_start_ms);
    EXPECT_EQ(-1, final_intel.ssl_end_ms);
  }

  ASSERT_NE(-1, final_intel.stream_start_ms);
  ASSERT_NE(-1, final_intel.connect_start_ms);
  ASSERT_NE(-1, final_intel.connect_end_ms);
  ASSERT_NE(-1, final_intel.sending_start_ms);
  ASSERT_NE(-1, final_intel.sending_end_ms);
  ASSERT_NE(-1, final_intel.response_start_ms);
  ASSERT_NE(-1, final_intel.stream_end_ms);

  if (is_first_request) {
    ASSERT_LE(final_intel.stream_start_ms, final_intel.connect_start_ms);
  }
  ASSERT_LE(final_intel.connect_start_ms, final_intel.connect_end_ms);
  ASSERT_LE(final_intel.connect_end_ms, final_intel.sending_start_ms);
  ASSERT_LE(final_intel.sending_start_ms, final_intel.sending_end_ms);
  ASSERT_LE(final_intel.response_start_ms, final_intel.stream_end_ms);
}

// Use the Envoy mobile default config as much as possible in this test.
// There are some config modifiers below which do result in deltas.
std::string defaultConfig() {
  Platform::EngineBuilder builder;
  std::string config_str = absl::StrCat(config_header, builder.generateConfigStr());
  return config_str;
}

} // namespace

BaseClientIntegrationTest::BaseClientIntegrationTest(Network::Address::IpVersion ip_version)
    : BaseIntegrationTest(ip_version, defaultConfig()) {
  skip_tag_extraction_rule_check_ = true;
  full_dispatcher_ = api_->allocateDispatcher("fake_envoy_mobile");
  use_lds_ = false;
  autonomous_upstream_ = true;
  defer_listener_finalization_ = true;
}

void BaseClientIntegrationTest::initialize() {
  BaseIntegrationTest::initialize();
  stream_prototype_ = engine_->streamClient()->newStreamPrototype();

  stream_prototype_->setOnHeaders(
      [this](Platform::ResponseHeadersSharedPtr headers, bool, envoy_stream_intel intel) {
        cc_.on_headers_calls++;
        cc_.status = absl::StrCat(headers->httpStatus());
        cc_.on_header_consumed_bytes_from_response = intel.consumed_bytes_from_response;
      });
  stream_prototype_->setOnData([this](envoy_data c_data, bool) {
    cc_.on_data_calls++;
    release_envoy_data(c_data);
  });
  stream_prototype_->setOnComplete(
      [this](envoy_stream_intel, envoy_final_stream_intel final_intel) {
        validateStreamIntel(final_intel, expect_dns_, upstream_tls_, cc_.on_complete_calls == 0);
        cc_.on_complete_received_byte_count = final_intel.received_byte_count;
        cc_.on_complete_calls++;
        cc_.terminal_callback->setReady();
      });
  stream_prototype_->setOnError(
      [this](Platform::EnvoyErrorSharedPtr, envoy_stream_intel, envoy_final_stream_intel) {
        cc_.on_error_calls++;
        cc_.terminal_callback->setReady();
      });
  stream_prototype_->setOnCancel([this](envoy_stream_intel, envoy_final_stream_intel final_intel) {
    EXPECT_NE(-1, final_intel.stream_start_ms);
    cc_.on_cancel_calls++;
    cc_.terminal_callback->setReady();
  });

  stream_ = (*stream_prototype_).start(explicit_flow_control_);
  HttpTestUtility::addDefaultHeaders(default_request_headers_);
  default_request_headers_.setHost(fake_upstreams_[0]->localAddress()->asStringView());
}

std::shared_ptr<Platform::RequestHeaders> BaseClientIntegrationTest::envoyToMobileHeaders(
    const Http::TestRequestHeaderMapImpl& request_headers) {

  Platform::RequestHeadersBuilder builder(
      Platform::RequestMethod::GET,
      std::string(default_request_headers_.Scheme()->value().getStringView()),
      std::string(default_request_headers_.Host()->value().getStringView()),
      std::string(default_request_headers_.Path()->value().getStringView()));
  if (upstreamProtocol() == Http::CodecType::HTTP2) {
    builder.addUpstreamHttpProtocol(Platform::UpstreamHttpProtocol::HTTP2);
  }

  request_headers.iterate(
      [&request_headers, &builder](const Http::HeaderEntry& header) -> Http::HeaderMap::Iterate {
        std::string key = std::string(header.key().getStringView());
        if (request_headers.formatter().has_value()) {
          const Envoy::Http::StatefulHeaderKeyFormatter& formatter =
              request_headers.formatter().value();
          key = formatter.format(key);
        }
        auto value = std::vector<std::string>();
        value.push_back(std::string(header.value().getStringView()));
        builder.set(key, value);
        return Http::HeaderMap::Iterate::Continue;
      });

  return std::make_shared<Platform::RequestHeaders>(builder.build());
}

void BaseClientIntegrationTest::threadRoutine(absl::Notification& engine_running) {
  setOnEngineRunning([&]() { engine_running.Notify(); });
  engine_ = build();
  full_dispatcher_->run(Event::Dispatcher::RunType::Block);
}

void BaseClientIntegrationTest::TearDown() {
  test_server_.reset();
  fake_upstreams_.clear();
  engine_->terminate();
  engine_.reset();
  full_dispatcher_->exit();
  envoy_thread_->join();
}

void BaseClientIntegrationTest::createEnvoy() {
  std::vector<uint32_t> ports;
  for (auto& upstream : fake_upstreams_) {
    if (upstream->localAddress()->ip()) {
      ports.push_back(upstream->localAddress()->ip()->port());
    }
  }

  finalizeConfigWithPorts(config_helper_, ports, use_lds_);

  if (override_builder_config_) {
    setOverrideConfigForTests(MessageUtil::getYamlStringFromMessage(config_helper_.bootstrap()));
  } else {
    ENVOY_LOG_MISC(warn, "Using builder config and ignoring config modifiers");
  }

  absl::Notification engine_running;
  envoy_thread_ = api_->threadFactory().createThread(
      [this, &engine_running]() -> void { threadRoutine(engine_running); });
  engine_running.WaitForNotification();
}

void BaseClientIntegrationTest::cleanup() {
  if (xds_connection_ != nullptr) {
    cleanUpXdsConnection();
  }
  test_server_.reset();
  fake_upstreams_.clear();
}

} // namespace Envoy
<commit_msg>Honor the `-l` log level command line setting for C++ integration tests (#2677)<commit_after>#include "test/common/integration/base_client_integration_test.h"

#include <string>

#include "test/common/http/common.h"

#include "gtest/gtest.h"
#include "library/cc/bridge_utility.h"
#include "library/cc/log_level.h"
#include "library/common/config/internal.h"
#include "library/common/http/header_utility.h"
#include "spdlog/spdlog.h"

namespace Envoy {
namespace {

void validateStreamIntel(const envoy_final_stream_intel& final_intel, bool expect_dns,
                         bool upstream_tls, bool is_first_request) {
  if (expect_dns) {
    EXPECT_NE(-1, final_intel.dns_start_ms);
    EXPECT_NE(-1, final_intel.dns_end_ms);
  }

  if (upstream_tls) {
    EXPECT_GT(final_intel.ssl_start_ms, 0);
    EXPECT_GT(final_intel.ssl_end_ms, 0);
  } else {
    EXPECT_EQ(-1, final_intel.ssl_start_ms);
    EXPECT_EQ(-1, final_intel.ssl_end_ms);
  }

  ASSERT_NE(-1, final_intel.stream_start_ms);
  ASSERT_NE(-1, final_intel.connect_start_ms);
  ASSERT_NE(-1, final_intel.connect_end_ms);
  ASSERT_NE(-1, final_intel.sending_start_ms);
  ASSERT_NE(-1, final_intel.sending_end_ms);
  ASSERT_NE(-1, final_intel.response_start_ms);
  ASSERT_NE(-1, final_intel.stream_end_ms);

  if (is_first_request) {
    ASSERT_LE(final_intel.stream_start_ms, final_intel.connect_start_ms);
  }
  ASSERT_LE(final_intel.connect_start_ms, final_intel.connect_end_ms);
  ASSERT_LE(final_intel.connect_end_ms, final_intel.sending_start_ms);
  ASSERT_LE(final_intel.sending_start_ms, final_intel.sending_end_ms);
  ASSERT_LE(final_intel.response_start_ms, final_intel.stream_end_ms);
}

// Use the Envoy mobile default config as much as possible in this test.
// There are some config modifiers below which do result in deltas.
std::string defaultConfig() {
  Platform::EngineBuilder builder;
  std::string config_str = absl::StrCat(config_header, builder.generateConfigStr());
  return config_str;
}

// Gets the spdlog level from the test options and converts it to the Platform::LogLevel used by
// the Envoy Mobile engine.
Platform::LogLevel getPlatformLogLevelFromOptions() {
  switch (TestEnvironment::getOptions().logLevel()) {
  case spdlog::level::level_enum::trace:
    return Platform::LogLevel::trace;
  case spdlog::level::level_enum::debug:
    return Platform::LogLevel::debug;
  case spdlog::level::level_enum::info:
    return Platform::LogLevel::info;
  case spdlog::level::level_enum::warn:
    return Platform::LogLevel::warn;
  case spdlog::level::level_enum::err:
    return Platform::LogLevel::error;
  case spdlog::level::level_enum::critical:
    return Platform::LogLevel::critical;
  case spdlog::level::level_enum::off:
    return Platform::LogLevel::off;
  default:
    ENVOY_LOG_MISC(warn, "Couldn't map spdlog level {}. Using `info` level.",
                   TestEnvironment::getOptions().logLevel());
    return Platform::LogLevel::info;
  }
}

} // namespace

BaseClientIntegrationTest::BaseClientIntegrationTest(Network::Address::IpVersion ip_version)
    : BaseIntegrationTest(ip_version, defaultConfig()) {
  skip_tag_extraction_rule_check_ = true;
  full_dispatcher_ = api_->allocateDispatcher("fake_envoy_mobile");
  use_lds_ = false;
  autonomous_upstream_ = true;
  defer_listener_finalization_ = true;

  addLogLevel(getPlatformLogLevelFromOptions());
}

void BaseClientIntegrationTest::initialize() {
  BaseIntegrationTest::initialize();
  stream_prototype_ = engine_->streamClient()->newStreamPrototype();

  stream_prototype_->setOnHeaders(
      [this](Platform::ResponseHeadersSharedPtr headers, bool, envoy_stream_intel intel) {
        cc_.on_headers_calls++;
        cc_.status = absl::StrCat(headers->httpStatus());
        cc_.on_header_consumed_bytes_from_response = intel.consumed_bytes_from_response;
      });
  stream_prototype_->setOnData([this](envoy_data c_data, bool) {
    cc_.on_data_calls++;
    release_envoy_data(c_data);
  });
  stream_prototype_->setOnComplete(
      [this](envoy_stream_intel, envoy_final_stream_intel final_intel) {
        validateStreamIntel(final_intel, expect_dns_, upstream_tls_, cc_.on_complete_calls == 0);
        cc_.on_complete_received_byte_count = final_intel.received_byte_count;
        cc_.on_complete_calls++;
        cc_.terminal_callback->setReady();
      });
  stream_prototype_->setOnError(
      [this](Platform::EnvoyErrorSharedPtr, envoy_stream_intel, envoy_final_stream_intel) {
        cc_.on_error_calls++;
        cc_.terminal_callback->setReady();
      });
  stream_prototype_->setOnCancel([this](envoy_stream_intel, envoy_final_stream_intel final_intel) {
    EXPECT_NE(-1, final_intel.stream_start_ms);
    cc_.on_cancel_calls++;
    cc_.terminal_callback->setReady();
  });

  stream_ = (*stream_prototype_).start(explicit_flow_control_);
  HttpTestUtility::addDefaultHeaders(default_request_headers_);
  default_request_headers_.setHost(fake_upstreams_[0]->localAddress()->asStringView());
}

std::shared_ptr<Platform::RequestHeaders> BaseClientIntegrationTest::envoyToMobileHeaders(
    const Http::TestRequestHeaderMapImpl& request_headers) {

  Platform::RequestHeadersBuilder builder(
      Platform::RequestMethod::GET,
      std::string(default_request_headers_.Scheme()->value().getStringView()),
      std::string(default_request_headers_.Host()->value().getStringView()),
      std::string(default_request_headers_.Path()->value().getStringView()));
  if (upstreamProtocol() == Http::CodecType::HTTP2) {
    builder.addUpstreamHttpProtocol(Platform::UpstreamHttpProtocol::HTTP2);
  }

  request_headers.iterate(
      [&request_headers, &builder](const Http::HeaderEntry& header) -> Http::HeaderMap::Iterate {
        std::string key = std::string(header.key().getStringView());
        if (request_headers.formatter().has_value()) {
          const Envoy::Http::StatefulHeaderKeyFormatter& formatter =
              request_headers.formatter().value();
          key = formatter.format(key);
        }
        auto value = std::vector<std::string>();
        value.push_back(std::string(header.value().getStringView()));
        builder.set(key, value);
        return Http::HeaderMap::Iterate::Continue;
      });

  return std::make_shared<Platform::RequestHeaders>(builder.build());
}

void BaseClientIntegrationTest::threadRoutine(absl::Notification& engine_running) {
  setOnEngineRunning([&]() { engine_running.Notify(); });
  engine_ = build();
  full_dispatcher_->run(Event::Dispatcher::RunType::Block);
}

void BaseClientIntegrationTest::TearDown() {
  test_server_.reset();
  fake_upstreams_.clear();
  engine_->terminate();
  engine_.reset();
  full_dispatcher_->exit();
  envoy_thread_->join();
}

void BaseClientIntegrationTest::createEnvoy() {
  std::vector<uint32_t> ports;
  for (auto& upstream : fake_upstreams_) {
    if (upstream->localAddress()->ip()) {
      ports.push_back(upstream->localAddress()->ip()->port());
    }
  }

  finalizeConfigWithPorts(config_helper_, ports, use_lds_);

  if (override_builder_config_) {
    setOverrideConfigForTests(MessageUtil::getYamlStringFromMessage(config_helper_.bootstrap()));
  } else {
    ENVOY_LOG_MISC(warn, "Using builder config and ignoring config modifiers");
  }

  absl::Notification engine_running;
  envoy_thread_ = api_->threadFactory().createThread(
      [this, &engine_running]() -> void { threadRoutine(engine_running); });
  engine_running.WaitForNotification();
}

void BaseClientIntegrationTest::cleanup() {
  if (xds_connection_ != nullptr) {
    cleanUpXdsConnection();
  }
  test_server_.reset();
  fake_upstreams_.clear();
}

} // namespace Envoy
<|endoftext|>


<commit_before>#include <node.h>
#include "nan.h"

using namespace v8;

int32_t jumpConsistentHash(uint64_t key, int32_t num_buckets)
{
    int64_t b = -1, j = 0;
    while (j < num_buckets)
    {
        b = j;
        key = key * 2862933555777941757ULL + 1;
        j = (b + 1) * (double(1LL << 31) / double((key >> 33) + 1));
    }

    return b;
}

NAN_METHOD(JumpConsistentHash)
{
	NanScope();

    uint64_t key = args[0]->IntegerValue();
    int32_t buckets = args[1]->Uint32Value();

    int32_t dest = jumpConsistentHash(key, buckets);

    NanReturnValue(NanNew<Number>(dest));
}

NAN_METHOD(JumpBuffer)
{
    NanScope();

    Local<Object> buffer = args[0].As<Object>();
    size_t length = node::Buffer::Length(buffer);
    const uint8_t* data = reinterpret_cast<const uint8_t* >(node::Buffer::Data(buffer));
    int bytelen = (length < 8 ? length : 8);
    int32_t buckets = args[1]->Uint32Value();

    uint64_t key = 0;
    for (int i = 0; i < bytelen; i++)
        key = (key << 8) ^ data[i];

    int32_t dest = jumpConsistentHash(key, buckets);
    NanReturnValue(NanNew<Number>(dest));
}

// ------------ ceremony

void InitAll(Handle<Object> exports, Handle<Object> module)
{
	exports->Set(NanNew<String>("jumphash"), NanNew<FunctionTemplate>(JumpConsistentHash)->GetFunction());
    exports->Set(NanNew<String>("jumpbuffer"), NanNew<FunctionTemplate>(JumpBuffer)->GetFunction());
}

NODE_MODULE(jumpsuit, InitAll)
<commit_msg>Whitespace.<commit_after>#include <node.h>
#include "nan.h"

using namespace v8;

int32_t jumpConsistentHash(uint64_t key, int32_t num_buckets)
{
    int64_t b = -1, j = 0;
    while (j < num_buckets)
    {
        b = j;
        key = key * 2862933555777941757ULL + 1;
        j = (b + 1) * (double(1LL << 31) / double((key >> 33) + 1));
    }

    return b;
}

NAN_METHOD(JumpConsistentHash)
{
    NanScope();

    uint64_t key = args[0]->IntegerValue();
    int32_t buckets = args[1]->Uint32Value();

    int32_t dest = jumpConsistentHash(key, buckets);

    NanReturnValue(NanNew<Number>(dest));
}

NAN_METHOD(JumpBuffer)
{
    NanScope();

    Local<Object> buffer = args[0].As<Object>();
    size_t length = node::Buffer::Length(buffer);
    const uint8_t* data = reinterpret_cast<const uint8_t* >(node::Buffer::Data(buffer));
    int bytelen = (length < 8 ? length : 8);
    int32_t buckets = args[1]->Uint32Value();

    uint64_t key = 0;
    for (int i = 0; i < bytelen; i++)
        key = (key << 8) ^ data[i];

    int32_t dest = jumpConsistentHash(key, buckets);
    NanReturnValue(NanNew<Number>(dest));
}

// ------------ ceremony

void InitAll(Handle<Object> exports, Handle<Object> module)
{
    exports->Set(NanNew<String>("jumphash"), NanNew<FunctionTemplate>(JumpConsistentHash)->GetFunction());
    exports->Set(NanNew<String>("jumpbuffer"), NanNew<FunctionTemplate>(JumpBuffer)->GetFunction());
}

NODE_MODULE(jumpsuit, InitAll)
<|endoftext|>


<commit_before>#include <memory.h>
#include <stdio.h>

#include "KeyboardInjector.h"

int main(int argc, char** argv) {
  if (argc == 2 && (strcmp(argv[1], "-?") == 0 ||
                    strcmp(argv[1], "--help") == 0)) {
    printf("%s - Send commands to the keyboard device\n", argv[0]);
    printf("  sleep N - sleeps N microseconds\n");
    printf("  sleepms N - sleeps N milliseconds\n");
    printf("  up N - sends keyup command for N key\n");
    printf("  up N - sends keydown command for N key\n");
    return 0;
  }

  KeyboardInjector inject;
  if (!inject.Init()) {
    fprintf(stderr, "Init failed; are you su?\n");
    return -1;
  }
  inject.Run();
  return 0;
}
<commit_msg>Fix typo<commit_after>#include <memory.h>
#include <stdio.h>

#include "KeyboardInjector.h"

int main(int argc, char** argv) {
  if (argc == 2 && (strcmp(argv[1], "-?") == 0 ||
                    strcmp(argv[1], "--help") == 0)) {
    printf("%s - Send commands to the keyboard device\n", argv[0]);
    printf("  sleep N - sleeps N microseconds\n");
    printf("  sleepms N - sleeps N milliseconds\n");
    printf("  up N - sends keyup command for N key\n");
    printf("  down N - sends keydown command for N key\n");
    return 0;
  }

  KeyboardInjector inject;
  if (!inject.Init()) {
    fprintf(stderr, "Init failed; are you su?\n");
    return -1;
  }
  inject.Run();
  return 0;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

#include <iostream>
#include <string>
#include <list>

#include <gflags/gflags.h>

#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>

#include <pqxx/pqxx>

#include <adns.h>

DEFINE_string(dbname, "", "Connect to this database");
DEFINE_string(user, "", "Connect as this user");
DEFINE_string(password, "", "Use this password to authenticate to database");
DEFINE_string(host, "", "Connect to database on this host");
DEFINE_string(port, "", "Connect to database on this port");
DEFINE_string(service, "", "Connect to database using this service");
DEFINE_string(table, "", "Modify this table");
DEFINE_string(domain, "", "Read domain from this column");
DEFINE_string(result, "", "Write response to this column");
DEFINE_int32(batchsize, 200, "Retrieve records in this batch size");
DEFINE_int32(outstanding, 5000, "Use this many concurrent DNS queries");

struct pendingquery {
  std::string domain;
  adns_query query;
};

bool exiting=false;

void sigint_handler(int)
{
  exiting = true;
}

int main(int argc, char **argv)
{
  google::SetUsageMessage("dbdnsresolve: Resolve MX records from one column of a table to another\nPerformance will be terrible unless there is an index on the column specified by --domain");
  google::ParseCommandLineFlags(&argc, &argv, true);
  if (FLAGS_domain == "" || FLAGS_result == "" || FLAGS_table == "") {
    std::cerr << "All of --table, --domain and --result must be specificed\n";
    exit(1);
  }
  std::string connstring;
  if (FLAGS_dbname.find("=") != std::string::npos ||
      boost::starts_with(FLAGS_dbname, "postgres://") ||
      boost::starts_with(FLAGS_dbname, "postgresql://")) {
    connstring = FLAGS_dbname;
  } else {
    connstring="";
    if (FLAGS_dbname != "") {
      connstring += " dbname=";
      connstring += FLAGS_dbname;
    }
    if (FLAGS_host != "") {
      connstring += " host=";
      connstring += FLAGS_host;
    }
    if (FLAGS_port != "") {
      connstring += " port=";
      connstring += FLAGS_port;
    }
    if (FLAGS_user != "") {
      connstring += " user=";
      connstring += FLAGS_user;
    }
    if (FLAGS_password != "") {
      connstring += " password=";
      connstring += FLAGS_password;
    }
    if (FLAGS_service != "") {
      connstring += " service=";
      connstring += FLAGS_service;
    }
  }

  struct sigaction sigIntHandler;

  sigIntHandler.sa_handler = sigint_handler;
  sigemptyset(&sigIntHandler.sa_mask);
  sigIntHandler.sa_flags = 0;

  sigaction(SIGINT, &sigIntHandler, NULL);

  adns_state adns;
  adns_initflags initflags = adns_if_none;
  adns_init_strcfg(&adns, initflags, stderr, "nameserver 127.0.0.1");

  pqxx::connection db(connstring);
  pqxx::work t(db);

  try {
    int processed=0;
    int total;

    std::string countq = str(boost::format("select count(*) from %1% where %2% is null") % FLAGS_table % FLAGS_result);
    db.prepare("count", countq);
    pqxx::result res = t.prepared("count").exec();
    if (res.empty()) {
      std::cerr << "Failed to count table\n";
      exit(1);
    }
    total = res[0][0].as<int>();

    std::string getcq = "declare get cursor with hold for select " + FLAGS_domain + ", " + FLAGS_result + " from " + FLAGS_table + " where " + FLAGS_result + " is null order by " + FLAGS_domain;
    //    std::cerr << getcq << "\n";
    t.exec(getcq);

    std::string fetchq = str(boost::format("fetch %1% from get") % FLAGS_batchsize);
    //    std::cerr << fetchq << "\n";
    db.prepare("fetch", fetchq);

    std::string updateq = str(boost::format("update %1% set %2%=$1 where %3% = $2") % FLAGS_table % FLAGS_result % FLAGS_domain);
    db.prepare("put", updateq);

    std::list<pendingquery*> pending;

    bool reading=true;
    while(!exiting && (reading || !pending.empty())) {
      if (reading && pending.size() < (unsigned int)FLAGS_outstanding) {
        pqxx::result res = t.prepared("fetch").exec();
        if (res.empty()) {
          reading = false;
        }
        for (pqxx::result::const_iterator row = res.begin(); row != res.end(); ++row) {
          if (row[1].is_null()) {
            pendingquery *p = new pendingquery;
            p->domain = row[0].as<std::string>();
            int err = adns_submit(adns, p->domain.c_str(), adns_r_mx_raw, adns_qf_cname_loose, 0, &p->query);
            if (err) {
              std::cerr << "adns_submit failed " << strerror(err) << "\n";
              exit(1);
            }
            pending.push_back(p);
          }
        }
      }
      pendingquery *p = pending.front();
      pending.pop_front();
      adns_answer *answer;
      int err=adns_wait_poll(adns, &p->query, &answer, 0);
      if (err == EAGAIN) {
        break;
      }
      if (err) {
        std::cerr << "adns_wait_poll failed: " << strerror(err) << "\n";
        exit(1);
      }
      std::string mx = "(none)";
      if (answer->status == adns_s_ok) {
        int prio = 70000;
        adns_rr_intstr *pp = answer->rrs.intstr;
        for (int i = 0; i < answer->nrrs; ++i) {
          if (pp->i < prio) {
            mx = pp->str;
            prio = pp->i;
          }
          ++pp;
        }
      }
      t.prepared("put")(mx)(p->domain).exec();
      processed++;
      if((processed % 100) == 0) {
        std::cerr << boost::format("  %1% / %2% %|22t|%3%                    \r") % processed % total % p->domain;
      }
      //      std::cerr << p->domain << " -> " << mx << "\n";
      delete p;
    }
    t.commit();
  }
  catch (const std::exception &e) {
    std::cerr << e.what() << std::endl;
    t.abort();
    exit(1);
  }
  if (exiting) {
    std::cerr << "\n\nStopping due to user request\n";
  } else {
    std::cerr << "\n\nFinished\n";
  }
  exit(0);
}
<commit_msg>... fix a bug or something, I guess?<commit_after>#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

#include <iostream>
#include <string>
#include <list>

#include <gflags/gflags.h>

#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>

#include <pqxx/pqxx>

#include <adns.h>

DEFINE_string(dbname, "", "Connect to this database");
DEFINE_string(user, "", "Connect as this user");
DEFINE_string(password, "", "Use this password to authenticate to database");
DEFINE_string(host, "", "Connect to database on this host");
DEFINE_string(port, "", "Connect to database on this port");
DEFINE_string(service, "", "Connect to database using this service");
DEFINE_string(table, "", "Modify this table");
DEFINE_string(domain, "", "Read domain from this column");
DEFINE_string(result, "", "Write response to this column");
DEFINE_int32(batchsize, 200, "Retrieve records in this batch size");
DEFINE_int32(outstanding, 5000, "Use this many concurrent DNS queries");

struct pendingquery {
  std::string domain;
  adns_query query;
};

bool exiting=false;

void sigint_handler(int)
{
  exiting = true;
}

int main(int argc, char **argv)
{
  google::SetUsageMessage("dbdnsresolve: Resolve MX records from one column of a table to another\nPerformance will be terrible unless there is an index on the column specified by --domain");
  google::ParseCommandLineFlags(&argc, &argv, true);
  if (FLAGS_domain == "" || FLAGS_result == "" || FLAGS_table == "") {
    std::cerr << "All of --table, --domain and --result must be specificed\n";
    exit(1);
  }
  std::string connstring;
  if (FLAGS_dbname.find("=") != std::string::npos ||
      boost::starts_with(FLAGS_dbname, "postgres://") ||
      boost::starts_with(FLAGS_dbname, "postgresql://")) {
    connstring = FLAGS_dbname;
  } else {
    connstring="";
    if (FLAGS_dbname != "") {
      connstring += " dbname=";
      connstring += FLAGS_dbname;
    }
    if (FLAGS_host != "") {
      connstring += " host=";
      connstring += FLAGS_host;
    }
    if (FLAGS_port != "") {
      connstring += " port=";
      connstring += FLAGS_port;
    }
    if (FLAGS_user != "") {
      connstring += " user=";
      connstring += FLAGS_user;
    }
    if (FLAGS_password != "") {
      connstring += " password=";
      connstring += FLAGS_password;
    }
    if (FLAGS_service != "") {
      connstring += " service=";
      connstring += FLAGS_service;
    }
  }

  struct sigaction sigIntHandler;

  sigIntHandler.sa_handler = sigint_handler;
  sigemptyset(&sigIntHandler.sa_mask);
  sigIntHandler.sa_flags = 0;

  sigaction(SIGINT, &sigIntHandler, NULL);

  adns_state adns;
  adns_initflags initflags = adns_if_none;
  adns_init_strcfg(&adns, initflags, stderr, "nameserver 127.0.0.1");

  pqxx::connection db(connstring);
  pqxx::work t(db);

  try {
    int processed=0;
    int total;

    std::string countq = str(boost::format("select count(*) from %1% where %2% is null") % FLAGS_table % FLAGS_result);
    db.prepare("count", countq);
    pqxx::result res = t.prepared("count").exec();
    if (res.empty()) {
      std::cerr << "Failed to count table\n";
      exit(1);
    }
    total = res[0][0].as<int>();

    std::string getcq = "declare get cursor with hold for select " + FLAGS_domain + ", " + FLAGS_result + " from " + FLAGS_table + " where " + FLAGS_result + " is null order by " + FLAGS_domain;
    //    std::cerr << getcq << "\n";
    t.exec(getcq);

    std::string fetchq = str(boost::format("fetch %1% from get") % FLAGS_batchsize);
    //    std::cerr << fetchq << "\n";
    db.prepare("fetch", fetchq);

    std::string updateq = str(boost::format("update %1% set %2%=$1 where %3% = $2") % FLAGS_table % FLAGS_result % FLAGS_domain);
    db.prepare("put", updateq);

    std::list<pendingquery*> pending;

    bool reading=true;
    while(!exiting && (reading || !pending.empty())) {
      if (reading && pending.size() < (unsigned int)FLAGS_outstanding) {
        pqxx::result res = t.prepared("fetch").exec();
        if (res.empty()) {
          reading = false;
        }
        for (pqxx::result::const_iterator row = res.begin(); row != res.end(); ++row) {
          if (row[1].is_null()) {
            pendingquery *p = new pendingquery;
            p->domain = row[0].as<std::string>();
            int err = adns_submit(adns, p->domain.c_str(), adns_r_mx_raw, adns_qf_cname_loose, 0, &p->query);
            if (err) {
              std::cerr << "adns_submit failed " << strerror(err) << "\n";
              exit(1);
            }
            pending.push_back(p);
          }
        }
      }
      if (pending.size() == 0) {
	continue;
      }
      pendingquery *p = pending.front();
      pending.pop_front();
      adns_answer *answer;
      int err=adns_wait_poll(adns, &p->query, &answer, 0);
      if (err == EAGAIN) {
        break;
      }
      if (err) {
        std::cerr << "adns_wait_poll failed: " << strerror(err) << "\n";
        exit(1);
      }
      std::string mx = "(none)";
      if (answer->status == adns_s_ok) {
        int prio = 70000;
        adns_rr_intstr *pp = answer->rrs.intstr;
        for (int i = 0; i < answer->nrrs; ++i) {
          if (pp->i < prio) {
            mx = pp->str;
            prio = pp->i;
          }
          ++pp;
        }
      }
      //      std::cerr << "p->domain = " << p->domain << std::endl;
      t.prepared("put")(mx)(p->domain).exec();
      processed++;
      if((processed % 100) == 0) {
        std::cerr << boost::format("  %1% / %2% %|22t|%3%                    \r") % processed % total % p->domain;
      }
      //            std::cerr << p->domain << " -> " << mx << "\n";
      delete p;
    }
    t.commit();
  }
  catch (const std::exception &e) {
    std::cerr << e.what() << std::endl;
    t.abort();
    exit(1);
  }
  if (exiting) {
    std::cerr << "\n\nStopping due to user request\n";
  } else {
    std::cerr << "\n\nFinished\n";
  }
  exit(0);
}
<|endoftext|>