<commit_before>/*************************************************************************
 *
 *  $RCSfile: txtnum.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2004-05-10 16:37:26 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#include <hintids.hxx>
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SVX_NUMITEM_HXX //autogen
#include <svx/numitem.hxx>
#endif
#ifndef _SVX_BRSHITEM_HXX //autogen wg. SvxBrushItem
#include <svx/brshitem.hxx>
#endif

#include "cmdid.h"
#include "wrtsh.hxx"
#include "view.hxx"
#include "viewopt.hxx"
#include "wdocsh.hxx"
#include "textsh.hxx"
#include "uiitems.hxx"
//CHINA001 #include "num.hxx"
#include "swabstdlg.hxx" //CHINA001
#include <globals.hrc> //CHINA001
#include <sfx2/tabdlg.hxx> //CHINA001

void SwTextShell::ExecEnterNum(SfxRequest &rReq)
{
    //wg. Aufzeichnung schon vor dem evtl. Shellwechsel
    switch(rReq.GetSlot())
    {
    case FN_NUM_NUMBERING_ON:
    {
        SFX_REQUEST_ARG( rReq, pItem, SfxBoolItem, FN_PARAM_1 , sal_False );
        BOOL bMode = !GetShell().GetCurNumRule();
        if ( pItem )
            bMode = pItem->GetValue();
        else
            rReq.AppendItem( SfxBoolItem( FN_PARAM_1, bMode ) );
        if ( bMode != (GetShell().GetCurNumRule()!=NULL) )
        {
            rReq.Done();
            if( bMode )
                GetShell().NumOn();
            else
                GetShell().DelNumRules();
        }
    }
    break;
    case FN_NUM_BULLET_ON:
    {
        SFX_REQUEST_ARG( rReq, pItem, SfxBoolItem, FN_PARAM_1 , sal_False );
        BOOL bMode = !GetShell().GetCurNumRule();
        if ( pItem )
            bMode = pItem->GetValue();
        else
            rReq.AppendItem( SfxBoolItem( FN_PARAM_1, bMode ) );
        if ( bMode != (GetShell().GetCurNumRule()!=NULL) )
        {
            rReq.Done();
            if( bMode )
                GetShell().BulletOn();
            else
                GetShell().DelNumRules();
        }
    }
    break;
    case FN_NUMBER_BULLETS:
    {
        // per default TRUE, damit die Schleife im Dialog richtig arbeitet!
        BOOL bHasChild = TRUE;
        SfxItemSet aSet(GetPool(),
                SID_HTML_MODE, SID_HTML_MODE,
                SID_ATTR_NUMBERING_RULE, SID_PARAM_CUR_NUM_LEVEL,
                0 );
        SwDocShell* pDocSh = GetView().GetDocShell();
        BOOL bHtml = 0 != PTR_CAST(SwWebDocShell, pDocSh);
        const SwNumRule* pCurRule = GetShell().GetCurNumRule();
        if( pCurRule )
        {
            SvxNumRule aRule = pCurRule->MakeSvxNumRule();

            //convert type of linked bitmaps from SVX_NUM_BITMAP to (SVX_NUM_BITMAP|LINK_TOKEN)
            for(USHORT i = 0; i < aRule.GetLevelCount(); i++)
            {
                SvxNumberFormat aFmt(aRule.GetLevel(i));
                if(SVX_NUM_BITMAP == aFmt.GetNumberingType())
                {
                    const SvxBrushItem* pBrush = aFmt.GetBrush();
                    const String* pLinkStr;
                    if(pBrush &&
                        0 != (pLinkStr = pBrush->GetGraphicLink()) &&
                            pLinkStr->Len())
                        aFmt.SetNumberingType(SvxExtNumType(SVX_NUM_BITMAP|LINK_TOKEN));
                    aRule.SetLevel(i, aFmt, aRule.Get(i) != 0);
                }
            }
            if(bHtml)
                aRule.SetFeatureFlag(NUM_ENABLE_EMBEDDED_BMP, FALSE);

            aSet.Put(SvxNumBulletItem(aRule));
            USHORT nLevel = GetRealLevel(GetShell().GetNumLevel( &bHasChild ));
            if( nLevel < MAXLEVEL )
            {
                nLevel = 1<<nLevel;
                aSet.Put( SfxUInt16Item( SID_PARAM_CUR_NUM_LEVEL, nLevel ));
            }
        }
        else
        {
            SwNumRule aRule( GetShell().GetUniqueNumRuleName() );
            SvxNumRule aSvxRule = aRule.MakeSvxNumRule();
            if(bHtml)
            {
                for( BYTE n = 1; n < MAXLEVEL; ++n )
                {
                    SvxNumberFormat aFmt( aSvxRule.GetLevel( n ) );
                    // 1/2" fuer HTML
                    aFmt.SetLSpace(720);
                    aFmt.SetAbsLSpace(n * 720);
                    aSvxRule.SetLevel( n, aFmt, FALSE );
                }
                aSvxRule.SetFeatureFlag(NUM_ENABLE_EMBEDDED_BMP, FALSE);
            }
            aSet.Put(SvxNumBulletItem(aSvxRule));
        }

        aSet.Put( SfxBoolItem( SID_PARAM_CHILD_LEVELS, bHasChild ));
        aSet.Put( SfxBoolItem( SID_PARAM_NUM_PRESET,FALSE ));

        // vor dem Dialog wird der HtmlMode an der DocShell versenkt
        pDocSh->PutItem(SfxUInt16Item(SID_HTML_MODE, ::GetHtmlMode(pDocSh)));

//CHINA001      SwSvxNumBulletTabDialog* pDlg = new SwSvxNumBulletTabDialog(
//CHINA001      GetView().GetWindow(), &aSet, GetShell() );
        SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
        DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
        SfxAbstractTabDialog* pDlg = pFact->CreateSwTabDialog( ResId(DLG_SVXTEST_NUM_BULLET),
                                                        GetView().GetWindow(), &aSet, GetShell());
        DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
        USHORT nRet = pDlg->Execute();
        const SfxPoolItem* pItem;
        if( RET_OK == nRet )
        {
            if( SFX_ITEM_SET == pDlg->GetOutputItemSet()->GetItemState( SID_ATTR_NUMBERING_RULE, FALSE, &pItem ))
            {
                rReq.AppendItem(*pItem);
                rReq.Done();
                SvxNumRule* pSetRule = ((SvxNumBulletItem*)pItem)->GetNumRule();
                pSetRule->UnLinkGraphics();
                SwNumRule aSetRule( pCurRule
                                        ? pCurRule->GetName()
                                        : GetShell().GetUniqueNumRuleName());
                aSetRule.SetSvxRule( *pSetRule, GetShell().GetDoc());
                aSetRule.SetAutoRule( TRUE );
                GetShell().SetCurNumRule( aSetRule );
            }
            // wenn der Dialog mit OK verlassen wurde, aber nichts ausgewaehlt
            // wurde dann muss die Numerierung zumindest eingeschaltet werden,
            // wenn sie das noch nicht ist
            else if( !pCurRule && SFX_ITEM_SET == aSet.GetItemState( SID_ATTR_NUMBERING_RULE, FALSE, &pItem ))
            {
                rReq.AppendItem( *pItem );
                rReq.Done();
                SvxNumRule* pSetRule = ((SvxNumBulletItem*)pItem)->GetNumRule();
                SwNumRule aSetRule(GetShell().GetUniqueNumRuleName());
                aSetRule.SetSvxRule(*pSetRule, GetShell().GetDoc());
                aSetRule.SetAutoRule( TRUE );
                GetShell().SetCurNumRule( aSetRule );
            }
        }
        else if(RET_USER == nRet)
            GetShell().DelNumRules();

        delete pDlg;
    }
    break;
    default:
        ASSERT(FALSE,  falscher Dispatcher);
        return;
    }
}

<commit_msg>INTEGRATION: CWS hbea1bugs01 (1.7.118); FILE MERGED 2004/05/27 09:24:36 hbrinkm 1.7.118.1: #i29560#<commit_after>/*************************************************************************
 *
 *  $RCSfile: txtnum.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: kz $ $Date: 2004-06-11 15:23:37 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#include <hintids.hxx>
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SVX_NUMITEM_HXX //autogen
#include <svx/numitem.hxx>
#endif
#ifndef _SVX_BRSHITEM_HXX //autogen wg. SvxBrushItem
#include <svx/brshitem.hxx>
#endif

#include "cmdid.h"
#include "wrtsh.hxx"
#include "view.hxx"
#include "viewopt.hxx"
#include "wdocsh.hxx"
#include "textsh.hxx"
#include "uiitems.hxx"
//CHINA001 #include "num.hxx"
#include "swabstdlg.hxx" //CHINA001
#include <globals.hrc> //CHINA001
#include <sfx2/tabdlg.hxx> //CHINA001

void SwTextShell::ExecEnterNum(SfxRequest &rReq)
{
    //wg. Aufzeichnung schon vor dem evtl. Shellwechsel
    switch(rReq.GetSlot())
    {
    case FN_NUM_NUMBERING_ON:
    {
        SFX_REQUEST_ARG( rReq, pItem, SfxBoolItem, FN_PARAM_1 , sal_False );
        BOOL bMode = !GetShell().HasNumber(); // #i29560#
        if ( pItem )
            bMode = pItem->GetValue();
        else
            rReq.AppendItem( SfxBoolItem( FN_PARAM_1, bMode ) );

        if ( bMode != (GetShell().HasNumber()) ) // #i29560#
        {
            rReq.Done();
            if( bMode )
                GetShell().NumOn();
            else
                GetShell().NumOrBulletOff(); // #i29560#
        }
    }
    break;
    case FN_NUM_BULLET_ON:
    {
        SFX_REQUEST_ARG( rReq, pItem, SfxBoolItem, FN_PARAM_1 , sal_False );
        BOOL bMode = !GetShell().HasBullet(); // #i29560#
        if ( pItem )
            bMode = pItem->GetValue();
        else
            rReq.AppendItem( SfxBoolItem( FN_PARAM_1, bMode ) );

        if ( bMode != (GetShell().HasBullet()) ) // #i29560#
        {
            rReq.Done();
            if( bMode )
                GetShell().BulletOn();
            else
                GetShell().NumOrBulletOff(); // #i29560#
        }
    }
    break;
    case FN_NUMBER_BULLETS:
    {
        // per default TRUE, damit die Schleife im Dialog richtig arbeitet!
        BOOL bHasChild = TRUE;
        SfxItemSet aSet(GetPool(),
                SID_HTML_MODE, SID_HTML_MODE,
                SID_ATTR_NUMBERING_RULE, SID_PARAM_CUR_NUM_LEVEL,
                0 );
        SwDocShell* pDocSh = GetView().GetDocShell();
        BOOL bHtml = 0 != PTR_CAST(SwWebDocShell, pDocSh);
        const SwNumRule* pCurRule = GetShell().GetCurNumRule();
        if( pCurRule )
        {
            SvxNumRule aRule = pCurRule->MakeSvxNumRule();

            //convert type of linked bitmaps from SVX_NUM_BITMAP to (SVX_NUM_BITMAP|LINK_TOKEN)
            for(USHORT i = 0; i < aRule.GetLevelCount(); i++)
            {
                SvxNumberFormat aFmt(aRule.GetLevel(i));
                if(SVX_NUM_BITMAP == aFmt.GetNumberingType())
                {
                    const SvxBrushItem* pBrush = aFmt.GetBrush();
                    const String* pLinkStr;
                    if(pBrush &&
                        0 != (pLinkStr = pBrush->GetGraphicLink()) &&
                            pLinkStr->Len())
                        aFmt.SetNumberingType(SvxExtNumType(SVX_NUM_BITMAP|LINK_TOKEN));
                    aRule.SetLevel(i, aFmt, aRule.Get(i) != 0);
                }
            }
            if(bHtml)
                aRule.SetFeatureFlag(NUM_ENABLE_EMBEDDED_BMP, FALSE);

            aSet.Put(SvxNumBulletItem(aRule));
            USHORT nLevel = GetRealLevel(GetShell().GetNumLevel( &bHasChild ));
            if( nLevel < MAXLEVEL )
            {
                nLevel = 1<<nLevel;
                aSet.Put( SfxUInt16Item( SID_PARAM_CUR_NUM_LEVEL, nLevel ));
            }
        }
        else
        {
            SwNumRule aRule( GetShell().GetUniqueNumRuleName() );
            SvxNumRule aSvxRule = aRule.MakeSvxNumRule();
            if(bHtml)
            {
                for( BYTE n = 1; n < MAXLEVEL; ++n )
                {
                    SvxNumberFormat aFmt( aSvxRule.GetLevel( n ) );
                    // 1/2" fuer HTML
                    aFmt.SetLSpace(720);
                    aFmt.SetAbsLSpace(n * 720);
                    aSvxRule.SetLevel( n, aFmt, FALSE );
                }
                aSvxRule.SetFeatureFlag(NUM_ENABLE_EMBEDDED_BMP, FALSE);
            }
            aSet.Put(SvxNumBulletItem(aSvxRule));
        }

        aSet.Put( SfxBoolItem( SID_PARAM_CHILD_LEVELS, bHasChild ));
        aSet.Put( SfxBoolItem( SID_PARAM_NUM_PRESET,FALSE ));

        // vor dem Dialog wird der HtmlMode an der DocShell versenkt
        pDocSh->PutItem(SfxUInt16Item(SID_HTML_MODE, ::GetHtmlMode(pDocSh)));

//CHINA001      SwSvxNumBulletTabDialog* pDlg = new SwSvxNumBulletTabDialog(
//CHINA001      GetView().GetWindow(), &aSet, GetShell() );
        SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
        DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001
        SfxAbstractTabDialog* pDlg = pFact->CreateSwTabDialog( ResId(DLG_SVXTEST_NUM_BULLET),
                                                        GetView().GetWindow(), &aSet, GetShell());
        DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
        USHORT nRet = pDlg->Execute();
        const SfxPoolItem* pItem;
        if( RET_OK == nRet )
        {
            if( SFX_ITEM_SET == pDlg->GetOutputItemSet()->GetItemState( SID_ATTR_NUMBERING_RULE, FALSE, &pItem ))
            {
                rReq.AppendItem(*pItem);
                rReq.Done();
                SvxNumRule* pSetRule = ((SvxNumBulletItem*)pItem)->GetNumRule();
                pSetRule->UnLinkGraphics();
                SwNumRule aSetRule( pCurRule
                                        ? pCurRule->GetName()
                                        : GetShell().GetUniqueNumRuleName());
                aSetRule.SetSvxRule( *pSetRule, GetShell().GetDoc());
                aSetRule.SetAutoRule( TRUE );
                GetShell().SetCurNumRule( aSetRule );
            }
            // wenn der Dialog mit OK verlassen wurde, aber nichts ausgewaehlt
            // wurde dann muss die Numerierung zumindest eingeschaltet werden,
            // wenn sie das noch nicht ist
            else if( !pCurRule && SFX_ITEM_SET == aSet.GetItemState( SID_ATTR_NUMBERING_RULE, FALSE, &pItem ))
            {
                rReq.AppendItem( *pItem );
                rReq.Done();
                SvxNumRule* pSetRule = ((SvxNumBulletItem*)pItem)->GetNumRule();
                SwNumRule aSetRule(GetShell().GetUniqueNumRuleName());
                aSetRule.SetSvxRule(*pSetRule, GetShell().GetDoc());
                aSetRule.SetAutoRule( TRUE );
                GetShell().SetCurNumRule( aSetRule );
            }
        }
        else if(RET_USER == nRet)
            GetShell().DelNumRules();

        delete pDlg;
    }
    break;
    default:
        ASSERT(FALSE,  falscher Dispatcher);
        return;
    }
}

<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif

#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif

#ifndef _MODOPT_HXX //autogen
#include <modcfg.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX //autogen
#include <svx/htmlmode.hxx>
#endif
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx>
#endif
#include "swmodule.hxx"
#include "cmdid.h"
#include "convert.hxx"
#include "tablemgr.hxx"
#include "wrtsh.hxx"
#include "view.hxx"
//CHINA001 #include "tautofmt.hxx"
#include "tblafmt.hxx"

#include "table.hrc"
#include "convert.hrc"
#include "swabstdlg.hxx" //CHINA001

namespace swui
{
    SwAbstractDialogFactory * GetFactory();
}

//keep the state of the buttons on runtime
static int nSaveButtonState = -1; // 0: tab, 1: semicolon, 2: paragraph, 3: other, -1: not yet used
static sal_Bool bIsKeepColumn = sal_True;
static sal_Unicode uOther = ',';

void SwConvertTableDlg::GetValues(  sal_Unicode& rDelim,
                                    SwInsertTableOptions& rInsTblOpts,
                                    SwTableAutoFmt *& prTAFmt )
{
    if( aTabBtn.IsChecked() )
    {
        //0x0b mustn't be set when re-converting table into text
        bIsKeepColumn = !aKeepColumn.IsVisible() || aKeepColumn.IsChecked();
        rDelim = bIsKeepColumn ? 0x09 : 0x0b;
        nSaveButtonState = 0;
    }
    else if( aSemiBtn.IsChecked() )
    {
        rDelim = ';';
        nSaveButtonState = 1;
    }
    else if( aOtherBtn.IsChecked() && aOtherEd.GetText().Len() )
    {
        uOther = aOtherEd.GetText().GetChar( 0 );
        rDelim = uOther;
        nSaveButtonState = 3;
    }
    else
    {
        nSaveButtonState = 2;
        rDelim = cParaDelim;
        if(aOtherBtn.IsChecked())
        {
            nSaveButtonState = 3;
            uOther = 0;
        }
    }

    USHORT nInsMode = 0;
    if (aBorderCB.IsChecked())
        nInsMode |= tabopts::DEFAULT_BORDER;
    if (aHeaderCB.IsChecked())
        nInsMode |= tabopts::HEADLINE;
    if (aRepeatHeaderCB.IsEnabled() && aRepeatHeaderCB.IsChecked())
        rInsTblOpts.mnRowsToRepeat = USHORT( aRepeatHeaderNF.GetValue() );
    else
        rInsTblOpts.mnRowsToRepeat = 0;
    if (!aDontSplitCB.IsChecked())
        nInsMode |= tabopts::SPLIT_LAYOUT;

    if( pTAutoFmt )
        prTAFmt = new SwTableAutoFmt( *pTAutoFmt );

    rInsTblOpts.mnInsMode = nInsMode;
}

SwConvertTableDlg::SwConvertTableDlg( SwView& rView, bool bToTable )

    : SfxModalDialog( &rView.GetViewFrame()->GetWindow(), SW_RES(DLG_CONV_TEXT_TABLE)),

#ifdef _MSC_VER
#pragma warning (disable : 4355)
#endif
    aTabBtn         (this, SW_RES(CB_TAB)),
    aSemiBtn        (this, SW_RES(CB_SEMI)),
    aParaBtn        (this, SW_RES(CB_PARA)),
    aDelimFL       (this, SW_RES(FL_DELIM)),
    aOtherBtn       (this, SW_RES(RB_OTHER)),
    aOtherEd        (this, SW_RES(ED_OTHER)),
    aKeepColumn     (this, SW_RES(CB_KEEPCOLUMN)),
    aHeaderCB       (this, SW_RES(CB_HEADER)),
    aRepeatHeaderCB (this, SW_RES(CB_REPEAT_HEADER)),
    aRepeatHeaderFT         (this, SW_RES(FT_REPEAT_HEADER)),
    aRepeatHeaderBeforeFT   (this),
    aRepeatHeaderNF         (this, SW_RES(NF_REPEAT_HEADER)),
    aRepeatHeaderAfterFT    (this),
    aRepeatHeaderCombo      (this, SW_RES(WIN_REPEAT_HEADER), aRepeatHeaderNF, aRepeatHeaderBeforeFT, aRepeatHeaderAfterFT),

    aDontSplitCB    (this, SW_RES(CB_DONT_SPLIT)),
    aBorderCB       (this, SW_RES(CB_BORDER)),
    aOptionsFL      (this, SW_RES(FL_OPTIONS)),

    aOkBtn(this,SW_RES(BT_OK)),
    aCancelBtn(this,SW_RES(BT_CANCEL)),
    aHelpBtn(this, SW_RES(BT_HELP)),
    aAutoFmtBtn(this,SW_RES(BT_AUTOFORMAT)),
#ifdef _MSC_VER
#pragma warning (default : 4355)
#endif

    pTAutoFmt( 0 ),
    pShell( &rView.GetWrtShell() ),
    sConvertTextTable(SW_RES(STR_CONVERT_TEXT_TABLE))
{
    FreeResource();
    if(nSaveButtonState > -1)
    {
        switch (nSaveButtonState)
        {
            case 0:
                aTabBtn.Check();
                aKeepColumn.Check(bIsKeepColumn);
            break;
            case 1: aSemiBtn.Check();break;
            case 2: aParaBtn.Check();break;
            case 3:
                aOtherBtn.Check();
                if(uOther)
                    aOtherEd.SetText(uOther);
            break;
        }

    }
    if( bToTable )
    {
        SetText( sConvertTextTable );
        aAutoFmtBtn.SetClickHdl(LINK(this, SwConvertTableDlg, AutoFmtHdl));
        aAutoFmtBtn.Show();
        aKeepColumn.Show();
        aKeepColumn.Enable( aTabBtn.IsChecked() );
        aRepeatHeaderCombo.Arrange( aRepeatHeaderFT );
    }
    else
    {
        //Einfuege-Optionen verstecken
        aHeaderCB          .Show(FALSE);
        aRepeatHeaderCB    .Show(FALSE);
        aDontSplitCB       .Show(FALSE);
        aBorderCB          .Show(FALSE);
        aOptionsFL         .Show(FALSE);
        aRepeatHeaderCombo.Show(FALSE);

        //Groesse anpassen
        Size aSize(GetSizePixel());
        aSize.Height() = 8 + aHelpBtn.GetSizePixel().Height() + aHelpBtn.GetPosPixel().Y();
        SetOutputSizePixel(aSize);
    }
    aKeepColumn.SaveValue();

    Link aLk( LINK(this, SwConvertTableDlg, BtnHdl) );
    aTabBtn.SetClickHdl( aLk );
    aSemiBtn.SetClickHdl( aLk );
    aParaBtn.SetClickHdl( aLk );
    aOtherBtn.SetClickHdl(aLk );
    aOtherEd.Enable( aOtherBtn.IsChecked() );

    const SwModuleOptions* pModOpt = SW_MOD()->GetModuleConfig();

    BOOL bHTMLMode = 0 != (::GetHtmlMode(rView.GetDocShell())&HTMLMODE_ON);

    SwInsertTableOptions aInsOpts = pModOpt->GetInsTblFlags(bHTMLMode);
    USHORT nInsTblFlags = aInsOpts.mnInsMode;

    aHeaderCB.Check(nInsTblFlags & tabopts::HEADLINE);
    aRepeatHeaderCB.Check(aInsOpts.mnRowsToRepeat > 0);
    aDontSplitCB.Check(!(nInsTblFlags & tabopts::SPLIT_LAYOUT));
    aBorderCB.Check(nInsTblFlags & tabopts::DEFAULT_BORDER);

    aHeaderCB.SetClickHdl(LINK(this, SwConvertTableDlg, CheckBoxHdl));
    aRepeatHeaderCB.SetClickHdl(LINK(this, SwConvertTableDlg, ReapeatHeaderCheckBoxHdl));
    ReapeatHeaderCheckBoxHdl();
    CheckBoxHdl();
}

SwConvertTableDlg:: ~SwConvertTableDlg()
{
    delete pTAutoFmt;
}

IMPL_LINK( SwConvertTableDlg, AutoFmtHdl, PushButton*, pButton )
{
    //CHINA001 SwAutoFormatDlg aDlg( pButton, pShell, FALSE, pTAutoFmt );
    SwAbstractDialogFactory* pFact = swui::GetFactory();//CHINA001
    DBG_ASSERT(pFact, "SwAbstractDialogFactory fail!");//CHINA001

    AbstractSwAutoFormatDlg* pDlg = pFact->CreateSwAutoFormatDlg(pButton, pShell, DLG_AUTOFMT_TABLE, FALSE, pTAutoFmt);
    DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
    if( RET_OK == pDlg->Execute()) //CHINA001  if( RET_OK == aDlg.Execute())
        pDlg->FillAutoFmtOfIndex( pTAutoFmt ); //CHINA001  aDlg.FillAutoFmtOfIndex( pTAutoFmt );
    delete pDlg; //CHINA001
    return 0;
}

IMPL_LINK( SwConvertTableDlg, BtnHdl, Button*, pButton )
{
    if( pButton == &aTabBtn )
        aKeepColumn.SetState( aKeepColumn.GetSavedValue() );
    else
    {
        if( aKeepColumn.IsEnabled() )
            aKeepColumn.SaveValue();
        aKeepColumn.Check( TRUE );
    }
    aKeepColumn.Enable( aTabBtn.IsChecked() );
    aOtherEd.Enable( aOtherBtn.IsChecked() );
    return 0;
}

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

IMPL_LINK(SwConvertTableDlg, CheckBoxHdl, CheckBox*, EMPTYARG)
{
    aRepeatHeaderCB.Enable(aHeaderCB.IsChecked());
    ReapeatHeaderCheckBoxHdl();

    return 0;
}

IMPL_LINK(SwConvertTableDlg, ReapeatHeaderCheckBoxHdl, void*, EMPTYARG)
{
    sal_Bool bEnable = aHeaderCB.IsChecked() && aRepeatHeaderCB.IsChecked();
    aRepeatHeaderBeforeFT.Enable(bEnable);
    aRepeatHeaderAfterFT.Enable(bEnable);
    aRepeatHeaderNF.Enable(bEnable);

    return 0;
}
<commit_msg>INTEGRATION: CWS swwarnings (1.12.222); FILE MERGED 2007/05/29 14:14:21 os 1.12.222.4: RESYNC: (1.12-1.13); FILE MERGED 2007/04/13 12:18:16 tl 1.12.222.3: #i69287# binfilter related comments removed 2007/04/11 07:03:36 tl 1.12.222.2: #i69287# warning-free code 2007/02/28 12:22:19 os 1.12.222.1: #i69287# warnings removed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: convert.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 12:32: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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif

#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif

#ifndef _MODOPT_HXX //autogen
#include <modcfg.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX //autogen
#include <svx/htmlmode.hxx>
#endif
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx>
#endif
#include "swmodule.hxx"
#include "cmdid.h"
#include "convert.hxx"
#include "tablemgr.hxx"
#include "wrtsh.hxx"
#include "view.hxx"
#include "tblafmt.hxx"

#include "table.hrc"
#include "convert.hrc"
#include "swabstdlg.hxx"

namespace swui
{
    SwAbstractDialogFactory * GetFactory();
}

//keep the state of the buttons on runtime
static int nSaveButtonState = -1; // 0: tab, 1: semicolon, 2: paragraph, 3: other, -1: not yet used
static sal_Bool bIsKeepColumn = sal_True;
static sal_Unicode uOther = ',';

void SwConvertTableDlg::GetValues(  sal_Unicode& rDelim,
                                    SwInsertTableOptions& rInsTblOpts,
                                    SwTableAutoFmt *& prTAFmt )
{
    if( aTabBtn.IsChecked() )
    {
        //0x0b mustn't be set when re-converting table into text
        bIsKeepColumn = !aKeepColumn.IsVisible() || aKeepColumn.IsChecked();
        rDelim = bIsKeepColumn ? 0x09 : 0x0b;
        nSaveButtonState = 0;
    }
    else if( aSemiBtn.IsChecked() )
    {
        rDelim = ';';
        nSaveButtonState = 1;
    }
    else if( aOtherBtn.IsChecked() && aOtherEd.GetText().Len() )
    {
        uOther = aOtherEd.GetText().GetChar( 0 );
        rDelim = uOther;
        nSaveButtonState = 3;
    }
    else
    {
        nSaveButtonState = 2;
        rDelim = cParaDelim;
        if(aOtherBtn.IsChecked())
        {
            nSaveButtonState = 3;
            uOther = 0;
        }
    }

    USHORT nInsMode = 0;
    if (aBorderCB.IsChecked())
        nInsMode |= tabopts::DEFAULT_BORDER;
    if (aHeaderCB.IsChecked())
        nInsMode |= tabopts::HEADLINE;
    if (aRepeatHeaderCB.IsEnabled() && aRepeatHeaderCB.IsChecked())
        rInsTblOpts.mnRowsToRepeat = USHORT( aRepeatHeaderNF.GetValue() );
    else
        rInsTblOpts.mnRowsToRepeat = 0;
    if (!aDontSplitCB.IsChecked())
        nInsMode |= tabopts::SPLIT_LAYOUT;

    if( pTAutoFmt )
        prTAFmt = new SwTableAutoFmt( *pTAutoFmt );

    rInsTblOpts.mnInsMode = nInsMode;
}

SwConvertTableDlg::SwConvertTableDlg( SwView& rView, bool bToTable )

    : SfxModalDialog( &rView.GetViewFrame()->GetWindow(), SW_RES(DLG_CONV_TEXT_TABLE)),
#ifdef MSC
#pragma warning (disable : 4355)
#endif
    aTabBtn         (this, SW_RES(CB_TAB)),
    aSemiBtn        (this, SW_RES(CB_SEMI)),
    aParaBtn        (this, SW_RES(CB_PARA)),
    aOtherBtn       (this, SW_RES(RB_OTHER)),
    aOtherEd        (this, SW_RES(ED_OTHER)),
    aKeepColumn     (this, SW_RES(CB_KEEPCOLUMN)),
    aDelimFL       (this, SW_RES(FL_DELIM)),

    aHeaderCB       (this, SW_RES(CB_HEADER)),
    aRepeatHeaderCB (this, SW_RES(CB_REPEAT_HEADER)),

    aRepeatHeaderFT         (this, SW_RES(FT_REPEAT_HEADER)),
    aRepeatHeaderBeforeFT   (this),
    aRepeatHeaderNF         (this, SW_RES(NF_REPEAT_HEADER)),
    aRepeatHeaderAfterFT    (this),
    aRepeatHeaderCombo      (this, SW_RES(WIN_REPEAT_HEADER), aRepeatHeaderNF, aRepeatHeaderBeforeFT, aRepeatHeaderAfterFT),

    aDontSplitCB    (this, SW_RES(CB_DONT_SPLIT)),
    aBorderCB       (this, SW_RES(CB_BORDER)),
    aOptionsFL      (this, SW_RES(FL_OPTIONS)),

    aOkBtn(this,SW_RES(BT_OK)),
    aCancelBtn(this,SW_RES(BT_CANCEL)),
    aHelpBtn(this, SW_RES(BT_HELP)),
    aAutoFmtBtn(this,SW_RES(BT_AUTOFORMAT)),
#ifdef MSC
#pragma warning (default : 4355)
#endif
    sConvertTextTable(SW_RES(STR_CONVERT_TEXT_TABLE)),
    pTAutoFmt( 0 ),
    pShell( &rView.GetWrtShell() )
{
    FreeResource();
    if(nSaveButtonState > -1)
    {
        switch (nSaveButtonState)
        {
            case 0:
                aTabBtn.Check();
                aKeepColumn.Check(bIsKeepColumn);
            break;
            case 1: aSemiBtn.Check();break;
            case 2: aParaBtn.Check();break;
            case 3:
                aOtherBtn.Check();
                if(uOther)
                    aOtherEd.SetText(uOther);
            break;
        }

    }
    if( bToTable )
    {
        SetText( sConvertTextTable );
        aAutoFmtBtn.SetClickHdl(LINK(this, SwConvertTableDlg, AutoFmtHdl));
        aAutoFmtBtn.Show();
        aKeepColumn.Show();
        aKeepColumn.Enable( aTabBtn.IsChecked() );
        aRepeatHeaderCombo.Arrange( aRepeatHeaderFT );
    }
    else
    {
        //Einfuege-Optionen verstecken
        aHeaderCB          .Show(FALSE);
        aRepeatHeaderCB    .Show(FALSE);
        aDontSplitCB       .Show(FALSE);
        aBorderCB          .Show(FALSE);
        aOptionsFL         .Show(FALSE);
        aRepeatHeaderCombo.Show(FALSE);

        //Groesse anpassen
        Size aSize(GetSizePixel());
        aSize.Height() = 8 + aHelpBtn.GetSizePixel().Height() + aHelpBtn.GetPosPixel().Y();
        SetOutputSizePixel(aSize);
    }
    aKeepColumn.SaveValue();

    Link aLk( LINK(this, SwConvertTableDlg, BtnHdl) );
    aTabBtn.SetClickHdl( aLk );
    aSemiBtn.SetClickHdl( aLk );
    aParaBtn.SetClickHdl( aLk );
    aOtherBtn.SetClickHdl(aLk );
    aOtherEd.Enable( aOtherBtn.IsChecked() );

    const SwModuleOptions* pModOpt = SW_MOD()->GetModuleConfig();

    BOOL bHTMLMode = 0 != (::GetHtmlMode(rView.GetDocShell())&HTMLMODE_ON);

    SwInsertTableOptions aInsOpts = pModOpt->GetInsTblFlags(bHTMLMode);
    USHORT nInsTblFlags = aInsOpts.mnInsMode;

    aHeaderCB.Check( 0 != (nInsTblFlags & tabopts::HEADLINE) );
    aRepeatHeaderCB.Check(aInsOpts.mnRowsToRepeat > 0);
    aDontSplitCB.Check( 0 == (nInsTblFlags & tabopts::SPLIT_LAYOUT));
    aBorderCB.Check( 0!= (nInsTblFlags & tabopts::DEFAULT_BORDER) );

    aHeaderCB.SetClickHdl(LINK(this, SwConvertTableDlg, CheckBoxHdl));
    aRepeatHeaderCB.SetClickHdl(LINK(this, SwConvertTableDlg, ReapeatHeaderCheckBoxHdl));
    ReapeatHeaderCheckBoxHdl();
    CheckBoxHdl();
}

SwConvertTableDlg:: ~SwConvertTableDlg()
{
    delete pTAutoFmt;
}

IMPL_LINK( SwConvertTableDlg, AutoFmtHdl, PushButton*, pButton )
{
    SwAbstractDialogFactory* pFact = swui::GetFactory();
    DBG_ASSERT(pFact, "SwAbstractDialogFactory fail!");

    AbstractSwAutoFormatDlg* pDlg = pFact->CreateSwAutoFormatDlg(pButton, pShell, DLG_AUTOFMT_TABLE, FALSE, pTAutoFmt);
    DBG_ASSERT(pDlg, "Dialogdiet fail!");
    if( RET_OK == pDlg->Execute())
        pDlg->FillAutoFmtOfIndex( pTAutoFmt );
    delete pDlg;
    return 0;
}

IMPL_LINK( SwConvertTableDlg, BtnHdl, Button*, pButton )
{
    if( pButton == &aTabBtn )
        aKeepColumn.SetState( aKeepColumn.GetSavedValue() );
    else
    {
        if( aKeepColumn.IsEnabled() )
            aKeepColumn.SaveValue();
        aKeepColumn.Check( TRUE );
    }
    aKeepColumn.Enable( aTabBtn.IsChecked() );
    aOtherEd.Enable( aOtherBtn.IsChecked() );
    return 0;
}

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

IMPL_LINK(SwConvertTableDlg, CheckBoxHdl, CheckBox*, EMPTYARG)
{
    aRepeatHeaderCB.Enable(aHeaderCB.IsChecked());
    ReapeatHeaderCheckBoxHdl();

    return 0;
}

IMPL_LINK(SwConvertTableDlg, ReapeatHeaderCheckBoxHdl, void*, EMPTYARG)
{
    sal_Bool bEnable = aHeaderCB.IsChecked() && aRepeatHeaderCB.IsChecked();
    aRepeatHeaderBeforeFT.Enable(bEnable);
    aRepeatHeaderAfterFT.Enable(bEnable);
    aRepeatHeaderNF.Enable(bEnable);

    return 0;
}
<|endoftext|>


<commit_before>//
// Transformations for begin, cobegin, and on statements
//

#include "astutil.h"
#include "expr.h"
#include "passes.h"
#include "runtime.h"
#include "stmt.h"
#include "symbol.h"
#include "stringutil.h"
#include "driver.h"
#include "files.h"

// Package args into a class and call a wrapper function with that
// object. The wrapper function will then call the function
// created by the previous parallel pass. This is a way to pass along
// multiple args through the limitation of one arg in the runtime's
// thread creation interface.
static void
bundleArgs(BlockStmt* block) {
  currentLineno = block->lineno;
  currentFilename = block->filename;
  ModuleSymbol* mod = block->getModule();
  BlockStmt *newb = new BlockStmt();
  newb->blockTag = block->blockTag;
  for_alist(expr, block->body) {
    CallExpr* fcall = toCallExpr(expr);
    if (!fcall || !fcall->isResolved()) {
      block->insertBefore(expr->remove());
      continue;
    } else {
      FnSymbol* fn = fcall->isResolved();

      // create a new class to capture refs to locals
      ClassType* ctype = new ClassType( CLASS_CLASS);
      TypeSymbol* new_c = new TypeSymbol( astr("_class_locals",
                                               fn->name),
                                          ctype);
      new_c->addPragma("no wide class");

      // add the function args as fields in the class
      int i = 1;
      bool first = true;
      for_actuals(arg, fcall) {
        if (block->blockTag == BLOCK_ON && first) {
          first = false;
          continue;
        }
        SymExpr *s = toSymExpr(arg);
        Symbol  *var = s->var; // arg or var
        var->isConcurrent = true;
        VarSymbol* field = new VarSymbol(astr("_", istr(i), "_", var->name), var->type);
        ctype->fields.insertAtTail(new DefExpr(field));
        i++;
      }
      mod->block->insertAtHead(new DefExpr(new_c));

      // create the class variable instance and allocate it
      VarSymbol *tempc = new VarSymbol( astr( "_args_for",
                                              fn->name),
                                        ctype);
      block->insertBefore( new DefExpr( tempc));
      CallExpr *tempc_alloc = new CallExpr( PRIMITIVE_CHPL_ALLOC,
                                            ctype->symbol,
                                            new_StringSymbol( astr( "instance of class ", ctype->symbol->name)));
      block->insertBefore( new CallExpr( PRIMITIVE_MOVE,
                                     tempc,
                                     tempc_alloc));

      // set the references in the class instance
      i = 1;
      first = true;
      for_actuals(arg, fcall) {
        if (block->blockTag == BLOCK_ON && first) {
          first = false;
          continue;
        }
        SymExpr *s = toSymExpr(arg);
        Symbol  *var = s->var; // var or arg
        CallExpr *setc=new CallExpr(PRIMITIVE_SET_MEMBER,
                                    tempc,
                                    ctype->getField(i),
                                    var);
        block->insertBefore( setc);
        i++;
      }

      // create wrapper-function that uses the class instance

      FnSymbol *wrap_fn = new FnSymbol( astr("wrap", fn->name));
      DefExpr  *fcall_def= (toSymExpr( fcall->baseExpr))->var->defPoint;
      if (block->blockTag == BLOCK_ON) {
        wrap_fn->addPragma("on block");
        ArgSymbol* locale = new ArgSymbol(INTENT_BLANK, "_dummy_locale_arg", dtInt[INT_SIZE_32]);
        wrap_fn->insertFormalAtTail(locale);
      }
      ArgSymbol *wrap_c = new ArgSymbol( INTENT_BLANK, "c", ctype);
      wrap_fn->insertFormalAtTail( wrap_c);

      mod->block->insertAtTail(new DefExpr(wrap_fn));
      if (block->blockTag == BLOCK_ON) {
        newb->insertAtTail(new CallExpr(wrap_fn, fcall->get(1)->remove(), tempc));
      } else
        newb->insertAtTail(new CallExpr(wrap_fn, tempc));

      if (block->blockTag == BLOCK_BEGIN || block->blockTag == BLOCK_COBEGIN)
        wrap_fn->insertAtHead(new CallExpr(PRIMITIVE_THREAD_INIT));

      // translate the original cobegin function
      CallExpr *new_cofn = new CallExpr( (toSymExpr(fcall->baseExpr))->var);
      if (block->blockTag == BLOCK_ON)
        new_cofn->insertAtTail(new_IntSymbol(0)); // bogus actual
      for_fields(field, ctype) {  // insert args

        VarSymbol* tmp = new VarSymbol("_tmp", field->type);
        tmp->isCompilerTemp = true;
        wrap_fn->insertAtTail(new DefExpr(tmp));
        wrap_fn->insertAtTail(
          new CallExpr(PRIMITIVE_MOVE, tmp,
            new CallExpr(PRIMITIVE_GET_MEMBER_VALUE, wrap_c, field)));
        new_cofn->insertAtTail(tmp);
      }

      wrap_fn->retType = dtVoid;
      fcall->remove();                     // rm orig. call
      wrap_fn->insertAtTail(new_cofn);     // add new call
      if (block->blockTag == BLOCK_ON)
        block->insertAfter(new CallExpr(PRIMITIVE_CHPL_FREE, tempc));
      else
        wrap_fn->insertAtTail(new CallExpr(PRIMITIVE_CHPL_FREE, wrap_c));

      fcall_def->remove();                 // move orig. def
      mod->block->insertAtTail(fcall_def); // to top-level
      normalize(wrap_fn);
    }
  }
  block->replace(newb);
}

void
parallel(void) {
  compute_sym_uses();

  Vec<BlockStmt*> blocks;
  forv_Vec(BaseAST, ast, gAsts) {
    if (BlockStmt* block = toBlockStmt(ast))
      blocks.add(block);
  }

  forv_Vec(BlockStmt, block, blocks) {
    if (block->blockTag == BLOCK_ON ||
        block->blockTag == BLOCK_BEGIN ||
        block->blockTag == BLOCK_COBEGIN)
      bundleArgs(block);
  }
}

static void
buildWideClass(Type* type) {
  ClassType* wide = new ClassType(CLASS_RECORD);
  TypeSymbol* wts = new TypeSymbol(astr("_wide_", type->symbol->cname), wide);
  wts->addPragma("wide class");
  theProgram->block->insertAtTail(new DefExpr(wts));
  wide->fields.insertAtTail(new DefExpr(new VarSymbol("locale", dtInt[INT_SIZE_32])));
  wide->fields.insertAtTail(new DefExpr(new VarSymbol("addr", type)));
  wideClassMap.put(type, wide);

  //
  // build reference type for wide class type
  //
  ClassType* ref = new ClassType(CLASS_CLASS);
  TypeSymbol* rts = new TypeSymbol(astr("_ref_wide_", type->symbol->cname), ref);
  rts->addPragma("ref");
  theProgram->block->insertAtTail(new DefExpr(rts));
  ref->fields.insertAtTail(new DefExpr(new VarSymbol("_val", type)));
  wide->refType = ref;
}

//
// change all classes into wide classes
// change all references into wide references
//
void
insertWideReferences(void) {
  if (fLocal)
    return;

  wideClassMap.clear();

  //
  // build wide class type for every class type
  //
  forv_Vec(TypeSymbol, ts, gTypes) {
    ClassType* ct = toClassType(ts->type);
    if (ct && ct->classTag == CLASS_CLASS && !ts->hasPragma("ref") && !ts->hasPragma("no wide class")) {

      //
      // do not yet support remote sync and single variables
      //
      if (ts->hasPragma("sync") || ts->hasPragma("single"))
        continue;

      buildWideClass(ct);
    }
  }
  buildWideClass(dtObject);

  //
  // change all classes into wide classes
  //
  forv_Vec(BaseAST, ast, gAsts) {
    if (DefExpr* def = toDefExpr(ast)) {

      //
      // do not change class field in wide class type
      //
      if (TypeSymbol* ts = toTypeSymbol(def->parentSymbol))
        if (ts->hasPragma("wide class"))
          continue;

      if (FnSymbol* fn = toFnSymbol(def->sym)) {
        if (Type* wide = wideClassMap.get(fn->retType))
          fn->retType = wide;
      } else if (!isTypeSymbol(def->sym)) {
        if (Type* wide = wideClassMap.get(def->sym->type))
          def->sym->type = wide;
      }
    }
  }

  //
  // change arrays of classes into arrays of wide classes
  //
  forv_Vec(TypeSymbol, ts, gTypes) {
    if (ts->hasPragma("data class")) {
      if (Type* nt = wideClassMap.get(toType(ts->type->substitutions.v[0].value))) {
        ts->type->substitutions.v[0].value = nt;
      }
    }
  }

  wideRefMap.clear();

  //
  // build wide reference type for every reference type
  //
  forv_Vec(TypeSymbol, ts, gTypes) {
    if (ts->hasPragma("ref")) {
      ClassType* wide = new ClassType(CLASS_RECORD);
      TypeSymbol* wts = new TypeSymbol(astr("_wide_", ts->cname), wide);
      wts->addPragma("wide");
      theProgram->block->insertAtTail(new DefExpr(wts));
      wide->fields.insertAtTail(new DefExpr(new VarSymbol("locale", dtInt[INT_SIZE_32])));
      wide->fields.insertAtTail(new DefExpr(new VarSymbol("addr", ts->type)));
      wideRefMap.put(ts->type, wide);
    }
  }

  //
  // change all references into wide references
  //
  forv_Vec(BaseAST, ast, gAsts) {
    if (DefExpr* def = toDefExpr(ast)) {

      //
      // do not change reference field in wide reference type
      //
      if (TypeSymbol* ts = toTypeSymbol(def->parentSymbol))
        if (ts->hasPragma("wide"))
          continue;

      if (FnSymbol* fn = toFnSymbol(def->sym)) {
        if (Type* wide = wideRefMap.get(fn->retType))
          fn->retType = wide;
      } else if (!isTypeSymbol(def->sym)) {
        if (Type* wide = wideRefMap.get(def->sym->type))
          def->sym->type = wide;
      }
    }
  }
}
<commit_msg>Added code at the beginning of insertWideReferences to convert all uses of type dtNil into uses of type dtObject before insert wide references.<commit_after>//
// Transformations for begin, cobegin, and on statements
//

#include "astutil.h"
#include "expr.h"
#include "passes.h"
#include "runtime.h"
#include "stmt.h"
#include "symbol.h"
#include "stringutil.h"
#include "driver.h"
#include "files.h"

// Package args into a class and call a wrapper function with that
// object. The wrapper function will then call the function
// created by the previous parallel pass. This is a way to pass along
// multiple args through the limitation of one arg in the runtime's
// thread creation interface.
static void
bundleArgs(BlockStmt* block) {
  currentLineno = block->lineno;
  currentFilename = block->filename;
  ModuleSymbol* mod = block->getModule();
  BlockStmt *newb = new BlockStmt();
  newb->blockTag = block->blockTag;
  for_alist(expr, block->body) {
    CallExpr* fcall = toCallExpr(expr);
    if (!fcall || !fcall->isResolved()) {
      block->insertBefore(expr->remove());
      continue;
    } else {
      FnSymbol* fn = fcall->isResolved();

      // create a new class to capture refs to locals
      ClassType* ctype = new ClassType( CLASS_CLASS);
      TypeSymbol* new_c = new TypeSymbol( astr("_class_locals",
                                               fn->name),
                                          ctype);
      new_c->addPragma("no wide class");

      // add the function args as fields in the class
      int i = 1;
      bool first = true;
      for_actuals(arg, fcall) {
        if (block->blockTag == BLOCK_ON && first) {
          first = false;
          continue;
        }
        SymExpr *s = toSymExpr(arg);
        Symbol  *var = s->var; // arg or var
        var->isConcurrent = true;
        VarSymbol* field = new VarSymbol(astr("_", istr(i), "_", var->name), var->type);
        ctype->fields.insertAtTail(new DefExpr(field));
        i++;
      }
      mod->block->insertAtHead(new DefExpr(new_c));

      // create the class variable instance and allocate it
      VarSymbol *tempc = new VarSymbol( astr( "_args_for",
                                              fn->name),
                                        ctype);
      block->insertBefore( new DefExpr( tempc));
      CallExpr *tempc_alloc = new CallExpr( PRIMITIVE_CHPL_ALLOC,
                                            ctype->symbol,
                                            new_StringSymbol( astr( "instance of class ", ctype->symbol->name)));
      block->insertBefore( new CallExpr( PRIMITIVE_MOVE,
                                     tempc,
                                     tempc_alloc));

      // set the references in the class instance
      i = 1;
      first = true;
      for_actuals(arg, fcall) {
        if (block->blockTag == BLOCK_ON && first) {
          first = false;
          continue;
        }
        SymExpr *s = toSymExpr(arg);
        Symbol  *var = s->var; // var or arg
        CallExpr *setc=new CallExpr(PRIMITIVE_SET_MEMBER,
                                    tempc,
                                    ctype->getField(i),
                                    var);
        block->insertBefore( setc);
        i++;
      }

      // create wrapper-function that uses the class instance

      FnSymbol *wrap_fn = new FnSymbol( astr("wrap", fn->name));
      DefExpr  *fcall_def= (toSymExpr( fcall->baseExpr))->var->defPoint;
      if (block->blockTag == BLOCK_ON) {
        wrap_fn->addPragma("on block");
        ArgSymbol* locale = new ArgSymbol(INTENT_BLANK, "_dummy_locale_arg", dtInt[INT_SIZE_32]);
        wrap_fn->insertFormalAtTail(locale);
      }
      ArgSymbol *wrap_c = new ArgSymbol( INTENT_BLANK, "c", ctype);
      wrap_fn->insertFormalAtTail( wrap_c);

      mod->block->insertAtTail(new DefExpr(wrap_fn));
      if (block->blockTag == BLOCK_ON) {
        newb->insertAtTail(new CallExpr(wrap_fn, fcall->get(1)->remove(), tempc));
      } else
        newb->insertAtTail(new CallExpr(wrap_fn, tempc));

      if (block->blockTag == BLOCK_BEGIN || block->blockTag == BLOCK_COBEGIN)
        wrap_fn->insertAtHead(new CallExpr(PRIMITIVE_THREAD_INIT));

      // translate the original cobegin function
      CallExpr *new_cofn = new CallExpr( (toSymExpr(fcall->baseExpr))->var);
      if (block->blockTag == BLOCK_ON)
        new_cofn->insertAtTail(new_IntSymbol(0)); // bogus actual
      for_fields(field, ctype) {  // insert args

        VarSymbol* tmp = new VarSymbol("_tmp", field->type);
        tmp->isCompilerTemp = true;
        wrap_fn->insertAtTail(new DefExpr(tmp));
        wrap_fn->insertAtTail(
          new CallExpr(PRIMITIVE_MOVE, tmp,
            new CallExpr(PRIMITIVE_GET_MEMBER_VALUE, wrap_c, field)));
        new_cofn->insertAtTail(tmp);
      }

      wrap_fn->retType = dtVoid;
      fcall->remove();                     // rm orig. call
      wrap_fn->insertAtTail(new_cofn);     // add new call
      if (block->blockTag == BLOCK_ON)
        block->insertAfter(new CallExpr(PRIMITIVE_CHPL_FREE, tempc));
      else
        wrap_fn->insertAtTail(new CallExpr(PRIMITIVE_CHPL_FREE, wrap_c));

      fcall_def->remove();                 // move orig. def
      mod->block->insertAtTail(fcall_def); // to top-level
      normalize(wrap_fn);
    }
  }
  block->replace(newb);
}

void
parallel(void) {
  compute_sym_uses();

  Vec<BlockStmt*> blocks;
  forv_Vec(BaseAST, ast, gAsts) {
    if (BlockStmt* block = toBlockStmt(ast))
      blocks.add(block);
  }

  forv_Vec(BlockStmt, block, blocks) {
    if (block->blockTag == BLOCK_ON ||
        block->blockTag == BLOCK_BEGIN ||
        block->blockTag == BLOCK_COBEGIN)
      bundleArgs(block);
  }
}

static void
buildWideClass(Type* type) {
  ClassType* wide = new ClassType(CLASS_RECORD);
  TypeSymbol* wts = new TypeSymbol(astr("_wide_", type->symbol->cname), wide);
  wts->addPragma("wide class");
  theProgram->block->insertAtTail(new DefExpr(wts));
  wide->fields.insertAtTail(new DefExpr(new VarSymbol("locale", dtInt[INT_SIZE_32])));
  wide->fields.insertAtTail(new DefExpr(new VarSymbol("addr", type)));
  wideClassMap.put(type, wide);

  //
  // build reference type for wide class type
  //
  ClassType* ref = new ClassType(CLASS_CLASS);
  TypeSymbol* rts = new TypeSymbol(astr("_ref_wide_", type->symbol->cname), ref);
  rts->addPragma("ref");
  theProgram->block->insertAtTail(new DefExpr(rts));
  ref->fields.insertAtTail(new DefExpr(new VarSymbol("_val", type)));
  wide->refType = ref;
}

//
// change all classes into wide classes
// change all references into wide references
//
void
insertWideReferences(void) {
  if (fLocal)
    return;

  //
  // change dtNil into dtObject
  //
  forv_Vec(BaseAST, ast, gAsts) {
    if (DefExpr* def = toDefExpr(ast)) {
      if (FnSymbol* fn = toFnSymbol(def->sym)) {
        if (fn->retType == dtNil)
          fn->retType = dtObject;
      } else if (!isTypeSymbol(def->sym)) {
        if (def->sym->type == dtNil)
          def->sym->type = dtObject;
      }
    }
  }

  wideClassMap.clear();

  //
  // build wide class type for every class type
  //
  forv_Vec(TypeSymbol, ts, gTypes) {
    ClassType* ct = toClassType(ts->type);
    if (ct && ct->classTag == CLASS_CLASS && !ts->hasPragma("ref") && !ts->hasPragma("no wide class")) {

      //
      // do not yet support remote sync and single variables
      //
      if (ts->hasPragma("sync") || ts->hasPragma("single"))
        continue;

      buildWideClass(ct);
    }
  }
  buildWideClass(dtObject);

  //
  // change all classes into wide classes
  //
  forv_Vec(BaseAST, ast, gAsts) {
    if (DefExpr* def = toDefExpr(ast)) {

      //
      // do not change class field in wide class type
      //
      if (TypeSymbol* ts = toTypeSymbol(def->parentSymbol))
        if (ts->hasPragma("wide class"))
          continue;

      if (FnSymbol* fn = toFnSymbol(def->sym)) {
        if (Type* wide = wideClassMap.get(fn->retType))
          fn->retType = wide;
      } else if (!isTypeSymbol(def->sym)) {
        if (Type* wide = wideClassMap.get(def->sym->type))
          def->sym->type = wide;
      }
    }
  }

  //
  // change arrays of classes into arrays of wide classes
  //
  forv_Vec(TypeSymbol, ts, gTypes) {
    if (ts->hasPragma("data class")) {
      if (Type* nt = wideClassMap.get(toType(ts->type->substitutions.v[0].value))) {
        ts->type->substitutions.v[0].value = nt;
      }
    }
  }

  wideRefMap.clear();

  //
  // build wide reference type for every reference type
  //
  forv_Vec(TypeSymbol, ts, gTypes) {
    if (ts->hasPragma("ref")) {
      ClassType* wide = new ClassType(CLASS_RECORD);
      TypeSymbol* wts = new TypeSymbol(astr("_wide_", ts->cname), wide);
      wts->addPragma("wide");
      theProgram->block->insertAtTail(new DefExpr(wts));
      wide->fields.insertAtTail(new DefExpr(new VarSymbol("locale", dtInt[INT_SIZE_32])));
      wide->fields.insertAtTail(new DefExpr(new VarSymbol("addr", ts->type)));
      wideRefMap.put(ts->type, wide);
    }
  }

  //
  // change all references into wide references
  //
  forv_Vec(BaseAST, ast, gAsts) {
    if (DefExpr* def = toDefExpr(ast)) {

      //
      // do not change reference field in wide reference type
      //
      if (TypeSymbol* ts = toTypeSymbol(def->parentSymbol))
        if (ts->hasPragma("wide"))
          continue;

      if (FnSymbol* fn = toFnSymbol(def->sym)) {
        if (Type* wide = wideRefMap.get(fn->retType))
          fn->retType = wide;
      } else if (!isTypeSymbol(def->sym)) {
        if (Type* wide = wideRefMap.get(def->sym->type))
          def->sym->type = wide;
      }
    }
  }

  //
  // insert wide class temps for nil
  //
  forv_Vec(BaseAST, ast, gAsts) {
    if (SymExpr* se = toSymExpr(ast)) {
      if (se->var == gNil) {
        if (CallExpr* call = toCallExpr(se->parentExpr)) {
          if (call->isResolved()) {
            if (Type* type = actual_to_formal(se)->typeInfo()) {
              if (type->symbol->hasPragma("wide class")) {
                VarSymbol* tmp = new VarSymbol("_tmp", type);
                call->getStmtExpr()->insertBefore(new DefExpr(tmp));
                se->replace(new SymExpr(tmp));
                call->getStmtExpr()->insertBefore(new CallExpr(PRIMITIVE_MOVE, tmp, se));
              }
            }
          }
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>#ifndef CLUSTERING_ADMINISTRATION_HTTP_JSON_ADAPTERS_HPP_
#define CLUSTERING_ADMINISTRATION_HTTP_JSON_ADAPTERS_HPP_

#include "http/json/json_adapter.hpp"
#include "protocol_api.hpp"
#include "rpc/connectivity/connectivity.hpp"
#include "rpc/semilattice/joins/deletable.hpp"
#include "rpc/semilattice/joins/vclock.hpp"

/* There are a couple of semilattice structures that we need to have json
 * adaptable for the administration server, this code shouldn't go with the
 * definition of these structures because they're deep in the rpc directory
 * which generally doesn't concern itself with how people interact with its
 * structures. */

/* The vclock_t type needs a special apapter which allows it to be resolved.
 * When the vector clock goes in to conflict all of the other requests will
 * fail. */
template <class T, class ctx_t>
class json_vclock_resolver_t : public json_adapter_if_t<ctx_t> {
private:
    vclock_t<T> *target;
private:
    typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_subfields_impl(const ctx_t &);
    cJSON *render_impl(const ctx_t &);
    void apply_impl(cJSON *change, const ctx_t &);
    void reset_impl(const ctx_t &);
    void erase_impl(const ctx_t &);
    boost::shared_ptr<subfield_change_functor_t<ctx_t> > get_change_callback();
public:
    explicit json_vclock_resolver_t(vclock_t<T> *);
};

template <class T, class ctx_t>
class json_vclock_adapter_t : public json_adapter_if_t<ctx_t> {
private:
    vclock_t<T> *target;
private:
    typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_subfields_impl(const ctx_t &);
    cJSON *render_impl(const ctx_t &);
    void apply_impl(cJSON *, const ctx_t &);
    void reset_impl(const ctx_t &);
    void erase_impl(const ctx_t &);
    boost::shared_ptr<subfield_change_functor_t<ctx_t> >  get_change_callback();
public:
    explicit json_vclock_adapter_t(vclock_t<T> *);
};

//json adapter concept for vclock_t
template <class T, class ctx_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(vclock_t<T> *, const ctx_t &);

template <class T, class ctx_t>
cJSON *render_as_json(vclock_t<T> *, const ctx_t &);

//Note this is not actually part of the json_adapter concept but is a special
//purpose rendering function which is needed by the json_vclock_resolver_t
template <class T, class ctx_t>
cJSON *render_all_values(vclock_t<T> *, const ctx_t &);

template <class T, class ctx_t>
void apply_json_to(cJSON *, vclock_t<T> *, const ctx_t &);

template <class T, class ctx_t>
void on_subfield_change(vclock_t<T> *, const ctx_t &);

//json adapter concept for deletable_t
template <class T, class ctx_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(deletable_t<T> *, const ctx_t &);

template <class T, class ctx_t>
cJSON *render_as_json(deletable_t<T> *, const ctx_t &);

template <class T, class ctx_t>
void apply_json_to(cJSON *, deletable_t<T> *, const ctx_t &);

template <class T, class ctx_t>
void erase_json(deletable_t<T> *, const ctx_t &);

template <class T, class ctx_t>
void on_subfield_change(deletable_t<T> *, const ctx_t &);

//json adapter concept for peer_id_t
template <class ctx_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(peer_id_t *, const ctx_t &);

template <class ctx_t>
cJSON *render_as_json(peer_id_t *, const ctx_t &);

template <class ctx_t>
void apply_json_to(cJSON *, peer_id_t *, const ctx_t &);

template <class ctx_t>
void on_subfield_change(peer_id_t *, const ctx_t &);

//json adapter concept for region map
template <class protocol_t, class value_t, class ctx_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(region_map_t<protocol_t, value_t> *, const ctx_t &);

template <class protocol_t, class value_t, class ctx_t>
cJSON *render_as_json(region_map_t<protocol_t, value_t> *, const ctx_t &);

template <class protocol_t, class value_t, class ctx_t>
void apply_json_to(cJSON *, region_map_t<protocol_t, value_t> *, const ctx_t &);

template <class protocol_t, class value_t, class ctx_t>
void on_subfield_change(region_map_t<protocol_t, value_t> *, const ctx_t &);

#include "clustering/administration/http/json_adapters.tcc"

#endif
<commit_msg>Added DISABLE_COPYING to json_vclock_resolver_t and made all the public/private ordering consistent with the rest of the project.<commit_after>#ifndef CLUSTERING_ADMINISTRATION_HTTP_JSON_ADAPTERS_HPP_
#define CLUSTERING_ADMINISTRATION_HTTP_JSON_ADAPTERS_HPP_

#include "http/json/json_adapter.hpp"
#include "protocol_api.hpp"
#include "rpc/connectivity/connectivity.hpp"
#include "rpc/semilattice/joins/deletable.hpp"
#include "rpc/semilattice/joins/vclock.hpp"

/* There are a couple of semilattice structures that we need to have json
 * adaptable for the administration server, this code shouldn't go with the
 * definition of these structures because they're deep in the rpc directory
 * which generally doesn't concern itself with how people interact with its
 * structures. */

/* The vclock_t type needs a special apapter which allows it to be resolved.
 * When the vector clock goes in to conflict all of the other requests will
 * fail. */
template <class T, class ctx_t>
class json_vclock_resolver_t : public json_adapter_if_t<ctx_t> {
public:
    explicit json_vclock_resolver_t(vclock_t<T> *);

private:
    typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_subfields_impl(const ctx_t &);
    cJSON *render_impl(const ctx_t &);
    void apply_impl(cJSON *change, const ctx_t &);
    void reset_impl(const ctx_t &);
    void erase_impl(const ctx_t &);
    boost::shared_ptr<subfield_change_functor_t<ctx_t> > get_change_callback();

    vclock_t<T> *target;

    DISABLE_COPYING(json_vclock_resolver_t);
};

template <class T, class ctx_t>
class json_vclock_adapter_t : public json_adapter_if_t<ctx_t> {
private:
    vclock_t<T> *target;
private:
    typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_subfields_impl(const ctx_t &);
    cJSON *render_impl(const ctx_t &);
    void apply_impl(cJSON *, const ctx_t &);
    void reset_impl(const ctx_t &);
    void erase_impl(const ctx_t &);
    boost::shared_ptr<subfield_change_functor_t<ctx_t> >  get_change_callback();
public:
    explicit json_vclock_adapter_t(vclock_t<T> *);
};

//json adapter concept for vclock_t
template <class T, class ctx_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(vclock_t<T> *, const ctx_t &);

template <class T, class ctx_t>
cJSON *render_as_json(vclock_t<T> *, const ctx_t &);

//Note this is not actually part of the json_adapter concept but is a special
//purpose rendering function which is needed by the json_vclock_resolver_t
template <class T, class ctx_t>
cJSON *render_all_values(vclock_t<T> *, const ctx_t &);

template <class T, class ctx_t>
void apply_json_to(cJSON *, vclock_t<T> *, const ctx_t &);

template <class T, class ctx_t>
void on_subfield_change(vclock_t<T> *, const ctx_t &);

//json adapter concept for deletable_t
template <class T, class ctx_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(deletable_t<T> *, const ctx_t &);

template <class T, class ctx_t>
cJSON *render_as_json(deletable_t<T> *, const ctx_t &);

template <class T, class ctx_t>
void apply_json_to(cJSON *, deletable_t<T> *, const ctx_t &);

template <class T, class ctx_t>
void erase_json(deletable_t<T> *, const ctx_t &);

template <class T, class ctx_t>
void on_subfield_change(deletable_t<T> *, const ctx_t &);

//json adapter concept for peer_id_t
template <class ctx_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(peer_id_t *, const ctx_t &);

template <class ctx_t>
cJSON *render_as_json(peer_id_t *, const ctx_t &);

template <class ctx_t>
void apply_json_to(cJSON *, peer_id_t *, const ctx_t &);

template <class ctx_t>
void on_subfield_change(peer_id_t *, const ctx_t &);

//json adapter concept for region map
template <class protocol_t, class value_t, class ctx_t>
typename json_adapter_if_t<ctx_t>::json_adapter_map_t get_json_subfields(region_map_t<protocol_t, value_t> *, const ctx_t &);

template <class protocol_t, class value_t, class ctx_t>
cJSON *render_as_json(region_map_t<protocol_t, value_t> *, const ctx_t &);

template <class protocol_t, class value_t, class ctx_t>
void apply_json_to(cJSON *, region_map_t<protocol_t, value_t> *, const ctx_t &);

template <class protocol_t, class value_t, class ctx_t>
void on_subfield_change(region_map_t<protocol_t, value_t> *, const ctx_t &);

#include "clustering/administration/http/json_adapters.tcc"

#endif
<|endoftext|>


<commit_before>#include <unordered_map>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "interpreter.h"

using namespace Interpreter;

static std::unordered_map<std::string, int> symbols;
static std::unordered_map<std::string, Statements*> functions;

Id::Id(const char *name) {
    this->name = strdup(name);
}

int Id::Evaluate()
{
    const char* name = this->name;

    try
    {
        return symbols.at(name);
    }
    catch(std::out_of_range e)
    {
        fprintf(stderr, "error: use of undeclared variable '%s'\n", name);
        exit(1);
    }
}

void Id::Assign(int val) {
    symbols[this->name] = val;
}

Val::Val(int val) {
    this->val = val;
}

int Val::Evaluate()
{
    return this->val;
}

Op::Op(const char *symbol) {
    this->symbol = strdup(symbol);
}

Statements::Statements(Statement *statement, Statements *childStatements) {
    this->statement = statement;
    this->childStatements = childStatements;
}

void Statements::Execute()
{
    if(this->statement != nullptr)
    {
        this->statement->Execute();
    }
    if(this->childStatements != nullptr)
    {
        this->childStatements->Execute();
    }
}

Assignment::Assignment(Id *id, Expression* right) {
    this->id= id;
    this->right = right;
}

void Assignment::Execute() {
    int val = this->right->Evaluate();
    this->id->Assign(val);
}

Conditional::Conditional(Expression* condition, Statement* statement) {
    this->condition = condition;
    this->statement = statement;
}

void Conditional::Execute()
{
    int result = this->condition->Evaluate();
    if(result) {
        this->statement->Execute();
    }
}

Print::Print(Expression *expr) {
    this->expr = expr;
}

void Print::Execute()
{
    int result = this->expr->Evaluate();
    printf("%d\n", result);
}

ExpressionNode::ExpressionNode(Expression *left, Expression *right, Op* op) {
    this->left = left;
    this->right = right;
    this->op = op;
}

int ExpressionNode::Evaluate()
{
    const char* op = this->op->symbol;
    int left = this->left->Evaluate();
    int right = this->right->Evaluate();

    if(strcmp(op,"+")==0) {
        return left+right;
    } else if(strcmp(op,"-")==0) {
        return left-right;
    } else if(strcmp(op,"*")==0) {
        return left*right;
    } else if(strcmp(op,"/")==0) {
        return left/right;
    } else if(strcmp(op,"<")==0) {
        return left<right;
    } else if(strcmp(op,"<=")==0) {
        return left<=right;
    } else if(strcmp(op,">")==0) {
        return left>right;
    } else if(strcmp(op,">=")==0) {
        return left>=right;
    } else if(strcmp(op,"==")==0) {
        return left==right;
    } else if(strcmp(op,"!=")==0) {
        return left!=right;
    } else {
        fprintf(stderr,"fatal error: invalid op '%s'\n", op);
        exit(1);
    }
}

FunctionAssignment::FunctionAssignment(Id *id, Statements *statements)
{
    this->id = id;
    this->statements = statements;
}

void FunctionAssignment::Execute()
{
    functions[this->id->name] = this->statements;
}

FunctionCall::FunctionCall(Id *id)
{
    this->id = id;
}

void FunctionCall::Execute()
{
    try
    {
        functions.at(this->id->name)->Execute();
    }
    catch(std::out_of_range e)
    {
        fprintf(stderr, "error: use of undeclared function '%s'\n", this->id->name);
        exit(1);
    }
}
<commit_msg>Eliminate recursion on statement chain<commit_after>#include <unordered_map>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "interpreter.h"

using namespace Interpreter;

static std::unordered_map<std::string, int> symbols;
static std::unordered_map<std::string, Statements*> functions;

Id::Id(const char *name) {
    this->name = strdup(name);
}

int Id::Evaluate()
{
    const char* name = this->name;

    try
    {
        return symbols.at(name);
    }
    catch(std::out_of_range e)
    {
        fprintf(stderr, "error: use of undeclared variable '%s'\n", name);
        exit(1);
    }
}

void Id::Assign(int val) {
    symbols[this->name] = val;
}

Val::Val(int val) {
    this->val = val;
}

int Val::Evaluate()
{
    return this->val;
}

Op::Op(const char *symbol) {
    this->symbol = strdup(symbol);
}

Statements::Statements(Statement *statement, Statements *childStatements) {
    this->statement = statement;
    this->childStatements = childStatements;
}

void Statements::Execute()
{
    Statements *nexts = this;
    while(nexts != nullptr)
    {
       nexts->statement->Execute();
       nexts = nexts->childStatements;
    }
}

Assignment::Assignment(Id *id, Expression* right) {
    this->id= id;
    this->right = right;
}

void Assignment::Execute() {
    int val = this->right->Evaluate();
    this->id->Assign(val);
}

Conditional::Conditional(Expression* condition, Statement* statement) {
    this->condition = condition;
    this->statement = statement;
}

void Conditional::Execute()
{
    int result = this->condition->Evaluate();
    if(result) {
        this->statement->Execute();
    }
}

Print::Print(Expression *expr) {
    this->expr = expr;
}

void Print::Execute()
{
    int result = this->expr->Evaluate();
    printf("%d\n", result);
}

ExpressionNode::ExpressionNode(Expression *left, Expression *right, Op* op) {
    this->left = left;
    this->right = right;
    this->op = op;
}

int ExpressionNode::Evaluate()
{
    const char* op = this->op->symbol;
    int left = this->left->Evaluate();
    int right = this->right->Evaluate();

    if(strcmp(op,"+")==0) {
        return left+right;
    } else if(strcmp(op,"-")==0) {
        return left-right;
    } else if(strcmp(op,"*")==0) {
        return left*right;
    } else if(strcmp(op,"/")==0) {
        return left/right;
    } else if(strcmp(op,"<")==0) {
        return left<right;
    } else if(strcmp(op,"<=")==0) {
        return left<=right;
    } else if(strcmp(op,">")==0) {
        return left>right;
    } else if(strcmp(op,">=")==0) {
        return left>=right;
    } else if(strcmp(op,"==")==0) {
        return left==right;
    } else if(strcmp(op,"!=")==0) {
        return left!=right;
    } else {
        fprintf(stderr,"fatal error: invalid op '%s'\n", op);
        exit(1);
    }
}

FunctionAssignment::FunctionAssignment(Id *id, Statements *statements)
{
    this->id = id;
    this->statements = statements;
}

void FunctionAssignment::Execute()
{
    functions[this->id->name] = this->statements;
}

FunctionCall::FunctionCall(Id *id)
{
    this->id = id;
}

void FunctionCall::Execute()
{
    try
    {
        functions.at(this->id->name)->Execute();
    }
    catch(std::out_of_range e)
    {
        fprintf(stderr, "error: use of undeclared function '%s'\n", this->id->name);
        exit(1);
    }
}
<|endoftext|>


<commit_before>#include "Config.hpp"
#include "EventOutputQueue.hpp"
#include "PointingRelativeToScroll.hpp"

namespace org_pqrs_KeyRemap4MacBook {
  namespace RemapFunc {
    List* PointingRelativeToScroll::queue_ = NULL;
    TimerWrapper PointingRelativeToScroll::timer_;

    void
    PointingRelativeToScroll::static_initialize(IOWorkLoop& workloop)
    {
      queue_ = new List();
      timer_.initialize(&workloop, NULL, PointingRelativeToScroll::callback);
    }

    void
    PointingRelativeToScroll::static_terminate(void)
    {
      timer_.terminate();

      if (queue_) {
        delete queue_;
      }
    }

    void
    PointingRelativeToScroll::cancelScroll(void)
    {
      timer_.cancelTimeout();

      if (queue_) {
        queue_->clear();
      }
    }

    void
    PointingRelativeToScroll::initialize(void)
    {}

    void
    PointingRelativeToScroll::terminate(void)
    {}

    void
    PointingRelativeToScroll::add(Flags newval)
    {
      fromFlags_ = newval;
    }

    void
    PointingRelativeToScroll::add(PointingButton newval)
    {
      fromButton_ = newval;
    }

    bool
    PointingRelativeToScroll::remap(RemapPointingParams_relative& remapParams)
    {
      bool active = fromkeychecker_.isactive();

      if (remapParams.isremapped) return false;
      if (fromButton_ == PointingButton::NONE) {
        if (! FlagStatus::makeFlags().isOn(fromFlags_)) return false;
      } else {
        if (! fromkeychecker_.isFromPointingButton(remapParams.params, fromButton_, fromFlags_) && ! active) return false;
      }
      remapParams.isremapped = true;

      if (fromButton_ == PointingButton::NONE) {
        goto doremap;
      }

      // first time
      if (! active) {
        // if the source buttons contains left button, we cancel left click for iPhoto, or some applications.
        // iPhoto store the scroll events when left button is pressed, and restore events after left button is released.
        // PointingRelativeToScroll doesn't aim it, we release the left button and do normal scroll event.
        ButtonStatus::decrease(fromButton_);
        EventOutputQueue::FireRelativePointer::fire();
        ButtonStatus::increase(fromButton_);

        absolute_distance_ = 0;
        begin_ic_.begin();
        chained_ic_.begin();
        chained_delta1_ = 0;
        chained_delta2_ = 0;

        goto doremap;
      }

      // last time
      if (! fromkeychecker_.isactive()) {
        cancelScroll();

        const uint32_t DISTANCE_THRESHOLD = 5;
        const uint32_t TIME_THRESHOLD = 300;
        if (absolute_distance_ <= DISTANCE_THRESHOLD && begin_ic_.getmillisec() < TIME_THRESHOLD) {
          // Fire by a click event.
          ButtonStatus::increase(fromButton_);
          EventOutputQueue::FireRelativePointer::fire();
          ButtonStatus::decrease(fromButton_);
          EventOutputQueue::FireRelativePointer::fire();
        }
        return true;
      }

    doremap:
      FlagStatus::temporary_decrease(fromFlags_);
      toscroll(remapParams);
      // We need to call temporary_increase.
      // Because when SimultaneousKeyPresses is enabled, temporary flags will be reset in unexpected timing.
      // So, we need to restore temporary flags explicitly.
      FlagStatus::temporary_increase(fromFlags_);

      return true;
    }

    void
    PointingRelativeToScroll::toscroll(RemapPointingParams_relative& remapParams)
    {
      if (! queue_) return;

      // ----------------------------------------
      const uint32_t CANCEL_THRESHOLD = 100;
      if (chained_ic_.getmillisec() > CANCEL_THRESHOLD) {
        chained_delta1_ = 0;
        chained_delta2_ = 0;
        cancelScroll();
      }

      int delta1 = -remapParams.params.dy;
      int delta2 = -remapParams.params.dx;

      chained_ic_.begin();

      // ----------------------------------------
      if (config.option_pointing_disable_vertical_scroll) delta1 = 0;
      if (config.option_pointing_disable_horizontal_scroll) delta2 = 0;

      // ----------------------------------------
      // ignore minuscule move
      const unsigned int abs1 = abs(delta1);
      const unsigned int abs2 = abs(delta2);

      if (abs1 > abs2 * 2) {
        delta2 = 0;
      }
      if (abs2 > abs1 * 2) {
        delta1 = 0;
      }

      // ----------------------------------------
      // Fixation processing

      if (config.option_pointing_enable_scrollwheel_fixation) {
        // When 300ms passes from the last event, we reset a value.
        const uint32_t FIXATION_MILLISEC = 300;
        if (fixation_ic_.getmillisec() > FIXATION_MILLISEC) {
          fixation_begin_ic_.begin();
          fixation_delta1_ = 0;
          fixation_delta2_ = 0;
        }
        fixation_ic_.begin();

        if (fixation_delta1_ > fixation_delta2_ * 2) {
          delta2 = 0;
        }
        if (fixation_delta2_ > fixation_delta1_ * 2) {
          delta1 = 0;
        }

        // Only first 1000ms performs the addition of fixation_delta1, fixation_delta2.
        const uint32_t FIXATION_EARLY_MILLISEC  = 1000;
        if (fixation_begin_ic_.getmillisec() < FIXATION_EARLY_MILLISEC) {
          if (delta1 == 0) fixation_delta2_ += abs2;
          if (delta2 == 0) fixation_delta1_ += abs1;
        }
      }

      // ------------------------------------------------------------
      if (abs(delta1) > abs(chained_delta1_) || delta1 * chained_delta1_ < 0 ||
          abs(delta2) > abs(chained_delta2_) || delta2 * chained_delta2_ < 0) {
        chained_delta1_ = delta1;
        chained_delta2_ = delta2;
      }

      absolute_distance_ += abs(chained_delta1_) + abs(chained_delta2_);
      queue_->push_back(new Item(chained_delta1_ * DELTA_SCALE, chained_delta2_ * DELTA_SCALE));

      timer_.setTimeoutMS(SCROLL_INTERVAL_MS, false);
    }

    void
    PointingRelativeToScroll::firescroll(int delta1, int delta2)
    {
      short deltaAxis1;
      short deltaAxis2;
      IOFixed fixedDelta1;
      IOFixed fixedDelta2;
      SInt32 pointDelta1;
      SInt32 pointDelta2;

      deltaAxis1 = (delta1 * config.pointing_relative2scroll_rate) / 1024 / DELTA_SCALE;
      deltaAxis2 = (delta2 * config.pointing_relative2scroll_rate) / 1024 / DELTA_SCALE;

      fixedDelta1 = (delta1 * config.pointing_relative2scroll_rate) * (POINTING_FIXED_SCALE / 1024) / DELTA_SCALE;
      fixedDelta2 = (delta2 * config.pointing_relative2scroll_rate) * (POINTING_FIXED_SCALE / 1024) / DELTA_SCALE;

      pointDelta1 = (delta1 * POINTING_POINT_SCALE * config.pointing_relative2scroll_rate) / 1024 / DELTA_SCALE;
      pointDelta2 = (delta2 * POINTING_POINT_SCALE * config.pointing_relative2scroll_rate) / 1024 / DELTA_SCALE;

      // see IOHIDSystem/IOHIDevicePrivateKeys.h about options.
      const int kScrollTypeContinuous_ = 0x0001;
      int options = kScrollTypeContinuous_;

      Params_ScrollWheelEventCallback::auto_ptr ptr(Params_ScrollWheelEventCallback::alloc(deltaAxis1,  deltaAxis2, 0,
                                                                                fixedDelta1, fixedDelta2, 0,
                                                                                pointDelta1, pointDelta2, 0,
                                                                                options));
      if (! ptr) return;
      EventOutputQueue::FireScrollWheel::fire(*ptr);
    }

    void
    PointingRelativeToScroll::callback(OSObject* owner, IOTimerEventSource* sender)
    {
      IOLockWrapper::ScopedLock lk(timer_.getlock());

      if (! queue_) return;

      // ----------------------------------------
      int delta1 = 0;
      int delta2 = 0;
      {
        Item* p = static_cast<Item*>(queue_->front());
        if (! p) return;

        delta1 = p->delta1;
        delta2 = p->delta2;

        queue_->pop_front();
      }

      // ----------------------------------------
      firescroll(delta1, delta2);

      if (! config.option_pointing_disable_momentum_scroll) {
        if (delta1 != 0 || delta2 != 0) {
          queue_->push_back(new Item(delta1 / 2, delta2 / 2));
        }
      }

      timer_.setTimeoutMS(SCROLL_INTERVAL_MS, false);
    }
  }
}
<commit_msg>adjusted PointingRelativeToScroll<commit_after>#include "Config.hpp"
#include "EventOutputQueue.hpp"
#include "PointingRelativeToScroll.hpp"

namespace org_pqrs_KeyRemap4MacBook {
  namespace RemapFunc {
    List* PointingRelativeToScroll::queue_ = NULL;
    TimerWrapper PointingRelativeToScroll::timer_;

    void
    PointingRelativeToScroll::static_initialize(IOWorkLoop& workloop)
    {
      queue_ = new List();
      timer_.initialize(&workloop, NULL, PointingRelativeToScroll::callback);
    }

    void
    PointingRelativeToScroll::static_terminate(void)
    {
      timer_.terminate();

      if (queue_) {
        delete queue_;
      }
    }

    void
    PointingRelativeToScroll::cancelScroll(void)
    {
      timer_.cancelTimeout();

      if (queue_) {
        queue_->clear();
      }
    }

    void
    PointingRelativeToScroll::initialize(void)
    {}

    void
    PointingRelativeToScroll::terminate(void)
    {}

    void
    PointingRelativeToScroll::add(Flags newval)
    {
      fromFlags_ = newval;
    }

    void
    PointingRelativeToScroll::add(PointingButton newval)
    {
      fromButton_ = newval;
    }

    bool
    PointingRelativeToScroll::remap(RemapPointingParams_relative& remapParams)
    {
      bool active = fromkeychecker_.isactive();

      if (remapParams.isremapped) return false;
      if (fromButton_ == PointingButton::NONE) {
        if (! FlagStatus::makeFlags().isOn(fromFlags_)) return false;
      } else {
        if (! fromkeychecker_.isFromPointingButton(remapParams.params, fromButton_, fromFlags_) && ! active) return false;
      }
      remapParams.isremapped = true;

      if (fromButton_ == PointingButton::NONE) {
        goto doremap;
      }

      // first time
      if (! active) {
        // if the source buttons contains left button, we cancel left click for iPhoto, or some applications.
        // iPhoto store the scroll events when left button is pressed, and restore events after left button is released.
        // PointingRelativeToScroll doesn't aim it, we release the left button and do normal scroll event.
        ButtonStatus::decrease(fromButton_);
        EventOutputQueue::FireRelativePointer::fire();
        ButtonStatus::increase(fromButton_);

        absolute_distance_ = 0;
        begin_ic_.begin();
        chained_ic_.begin();
        chained_delta1_ = 0;
        chained_delta2_ = 0;

        goto doremap;
      }

      // last time
      if (! fromkeychecker_.isactive()) {
        cancelScroll();

        const uint32_t DISTANCE_THRESHOLD = 5;
        const uint32_t TIME_THRESHOLD = 300;
        if (absolute_distance_ <= DISTANCE_THRESHOLD && begin_ic_.getmillisec() < TIME_THRESHOLD) {
          // Fire by a click event.
          ButtonStatus::increase(fromButton_);
          EventOutputQueue::FireRelativePointer::fire();
          ButtonStatus::decrease(fromButton_);
          EventOutputQueue::FireRelativePointer::fire();
        }
        return true;
      }

    doremap:
      FlagStatus::temporary_decrease(fromFlags_);
      toscroll(remapParams);
      // We need to call temporary_increase.
      // Because when SimultaneousKeyPresses is enabled, temporary flags will be reset in unexpected timing.
      // So, we need to restore temporary flags explicitly.
      FlagStatus::temporary_increase(fromFlags_);

      return true;
    }

    void
    PointingRelativeToScroll::toscroll(RemapPointingParams_relative& remapParams)
    {
      if (! queue_) return;

      // ----------------------------------------
      const uint32_t CANCEL_THRESHOLD = 100;
      if (chained_ic_.getmillisec() > CANCEL_THRESHOLD) {
        chained_delta1_ = 0;
        chained_delta2_ = 0;
        cancelScroll();
      }

      int delta1 = -remapParams.params.dy;
      int delta2 = -remapParams.params.dx;

      chained_ic_.begin();

      // ----------------------------------------
      if (config.option_pointing_disable_vertical_scroll) delta1 = 0;
      if (config.option_pointing_disable_horizontal_scroll) delta2 = 0;

      // ----------------------------------------
      // ignore minuscule move
      const unsigned int abs1 = abs(delta1);
      const unsigned int abs2 = abs(delta2);

      if (abs1 > abs2 * 2) {
        delta2 = 0;
      }
      if (abs2 > abs1 * 2) {
        delta1 = 0;
      }

      // ----------------------------------------
      // Fixation processing

      if (config.option_pointing_enable_scrollwheel_fixation) {
        // When 300ms passes from the last event, we reset a value.
        const uint32_t FIXATION_MILLISEC = 300;
        if (fixation_ic_.getmillisec() > FIXATION_MILLISEC) {
          fixation_begin_ic_.begin();
          fixation_delta1_ = 0;
          fixation_delta2_ = 0;
        }
        fixation_ic_.begin();

        if (fixation_delta1_ > fixation_delta2_ * 2) {
          delta2 = 0;
        }
        if (fixation_delta2_ > fixation_delta1_ * 2) {
          delta1 = 0;
        }

        // Only first 1000ms performs the addition of fixation_delta1, fixation_delta2.
        const uint32_t FIXATION_EARLY_MILLISEC  = 1000;
        if (fixation_begin_ic_.getmillisec() < FIXATION_EARLY_MILLISEC) {
          if (delta1 == 0) fixation_delta2_ += abs2;
          if (delta2 == 0) fixation_delta1_ += abs1;
        }
      }

      // ------------------------------------------------------------
      // when sign is different
      if (0 > delta1 * chained_delta1_ ||
          0 > delta2 * chained_delta2_) {
        queue_->clear();
        chained_delta1_ = delta1;
        chained_delta2_ = delta2;

      } else if (abs(delta1) > abs(chained_delta1_) ||
                 abs(delta2) > abs(chained_delta2_)) {
        // greater delta.
        chained_delta1_ = delta1;
        chained_delta2_ = delta2;
      }

      absolute_distance_ += abs(chained_delta1_) + abs(chained_delta2_);
      queue_->push_back(new Item(chained_delta1_ * DELTA_SCALE, chained_delta2_ * DELTA_SCALE));

      timer_.setTimeoutMS(SCROLL_INTERVAL_MS, false);
    }

    void
    PointingRelativeToScroll::firescroll(int delta1, int delta2)
    {
      short deltaAxis1;
      short deltaAxis2;
      IOFixed fixedDelta1;
      IOFixed fixedDelta2;
      SInt32 pointDelta1;
      SInt32 pointDelta2;

      deltaAxis1 = (delta1 * config.pointing_relative2scroll_rate) / 1024 / DELTA_SCALE;
      deltaAxis2 = (delta2 * config.pointing_relative2scroll_rate) / 1024 / DELTA_SCALE;

      fixedDelta1 = (delta1 * config.pointing_relative2scroll_rate) * (POINTING_FIXED_SCALE / 1024) / DELTA_SCALE;
      fixedDelta2 = (delta2 * config.pointing_relative2scroll_rate) * (POINTING_FIXED_SCALE / 1024) / DELTA_SCALE;

      pointDelta1 = (delta1 * POINTING_POINT_SCALE * config.pointing_relative2scroll_rate) / 1024 / DELTA_SCALE;
      pointDelta2 = (delta2 * POINTING_POINT_SCALE * config.pointing_relative2scroll_rate) / 1024 / DELTA_SCALE;

      // see IOHIDSystem/IOHIDevicePrivateKeys.h about options.
      const int kScrollTypeContinuous_ = 0x0001;
      int options = kScrollTypeContinuous_;

      Params_ScrollWheelEventCallback::auto_ptr ptr(Params_ScrollWheelEventCallback::alloc(deltaAxis1,  deltaAxis2, 0,
                                                                                fixedDelta1, fixedDelta2, 0,
                                                                                pointDelta1, pointDelta2, 0,
                                                                                options));
      if (! ptr) return;
      EventOutputQueue::FireScrollWheel::fire(*ptr);
    }

    void
    PointingRelativeToScroll::callback(OSObject* owner, IOTimerEventSource* sender)
    {
      IOLockWrapper::ScopedLock lk(timer_.getlock());

      if (! queue_) return;

      // ----------------------------------------
      int delta1 = 0;
      int delta2 = 0;
      {
        Item* p = static_cast<Item*>(queue_->front());
        if (! p) return;

        delta1 = p->delta1;
        delta2 = p->delta2;

        queue_->pop_front();
      }

      // ----------------------------------------
      firescroll(delta1, delta2);

      if (! config.option_pointing_disable_momentum_scroll) {
        if (delta1 != 0 || delta2 != 0) {
          queue_->push_back(new Item(delta1 / 2, delta2 / 2));
        }
      }

      timer_.setTimeoutMS(SCROLL_INTERVAL_MS, false);
    }
  }
}
<|endoftext|>