<commit_before>/*************************************************************************
 *
 *  $RCSfile: labelexp.cxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: jp $ $Date: 2001-11-14 16:32:50 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#ifndef _COM_SUN_STAR_TEXT_XTEXTFIELDSSUPPLIER_HPP_
#include <com/sun/star/text/XTextFieldsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XREFRESHABLE_HPP_
#include <com/sun/star/util/XRefreshable.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _LABFMT_HXX
#include <labfmt.hxx>
#endif
#ifndef _UNOTOOLS_HXX
#include <unotools.hxx>
#endif
#ifndef _UNOATXT_HXX //autogen wg. SwXAutoTextEntry
#include <unoatxt.hxx>
#endif
#ifndef _UNOOBJ_HXX //
#include <unoobj.hxx>
#endif
#ifndef _UNOPRNMS_HXX //
#include <unoprnms.hxx>
#endif

using namespace ::com::sun::star;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace com::sun::star::uno;
using namespace ::comphelper;
using namespace ::rtl;

#define C2U(char) rtl::OUString::createFromAscii(char)

/* -----------------08.07.99 15:15-------------------

 --------------------------------------------------*/
void SwVisitingCardPage::InitFrameControl()
{
    Link aLink(LINK(this, SwVisitingCardPage, FrameControlInitializedHdl));
    pExampleFrame = new SwOneExampleFrame( aExampleWIN,
                                    EX_SHOW_BUSINESS_CARDS, &aLink );

    uno::Reference< lang::XMultiServiceFactory >  xMgr =
                                            getProcessServiceFactory();
    //now the AutoText ListBoxes have to be filled

    uno::Reference< uno::XInterface >  xAText =
        xMgr->createInstance( C2U("com.sun.star.text.AutoTextContainer") );
    _xAutoText = uno::Reference< container::XNameAccess >(xAText, uno::UNO_QUERY);

    uno::Sequence<OUString> aNames = _xAutoText->getElementNames();
    const OUString* pGroups = aNames.getConstArray();
    OUString uTitleName( C2U(SW_PROP_NAME_STR(UNO_NAME_TITLE)) );

    for(sal_uInt16 i = 0; i < aNames.getLength(); i++)
    {
        uno::Any aGroup = _xAutoText->getByName(pGroups[i]);
        uno::Reference< text::XAutoTextGroup >  xGroup;
        aGroup >>= xGroup;
        uno::Reference< container::XIndexAccess >  xIdxAcc(xGroup, uno::UNO_QUERY);
        if(!xIdxAcc.is() || xIdxAcc->getCount())
        {
            uno::Reference< beans::XPropertySet >  xPrSet(xGroup, uno::UNO_QUERY);
            uno::Any aTitle = xPrSet->getPropertyValue( uTitleName );
            OUString uTitle;
            aTitle >>= uTitle;
            String sGroup(pGroups[i]);
            sal_uInt16 nEntry = aAutoTextGroupLB.InsertEntry(uTitle);
            aAutoTextGroupLB.SetEntryData(nEntry, new String(sGroup));
        }
    }
    if(aAutoTextGroupLB.GetEntryCount())
    {
        if(LISTBOX_ENTRY_NOTFOUND == aAutoTextGroupLB.GetSelectEntryPos())
            aAutoTextGroupLB.SelectEntryPos(0);
        String sCurGroupName(
            *(String*)aAutoTextGroupLB.GetEntryData(aAutoTextGroupLB.GetSelectEntryPos()));
        if(_xAutoText->hasByName(sCurGroupName))
        {
            uno::Any aGroup = _xAutoText->getByName(sCurGroupName);
            try
            {
                uno::Reference< text::XAutoTextGroup >  xGroup;
                aGroup >>= xGroup;
                uno::Sequence< OUString > aBlockNames = xGroup->getElementNames();
                uno::Sequence< OUString > aTitles = xGroup->getTitles() ;

                SetUserData( aBlockNames.getLength(), aTitles.getConstArray(),
                            aBlockNames.getConstArray() );
            }
            catch( uno::RuntimeException& )
            {
                // we'll be her if path settings were wrong
            }
        }
    }
}
/* -----------------01.10.99 13:19-------------------

 --------------------------------------------------*/
IMPL_LINK( SwVisitingCardPage, FrameControlInitializedHdl, void*, EMPTYARG )
{
    SvLBoxEntry* pSel = aAutoTextLB.FirstSelected();
    String sEntry;
    if( pSel )
        sEntry = *(String*)pSel->GetUserData();
    uno::Reference< text::XTextCursor > & xCrsr = pExampleFrame->GetTextCursor();
    OUString uEntry(sEntry);

    String sGroup( *(String*)aAutoTextGroupLB.GetEntryData(
                                aAutoTextGroupLB.GetSelectEntryPos() ) );
    uno::Any aGroup = _xAutoText->getByName(sGroup);
    uno::Reference< text::XAutoTextGroup >  xGroup;
    aGroup >>= xGroup;

    if( sEntry.Len() && xGroup->hasByName( uEntry ) )
    {
        uno::Any aEntry(xGroup->getByName(uEntry));
        uno::Reference< text::XAutoTextEntry >  xEntry;
        aEntry >>= xEntry;
        if(xEntry.is())
        {
            uno::Reference< text::XTextRange >  xRange(xCrsr, uno::UNO_QUERY);
            xEntry->applyTo(xRange);
        }
        UpdateFields();
    }
    return 0;
}
/* -----------------22.07.99 11:06-------------------

 --------------------------------------------------*/
IMPL_LINK( SwVisitingCardPage, AutoTextSelectHdl, void*, pBox )
{
    if(_xAutoText.is())
    {
        if( &aAutoTextGroupLB == pBox )
        {
            String sGroup( *(String*)aAutoTextGroupLB.GetEntryData(
                                    aAutoTextGroupLB.GetSelectEntryPos()));
            uno::Any aGroup = _xAutoText->getByName(sGroup);
            uno::Reference< text::XAutoTextGroup >  xGroup;
            aGroup >>= xGroup;

            ClearUserData();
            aAutoTextLB.Clear();

            uno::Sequence<OUString> aBlockNames = xGroup->getElementNames();
            uno::Sequence< OUString > aTitles = xGroup->getTitles() ;
            SetUserData( aBlockNames.getLength(), aTitles.getConstArray(),
                        aBlockNames.getConstArray() );
        }
        if(pExampleFrame->IsInitialized())
            pExampleFrame->ClearDocument( TRUE );
    }
    return 0;
}

/* -----------------01.10.99 11:59-------------------

 --------------------------------------------------*/
void SwVisitingCardPage::UpdateFields()
{
    uno::Reference< frame::XModel >  xModel;
    if( pExampleFrame && (xModel = pExampleFrame->GetModel()).is())
    {
        SwLabDlg::UpdateFieldInformation(xModel, aLabItem);
    }
}
/* -----------------01.10.99 15:16-------------------

 --------------------------------------------------*/
void SwLabDlg::UpdateFieldInformation(uno::Reference< frame::XModel > & xModel, const SwLabItem& rItem)
{
    uno::Reference< text::XTextFieldsSupplier >  xFlds(xModel, uno::UNO_QUERY);
    uno::Reference< container::XNameAccess >  xFldMasters = xFlds->getTextFieldMasters();

    static const struct _SwLabItemMap {
        const char* pName;
        rtl::OUString SwLabItem:: *pValue;
    }  aArr[] = {
        { "BC_PRIV_FIRSTNAME"  , &SwLabItem::aPrivFirstName },
        { "BC_PRIV_NAME"       , &SwLabItem::aPrivName },
        { "BC_PRIV_INITIALS"   , &SwLabItem::aPrivShortCut },
        { "BC_PRIV_FIRSTNAME_2", &SwLabItem::aPrivFirstName2 },
        { "BC_PRIV_NAME_2"     , &SwLabItem::aPrivName2 },
        { "BC_PRIV_INITIALS_2" , &SwLabItem::aPrivShortCut2 },
        { "BC_PRIV_STREET"     , &SwLabItem::aPrivStreet },
        { "BC_PRIV_ZIP"        , &SwLabItem::aPrivZip },
        { "BC_PRIV_CITY"       , &SwLabItem::aPrivCity },
        { "BC_PRIV_COUNTRY"    , &SwLabItem::aPrivCountry },
        { "BC_PRIV_STATE"      , &SwLabItem::aPrivState },
        { "BC_PRIV_TITLE"      , &SwLabItem::aPrivTitle },
        { "BC_PRIV_PROFESSION" , &SwLabItem::aPrivProfession },
        { "BC_PRIV_PHONE"      , &SwLabItem::aPrivPhone },
        { "BC_PRIV_MOBILE"     , &SwLabItem::aPrivMobile },
        { "BC_PRIV_FAX"        , &SwLabItem::aPrivFax },
        { "BC_PRIV_WWW"        , &SwLabItem::aPrivWWW },
        { "BC_PRIV_MAIL"       , &SwLabItem::aPrivMail },
        { "BC_COMP_COMPANY"    , &SwLabItem::aCompCompany },
        { "BC_COMP_COMPANYEXT" , &SwLabItem::aCompCompanyExt },
        { "BC_COMP_SLOGAN"     , &SwLabItem::aCompSlogan },
        { "BC_COMP_STREET"     , &SwLabItem::aCompStreet },
        { "BC_COMP_ZIP"        , &SwLabItem::aCompZip },
        { "BC_COMP_CITY"       , &SwLabItem::aCompCity },
        { "BC_COMP_COUNTRY"    , &SwLabItem::aCompCountry },
        { "BC_COMP_STATE"      , &SwLabItem::aCompState },
        { "BC_COMP_POSITION"   , &SwLabItem::aCompPosition },
        { "BC_COMP_PHONE"      , &SwLabItem::aCompPhone },
        { "BC_COMP_MOBILE"     , &SwLabItem::aCompMobile },
        { "BC_COMP_FAX"        , &SwLabItem::aCompFax },
        { "BC_COMP_WWW"        , &SwLabItem::aCompWWW },
        { "BC_COMP_MAIL"       , &SwLabItem::aCompMail },
        { 0, 0 }
    };

    try
    {
        String sFldName( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM(
                            "com.sun.star.text.FieldMaster.User." )));
        OUString uCntName( C2U( SW_PROP_NAME_STR(UNO_NAME_CONTENT )));
        for( const _SwLabItemMap* p = aArr; p->pName; ++p )
        {
            String sCurFldName( sFldName );
            sCurFldName.AppendAscii( p->pName );
            OUString uFldName( sCurFldName );
            if( xFldMasters->hasByName( uFldName ))
            {
                uno::Any aFirstName = xFldMasters->getByName( uFldName );
                uno::Reference< beans::XPropertySet >  xFld;
                aFirstName >>= xFld;
                uno::Any aContent;
                aContent <<= rItem.*p->pValue;
                xFld->setPropertyValue( uCntName, aContent );
            }
        }
    }
    catch( uno::RuntimeException&)
    {
        //
    }

    uno::Reference< container::XEnumerationAccess >  xFldAcc = xFlds->getTextFields();
    uno::Reference< util::XRefreshable >  xRefresh(xFldAcc, uno::UNO_QUERY);
    xRefresh->refresh();
}

<commit_msg>#96118# catch another exception<commit_after>/*************************************************************************
 *
 *  $RCSfile: labelexp.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: os $ $Date: 2001-12-19 11:08:57 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#ifndef _COM_SUN_STAR_TEXT_XTEXTFIELDSSUPPLIER_HPP_
#include <com/sun/star/text/XTextFieldsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XREFRESHABLE_HPP_
#include <com/sun/star/util/XRefreshable.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _LABFMT_HXX
#include <labfmt.hxx>
#endif
#ifndef _UNOTOOLS_HXX
#include <unotools.hxx>
#endif
#ifndef _UNOATXT_HXX //autogen wg. SwXAutoTextEntry
#include <unoatxt.hxx>
#endif
#ifndef _UNOOBJ_HXX //
#include <unoobj.hxx>
#endif
#ifndef _UNOPRNMS_HXX //
#include <unoprnms.hxx>
#endif

using namespace ::com::sun::star;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace com::sun::star::uno;
using namespace ::comphelper;
using namespace ::rtl;

#define C2U(char) rtl::OUString::createFromAscii(char)

/* -----------------08.07.99 15:15-------------------

 --------------------------------------------------*/
void SwVisitingCardPage::InitFrameControl()
{
    Link aLink(LINK(this, SwVisitingCardPage, FrameControlInitializedHdl));
    pExampleFrame = new SwOneExampleFrame( aExampleWIN,
                                    EX_SHOW_BUSINESS_CARDS, &aLink );

    uno::Reference< lang::XMultiServiceFactory >  xMgr =
                                            getProcessServiceFactory();
    //now the AutoText ListBoxes have to be filled

    uno::Reference< uno::XInterface >  xAText =
        xMgr->createInstance( C2U("com.sun.star.text.AutoTextContainer") );
    _xAutoText = uno::Reference< container::XNameAccess >(xAText, uno::UNO_QUERY);

    uno::Sequence<OUString> aNames = _xAutoText->getElementNames();
    const OUString* pGroups = aNames.getConstArray();
    OUString uTitleName( C2U(SW_PROP_NAME_STR(UNO_NAME_TITLE)) );

    for(sal_uInt16 i = 0; i < aNames.getLength(); i++)
    {
        uno::Any aGroup = _xAutoText->getByName(pGroups[i]);
        uno::Reference< text::XAutoTextGroup >  xGroup;
        aGroup >>= xGroup;
        uno::Reference< container::XIndexAccess >  xIdxAcc(xGroup, uno::UNO_QUERY);
        try
        {
            if(!xIdxAcc.is() || xIdxAcc->getCount())
            {
                uno::Reference< beans::XPropertySet >  xPrSet(xGroup, uno::UNO_QUERY);
                uno::Any aTitle = xPrSet->getPropertyValue( uTitleName );
                OUString uTitle;
                aTitle >>= uTitle;
                String sGroup(pGroups[i]);
                sal_uInt16 nEntry = aAutoTextGroupLB.InsertEntry(uTitle);
                aAutoTextGroupLB.SetEntryData(nEntry, new String(sGroup));
            }
        }
        catch(Exception&)
        {
        }
    }
    if(aAutoTextGroupLB.GetEntryCount())
    {
        if(LISTBOX_ENTRY_NOTFOUND == aAutoTextGroupLB.GetSelectEntryPos())
            aAutoTextGroupLB.SelectEntryPos(0);
        String sCurGroupName(
            *(String*)aAutoTextGroupLB.GetEntryData(aAutoTextGroupLB.GetSelectEntryPos()));
        if(_xAutoText->hasByName(sCurGroupName))
        {
            uno::Any aGroup = _xAutoText->getByName(sCurGroupName);
            try
            {
                uno::Reference< text::XAutoTextGroup >  xGroup;
                aGroup >>= xGroup;
                uno::Sequence< OUString > aBlockNames = xGroup->getElementNames();
                uno::Sequence< OUString > aTitles = xGroup->getTitles() ;

                SetUserData( aBlockNames.getLength(), aTitles.getConstArray(),
                            aBlockNames.getConstArray() );
            }
            catch( uno::RuntimeException& )
            {
                // we'll be her if path settings were wrong
            }
        }
    }
}
/* -----------------01.10.99 13:19-------------------

 --------------------------------------------------*/
IMPL_LINK( SwVisitingCardPage, FrameControlInitializedHdl, void*, EMPTYARG )
{
    SvLBoxEntry* pSel = aAutoTextLB.FirstSelected();
    String sEntry;
    if( pSel )
        sEntry = *(String*)pSel->GetUserData();
    uno::Reference< text::XTextCursor > & xCrsr = pExampleFrame->GetTextCursor();
    OUString uEntry(sEntry);

    String sGroup( *(String*)aAutoTextGroupLB.GetEntryData(
                                aAutoTextGroupLB.GetSelectEntryPos() ) );
    uno::Any aGroup = _xAutoText->getByName(sGroup);
    uno::Reference< text::XAutoTextGroup >  xGroup;
    aGroup >>= xGroup;

    if( sEntry.Len() && xGroup->hasByName( uEntry ) )
    {
        uno::Any aEntry(xGroup->getByName(uEntry));
        uno::Reference< text::XAutoTextEntry >  xEntry;
        aEntry >>= xEntry;
        if(xEntry.is())
        {
            uno::Reference< text::XTextRange >  xRange(xCrsr, uno::UNO_QUERY);
            xEntry->applyTo(xRange);
        }
        UpdateFields();
    }
    return 0;
}
/* -----------------22.07.99 11:06-------------------

 --------------------------------------------------*/
IMPL_LINK( SwVisitingCardPage, AutoTextSelectHdl, void*, pBox )
{
    if(_xAutoText.is())
    {
        if( &aAutoTextGroupLB == pBox )
        {
            String sGroup( *(String*)aAutoTextGroupLB.GetEntryData(
                                    aAutoTextGroupLB.GetSelectEntryPos()));
            uno::Any aGroup = _xAutoText->getByName(sGroup);
            uno::Reference< text::XAutoTextGroup >  xGroup;
            aGroup >>= xGroup;

            ClearUserData();
            aAutoTextLB.Clear();

            uno::Sequence<OUString> aBlockNames = xGroup->getElementNames();
            uno::Sequence< OUString > aTitles = xGroup->getTitles() ;
            SetUserData( aBlockNames.getLength(), aTitles.getConstArray(),
                        aBlockNames.getConstArray() );
        }
        if(pExampleFrame->IsInitialized())
            pExampleFrame->ClearDocument( TRUE );
    }
    return 0;
}

/* -----------------01.10.99 11:59-------------------

 --------------------------------------------------*/
void SwVisitingCardPage::UpdateFields()
{
    uno::Reference< frame::XModel >  xModel;
    if( pExampleFrame && (xModel = pExampleFrame->GetModel()).is())
    {
        SwLabDlg::UpdateFieldInformation(xModel, aLabItem);
    }
}
/* -----------------01.10.99 15:16-------------------

 --------------------------------------------------*/
void SwLabDlg::UpdateFieldInformation(uno::Reference< frame::XModel > & xModel, const SwLabItem& rItem)
{
    uno::Reference< text::XTextFieldsSupplier >  xFlds(xModel, uno::UNO_QUERY);
    uno::Reference< container::XNameAccess >  xFldMasters = xFlds->getTextFieldMasters();

    static const struct _SwLabItemMap {
        const char* pName;
        rtl::OUString SwLabItem:: *pValue;
    }  aArr[] = {
        { "BC_PRIV_FIRSTNAME"  , &SwLabItem::aPrivFirstName },
        { "BC_PRIV_NAME"       , &SwLabItem::aPrivName },
        { "BC_PRIV_INITIALS"   , &SwLabItem::aPrivShortCut },
        { "BC_PRIV_FIRSTNAME_2", &SwLabItem::aPrivFirstName2 },
        { "BC_PRIV_NAME_2"     , &SwLabItem::aPrivName2 },
        { "BC_PRIV_INITIALS_2" , &SwLabItem::aPrivShortCut2 },
        { "BC_PRIV_STREET"     , &SwLabItem::aPrivStreet },
        { "BC_PRIV_ZIP"        , &SwLabItem::aPrivZip },
        { "BC_PRIV_CITY"       , &SwLabItem::aPrivCity },
        { "BC_PRIV_COUNTRY"    , &SwLabItem::aPrivCountry },
        { "BC_PRIV_STATE"      , &SwLabItem::aPrivState },
        { "BC_PRIV_TITLE"      , &SwLabItem::aPrivTitle },
        { "BC_PRIV_PROFESSION" , &SwLabItem::aPrivProfession },
        { "BC_PRIV_PHONE"      , &SwLabItem::aPrivPhone },
        { "BC_PRIV_MOBILE"     , &SwLabItem::aPrivMobile },
        { "BC_PRIV_FAX"        , &SwLabItem::aPrivFax },
        { "BC_PRIV_WWW"        , &SwLabItem::aPrivWWW },
        { "BC_PRIV_MAIL"       , &SwLabItem::aPrivMail },
        { "BC_COMP_COMPANY"    , &SwLabItem::aCompCompany },
        { "BC_COMP_COMPANYEXT" , &SwLabItem::aCompCompanyExt },
        { "BC_COMP_SLOGAN"     , &SwLabItem::aCompSlogan },
        { "BC_COMP_STREET"     , &SwLabItem::aCompStreet },
        { "BC_COMP_ZIP"        , &SwLabItem::aCompZip },
        { "BC_COMP_CITY"       , &SwLabItem::aCompCity },
        { "BC_COMP_COUNTRY"    , &SwLabItem::aCompCountry },
        { "BC_COMP_STATE"      , &SwLabItem::aCompState },
        { "BC_COMP_POSITION"   , &SwLabItem::aCompPosition },
        { "BC_COMP_PHONE"      , &SwLabItem::aCompPhone },
        { "BC_COMP_MOBILE"     , &SwLabItem::aCompMobile },
        { "BC_COMP_FAX"        , &SwLabItem::aCompFax },
        { "BC_COMP_WWW"        , &SwLabItem::aCompWWW },
        { "BC_COMP_MAIL"       , &SwLabItem::aCompMail },
        { 0, 0 }
    };

    try
    {
        String sFldName( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM(
                            "com.sun.star.text.FieldMaster.User." )));
        OUString uCntName( C2U( SW_PROP_NAME_STR(UNO_NAME_CONTENT )));
        for( const _SwLabItemMap* p = aArr; p->pName; ++p )
        {
            String sCurFldName( sFldName );
            sCurFldName.AppendAscii( p->pName );
            OUString uFldName( sCurFldName );
            if( xFldMasters->hasByName( uFldName ))
            {
                uno::Any aFirstName = xFldMasters->getByName( uFldName );
                uno::Reference< beans::XPropertySet >  xFld;
                aFirstName >>= xFld;
                uno::Any aContent;
                aContent <<= rItem.*p->pValue;
                xFld->setPropertyValue( uCntName, aContent );
            }
        }
    }
    catch( uno::RuntimeException&)
    {
        //
    }

    uno::Reference< container::XEnumerationAccess >  xFldAcc = xFlds->getTextFields();
    uno::Reference< util::XRefreshable >  xRefresh(xFldAcc, uno::UNO_QUERY);
    xRefresh->refresh();
}

<|endoftext|>


<commit_before>#define UNICODE
#include <windows.h>
#include <ole2.h>
#include <oaidl.h>
#include <objbase.h>
#include <AtlBase.h>
#include <AtlConv.h>
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
#include "dictationbridge-core/master/master.h"

#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "oleacc.lib")

#define ERR(x, msg) do { \
if(x != S_OK) {\
printf(msg "\n");\
printf("%x\n", res);\
exit(1);\
}\
} while(0)

std::string wideToString(wchar_t const * text, unsigned int length) {
	auto tmp = new char[length*2+1];
	auto resultingLen = WideCharToMultiByte(CP_UTF8, NULL, text,
		length, tmp, length*2,
		NULL, NULL);
	tmp[resultingLen] = '\0';
	std::string ret(tmp);
	delete[] tmp;
	return ret;
}

std::string BSTRToString(BSTR text) {
	unsigned int len = SysStringLen(text);
	return wideToString(text, len);
}

DISPID id;
DISPPARAMS params;
VARIANTARG args[2];
IDispatch *jfw = nullptr;

void initSpeak() {
	CLSID JFWClass;
	auto res = CLSIDFromProgID(L"FreedomSci.JawsApi", &JFWClass);
	ERR(res, "Couldn't get Jaws interface ID");
	res = CoCreateInstance(JFWClass, NULL, CLSCTX_ALL, __uuidof(IDispatch), (void**)&jfw);
	ERR(res, "Couldn't create Jaws interface");
	/* Setup to call jaws. IDL is:
	HRESULT SayString(
	[in] BSTR StringToSpeak,
	[in, optional, defaultvalue(-1)] VARIANT_BOOL bFlush,
	[out, retval] VARIANT_BOOL* vbSuccess);
	*/
	LPOLESTR name = L"SayString";
	args[1].vt = VT_BSTR;
	args[0].vt = VT_BOOL;
	args[0].boolVal = 0;
	params.rgvarg = args;
	params.rgdispidNamedArgs = NULL;
	params.cArgs = 2;
	params.cNamedArgs = 0;
	res = jfw->GetIDsOfNames(IID_NULL, &name, 1, LOCALE_SYSTEM_DEFAULT, &id);
	ERR(res, "Couldn't get SayString");
}

void speak(wchar_t const * text) {
	auto s = SysAllocString(text);
	args[1].bstrVal = s;
	jfw->Invoke(id, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &params, NULL, NULL, NULL);
	//Temporary, for debugging.
	auto tmp = BSTRToString(s);
	printf(&tmp[0]);
	printf("\n");
	SysFreeString(s);
}

void WINAPI textCallback(HWND hwnd, DWORD startPosition, LPCWSTR textUnprocessed) {
	//We need to replace \r with nothing.
	int len = wcslen(textUnprocessed);
	wchar_t* text = new wchar_t[len+1];
	int copied = 0;
	for(int i = 0; i < len; i++) {
		if(textUnprocessed[i] != L'\r') {
			text[copied] = textUnprocessed[i];
			copied += 1;
		}
	}
	text[copied+1] = 0;
	if(wcscmp(text, L"\n\n") == 0
		|| wcscmp(text, L"") == 0 //new paragraph in word.
	) {
		speak(L"New paragraph.");
	}
	else if(wcscmp(text, L"\n")  == 0) {
		speak(L"New line.");
	}
	else {
		speak(text);
	}
}

void WINAPI textDeletedCallback(HWND hwnd, DWORD startPosition, LPCWSTR text) {
	int len = wcslen(text);
	int neededLen = len + strlen("Deleted ");
	wchar_t* tmp = new wchar_t[neededLen+1];
	wcscpy(tmp, L"Deleted ");
	int offset = strlen("Deleted ");
	for(int i = 0; i < len; i++) tmp[i+offset] = text[i];
	tmp[neededLen] = 0;
	speak(tmp);
	delete[] tmp;
}

//These are string constants for the microphone status, as well as the status itself:
//The pointer below is set to the last one we saw.
const char* MICROPHONE_OFF = "Dragon's microphone is off;";
const char* MICROPHONE_ON = "Normal mode: You can dictate and use voice";
const char* MICROPHONE_SLEEPING = "The microphone is asleep;";

const char* microphoneState = nullptr;

void announceMicrophoneState(const char* state) {
	if(state == MICROPHONE_ON) speak(L"Microphone on.");
	else if(state == MICROPHONE_OFF) speak(L"Microphone off.");
	else if(state == MICROPHONE_SLEEPING) speak(L"Microphone sleeping.");
	else speak(L"Microphone in unknown state.");
}

wchar_t processNameBuffer[1024] = {0};

void CALLBACK nameChanged(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime) {
	//First, is it coming from natspeak.exe?
	DWORD procId;
	GetWindowThreadProcessId(hwnd, &procId);
	auto procHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, procId);
	//We can't recover from this failing, so abort.
	if(procHandle == NULL) return;
	DWORD len = 1024;
	auto res = QueryFullProcessImageName(procHandle, 0, processNameBuffer, &len);
	CloseHandle(procHandle);
	if(res == 0) return;
	auto processName = wideToString(processNameBuffer, (unsigned int) len);
	if(processName.find("dragonbar.exe") == std::string::npos
		&& processName.find("natspeak.exe") == std::string::npos) return;
	//Attempt to get the new text.
	IAccessible* acc = nullptr;
	VARIANT child;
	HRESULT hres = AccessibleObjectFromEvent(hwnd, idObject, idChild, &acc, &child);
	if(hres != S_OK || acc == nullptr) return;
	BSTR nameBSTR;
	hres = acc->get_accName(child, &nameBSTR);
	acc->Release();
	if(hres != S_OK) return;
	auto name = BSTRToString(nameBSTR);
	SysFreeString(nameBSTR);
	const char* possibles[] = {MICROPHONE_ON, MICROPHONE_OFF, MICROPHONE_SLEEPING};
	const char* newState = microphoneState;
	for(int i = 0; i < 3; i++) {
		if(name.find(possibles[i]) != std::string::npos) {
			newState = possibles[i];
			break;
		}
	}
	if(newState != microphoneState) {
		announceMicrophoneState(newState);
		microphoneState = newState;
	}
}

int CALLBACK WinMain(_In_ HINSTANCE hInstance,
	_In_ HINSTANCE hPrevInstance,
	_In_ LPSTR lpCmdLine,
	_In_ int nCmdShow) {
	HRESULT res;
	res = OleInitialize(NULL);
	ERR(res, "Couldn't initialize OLE");
	initSpeak();
	auto started = DBMaster_Start();
	if(!started) {
		printf("Couldn't start DictationBridge-core\n");
		return 1;
	}
	DBMaster_SetTextInsertedCallback(textCallback);
	DBMaster_SetTextDeletedCallback(textDeletedCallback);
	if(SetWinEventHook(EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, NULL, nameChanged, 0, 0, WINEVENT_OUTOFCONTEXT) == 0) {
		printf("Couldn't register to receive events\n");
		return 1;
	}
	MSG msg;
	while(GetMessage(&msg, NULL, NULL, NULL) > 0) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	DBMaster_Stop();
	OleUninitialize();
	return 0;
}
<commit_msg>Remove some old debugging code.<commit_after>#define UNICODE
#include <windows.h>
#include <ole2.h>
#include <oaidl.h>
#include <objbase.h>
#include <AtlBase.h>
#include <AtlConv.h>
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
#include "dictationbridge-core/master/master.h"

#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "oleacc.lib")

#define ERR(x, msg) do { \
if(x != S_OK) {\
printf(msg "\n");\
printf("%x\n", res);\
exit(1);\
}\
} while(0)

std::string wideToString(wchar_t const * text, unsigned int length) {
	auto tmp = new char[length*2+1];
	auto resultingLen = WideCharToMultiByte(CP_UTF8, NULL, text,
		length, tmp, length*2,
		NULL, NULL);
	tmp[resultingLen] = '\0';
	std::string ret(tmp);
	delete[] tmp;
	return ret;
}

std::string BSTRToString(BSTR text) {
	unsigned int len = SysStringLen(text);
	return wideToString(text, len);
}

DISPID id;
DISPPARAMS params;
VARIANTARG args[2];
IDispatch *jfw = nullptr;

void initSpeak() {
	CLSID JFWClass;
	auto res = CLSIDFromProgID(L"FreedomSci.JawsApi", &JFWClass);
	ERR(res, "Couldn't get Jaws interface ID");
	res = CoCreateInstance(JFWClass, NULL, CLSCTX_ALL, __uuidof(IDispatch), (void**)&jfw);
	ERR(res, "Couldn't create Jaws interface");
	/* Setup to call jaws. IDL is:
	HRESULT SayString(
	[in] BSTR StringToSpeak,
	[in, optional, defaultvalue(-1)] VARIANT_BOOL bFlush,
	[out, retval] VARIANT_BOOL* vbSuccess);
	*/
	LPOLESTR name = L"SayString";
	args[1].vt = VT_BSTR;
	args[0].vt = VT_BOOL;
	args[0].boolVal = 0;
	params.rgvarg = args;
	params.rgdispidNamedArgs = NULL;
	params.cArgs = 2;
	params.cNamedArgs = 0;
	res = jfw->GetIDsOfNames(IID_NULL, &name, 1, LOCALE_SYSTEM_DEFAULT, &id);
	ERR(res, "Couldn't get SayString");
}

void speak(wchar_t const * text) {
	auto s = SysAllocString(text);
	args[1].bstrVal = s;
	jfw->Invoke(id, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &params, NULL, NULL, NULL);
	SysFreeString(s);
}

void WINAPI textCallback(HWND hwnd, DWORD startPosition, LPCWSTR textUnprocessed) {
	//We need to replace \r with nothing.
	int len = wcslen(textUnprocessed);
	wchar_t* text = new wchar_t[len+1];
	int copied = 0;
	for(int i = 0; i < len; i++) {
		if(textUnprocessed[i] != L'\r') {
			text[copied] = textUnprocessed[i];
			copied += 1;
		}
	}
	text[copied+1] = 0;
	if(wcscmp(text, L"\n\n") == 0
		|| wcscmp(text, L"") == 0 //new paragraph in word.
	) {
		speak(L"New paragraph.");
	}
	else if(wcscmp(text, L"\n")  == 0) {
		speak(L"New line.");
	}
	else {
		speak(text);
	}
}

void WINAPI textDeletedCallback(HWND hwnd, DWORD startPosition, LPCWSTR text) {
	int len = wcslen(text);
	int neededLen = len + strlen("Deleted ");
	wchar_t* tmp = new wchar_t[neededLen+1];
	wcscpy(tmp, L"Deleted ");
	int offset = strlen("Deleted ");
	for(int i = 0; i < len; i++) tmp[i+offset] = text[i];
	tmp[neededLen] = 0;
	speak(tmp);
	delete[] tmp;
}

//These are string constants for the microphone status, as well as the status itself:
//The pointer below is set to the last one we saw.
const char* MICROPHONE_OFF = "Dragon's microphone is off;";
const char* MICROPHONE_ON = "Normal mode: You can dictate and use voice";
const char* MICROPHONE_SLEEPING = "The microphone is asleep;";

const char* microphoneState = nullptr;

void announceMicrophoneState(const char* state) {
	if(state == MICROPHONE_ON) speak(L"Microphone on.");
	else if(state == MICROPHONE_OFF) speak(L"Microphone off.");
	else if(state == MICROPHONE_SLEEPING) speak(L"Microphone sleeping.");
	else speak(L"Microphone in unknown state.");
}

wchar_t processNameBuffer[1024] = {0};

void CALLBACK nameChanged(HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime) {
	//First, is it coming from natspeak.exe?
	DWORD procId;
	GetWindowThreadProcessId(hwnd, &procId);
	auto procHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, procId);
	//We can't recover from this failing, so abort.
	if(procHandle == NULL) return;
	DWORD len = 1024;
	auto res = QueryFullProcessImageName(procHandle, 0, processNameBuffer, &len);
	CloseHandle(procHandle);
	if(res == 0) return;
	auto processName = wideToString(processNameBuffer, (unsigned int) len);
	if(processName.find("dragonbar.exe") == std::string::npos
		&& processName.find("natspeak.exe") == std::string::npos) return;
	//Attempt to get the new text.
	IAccessible* acc = nullptr;
	VARIANT child;
	HRESULT hres = AccessibleObjectFromEvent(hwnd, idObject, idChild, &acc, &child);
	if(hres != S_OK || acc == nullptr) return;
	BSTR nameBSTR;
	hres = acc->get_accName(child, &nameBSTR);
	acc->Release();
	if(hres != S_OK) return;
	auto name = BSTRToString(nameBSTR);
	SysFreeString(nameBSTR);
	const char* possibles[] = {MICROPHONE_ON, MICROPHONE_OFF, MICROPHONE_SLEEPING};
	const char* newState = microphoneState;
	for(int i = 0; i < 3; i++) {
		if(name.find(possibles[i]) != std::string::npos) {
			newState = possibles[i];
			break;
		}
	}
	if(newState != microphoneState) {
		announceMicrophoneState(newState);
		microphoneState = newState;
	}
}

int CALLBACK WinMain(_In_ HINSTANCE hInstance,
	_In_ HINSTANCE hPrevInstance,
	_In_ LPSTR lpCmdLine,
	_In_ int nCmdShow) {
	HRESULT res;
	res = OleInitialize(NULL);
	ERR(res, "Couldn't initialize OLE");
	initSpeak();
	auto started = DBMaster_Start();
	if(!started) {
		printf("Couldn't start DictationBridge-core\n");
		return 1;
	}
	DBMaster_SetTextInsertedCallback(textCallback);
	DBMaster_SetTextDeletedCallback(textDeletedCallback);
	if(SetWinEventHook(EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, NULL, nameChanged, 0, 0, WINEVENT_OUTOFCONTEXT) == 0) {
		printf("Couldn't register to receive events\n");
		return 1;
	}
	MSG msg;
	while(GetMessage(&msg, NULL, NULL, NULL) > 0) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	DBMaster_Stop();
	OleUninitialize();
	return 0;
}
<|endoftext|>


<commit_before>#include <Column.h>
#include <Terminal.h>

#include <iostream>
#include <cstdlib>
#include <ctime>

void setupColors();

int main()
{
	//seed the rng
	std::srand(std::time(NULL));

	//initialize screen
	matrix::Terminal::init();
	setupColors();

	//Column(Column * head, int column, int speed, int length, int height);
	matrix::Column * columns = new matrix::Column(0,0);
	matrix::Column * tmp = NULL;

	//get terminal size
	int rows,cols;
	matrix::Terminal::getSize(rows,cols);

	//set up for loop
	int column, speed = 1, length;
	int tick, nextSpawn = 1;

	//perform the loop
	//we'll do 100 ticks per second, 10 second run
	for (tick = 1; tick < 1000; tick++)
	{
		if (tick == nextSpawn)
		{
			nextSpawn = 1 + tick + (std::rand() % 5);

			column = std::rand() % cols;
			speed = 2 + (std::rand() % 10);
			length = 5 + (std::rand() % 50);

			tmp = new matrix::Column(column,rows);
			tmp->setSpeed(speed);
			tmp->setLength(length);
			tmp->insert(columns);
		}

		//do the draw
		matrix::Terminal::blank();
		matrix::Column::drawAll(columns,tick);
		matrix::Terminal::draw();
		matrix::Terminal::pause(10);
	}

	delete columns;

	matrix::Terminal::end();

	return 0;
}

void setupColors()
{
	int r[8], g[8], b[8];

	int i;
	for (i = 0; i < 8; i++)
	{
		r[i] = 0;
		g[i] = 125 * i;
		b[i] = 0;
	}

	matrix::Terminal::makePalette(8,r,g,b);
}
<commit_msg>added command line arguments for run time<commit_after>#include <Column.h>
#include <Terminal.h>

#include <iostream>//for cout
#include <cstdlib> //for atoi(), srand(), and rand()
#include <ctime>   //for time() (to seed rand)

void setupColors();
void printUsage(const char * name);

int main(int argc, char * argv[])
{
	int seconds = 10;

	if (argc > 2)
	{
		printUsage(argv[0]);
		return 0;
	}

	if (argc == 2)
	{
		seconds = std::atoi(argv[1]);
		if (seconds <= 0)
		{
			printUsage(argv[0]);
			return 0;
		}
	}

	//seed the rng
	std::srand(std::time(NULL));

	//initialize screen
	matrix::Terminal::init();
	setupColors();

	//Column(Column * head, int column, int speed, int length, int height);
	matrix::Column * columns = new matrix::Column(0,0);
	matrix::Column * tmp = NULL;

	//get terminal size
	int rows,cols;
	matrix::Terminal::getSize(rows,cols);

	//set up for loop
	int column, speed = 1, length;
	int tick, nextSpawn = 1;
	int runtime = seconds * 100;

	//perform the loop
	//we'll do 100 ticks per second, 10 second run
	for (tick = 1; tick < runtime; tick++)
	{
		if (tick == nextSpawn)
		{
			nextSpawn = 1 + tick + (std::rand() % 5);

			column = std::rand() % cols;
			speed = 2 + (std::rand() % 10);
			length = 5 + (std::rand() % 50);

			tmp = new matrix::Column(column,rows);
			tmp->setSpeed(speed);
			tmp->setLength(length);
			tmp->insert(columns);
		}

		//do the draw
		matrix::Terminal::blank();
		matrix::Column::drawAll(columns,tick);
		matrix::Terminal::draw();
		matrix::Terminal::pause(10);
	}

	delete columns;

	matrix::Terminal::end();

	return 0;
}

void printUsage(const char * name)
{
	std::cout << "    usage: " << name << " [seconds]\n";
}

void setupColors()
{
	int r[8], g[8], b[8];

	int i;
	for (i = 0; i < 8; i++)
	{
		r[i] = 0;
		g[i] = 125 * i;
		b[i] = 0;
	}

	matrix::Terminal::makePalette(8,r,g,b);
}
<|endoftext|>


<commit_before>//This file is not used, for function definitions refer photon_math.h
<commit_msg>updating according to conformation<commit_after>//This file is not used, for function definitions refer photon_math.h
#include "photon_math.h"

int photon_math::add_nos(int a[], int size)
{
int ret_sum,i;
ret_sum = i = 0;
for(i=0;i<size;i++)
{
ret_sum += a[i];
}
return ret_sum;
}
<|endoftext|>


<commit_before>#include "Server.hpp"
#include "FileHandler.hpp"
#include "CommandHandler.hpp"

#include <memory>

//Define constants
const int Server::BUFFER_SIZE = 16384;

//Constructor
Server::Server(int s) : sock(s) {
	sstr s2; s2 << "Child server has started.";
	FileHandler::log(s2);
	start();
}

//Destructor
Server::~Server() {
	sstr s2; s2 << "Client disconnected from server.";
	FileHandler::userQuit(me());
	FileHandler::log(s2);
}

//Log and send a string
inline void respond(int sock, const std::string& s, const bool addNewL = true) {

	//Add newline if wanted
	string s2 = s; if(addNewL) s2 += '\n';

	//Log the message
	FileHandler::log(s2);

	//Send the string
	Assert(send( sock, s2.data(), s2.size(), 0) == s2.size(),
		"send() failed.");
}

//The function that runs the server
void Server::start() {

	//Create a buffer
	char buf[BUFFER_SIZE+1]; buf[BUFFER_SIZE] = 0;

	//Loop and recieve data from the client
	for(int n; (n = (int)recv( sock, buf, BUFFER_SIZE, 0 ) ); ) {

		//Check for errors or disconnects
		if (n < 0) Err("recv() failed");
		else if (!n) return;
		else buf[n] = 0;

		//Ignore prepended whitespace
		int i; for(i = 0; i < n; i++)
			if (buf[i] && !isspace(buf[i])) break;

		//If an empty string was recieved, note so then continue
		if (i == n) {
			respond( sock, "Empty string recieved" );
			//TODO
			continue;
		}

		//Find the command
		int k; for(k = i + 1; k < n; k++)
			if (!buf[k] || isspace(buf[k])) break;

		if (k == n) {
			respond( sock, "Incomplete command recieved" );
			//TODO
			continue;
		}

		//Create needed strings string of arguments
		std::string args(&buf[k+1], n-(k+1));
		std::string cmd(&buf[i], k-i);

		//Log the command, or at least part of it
		sstr s2; s2 << "Running command: " << cmd;
		respond(sock, s2.str());
		FileHandler::log(s2);

		//TODO: change, thePath, thread
		std::string pth = "";

		//TODO: change, thePath, thread
		//Run the command and send the result
		respond(sock, CommandHandler::runCmd( std::move(cmd), std::move(args),
		                                      std::move(pth), false), false );
	}
}
<commit_msg>Minor tweak<commit_after>#include "Server.hpp"
#include "FileHandler.hpp"
#include "CommandHandler.hpp"

#include <memory>

//Define constants
const int Server::BUFFER_SIZE = 16384;

//Constructor
Server::Server(int s) : sock(s) {
	sstr s2; s2 << "Child server has started.";
	FileHandler::log(s2);
	start();
}

//Destructor
Server::~Server() {
	sstr s2; s2 << "Client disconnected from server.";
	FileHandler::userQuit(me());
	FileHandler::log(s2);
}

//Log and send a string
inline void respond(int sock, std::string&& s, const bool addNewL = true) {

	//Add newline if wanted
	if(addNewL) s += '\n';

	//Log the message
	FileHandler::log(s);

	//Send the string
	Assert(send( sock, s.data(), s.size(), 0) == s.size(),
		"send() failed.");
}

//The function that runs the server
void Server::start() {

	//Create a buffer
	char buf[BUFFER_SIZE+1]; buf[BUFFER_SIZE] = 0;

	//Loop and recieve data from the client
	for(int n; (n = (int)recv( sock, buf, BUFFER_SIZE, 0 ) ); ) {

		//Check for errors or disconnects
		if (n < 0) Err("recv() failed");
		else if (!n) return;
		else buf[n] = 0;

		//Ignore prepended whitespace
		int i; for(i = 0; i < n; i++)
			if (buf[i] && !isspace(buf[i])) break;

		//If an empty string was recieved, note so then continue
		if (i == n) {
			respond( sock, "Empty string recieved" );
			//TODO
			continue;
		}

		//Find the command
		int k; for(k = i + 1; k < n; k++)
			if (!buf[k] || isspace(buf[k])) break;

		if (k == n) {
			respond( sock, "Incomplete command recieved" );
			//TODO
			continue;
		}

		//Create needed strings string of arguments
		std::string args(&buf[k+1], n-(k+1));
		std::string cmd(&buf[i], k-i);

		//Log the command, or at least part of it
		sstr s2; s2 << "Running command: " << cmd;
		respond(sock, s2.str());
		FileHandler::log(s2);

		//TODO: change, thePath, thread
		std::string pth = "";

		//TODO: change, thePath, thread
		//Run the command and send the result
		respond(sock, CommandHandler::runCmd( std::move(cmd), std::move(args),
		                                      std::move(pth), false), false );
	}
}
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------

#include "platform/platform.h"
#include "gui/containers/guiContainer.h"

#include "gui/containers/guiPanel.h"
#include "console/consoleTypes.h"
#include "console/engineAPI.h"

IMPLEMENT_CONOBJECT( GuiContainer );

ConsoleDocClass( GuiContainer,
   "@brief Brief Desc.\n\n"

   "@tsexample\n"
   "// Comment:\n"
   "%okButton = new ClassObject()\n"
   "instantiation\n"
   "@endtsexample\n\n"

   "@ingroup GuiContainers"
);

ImplementEnumType( GuiDockingType,
   "\n\n"
   "@ingroup GuiContainers" )
   { Docking::dockNone,         "None"   },
   { Docking::dockClient,       "Client" },
   { Docking::dockTop,          "Top"    },
   { Docking::dockBottom,       "Bottom" },
   { Docking::dockLeft,         "Left"   },
   { Docking::dockRight,        "Right"  }
EndImplementEnumType;

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

GuiContainer::GuiContainer()
{
   mUpdateLayout = false;
   mValidDockingMask =  Docking::dockNone | Docking::dockBottom |
      Docking::dockTop  | Docking::dockClient |
      Docking::dockLeft | Docking::dockRight;
   mIsContainer = true;
}

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

GuiContainer::~GuiContainer()
{
}

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

void GuiContainer::initPersistFields()
{
   Con::setIntVariable("$DOCKING_NONE",   Docking::dockNone);
   Con::setIntVariable("$DOCKING_CLIENT", Docking::dockClient);
   Con::setIntVariable("$DOCKING_TOP",    Docking::dockTop);
   Con::setIntVariable("$DOCKING_BOTTOM", Docking::dockBottom);
   Con::setIntVariable("$DOCKING_LEFT",   Docking::dockLeft);
   Con::setIntVariable("$DOCKING_RIGHT",  Docking::dockRight);

   addGroup( "Layout" );

      addProtectedField("docking",  TYPEID< Docking::DockingType >(),   Offset(mSizingOptions.mDocking, GuiContainer), &setDockingField, &defaultProtectedGetFn, "" );
      addField("margin",         TypeRectSpacingI, Offset(mSizingOptions.mPadding, GuiContainer));
      addField("padding",        TypeRectSpacingI, Offset(mSizingOptions.mInternalPadding, GuiContainer));
      addField("anchorTop",      TypeBool,          Offset(mSizingOptions.mAnchorTop, GuiContainer));
      addField("anchorBottom",   TypeBool,          Offset(mSizingOptions.mAnchorBottom, GuiContainer));
      addField("anchorLeft",     TypeBool,          Offset(mSizingOptions.mAnchorLeft, GuiContainer));
      addField("anchorRight",    TypeBool,          Offset(mSizingOptions.mAnchorRight, GuiContainer));

   endGroup( "Layout" );

   Parent::initPersistFields();
}

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

void GuiContainer::onChildAdded(GuiControl* control)
{
   Parent::onChildAdded( control );
   setUpdateLayout();
}

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

void GuiContainer::onChildRemoved(GuiControl* control)
{
   Parent::onChildRemoved( control );
   setUpdateLayout();
}

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

bool GuiContainer::reOrder(SimObject* obj, SimObject* target)
{
   if ( !Parent::reOrder(obj, target) )
      return false;

   setUpdateLayout();
   return true;
}

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

bool GuiContainer::resize( const Point2I &newPosition, const Point2I &newExtent )
{
   RectI oldBounds = getBounds();
   Point2I minExtent = getMinExtent();

   if( !Parent::resize( newPosition, newExtent ) )
      return false;

   RectI clientRect = getClientRect();
   layoutControls( clientRect );

   GuiControl *parent = getParent();
   S32 docking = getDocking();
   if( parent && docking != Docking::dockNone && docking != Docking::dockInvalid )
      setUpdateLayout( updateParent );

   return true;
}

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

void GuiContainer::addObject(SimObject *obj)
{
   Parent::addObject(obj);

   setUpdateLayout();
}

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

void GuiContainer::removeObject(SimObject *obj)
{
   Parent::removeObject(obj);

   setUpdateLayout();
}

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

void GuiContainer::parentResized(const RectI &oldParentRect, const RectI &newParentRect)
{
	//if(!mCanResize)
	//	return;

   // If it's a control that specifies invalid docking, we'll just treat it as an old GuiControl
   if( getDocking() & Docking::dockInvalid || getDocking() & Docking::dockNone)
      return Parent::parentResized( oldParentRect, newParentRect );

   S32 deltaX = newParentRect.extent.x - oldParentRect.extent.x;
   S32 deltaY = newParentRect.extent.y - oldParentRect.extent.y;

   // Update Self
   RectI oldThisRect = getBounds();
   anchorControl( this, Point2I( deltaX, deltaY ) );
   RectI newThisRect = getBounds();

   // Update Deltas to pass on to children
   deltaX = newThisRect.extent.x - oldThisRect.extent.x;
   deltaY = newThisRect.extent.y - oldThisRect.extent.y;

   // Iterate over all children and update their anchors
   iterator nI = begin();
   for( ; nI != end(); nI++ )
   {
      // Sanity
      GuiControl *control = dynamic_cast<GuiControl*>( (*nI) );
      if( control )
         control->parentResized( oldThisRect, newThisRect );
   }
}

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

void GuiContainer::childResized(GuiControl *child)
{
   Parent::childResized( child );
   setUpdateLayout();
}

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

bool GuiContainer::layoutControls(  RectI &clientRect )
{
   // This variable is set to the first 'Client' docking
   //  control that is found.  We defer client docking until
   //  after all other docks have been made since it will consume
   //  the remaining client area available.
   GuiContainer *clientDocking = NULL;

   // Iterate over all children and perform docking
   iterator nI = begin();
   for( ; nI != end(); nI++ )
   {
      // Layout Content with proper docking (Client Default)
      GuiControl *control = static_cast<GuiControl*>(*nI);

      // If we're invisible we don't get counted in docking
      if( control == NULL || !control->isVisible() )
         continue;

	  S32 dockingMode = Docking::dockNone;
	  GuiContainer *container = dynamic_cast<GuiContainer*>(control);
	  if( container != NULL )
		  dockingMode = container->getDocking();
     else
        continue;

     // See above note about clientDocking pointer
     if( dockingMode & Docking::dockClient && clientDocking == NULL )
        clientDocking = container;

      // Dock Appropriately
     if( !(dockingMode & Docking::dockClient) )
        dockControl( container, dockingMode, clientRect );
   }

   // Do client dock
   if( clientDocking != NULL )
      dockControl( clientDocking, Docking::dockClient, clientRect );

   return true;
}

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

bool GuiContainer::dockControl( GuiContainer *control, S32 dockingMode, RectI &clientRect )
{
   if( !control )
      return false;

   // Make sure this class support docking of this type
   if( !(dockingMode & getValidDockingMask()))
      return false;

   // If our client rect has run out of room, we can't dock any more
   if( !clientRect.isValidRect() )
      return false;

   // Dock Appropriately
   RectI dockRect;
   RectSpacingI rectShrinker;
   ControlSizing sizingOptions = control->getSizingOptions();
   switch( dockingMode )
   {
   case Docking::dockClient:

      // Inset by padding
      sizingOptions.mPadding.insetRect(clientRect);

      // Dock to entirety of client rectangle
      control->resize( clientRect.point, clientRect.extent );

      // Remove Client Rect, can only have one client dock
      clientRect.set(0,0,0,0);
      break;
   case Docking::dockTop:

      dockRect = clientRect;
      dockRect.extent.y = getMin( control->getHeight() + sizingOptions.mPadding.top + sizingOptions.mPadding.bottom , clientRect.extent.y );

      // Subtract our rect
      clientRect.point.y += dockRect.extent.y;
      clientRect.extent.y -= dockRect.extent.y;

      // Inset by padding
      sizingOptions.mPadding.insetRect(dockRect);

      // Resize
      control->resize( dockRect.point, dockRect.extent );

      break;
   case Docking::dockBottom:

      dockRect = clientRect;
      dockRect.extent.y = getMin( control->getHeight() + sizingOptions.mPadding.top + sizingOptions.mPadding.bottom, clientRect.extent.y );
      dockRect.point.y += clientRect.extent.y - dockRect.extent.y;

      // Subtract our rect
      clientRect.extent.y -= dockRect.extent.y;

      // Inset by padding
      sizingOptions.mPadding.insetRect(dockRect);

      // Resize
      control->resize( dockRect.point, dockRect.extent );

      break;
   case Docking::dockLeft:

      dockRect = clientRect;
      dockRect.extent.x = getMin( control->getWidth() + sizingOptions.mPadding.left + sizingOptions.mPadding.right, clientRect.extent.x );

      // Subtract our rect
      clientRect.point.x += dockRect.extent.x;
      clientRect.extent.x -= dockRect.extent.x;

      // Inset by padding
      sizingOptions.mPadding.insetRect(dockRect);

      // Resize
      control->resize( dockRect.point, dockRect.extent );

      break;
   case Docking::dockRight:

      dockRect = clientRect;
      dockRect.extent.x = getMin( control->getWidth() + sizingOptions.mPadding.left + sizingOptions.mPadding.right, clientRect.extent.x );
      dockRect.point.x += clientRect.extent.x - dockRect.extent.x;

      // Subtract our rect
      clientRect.extent.x -= dockRect.extent.x;

      // Inset by padding
      sizingOptions.mPadding.insetRect(dockRect);

      // Resize
      control->resize( dockRect.point, dockRect.extent );

      break;
   case Docking::dockNone:
      control->setUpdateLayout();
      break;
   }

   return true;
}

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

bool GuiContainer::anchorControl( GuiControl *control, const Point2I &deltaParentExtent )
{
   GuiContainer *container = dynamic_cast<GuiContainer*>( control );
   if( !control || !container )
      return false;

   // If we're docked, we don't anchor to anything
   if( (container->getDocking() & Docking::dockAny) || !(container->getDocking() & Docking::dockInvalid)  )
      return false;

   if( deltaParentExtent.isZero() )
      return false;

   RectI oldRect = control->getBounds();
   RectI newRect = control->getBounds();

   F32 deltaBottom = mSizingOptions.mAnchorBottom ? (F32)deltaParentExtent.y : 0.0f;
   F32 deltaRight = mSizingOptions.mAnchorRight ? (F32)deltaParentExtent.x : 0.0f;
   F32 deltaLeft = mSizingOptions.mAnchorLeft ? 0.0f : (F32)deltaParentExtent.x;
   F32 deltaTop = mSizingOptions.mAnchorTop ? 0.0f : (F32)deltaParentExtent.y;

   // Apply Delta's to newRect
   newRect.point.x += (S32)deltaLeft;
   newRect.extent.x += (S32)(deltaRight - deltaLeft);
   newRect.point.y += (S32)deltaTop;
   newRect.extent.y += (S32)(deltaBottom - deltaTop);

   Point2I minExtent = control->getMinExtent();
   // Only resize if our minExtent is satisfied with it.
   if( !( newRect.extent.x >= control->getMinExtent().x && newRect.extent.y >= control->getMinExtent().y ) )
      return false;

   if( newRect.point == oldRect.point && newRect.extent == oldRect.extent )
      return false;

   // Finally Size the control
   control->resize( newRect.point, newRect.extent );

   // We made changes
   return true;
}

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

void GuiContainer::onPreRender()
{
   if( mUpdateLayout == updateNone )
      return;

   RectI clientRect = getClientRect();
   if( mUpdateLayout & updateSelf )
      layoutControls( clientRect );

   GuiContainer *parent = dynamic_cast<GuiContainer*>( getParent() );
   if( parent && ( mUpdateLayout & updateParent ) )
      parent->setUpdateLayout();

   // Always set AFTER layoutControls call to prevent recursive calling of layoutControls - JDD
   mUpdateLayout = updateNone;

   Parent::onPreRender();
}

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

const RectI GuiContainer::getClientRect()
{
   RectI resRect = RectI( Point2I(0,0), getExtent() );

   // Inset by padding
   mSizingOptions.mInternalPadding.insetRect( resRect );

   return resRect;
}

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

void GuiContainer::setDocking( S32 docking )
{
   mSizingOptions.mDocking = docking;
   setUpdateLayout( updateParent );
}
<commit_msg>Removed unused variables<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------

#include "platform/platform.h"
#include "gui/containers/guiContainer.h"

#include "gui/containers/guiPanel.h"
#include "console/consoleTypes.h"
#include "console/engineAPI.h"

IMPLEMENT_CONOBJECT( GuiContainer );

ConsoleDocClass( GuiContainer,
   "@brief Brief Desc.\n\n"

   "@tsexample\n"
   "// Comment:\n"
   "%okButton = new ClassObject()\n"
   "instantiation\n"
   "@endtsexample\n\n"

   "@ingroup GuiContainers"
);

ImplementEnumType( GuiDockingType,
   "\n\n"
   "@ingroup GuiContainers" )
   { Docking::dockNone,         "None"   },
   { Docking::dockClient,       "Client" },
   { Docking::dockTop,          "Top"    },
   { Docking::dockBottom,       "Bottom" },
   { Docking::dockLeft,         "Left"   },
   { Docking::dockRight,        "Right"  }
EndImplementEnumType;

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

GuiContainer::GuiContainer()
{
   mUpdateLayout = false;
   mValidDockingMask =  Docking::dockNone | Docking::dockBottom |
      Docking::dockTop  | Docking::dockClient |
      Docking::dockLeft | Docking::dockRight;
   mIsContainer = true;
}

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

GuiContainer::~GuiContainer()
{
}

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

void GuiContainer::initPersistFields()
{
   Con::setIntVariable("$DOCKING_NONE",   Docking::dockNone);
   Con::setIntVariable("$DOCKING_CLIENT", Docking::dockClient);
   Con::setIntVariable("$DOCKING_TOP",    Docking::dockTop);
   Con::setIntVariable("$DOCKING_BOTTOM", Docking::dockBottom);
   Con::setIntVariable("$DOCKING_LEFT",   Docking::dockLeft);
   Con::setIntVariable("$DOCKING_RIGHT",  Docking::dockRight);

   addGroup( "Layout" );

      addProtectedField("docking",  TYPEID< Docking::DockingType >(),   Offset(mSizingOptions.mDocking, GuiContainer), &setDockingField, &defaultProtectedGetFn, "" );
      addField("margin",         TypeRectSpacingI, Offset(mSizingOptions.mPadding, GuiContainer));
      addField("padding",        TypeRectSpacingI, Offset(mSizingOptions.mInternalPadding, GuiContainer));
      addField("anchorTop",      TypeBool,          Offset(mSizingOptions.mAnchorTop, GuiContainer));
      addField("anchorBottom",   TypeBool,          Offset(mSizingOptions.mAnchorBottom, GuiContainer));
      addField("anchorLeft",     TypeBool,          Offset(mSizingOptions.mAnchorLeft, GuiContainer));
      addField("anchorRight",    TypeBool,          Offset(mSizingOptions.mAnchorRight, GuiContainer));

   endGroup( "Layout" );

   Parent::initPersistFields();
}

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

void GuiContainer::onChildAdded(GuiControl* control)
{
   Parent::onChildAdded( control );
   setUpdateLayout();
}

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

void GuiContainer::onChildRemoved(GuiControl* control)
{
   Parent::onChildRemoved( control );
   setUpdateLayout();
}

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

bool GuiContainer::reOrder(SimObject* obj, SimObject* target)
{
   if ( !Parent::reOrder(obj, target) )
      return false;

   setUpdateLayout();
   return true;
}

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

bool GuiContainer::resize( const Point2I &newPosition, const Point2I &newExtent )
{
   if( !Parent::resize( newPosition, newExtent ) )
      return false;

   RectI clientRect = getClientRect();
   layoutControls( clientRect );

   GuiControl *parent = getParent();
   S32 docking = getDocking();
   if( parent && docking != Docking::dockNone && docking != Docking::dockInvalid )
      setUpdateLayout( updateParent );

   return true;
}

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

void GuiContainer::addObject(SimObject *obj)
{
   Parent::addObject(obj);

   setUpdateLayout();
}

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

void GuiContainer::removeObject(SimObject *obj)
{
   Parent::removeObject(obj);

   setUpdateLayout();
}

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

void GuiContainer::parentResized(const RectI &oldParentRect, const RectI &newParentRect)
{
	//if(!mCanResize)
	//	return;

   // If it's a control that specifies invalid docking, we'll just treat it as an old GuiControl
   if( getDocking() & Docking::dockInvalid || getDocking() & Docking::dockNone)
      return Parent::parentResized( oldParentRect, newParentRect );

   S32 deltaX = newParentRect.extent.x - oldParentRect.extent.x;
   S32 deltaY = newParentRect.extent.y - oldParentRect.extent.y;

   // Update Self
   RectI oldThisRect = getBounds();
   anchorControl( this, Point2I( deltaX, deltaY ) );
   RectI newThisRect = getBounds();

   // Update Deltas to pass on to children
   deltaX = newThisRect.extent.x - oldThisRect.extent.x;
   deltaY = newThisRect.extent.y - oldThisRect.extent.y;

   // Iterate over all children and update their anchors
   iterator nI = begin();
   for( ; nI != end(); nI++ )
   {
      // Sanity
      GuiControl *control = dynamic_cast<GuiControl*>( (*nI) );
      if( control )
         control->parentResized( oldThisRect, newThisRect );
   }
}

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

void GuiContainer::childResized(GuiControl *child)
{
   Parent::childResized( child );
   setUpdateLayout();
}

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

bool GuiContainer::layoutControls(  RectI &clientRect )
{
   // This variable is set to the first 'Client' docking
   //  control that is found.  We defer client docking until
   //  after all other docks have been made since it will consume
   //  the remaining client area available.
   GuiContainer *clientDocking = NULL;

   // Iterate over all children and perform docking
   iterator nI = begin();
   for( ; nI != end(); nI++ )
   {
      // Layout Content with proper docking (Client Default)
      GuiControl *control = static_cast<GuiControl*>(*nI);

      // If we're invisible we don't get counted in docking
      if( control == NULL || !control->isVisible() )
         continue;

	  S32 dockingMode = Docking::dockNone;
	  GuiContainer *container = dynamic_cast<GuiContainer*>(control);
	  if( container != NULL )
		  dockingMode = container->getDocking();
     else
        continue;

     // See above note about clientDocking pointer
     if( dockingMode & Docking::dockClient && clientDocking == NULL )
        clientDocking = container;

      // Dock Appropriately
     if( !(dockingMode & Docking::dockClient) )
        dockControl( container, dockingMode, clientRect );
   }

   // Do client dock
   if( clientDocking != NULL )
      dockControl( clientDocking, Docking::dockClient, clientRect );

   return true;
}

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

bool GuiContainer::dockControl( GuiContainer *control, S32 dockingMode, RectI &clientRect )
{
   if( !control )
      return false;

   // Make sure this class support docking of this type
   if( !(dockingMode & getValidDockingMask()))
      return false;

   // If our client rect has run out of room, we can't dock any more
   if( !clientRect.isValidRect() )
      return false;

   // Dock Appropriately
   RectI dockRect;
   RectSpacingI rectShrinker;
   ControlSizing sizingOptions = control->getSizingOptions();
   switch( dockingMode )
   {
   case Docking::dockClient:

      // Inset by padding
      sizingOptions.mPadding.insetRect(clientRect);

      // Dock to entirety of client rectangle
      control->resize( clientRect.point, clientRect.extent );

      // Remove Client Rect, can only have one client dock
      clientRect.set(0,0,0,0);
      break;
   case Docking::dockTop:

      dockRect = clientRect;
      dockRect.extent.y = getMin( control->getHeight() + sizingOptions.mPadding.top + sizingOptions.mPadding.bottom , clientRect.extent.y );

      // Subtract our rect
      clientRect.point.y += dockRect.extent.y;
      clientRect.extent.y -= dockRect.extent.y;

      // Inset by padding
      sizingOptions.mPadding.insetRect(dockRect);

      // Resize
      control->resize( dockRect.point, dockRect.extent );

      break;
   case Docking::dockBottom:

      dockRect = clientRect;
      dockRect.extent.y = getMin( control->getHeight() + sizingOptions.mPadding.top + sizingOptions.mPadding.bottom, clientRect.extent.y );
      dockRect.point.y += clientRect.extent.y - dockRect.extent.y;

      // Subtract our rect
      clientRect.extent.y -= dockRect.extent.y;

      // Inset by padding
      sizingOptions.mPadding.insetRect(dockRect);

      // Resize
      control->resize( dockRect.point, dockRect.extent );

      break;
   case Docking::dockLeft:

      dockRect = clientRect;
      dockRect.extent.x = getMin( control->getWidth() + sizingOptions.mPadding.left + sizingOptions.mPadding.right, clientRect.extent.x );

      // Subtract our rect
      clientRect.point.x += dockRect.extent.x;
      clientRect.extent.x -= dockRect.extent.x;

      // Inset by padding
      sizingOptions.mPadding.insetRect(dockRect);

      // Resize
      control->resize( dockRect.point, dockRect.extent );

      break;
   case Docking::dockRight:

      dockRect = clientRect;
      dockRect.extent.x = getMin( control->getWidth() + sizingOptions.mPadding.left + sizingOptions.mPadding.right, clientRect.extent.x );
      dockRect.point.x += clientRect.extent.x - dockRect.extent.x;

      // Subtract our rect
      clientRect.extent.x -= dockRect.extent.x;

      // Inset by padding
      sizingOptions.mPadding.insetRect(dockRect);

      // Resize
      control->resize( dockRect.point, dockRect.extent );

      break;
   case Docking::dockNone:
      control->setUpdateLayout();
      break;
   }

   return true;
}

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

bool GuiContainer::anchorControl( GuiControl *control, const Point2I &deltaParentExtent )
{
   GuiContainer *container = dynamic_cast<GuiContainer*>( control );
   if( !control || !container )
      return false;

   // If we're docked, we don't anchor to anything
   if( (container->getDocking() & Docking::dockAny) || !(container->getDocking() & Docking::dockInvalid)  )
      return false;

   if( deltaParentExtent.isZero() )
      return false;

   RectI oldRect = control->getBounds();
   RectI newRect = control->getBounds();

   F32 deltaBottom = mSizingOptions.mAnchorBottom ? (F32)deltaParentExtent.y : 0.0f;
   F32 deltaRight = mSizingOptions.mAnchorRight ? (F32)deltaParentExtent.x : 0.0f;
   F32 deltaLeft = mSizingOptions.mAnchorLeft ? 0.0f : (F32)deltaParentExtent.x;
   F32 deltaTop = mSizingOptions.mAnchorTop ? 0.0f : (F32)deltaParentExtent.y;

   // Apply Delta's to newRect
   newRect.point.x += (S32)deltaLeft;
   newRect.extent.x += (S32)(deltaRight - deltaLeft);
   newRect.point.y += (S32)deltaTop;
   newRect.extent.y += (S32)(deltaBottom - deltaTop);

   Point2I minExtent = control->getMinExtent();
   // Only resize if our minExtent is satisfied with it.
   if( !( newRect.extent.x >= control->getMinExtent().x && newRect.extent.y >= control->getMinExtent().y ) )
      return false;

   if( newRect.point == oldRect.point && newRect.extent == oldRect.extent )
      return false;

   // Finally Size the control
   control->resize( newRect.point, newRect.extent );

   // We made changes
   return true;
}

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

void GuiContainer::onPreRender()
{
   if( mUpdateLayout == updateNone )
      return;

   RectI clientRect = getClientRect();
   if( mUpdateLayout & updateSelf )
      layoutControls( clientRect );

   GuiContainer *parent = dynamic_cast<GuiContainer*>( getParent() );
   if( parent && ( mUpdateLayout & updateParent ) )
      parent->setUpdateLayout();

   // Always set AFTER layoutControls call to prevent recursive calling of layoutControls - JDD
   mUpdateLayout = updateNone;

   Parent::onPreRender();
}

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

const RectI GuiContainer::getClientRect()
{
   RectI resRect = RectI( Point2I(0,0), getExtent() );

   // Inset by padding
   mSizingOptions.mInternalPadding.insetRect( resRect );

   return resRect;
}

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

void GuiContainer::setDocking( S32 docking )
{
   mSizingOptions.mDocking = docking;
   setUpdateLayout( updateParent );
}
<|endoftext|>


<commit_before>/*************************************************************************
*    UrBackup - Client/Server backup system
*    Copyright (C) 2011-2016 Martin Raiber
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU Affero General Public License as published by
*    the Free Software Foundation, either version 3 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 Affero General Public License for more details.
*
*    You should have received a copy of the GNU Affero General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/

#include "snapshot_helper.h"
#include "../Interface/Server.h"
#include <stdlib.h>
#include "../stringtools.h"
#include "server.h"
#include "../urbackupcommon/os_functions.h"
#ifdef _WIN32
#define WEXITSTATUS(x) x
#else
#include <sys/types.h>
#include <sys/wait.h>
#endif

std::string SnapshotHelper::helper_name="urbackup_snapshot_helper";

int SnapshotHelper::isAvailable(void)
{
	int rc=system((helper_name+" test").c_str());

	rc = WEXITSTATUS(rc);
	if (rc > 10)
	{
		return rc - 10;
	}

	return -1;
}

bool SnapshotHelper::createEmptyFilesystem(std::string clientname, std::string name)
{
	int rc=system((helper_name + " " + convert(BackupServer::getSnapshotMethod()) + " create \""+(clientname)+"\" \""+(name)+"\"").c_str());
	return rc==0;
}

bool SnapshotHelper::snapshotFileSystem(std::string clientname, std::string old_name, std::string snapshot_name)
{
	int rc=system((helper_name + " " + convert(BackupServer::getSnapshotMethod()) + " snapshot \""+(clientname)+"\" \""+(old_name)+"\" \""+(snapshot_name)+"\"").c_str());
	return rc==0;
}

bool SnapshotHelper::removeFilesystem(std::string clientname, std::string name)
{
	int rc=system((helper_name + " " + convert(BackupServer::getSnapshotMethod()) + " remove \""+(clientname)+"\" \""+(name)+"\"").c_str());
	return rc==0;
}

bool SnapshotHelper::isSubvolume(std::string clientname, std::string name)
{
	int rc=system((helper_name + " "+convert(BackupServer::getSnapshotMethod())+" issubvolume \""+(clientname)+"\" \""+(name)+"\"").c_str());
	return rc==0;
}

void SnapshotHelper::setSnapshotHelperCommand(std::string helper_command)
{
	helper_name=helper_command;
}

bool SnapshotHelper::makeReadonly(std::string clientname, std::string name)
{
	int rc = system((helper_name + " " + convert(BackupServer::getSnapshotMethod()) + " makereadonly \"" + clientname + "\" \"" + name + "\"").c_str());
	return rc == 0;
}

std::string SnapshotHelper::getMountpoint(std::string clientname, std::string name)
{
	std::string ret;
	int rc = os_popen(helper_name + " " + convert(BackupServer::getSnapshotMethod()) + " mountpoint \"" + clientname + "\" \"" + name + "\"",
		ret);

	if (rc != 0)
	{
		return std::string();
	}

	return trim(ret);
}
<commit_msg>Fix btrfs test<commit_after>/*************************************************************************
*    UrBackup - Client/Server backup system
*    Copyright (C) 2011-2016 Martin Raiber
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU Affero General Public License as published by
*    the Free Software Foundation, either version 3 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 Affero General Public License for more details.
*
*    You should have received a copy of the GNU Affero General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/

#include "snapshot_helper.h"
#include "../Interface/Server.h"
#include <stdlib.h>
#include "../stringtools.h"
#include "server.h"
#include "../urbackupcommon/os_functions.h"
#ifdef _WIN32
#define WEXITSTATUS(x) x
#else
#include <sys/types.h>
#include <sys/wait.h>
#endif

std::string SnapshotHelper::helper_name="urbackup_snapshot_helper";

int SnapshotHelper::isAvailable(void)
{
	int rc=system((helper_name+" test").c_str());

	rc = WEXITSTATUS(rc);
	if (rc >= 10)
	{
		return rc - 10;
	}

	return -1;
}

bool SnapshotHelper::createEmptyFilesystem(std::string clientname, std::string name)
{
	int rc=system((helper_name + " " + convert(BackupServer::getSnapshotMethod()) + " create \""+(clientname)+"\" \""+(name)+"\"").c_str());
	return rc==0;
}

bool SnapshotHelper::snapshotFileSystem(std::string clientname, std::string old_name, std::string snapshot_name)
{
	int rc=system((helper_name + " " + convert(BackupServer::getSnapshotMethod()) + " snapshot \""+(clientname)+"\" \""+(old_name)+"\" \""+(snapshot_name)+"\"").c_str());
	return rc==0;
}

bool SnapshotHelper::removeFilesystem(std::string clientname, std::string name)
{
	int rc=system((helper_name + " " + convert(BackupServer::getSnapshotMethod()) + " remove \""+(clientname)+"\" \""+(name)+"\"").c_str());
	return rc==0;
}

bool SnapshotHelper::isSubvolume(std::string clientname, std::string name)
{
	int rc=system((helper_name + " "+convert(BackupServer::getSnapshotMethod())+" issubvolume \""+(clientname)+"\" \""+(name)+"\"").c_str());
	return rc==0;
}

void SnapshotHelper::setSnapshotHelperCommand(std::string helper_command)
{
	helper_name=helper_command;
}

bool SnapshotHelper::makeReadonly(std::string clientname, std::string name)
{
	int rc = system((helper_name + " " + convert(BackupServer::getSnapshotMethod()) + " makereadonly \"" + clientname + "\" \"" + name + "\"").c_str());
	return rc == 0;
}

std::string SnapshotHelper::getMountpoint(std::string clientname, std::string name)
{
	std::string ret;
	int rc = os_popen(helper_name + " " + convert(BackupServer::getSnapshotMethod()) + " mountpoint \"" + clientname + "\" \"" + name + "\"",
		ret);

	if (rc != 0)
	{
		return std::string();
	}

	return trim(ret);
}
<|endoftext|>


<commit_before>//
//  Created by Derek van Vliet on 2015-03-25.
//  Copyright (c) 2015 Get Set Games Inc. All rights reserved.
//

#include "FacebookParsePrivatePCH.h"
#include "CallbackDevice.h"

#if PLATFORM_IOS
NSArray* GetNSStringArray(TArray<FString> FStringArray)
{
	NSMutableArray* NewArray = [NSMutableArray array];

	for (auto Itr(FStringArray.CreateIterator()); Itr; Itr++)
	{
		FString String = (*Itr);
		[NewArray addObject:String.GetNSString()];
	}

	return NewArray;
}
#elif PLATFORM_ANDROID

#include "Android/AndroidJNI.h"
#include "AndroidApplication.h"

#endif

void UFacebookLoginComponent::OnRegister()
{
	Super::OnRegister();

	// init here
	FCoreDelegates::ApplicationOpenURLDelegate.AddUObject(this, &UFacebookLoginComponent::ApplicationOpenURL_Handler);
	UFacebookLoginComponent::FacebookLoginCancelledDelegate.AddUObject(this, &UFacebookLoginComponent::FacebookLoginCancelled_Handler);
	UFacebookLoginComponent::FacebookLoginErrorDelegate.AddUObject(this, &UFacebookLoginComponent::FacebookLoginError_Handler);
	UFacebookLoginComponent::FacebookLoginSucceededDelegate.AddUObject(this, &UFacebookLoginComponent::FacebookLoginSucceeded_Handler);
}

void UFacebookLoginComponent::OnUnregister()
{
	Super::OnUnregister();

	// clean up here

	FCoreDelegates::ApplicationOpenURLDelegate.RemoveAll(this);
	UFacebookLoginComponent::FacebookLoginCancelledDelegate.RemoveAll(this);
	UFacebookLoginComponent::FacebookLoginErrorDelegate.RemoveAll(this);
	UFacebookLoginComponent::FacebookLoginSucceededDelegate.RemoveAll(this);
}

void UFacebookLoginComponent::FacebookLoginWithReadPermissions(TArray<FString> Permissions)
{
#if PLATFORM_IOS
	dispatch_async(dispatch_get_main_queue(), ^{
		FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
		[login logInWithReadPermissions:GetNSStringArray(Permissions) handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
		 {
			if (error)
			{
				UFacebookLoginComponent::FacebookLoginErrorDelegate.Broadcast(FString([error description]));
			}
			else if (result.isCancelled)
			{
				UFacebookLoginComponent::FacebookLoginCancelledDelegate.Broadcast();
			}
			else
			{
				UFacebookLoginComponent::FacebookLoginSucceededDelegate.Broadcast(UFacebookFunctions::FacebookGetUserId(), UFacebookFunctions::FacebookGetAccessToken(), UFacebookFunctions::FacebookGetAccessTokenExpirationDate());
			}
		 }];
	});
#elif PLATFORM_ANDROID
    if (JNIEnv* Env = FAndroidApplication::GetJavaEnv())
    {
        jobjectArray PermissionsArray = (jobjectArray)Env->NewObjectArray(Permissions.Num(), FJavaWrapper::JavaStringClass, NULL);

        for (uint32 Param = 0; Param < Permissions.Num(); Param++)
        {
            jstring p = Env->NewStringUTF(TCHAR_TO_UTF8(*Permissions[Param]));
            Env->SetObjectArrayElement(PermissionsArray, Param, p);
            Env->DeleteLocalRef(p);
        }

        static jmethodID Method = FJavaWrapper::FindMethod(Env,
                                                           FJavaWrapper::GameActivityClassID,
                                                           "AndroidThunk_Java_FacebookLoginWithReadPermissions",
                                                           "([Ljava/lang/String;)V",
                                                           false);
        FJavaWrapper::CallVoidMethod(Env, FJavaWrapper::GameActivityThis, Method, PermissionsArray);
        Env->DeleteLocalRef(PermissionsArray);
    }
#endif
}

void UFacebookLoginComponent::ApplicationOpenURL_Handler(FString URL, FString SourceApplication)
{
#if PLATFORM_IOS
	IOSAppDelegate* appDelegate = (IOSAppDelegate*)[[UIApplication sharedApplication] delegate];

	[[FBSDKApplicationDelegate sharedInstance] application:[UIApplication sharedApplication]
												   openURL:[NSURL URLWithString:URL.GetNSString()]
										 sourceApplication:SourceApplication.GetNSString()
												annotation:appDelegate.launchAnnotation];
#endif
}

UFacebookLoginComponent::FFacebookLoginSucceededDelegate UFacebookLoginComponent::FacebookLoginSucceededDelegate;
UFacebookLoginComponent::FFacebookLoginCancelledDelegate UFacebookLoginComponent::FacebookLoginCancelledDelegate;
UFacebookLoginComponent::FFacebookLoginErrorDelegate UFacebookLoginComponent::FacebookLoginErrorDelegate;
<commit_msg>[change] creates comma separated permissions list from permissions passed in via function argument<commit_after>//
//  Created by Derek van Vliet on 2015-03-25.
//  Copyright (c) 2015 Get Set Games Inc. All rights reserved.
//

#include "FacebookParsePrivatePCH.h"
#include "CallbackDevice.h"

#if PLATFORM_IOS
NSArray* GetNSStringArray(TArray<FString> FStringArray)
{
	NSMutableArray* NewArray = [NSMutableArray array];

	for (auto Itr(FStringArray.CreateIterator()); Itr; Itr++)
	{
		FString String = (*Itr);
		[NewArray addObject:String.GetNSString()];
	}

	return NewArray;
}
#elif PLATFORM_ANDROID

#include "Android/AndroidJNI.h"
#include "AndroidApplication.h"

#endif

void UFacebookLoginComponent::OnRegister()
{
	Super::OnRegister();

	// init here
	FCoreDelegates::ApplicationOpenURLDelegate.AddUObject(this, &UFacebookLoginComponent::ApplicationOpenURL_Handler);
	UFacebookLoginComponent::FacebookLoginCancelledDelegate.AddUObject(this, &UFacebookLoginComponent::FacebookLoginCancelled_Handler);
	UFacebookLoginComponent::FacebookLoginErrorDelegate.AddUObject(this, &UFacebookLoginComponent::FacebookLoginError_Handler);
	UFacebookLoginComponent::FacebookLoginSucceededDelegate.AddUObject(this, &UFacebookLoginComponent::FacebookLoginSucceeded_Handler);
}

void UFacebookLoginComponent::OnUnregister()
{
	Super::OnUnregister();

	// clean up here

	FCoreDelegates::ApplicationOpenURLDelegate.RemoveAll(this);
	UFacebookLoginComponent::FacebookLoginCancelledDelegate.RemoveAll(this);
	UFacebookLoginComponent::FacebookLoginErrorDelegate.RemoveAll(this);
	UFacebookLoginComponent::FacebookLoginSucceededDelegate.RemoveAll(this);
}

void UFacebookLoginComponent::FacebookLoginWithReadPermissions(TArray<FString> Permissions)
{
#if PLATFORM_IOS
	dispatch_async(dispatch_get_main_queue(), ^{
		FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
		[login logInWithReadPermissions:GetNSStringArray(Permissions) handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
		 {
			if (error)
			{
				UFacebookLoginComponent::FacebookLoginErrorDelegate.Broadcast(FString([error description]));
			}
			else if (result.isCancelled)
			{
				UFacebookLoginComponent::FacebookLoginCancelledDelegate.Broadcast();
			}
			else
			{
				UFacebookLoginComponent::FacebookLoginSucceededDelegate.Broadcast(UFacebookFunctions::FacebookGetUserId(), UFacebookFunctions::FacebookGetAccessToken(), UFacebookFunctions::FacebookGetAccessTokenExpirationDate());
			}
		 }];
	});
#elif PLATFORM_ANDROID
    if (JNIEnv* Env = FAndroidApplication::GetJavaEnv())
    {
		FString p;

		const int32 kNumPermissions = Permissions.Num();

		for (int32 i = 0; i < kNumPermissions; i++)
		{
			p += Permissions[i];

			if (i < kNumPermissions - 1)
			{
				p += ",";
			}
		}

		jstring j = Env->NewStringUTF(TCHAR_TO_UTF8(*p));

        static jmethodID Method = FJavaWrapper::FindMethod(Env,
                                                           FJavaWrapper::GameActivityClassID,
                                                           "AndroidThunk_Java_FacebookLoginWithReadPermissions",
                                                           "(Ljava/lang/String;)V",
                                                           false);
        FJavaWrapper::CallVoidMethod(Env, FJavaWrapper::GameActivityThis, Method, j);
		Env->DeleteLocalRef(j);
    }
#endif
}

void UFacebookLoginComponent::ApplicationOpenURL_Handler(FString URL, FString SourceApplication)
{
#if PLATFORM_IOS
	IOSAppDelegate* appDelegate = (IOSAppDelegate*)[[UIApplication sharedApplication] delegate];

	[[FBSDKApplicationDelegate sharedInstance] application:[UIApplication sharedApplication]
												   openURL:[NSURL URLWithString:URL.GetNSString()]
										 sourceApplication:SourceApplication.GetNSString()
												annotation:appDelegate.launchAnnotation];
#endif
}

UFacebookLoginComponent::FFacebookLoginSucceededDelegate UFacebookLoginComponent::FacebookLoginSucceededDelegate;
UFacebookLoginComponent::FFacebookLoginCancelledDelegate UFacebookLoginComponent::FacebookLoginCancelledDelegate;
UFacebookLoginComponent::FFacebookLoginErrorDelegate UFacebookLoginComponent::FacebookLoginErrorDelegate;
<|endoftext|>