<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: prtopt.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 06:46:15 $
 *
 *  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
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _PRTOPT_HXX
#include <prtopt.hxx>
#endif
#ifndef _SWPRTOPT_HXX
#include <swprtopt.hxx>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;

#define C2U(cChar) OUString::createFromAscii(cChar)
/*--------------------------------------------------------------------
     Beschreibung: Ctor
 --------------------------------------------------------------------*/

Sequence<OUString> SwPrintOptions::GetPropertyNames()
{
    static const char* aPropNames[] =
    {
        "Content/Graphic",              //  0
        "Content/Table",                //  1
        "Content/Control",              //  2
        "Content/Background",           //  3
        "Content/PrintBlack",           //  4
        "Content/Note",                 //  5
        "Page/Reversed",                //  6
        "Page/Brochure",                //  7
        "Output/SinglePrintJob",        //  8
        "Output/Fax",                   //  9
        "Papertray/FromPrinterSetup",   // 10
        "Content/Drawing",              // 11 not in SW/Web
        "Page/LeftPage",                // 12 not in SW/Web
        "Page/RightPage"                // 13 not in SW/Web
    };
    const int nCount = bIsWeb ? 11 : 14;
    Sequence<OUString> aNames(nCount);
    OUString* pNames = aNames.getArray();
    for(int i = 0; i < nCount; i++)
    {
        pNames[i] = OUString::createFromAscii(aPropNames[i]);
    }
    return aNames;
}
/* -----------------------------06.09.00 16:44--------------------------------

 ---------------------------------------------------------------------------*/
SwPrintOptions::SwPrintOptions(sal_Bool bWeb) :
    ConfigItem(bWeb ? C2U("Office.WriterWeb/Print") :  C2U("Office.Writer/Print"),
        CONFIG_MODE_DELAYED_UPDATE|CONFIG_MODE_RELEASE_TREE),
    bIsWeb(bWeb)
{
    bPrintPageBackground = !bWeb;
    bPrintBlackFont = bWeb;
    Sequence<OUString> aNames = GetPropertyNames();
    Sequence<Any> aValues = GetProperties(aNames);
    const Any* pValues = aValues.getConstArray();
    DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed")
    if(aValues.getLength() == aNames.getLength())
    {
        for(int nProp = 0; nProp < aNames.getLength(); nProp++)
        {
            if(pValues[nProp].hasValue())
            {
                switch(nProp)
                {
                    case  0: bPrintGraphic      = *(sal_Bool*)pValues[nProp].getValue(); break;
                    case  1: bPrintTable            = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  2: bPrintControl      = *(sal_Bool*)pValues[nProp].getValue() ;  break;
                    case  3: bPrintPageBackground= *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  4: bPrintBlackFont        = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  5:
                    {
                        sal_Int32 nTmp;
                        pValues[nProp] >>=  nTmp;
                        nPrintPostIts = (sal_Int16)nTmp;
                    }
                    break;
                    case  6: bPrintReverse      = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  7: bPrintProspect      = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  8: bPrintSingleJobs   = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  9: pValues[nProp] >>= sFaxName;  break;
                    case 10: bPaperFromSetup    = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case 11: bPrintDraw         = *(sal_Bool*)pValues[nProp].getValue() ;  break;
                    case 12: bPrintLeftPage     = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case 13: bPrintRightPage        = *(sal_Bool*)pValues[nProp].getValue();  break;
                }
            }
        }
    }
}
/* -----------------------------06.09.00 16:50--------------------------------

 ---------------------------------------------------------------------------*/
SwPrintOptions::~SwPrintOptions()
{
}
/* -----------------------------06.09.00 16:43--------------------------------

 ---------------------------------------------------------------------------*/
void    SwPrintOptions::Commit()
{
    Sequence<OUString> aNames = GetPropertyNames();

    OUString* pNames = aNames.getArray();
    Sequence<Any> aValues(aNames.getLength());
    Any* pValues = aValues.getArray();

    const Type& rType = ::getBooleanCppuType();
    BOOL bVal;
    for(int nProp = 0; nProp < aNames.getLength(); nProp++)
    {
        switch(nProp)
        {
            case  0: bVal = bPrintGraphic; pValues[nProp].setValue(&bVal, rType);break;
            case  1: bVal = bPrintTable         ;pValues[nProp].setValue(&bVal, rType);  break;
            case  2: bVal = bPrintControl        ; pValues[nProp].setValue(&bVal, rType);  break;
            case  3: bVal = bPrintPageBackground; pValues[nProp].setValue(&bVal, rType);  break;
            case  4: bVal = bPrintBlackFont     ; pValues[nProp].setValue(&bVal, rType);  break;
            case  5: pValues[nProp] <<=  (sal_Int32)nPrintPostIts       ; break;
            case  6: bVal = bPrintReverse       ; pValues[nProp].setValue(&bVal, rType);  break;
            case  7: bVal = bPrintProspect      ; pValues[nProp].setValue(&bVal, rType);  break;
            case  8: bVal = bPrintSingleJobs     ; pValues[nProp].setValue(&bVal, rType);  break;
            case  9: pValues[nProp] <<= sFaxName;  break;
            case 10: bVal = bPaperFromSetup     ; pValues[nProp].setValue(&bVal, rType);  break;
            case 11: bVal = bPrintDraw           ; pValues[nProp].setValue(&bVal, rType);  break;
            case 12: bVal = bPrintLeftPage       ; pValues[nProp].setValue(&bVal, rType);  break;
            case 13: bVal = bPrintRightPage     ; pValues[nProp].setValue(&bVal, rType);  break;
        }
    }
    PutProperties(aNames, aValues);
}

<commit_msg>INTEGRATION: CWS emptypage (1.7.154); FILE MERGED 2005/12/13 15:27:26 fme 1.7.154.1: #b6354161# Feature - Print empty pages<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: prtopt.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2005-12-21 15:12:19 $
 *
 *  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
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _PRTOPT_HXX
#include <prtopt.hxx>
#endif
#ifndef _SWPRTOPT_HXX
#include <swprtopt.hxx>
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;

#define C2U(cChar) OUString::createFromAscii(cChar)
/*--------------------------------------------------------------------
     Beschreibung: Ctor
 --------------------------------------------------------------------*/

Sequence<OUString> SwPrintOptions::GetPropertyNames()
{
    static const char* aPropNames[] =
    {
        "Content/Graphic",              //  0
        "Content/Table",                //  1
        "Content/Control",              //  2
        "Content/Background",           //  3
        "Content/PrintBlack",           //  4
        "Content/Note",                 //  5
        "Page/Reversed",                //  6
        "Page/Brochure",                //  7
        "Output/SinglePrintJob",        //  8
        "Output/Fax",                   //  9
        "Papertray/FromPrinterSetup",   // 10
        "Content/Drawing",              // 11 not in SW/Web
        "Page/LeftPage",                // 12 not in SW/Web
        "Page/RightPage",               // 13 not in SW/Web
        "EmptyPages"                    // 14 not in SW/Web
    };
    const int nCount = bIsWeb ? 11 : 15;
    Sequence<OUString> aNames(nCount);
    OUString* pNames = aNames.getArray();
    for(int i = 0; i < nCount; i++)
    {
        pNames[i] = OUString::createFromAscii(aPropNames[i]);
    }
    return aNames;
}
/* -----------------------------06.09.00 16:44--------------------------------

 ---------------------------------------------------------------------------*/
SwPrintOptions::SwPrintOptions(sal_Bool bWeb) :
    ConfigItem(bWeb ? C2U("Office.WriterWeb/Print") :  C2U("Office.Writer/Print"),
        CONFIG_MODE_DELAYED_UPDATE|CONFIG_MODE_RELEASE_TREE),
    bIsWeb(bWeb)
{
    bPrintPageBackground = !bWeb;
    bPrintBlackFont = bWeb;
    Sequence<OUString> aNames = GetPropertyNames();
    Sequence<Any> aValues = GetProperties(aNames);
    const Any* pValues = aValues.getConstArray();
    DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed")
    if(aValues.getLength() == aNames.getLength())
    {
        for(int nProp = 0; nProp < aNames.getLength(); nProp++)
        {
            if(pValues[nProp].hasValue())
            {
                switch(nProp)
                {
                    case  0: bPrintGraphic      = *(sal_Bool*)pValues[nProp].getValue(); break;
                    case  1: bPrintTable            = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  2: bPrintControl      = *(sal_Bool*)pValues[nProp].getValue() ;  break;
                    case  3: bPrintPageBackground= *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  4: bPrintBlackFont        = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  5:
                    {
                        sal_Int32 nTmp;
                        pValues[nProp] >>=  nTmp;
                        nPrintPostIts = (sal_Int16)nTmp;
                    }
                    break;
                    case  6: bPrintReverse      = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  7: bPrintProspect      = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  8: bPrintSingleJobs   = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case  9: pValues[nProp] >>= sFaxName;  break;
                    case 10: bPaperFromSetup    = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case 11: bPrintDraw         = *(sal_Bool*)pValues[nProp].getValue() ;  break;
                    case 12: bPrintLeftPage     = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case 13: bPrintRightPage        = *(sal_Bool*)pValues[nProp].getValue();  break;
                    case 14: bPrintEmptyPages       = *(sal_Bool*)pValues[nProp].getValue();  break;
                }
            }
        }
    }
}
/* -----------------------------06.09.00 16:50--------------------------------

 ---------------------------------------------------------------------------*/
SwPrintOptions::~SwPrintOptions()
{
}
/* -----------------------------06.09.00 16:43--------------------------------

 ---------------------------------------------------------------------------*/
void    SwPrintOptions::Commit()
{
    Sequence<OUString> aNames = GetPropertyNames();

    OUString* pNames = aNames.getArray();
    Sequence<Any> aValues(aNames.getLength());
    Any* pValues = aValues.getArray();

    const Type& rType = ::getBooleanCppuType();
    BOOL bVal;
    for(int nProp = 0; nProp < aNames.getLength(); nProp++)
    {
        switch(nProp)
        {
            case  0: bVal = bPrintGraphic; pValues[nProp].setValue(&bVal, rType);break;
            case  1: bVal = bPrintTable         ;pValues[nProp].setValue(&bVal, rType);  break;
            case  2: bVal = bPrintControl        ; pValues[nProp].setValue(&bVal, rType);  break;
            case  3: bVal = bPrintPageBackground; pValues[nProp].setValue(&bVal, rType);  break;
            case  4: bVal = bPrintBlackFont     ; pValues[nProp].setValue(&bVal, rType);  break;
            case  5: pValues[nProp] <<=  (sal_Int32)nPrintPostIts       ; break;
            case  6: bVal = bPrintReverse       ; pValues[nProp].setValue(&bVal, rType);  break;
            case  7: bVal = bPrintProspect      ; pValues[nProp].setValue(&bVal, rType);  break;
            case  8: bVal = bPrintSingleJobs     ; pValues[nProp].setValue(&bVal, rType);  break;
            case  9: pValues[nProp] <<= sFaxName;  break;
            case 10: bVal = bPaperFromSetup     ; pValues[nProp].setValue(&bVal, rType);  break;
            case 11: bVal = bPrintDraw           ; pValues[nProp].setValue(&bVal, rType);  break;
            case 12: bVal = bPrintLeftPage       ; pValues[nProp].setValue(&bVal, rType);  break;
            case 13: bVal = bPrintRightPage     ; pValues[nProp].setValue(&bVal, rType);  break;
            case 14: bVal = bPrintEmptyPages    ; pValues[nProp].setValue(&bVal, rType);  break;
        }
    }
    PutProperties(aNames, aValues);
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: envprt.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-23 08:50:51 $
 *
 *  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 SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif

#pragma hdrstop

#ifndef _SV_PRINT_HXX //autogen
#include <vcl/print.hxx>
#endif
#ifndef _SV_PRNSETUP_HXX_ //autogen
#include <svtools/prnsetup.hxx>
#endif

#include "swtypes.hxx"
#include "cmdid.h"
#include "envprt.hxx"
#include "envlop.hxx"
#include "uitool.hxx"

#include "envprt.hrc"

SwEnvPrtPage::SwEnvPrtPage(Window* pParent, const SfxItemSet& rSet) :

    SfxTabPage(pParent, SW_RES(TP_ENV_PRT), rSet),

    aAlignBox    (this, SW_RES(BOX_ALIGN  )),
    aTopButton   (this, SW_RES(BTN_TOP    )),
    aBottomButton(this, SW_RES(BTN_BOTTOM )),
    aRightText   (this, SW_RES(TXT_RIGHT  )),
    aRightField  (this, SW_RES(FLD_RIGHT  )),
    aDownText    (this, SW_RES(TXT_DOWN   )),
    aDownField   (this, SW_RES(FLD_DOWN   )),
    aPrinterInfo (this, SW_RES(TXT_PRINTER)),
    aNoNameFL    (this, SW_RES(FL_NONAME )),
    aPrinterFL   (this, SW_RES(FL_PRINTER )),
    aPrtSetup    (this, SW_RES(BTN_PRTSETUP))

{
    FreeResource();
    SetExchangeSupport();

    // Metriken
    FieldUnit eUnit = ::GetDfltMetric(FALSE);
    SetMetric(aRightField, eUnit);
    SetMetric(aDownField , eUnit);

    // Handler installieren
    aTopButton   .SetClickHdl(LINK(this, SwEnvPrtPage, ClickHdl));
    aBottomButton.SetClickHdl(LINK(this, SwEnvPrtPage, ClickHdl));

    aPrtSetup    .SetClickHdl(LINK(this, SwEnvPrtPage, ButtonHdl));

    // Bitmaps
    aBottomButton.GetClickHdl().Call(&aBottomButton);

    // ToolBox
    Size aSz = aAlignBox.CalcWindowSizePixel();
    aAlignBox.SetSizePixel(aSz);
//    aAlignBox.SetPosPixel(Point(aNoNameFL.GetPosPixel().X() + (aNoNameFL.GetSizePixel().Width() - aSz.Width()) / 2, aAlignBox.GetPosPixel().Y()));
    aAlignBox.SetClickHdl(LINK(this, SwEnvPrtPage, AlignHdl));

}

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

SwEnvPrtPage::~SwEnvPrtPage()
{
}

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

IMPL_LINK( SwEnvPrtPage, ClickHdl, Button *, EMPTYARG )
{
    sal_Bool bHC = GetDisplayBackground().GetColor().IsDark();
    if (aBottomButton.IsChecked())
    {
        // Briefumschlaege von unten
        aAlignBox.SetItemImage(ITM_HOR_LEFT, Bitmap(SW_RES(bHC ? BMP_HOR_LEFT_LOWER_H : BMP_HOR_LEFT_LOWER)));
        aAlignBox.SetItemImage(ITM_HOR_CNTR, Bitmap(SW_RES(bHC ? BMP_HOR_CNTR_LOWER_H : BMP_HOR_CNTR_LOWER)));
        aAlignBox.SetItemImage(ITM_HOR_RGHT, Bitmap(SW_RES(bHC ? BMP_HOR_RGHT_LOWER_H : BMP_HOR_RGHT_LOWER)));
        aAlignBox.SetItemImage(ITM_VER_LEFT, Bitmap(SW_RES(bHC ? BMP_VER_LEFT_LOWER_H : BMP_VER_LEFT_LOWER)));
        aAlignBox.SetItemImage(ITM_VER_CNTR, Bitmap(SW_RES(bHC ? BMP_VER_CNTR_LOWER_H : BMP_VER_CNTR_LOWER)));
        aAlignBox.SetItemImage(ITM_VER_RGHT, Bitmap(SW_RES(bHC ? BMP_VER_RGHT_LOWER_H : BMP_VER_RGHT_LOWER)));
    }
    else
    {
        // Briefumschlaege von oben
        aAlignBox.SetItemImage(ITM_HOR_LEFT, Bitmap(SW_RES(bHC ? BMP_HOR_LEFT_UPPER_H : BMP_HOR_LEFT_UPPER)));
        aAlignBox.SetItemImage(ITM_HOR_CNTR, Bitmap(SW_RES(bHC ? BMP_HOR_CNTR_UPPER_H : BMP_HOR_CNTR_UPPER)));
        aAlignBox.SetItemImage(ITM_HOR_RGHT, Bitmap(SW_RES(bHC ? BMP_HOR_RGHT_UPPER_H : BMP_HOR_RGHT_UPPER)));
        aAlignBox.SetItemImage(ITM_VER_LEFT, Bitmap(SW_RES(bHC ? BMP_VER_LEFT_UPPER_H : BMP_VER_LEFT_UPPER)));
        aAlignBox.SetItemImage(ITM_VER_CNTR, Bitmap(SW_RES(bHC ? BMP_VER_CNTR_UPPER_H : BMP_VER_CNTR_UPPER)));
        aAlignBox.SetItemImage(ITM_VER_RGHT, Bitmap(SW_RES(bHC ? BMP_VER_RGHT_UPPER_H : BMP_VER_RGHT_UPPER)));
    }
    return 0;
}

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

IMPL_LINK( SwEnvPrtPage, ButtonHdl, Button *, pBtn )
{
    if (pBtn == &aPrtSetup)
    {
        // Druck-Setup aufrufen
        if (pPrt)
        {
            PrinterSetupDialog* pDlg = new PrinterSetupDialog(this );
            pDlg->SetPrinter(pPrt);
            pDlg->Execute();
            delete pDlg;
            GrabFocus();
            aPrinterInfo.SetText(pPrt->GetName());
        }
    }
    return 0;
}

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

IMPL_LINK( SwEnvPrtPage, AlignHdl, ToolBox *, EMPTYARG )
{
    if (aAlignBox.GetCurItemId())
    {
        for (USHORT i = ITM_HOR_LEFT; i <= ITM_VER_RGHT; i++)
            aAlignBox.CheckItem(i, FALSE);
        aAlignBox.CheckItem(aAlignBox.GetCurItemId(), TRUE);
    }
    else
    {
        // GetCurItemId() == 0 ist moeglich!
        const SwEnvItem& rItem = (const SwEnvItem&) GetItemSet().Get(FN_ENVELOP);
        aAlignBox.CheckItem((USHORT) rItem.eAlign + ITM_HOR_LEFT, TRUE);
    }
    return 0;
}

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

SfxTabPage* SwEnvPrtPage::Create(Window* pParent, const SfxItemSet& rSet)
{
    return new SwEnvPrtPage(pParent, rSet);
}

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

void SwEnvPrtPage::ActivatePage(const SfxItemSet& rSet)
{
    if (pPrt)
        aPrinterInfo.SetText(pPrt->GetName());
}

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

int SwEnvPrtPage::DeactivatePage(SfxItemSet* pSet)
{
    if( pSet )
        FillItemSet(*pSet);
    return SfxTabPage::LEAVE_PAGE;
}

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

void SwEnvPrtPage::FillItem(SwEnvItem& rItem)
{
    USHORT nID = 0;
    for (USHORT i = ITM_HOR_LEFT; i <= ITM_VER_RGHT && !nID; i++)
        if (aAlignBox.IsItemChecked(i))
            nID = i;

    rItem.eAlign          = (SwEnvAlign) (nID - ITM_HOR_LEFT);
    rItem.bPrintFromAbove = aTopButton.IsChecked();
    rItem.lShiftRight     = GetFldVal(aRightField);
    rItem.lShiftDown      = GetFldVal(aDownField );
}

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

BOOL SwEnvPrtPage::FillItemSet(SfxItemSet& rSet)
{
    FillItem(GetParent()->aEnvItem);
    rSet.Put(GetParent()->aEnvItem);
    return TRUE;
}

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

void SwEnvPrtPage::Reset(const SfxItemSet& rSet)
{
//    SfxItemSet aSet(rSet);
//    aSet.Put(GetParent()->aEnvItem);

    // Item auslesen
    const SwEnvItem& rItem = (const SwEnvItem&) rSet.Get(FN_ENVELOP);
    aAlignBox.CheckItem((USHORT) rItem.eAlign + ITM_HOR_LEFT);

    if (rItem.bPrintFromAbove)
        aTopButton   .Check();
    else
        aBottomButton.Check();

    SetFldVal(aRightField, rItem.lShiftRight);
    SetFldVal(aDownField , rItem.lShiftDown );

    ActivatePage(rSet);
    ClickHdl(&aTopButton);
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.8.596); FILE MERGED 2005/09/05 13:44:12 rt 1.8.596.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: envprt.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 07:26:25 $
 *
 *  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
 *
 ************************************************************************/

#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif

#pragma hdrstop

#ifndef _SV_PRINT_HXX //autogen
#include <vcl/print.hxx>
#endif
#ifndef _SV_PRNSETUP_HXX_ //autogen
#include <svtools/prnsetup.hxx>
#endif

#include "swtypes.hxx"
#include "cmdid.h"
#include "envprt.hxx"
#include "envlop.hxx"
#include "uitool.hxx"

#include "envprt.hrc"

SwEnvPrtPage::SwEnvPrtPage(Window* pParent, const SfxItemSet& rSet) :

    SfxTabPage(pParent, SW_RES(TP_ENV_PRT), rSet),

    aAlignBox    (this, SW_RES(BOX_ALIGN  )),
    aTopButton   (this, SW_RES(BTN_TOP    )),
    aBottomButton(this, SW_RES(BTN_BOTTOM )),
    aRightText   (this, SW_RES(TXT_RIGHT  )),
    aRightField  (this, SW_RES(FLD_RIGHT  )),
    aDownText    (this, SW_RES(TXT_DOWN   )),
    aDownField   (this, SW_RES(FLD_DOWN   )),
    aPrinterInfo (this, SW_RES(TXT_PRINTER)),
    aNoNameFL    (this, SW_RES(FL_NONAME )),
    aPrinterFL   (this, SW_RES(FL_PRINTER )),
    aPrtSetup    (this, SW_RES(BTN_PRTSETUP))

{
    FreeResource();
    SetExchangeSupport();

    // Metriken
    FieldUnit eUnit = ::GetDfltMetric(FALSE);
    SetMetric(aRightField, eUnit);
    SetMetric(aDownField , eUnit);

    // Handler installieren
    aTopButton   .SetClickHdl(LINK(this, SwEnvPrtPage, ClickHdl));
    aBottomButton.SetClickHdl(LINK(this, SwEnvPrtPage, ClickHdl));

    aPrtSetup    .SetClickHdl(LINK(this, SwEnvPrtPage, ButtonHdl));

    // Bitmaps
    aBottomButton.GetClickHdl().Call(&aBottomButton);

    // ToolBox
    Size aSz = aAlignBox.CalcWindowSizePixel();
    aAlignBox.SetSizePixel(aSz);
//    aAlignBox.SetPosPixel(Point(aNoNameFL.GetPosPixel().X() + (aNoNameFL.GetSizePixel().Width() - aSz.Width()) / 2, aAlignBox.GetPosPixel().Y()));
    aAlignBox.SetClickHdl(LINK(this, SwEnvPrtPage, AlignHdl));

}

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

SwEnvPrtPage::~SwEnvPrtPage()
{
}

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

IMPL_LINK( SwEnvPrtPage, ClickHdl, Button *, EMPTYARG )
{
    sal_Bool bHC = GetDisplayBackground().GetColor().IsDark();
    if (aBottomButton.IsChecked())
    {
        // Briefumschlaege von unten
        aAlignBox.SetItemImage(ITM_HOR_LEFT, Bitmap(SW_RES(bHC ? BMP_HOR_LEFT_LOWER_H : BMP_HOR_LEFT_LOWER)));
        aAlignBox.SetItemImage(ITM_HOR_CNTR, Bitmap(SW_RES(bHC ? BMP_HOR_CNTR_LOWER_H : BMP_HOR_CNTR_LOWER)));
        aAlignBox.SetItemImage(ITM_HOR_RGHT, Bitmap(SW_RES(bHC ? BMP_HOR_RGHT_LOWER_H : BMP_HOR_RGHT_LOWER)));
        aAlignBox.SetItemImage(ITM_VER_LEFT, Bitmap(SW_RES(bHC ? BMP_VER_LEFT_LOWER_H : BMP_VER_LEFT_LOWER)));
        aAlignBox.SetItemImage(ITM_VER_CNTR, Bitmap(SW_RES(bHC ? BMP_VER_CNTR_LOWER_H : BMP_VER_CNTR_LOWER)));
        aAlignBox.SetItemImage(ITM_VER_RGHT, Bitmap(SW_RES(bHC ? BMP_VER_RGHT_LOWER_H : BMP_VER_RGHT_LOWER)));
    }
    else
    {
        // Briefumschlaege von oben
        aAlignBox.SetItemImage(ITM_HOR_LEFT, Bitmap(SW_RES(bHC ? BMP_HOR_LEFT_UPPER_H : BMP_HOR_LEFT_UPPER)));
        aAlignBox.SetItemImage(ITM_HOR_CNTR, Bitmap(SW_RES(bHC ? BMP_HOR_CNTR_UPPER_H : BMP_HOR_CNTR_UPPER)));
        aAlignBox.SetItemImage(ITM_HOR_RGHT, Bitmap(SW_RES(bHC ? BMP_HOR_RGHT_UPPER_H : BMP_HOR_RGHT_UPPER)));
        aAlignBox.SetItemImage(ITM_VER_LEFT, Bitmap(SW_RES(bHC ? BMP_VER_LEFT_UPPER_H : BMP_VER_LEFT_UPPER)));
        aAlignBox.SetItemImage(ITM_VER_CNTR, Bitmap(SW_RES(bHC ? BMP_VER_CNTR_UPPER_H : BMP_VER_CNTR_UPPER)));
        aAlignBox.SetItemImage(ITM_VER_RGHT, Bitmap(SW_RES(bHC ? BMP_VER_RGHT_UPPER_H : BMP_VER_RGHT_UPPER)));
    }
    return 0;
}

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

IMPL_LINK( SwEnvPrtPage, ButtonHdl, Button *, pBtn )
{
    if (pBtn == &aPrtSetup)
    {
        // Druck-Setup aufrufen
        if (pPrt)
        {
            PrinterSetupDialog* pDlg = new PrinterSetupDialog(this );
            pDlg->SetPrinter(pPrt);
            pDlg->Execute();
            delete pDlg;
            GrabFocus();
            aPrinterInfo.SetText(pPrt->GetName());
        }
    }
    return 0;
}

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

IMPL_LINK( SwEnvPrtPage, AlignHdl, ToolBox *, EMPTYARG )
{
    if (aAlignBox.GetCurItemId())
    {
        for (USHORT i = ITM_HOR_LEFT; i <= ITM_VER_RGHT; i++)
            aAlignBox.CheckItem(i, FALSE);
        aAlignBox.CheckItem(aAlignBox.GetCurItemId(), TRUE);
    }
    else
    {
        // GetCurItemId() == 0 ist moeglich!
        const SwEnvItem& rItem = (const SwEnvItem&) GetItemSet().Get(FN_ENVELOP);
        aAlignBox.CheckItem((USHORT) rItem.eAlign + ITM_HOR_LEFT, TRUE);
    }
    return 0;
}

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

SfxTabPage* SwEnvPrtPage::Create(Window* pParent, const SfxItemSet& rSet)
{
    return new SwEnvPrtPage(pParent, rSet);
}

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

void SwEnvPrtPage::ActivatePage(const SfxItemSet& rSet)
{
    if (pPrt)
        aPrinterInfo.SetText(pPrt->GetName());
}

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

int SwEnvPrtPage::DeactivatePage(SfxItemSet* pSet)
{
    if( pSet )
        FillItemSet(*pSet);
    return SfxTabPage::LEAVE_PAGE;
}

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

void SwEnvPrtPage::FillItem(SwEnvItem& rItem)
{
    USHORT nID = 0;
    for (USHORT i = ITM_HOR_LEFT; i <= ITM_VER_RGHT && !nID; i++)
        if (aAlignBox.IsItemChecked(i))
            nID = i;

    rItem.eAlign          = (SwEnvAlign) (nID - ITM_HOR_LEFT);
    rItem.bPrintFromAbove = aTopButton.IsChecked();
    rItem.lShiftRight     = GetFldVal(aRightField);
    rItem.lShiftDown      = GetFldVal(aDownField );
}

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

BOOL SwEnvPrtPage::FillItemSet(SfxItemSet& rSet)
{
    FillItem(GetParent()->aEnvItem);
    rSet.Put(GetParent()->aEnvItem);
    return TRUE;
}

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

void SwEnvPrtPage::Reset(const SfxItemSet& rSet)
{
//    SfxItemSet aSet(rSet);
//    aSet.Put(GetParent()->aEnvItem);

    // Item auslesen
    const SwEnvItem& rItem = (const SwEnvItem&) rSet.Get(FN_ENVELOP);
    aAlignBox.CheckItem((USHORT) rItem.eAlign + ITM_HOR_LEFT);

    if (rItem.bPrintFromAbove)
        aTopButton   .Check();
    else
        aBottomButton.Check();

    SetFldVal(aRightField, rItem.lShiftRight);
    SetFldVal(aDownField , rItem.lShiftDown );

    ActivatePage(rSet);
    ClickHdl(&aTopButton);
}

<|endoftext|>


<commit_before>createTriggerDescriptor_pp()
{
   // create Trigger Descriptor for p-p interactions

   AliTriggerDescriptor descrip( "p-p", "Default p-p Descriptor" );

   // Define a Cluster Detector
   //descrip.AddDetectorCluster( "ALL" );
   descrip.AddDetectorCluster( "ITS START VZERO TOF" ); // no CRT yet

   descrip.AddCondition( "VZERO_LEFT",      "VZERO_LEFT",      "VZERO A (Left)",            (ULong64_t)0x1  );
   descrip.AddCondition( "VZERO_RIGHT",     "VZERO_RIGHT",     "VZERO C (Right)",           (ULong64_t)0x1 << 1 );
   descrip.AddCondition( "VZERO_BEAMGAS",   "VZERO_BEAMGAS",   "VZERO beam gas rejection",  (ULong64_t)0x1 << 2 );
   descrip.AddCondition( "START_A_L0",      "START_A_L0",      "START A (Left)",            (ULong64_t)0x1 << 3 );
   descrip.AddCondition( "START_C_L0",      "START_C_L0",      "START C (Right)",           (ULong64_t)0x1 << 4 );
   descrip.AddCondition( "ITS_SPD_GFO_L0",  "ITS_SPD_GFO_L0",  "SPD global fast-or",        (ULong64_t)0x1 << 5 );
   descrip.AddCondition( "ITS_SPD_HMULT_L0","ITS_SPD_HMULT_L0","SPD high mult. 100 ",       (ULong64_t)0x1 << 6 );

   descrip.AddCondition( "ITS_SPD_GFO_L0 & VZERO_AND",
                         "MB",
                         "Minimum Bias",
                         (ULong64_t)0x1 << 7 );
   descrip.AddCondition( "ITS_SPD_GFO_L0 & VZERO_AND | TOF_pp_MB_L0",
                         "MB-TOF",
                         "Minimum Bias with TOF",
                         (ULong64_t)0x1 << 8 );

   cout << endl << endl;

   if( !descrip.CheckInputsConditions("Config.C") ) {
      cerr << "\n ERROR: There are some problems on descriptor definition..." << endl;
      return;
   }

   cout << endl << endl;

   cout << "************************************************************" << endl;
   cout << "New Trigger descriptor" << endl;
   cout << "************************************************************" << endl;
   descrip.Print();

   // save the descriptor to file
   descrip.WriteDescriptor();

   cout << endl << endl << endl;
   cout << "************************************************************" << endl;
   cout << "Available Trigger descriptors" << endl;
   cout << "************************************************************" << endl;

   // Get and print all available descriptors
   TObjArray* desc = AliTriggerDescriptor::GetAvailableDescriptors();

   if( !desc || !desc->GetEntriesFast() ) {
      cerr << "Not descriptors availables" << endl;
      return;
   }

   Int_t ndesc = desc->GetEntriesFast();
   for( Int_t j=0; j<ndesc; j++ ) {
      AliTriggerDescriptor* de = (AliTriggerDescriptor*)desc->At(j);
      de->Print();
   }

}

<commit_msg>MUON trigger inputs added to proton-proton CTP configuration<commit_after>createTriggerDescriptor_pp()
{
   // create Trigger Descriptor for p-p interactions

   AliTriggerDescriptor descrip( "p-p", "Default p-p Descriptor" );

   // Define a Cluster Detector
   //descrip.AddDetectorCluster( "ALL" );
   descrip.AddDetectorCluster( "ITS START VZERO MUON TOF" ); // no CRT yet

   // standalong V0 inputs
   descrip.AddCondition( "VZERO_LEFT",      "VZERO_LEFT",      "VZERO A (Left)",            (ULong64_t)0x1  );
   descrip.AddCondition( "VZERO_RIGHT",     "VZERO_RIGHT",     "VZERO C (Right)",           (ULong64_t)0x1 << 1 );
   descrip.AddCondition( "VZERO_BEAMGAS",   "VZERO_BEAMGAS",   "VZERO beam gas rejection",  (ULong64_t)0x1 << 2 );

   // standalong T0 inputs
   descrip.AddCondition( "START_A_L0",      "START_A_L0",      "START A (Left)",            (ULong64_t)0x1 << 3 );
   descrip.AddCondition( "START_C_L0",      "START_C_L0",      "START C (Right)",           (ULong64_t)0x1 << 4 );

   // standalong ITS-SPD inputs
   descrip.AddCondition( "ITS_SPD_GFO_L0",  "ITS_SPD_GFO_L0",  "SPD global fast-or",        (ULong64_t)0x1 << 5 );
   descrip.AddCondition( "ITS_SPD_HMULT_L0","ITS_SPD_HMULT_L0","SPD high mult. 100 ",       (ULong64_t)0x1 << 6 );

   // standalong MUON inputs
   descrip.AddCondition( "MUON_SPlus_LPt_L0",
                         "MUON_SPlus_LPt_L0",           "Muon Plus Low Pt",
                         (ULong64_t)0x1 << 7 );
   descrip.AddCondition( "MUON_Unlike_LPt_L0",
                         "MUON_Unlike_LPt_L0",          "Di Muon Unlike sign Low Pt",
                         (ULong64_t)0x1 << 8 );
   descrip.AddCondition( "MUON_Unlike_HPt_L0",
                         "MUON_Unlike_HPt_L0",          "Di Muon Unlike sign High Pt",
                         (ULong64_t)0x1 << 9 );
   descrip.AddCondition( "MUON_Like_LPt_L0",
                         "MUON_Like_LPt_L0",            "Di Muon Like sign Low Pt",
                         (ULong64_t)0x1 << 10 );
   descrip.AddCondition( "MUON_Like_HPt_L0",
                         "MUON_Like_HPt_L0",            "Di Muon Like sign High Pt",
                         (ULong64_t)0x1 << 11 );

   // combinations
   descrip.AddCondition( "ITS_SPD_GFO_L0 & VZERO_AND",
                         "MB",                           "Minimum Bias",
                         (ULong64_t)0x1 << 12 );

   descrip.AddCondition( "ITS_SPD_GFO_L0 & VZERO_AND | TOF_pp_MB_L0",
                         "MB-TOF",
                         "Minimum Bias with TOF",
                         (ULong64_t)0x1 << 13 );

   descrip.AddCondition( "ITS_SPD_GFO_L0 & VZERO_AND & MUON_SPlus_LPt_L0",
                         "MUONSingle_MB",                "Muon Single Low Pt Minimum Bias",
                         (ULong64_t)0x1 << 14 );
   descrip.AddCondition( "ITS_SPD_GFO_L0 & VZERO_AND & MUON_Unlike_LPt_L0",
                         "MUONUnlikeLPt_MB",              "Muon Unlike Low Pt Minimum Bias",
                         (ULong64_t)0x1 << 15 );
   descrip.AddCondition( "ITS_SPD_GFO_L0 & VZERO_AND & MUON_Like_LPt_L0",
                         "MUONLikeLPt_MB",                "Muon Like Low Pt Minimum Bias",
                         (ULong64_t)0x1 << 16 );

   cout << endl << endl;

   if( !descrip.CheckInputsConditions("Config.C") ) {
      cerr << "\n ERROR: There are some problems on descriptor definition..." << endl;
      return;
   }

   cout << endl << endl;

   cout << "************************************************************" << endl;
   cout << "New Trigger descriptor" << endl;
   cout << "************************************************************" << endl;
   descrip.Print();

   // save the descriptor to file
   descrip.WriteDescriptor();

   cout << endl << endl << endl;
   cout << "************************************************************" << endl;
   cout << "Available Trigger descriptors" << endl;
   cout << "************************************************************" << endl;

   // Get and print all available descriptors
   TObjArray* desc = AliTriggerDescriptor::GetAvailableDescriptors();

   if( !desc || !desc->GetEntriesFast() ) {
      cerr << "Not descriptors availables" << endl;
      return;
   }

   Int_t ndesc = desc->GetEntriesFast();
   for( Int_t j=0; j<ndesc; j++ ) {
      AliTriggerDescriptor* de = (AliTriggerDescriptor*)desc->At(j);
      de->Print();
   }

}

<|endoftext|>


<commit_before>//
//  MFMDiskController.hpp
//  Clock Signal
//
//  Created by Thomas Harte on 05/08/2017.
//  Copyright © 2017 Thomas Harte. All rights reserved.
//

#ifndef MFMDiskController_hpp
#define MFMDiskController_hpp

#include "DiskController.hpp"
#include "../../NumberTheory/CRC.hpp"
#include "../../ClockReceiver/ClockReceiver.hpp"

namespace Storage {
namespace Disk {

/*!
	Extends Controller with a built-in shift register and FM/MFM decoding logic,
	being able to post event messages to subclasses.
*/
class MFMController: public Controller {
	public:
		MFMController(Cycles clock_rate, int clock_rate_multiplier, int revolutions_per_minute);

	protected:
		void set_is_double_density(bool);
		bool get_is_double_density();

		enum DataMode {
			Scanning,
			Reading,
			Writing
		};
		void set_data_mode(DataMode);

		struct Token {
			enum Type {
				Index, ID, Data, DeletedData, Sync, Byte
			} type;
			uint8_t byte_value;
		};
		Token get_latest_token();

		// Events
		enum class Event: int {
			Command			= (1 << 0),	// Indicates receipt of a new command.
			Token			= (1 << 1),	// Indicates recognition of a new token in the flux stream. Use get_latest_token() for more details.
			IndexHole		= (1 << 2),	// Indicates the passing of a physical index hole.
			HeadLoad		= (1 << 3),	// Indicates the head has been loaded.
			DataWritten		= (1 << 4),	// Indicates that all queued bits have been written
		};
		virtual void posit_event(Event type) = 0;

	private:
		// Storage::Disk::Controller
		virtual void process_input_bit(int value, unsigned int cycles_since_index_hole);
		virtual void process_index_hole();
		virtual void process_write_completed();

		// PLL input state
		int bits_since_token_;
		int shift_register_;
		bool is_awaiting_marker_value_;

		// input configuration
		bool is_double_density_;
		DataMode data_mode_;

		// output
		Token latest_token_;

		// CRC generator
		NumberTheory::CRC16 crc_generator_;
};

}
}

#endif /* MFMDiskController_hpp */
<commit_msg>Documented, and removed a couple of Event types that are WD-specific but had accidentally flown into here. Will need to figure out how best to expose the CRC result too, but I'm willing to let that one drop out naturally as I implement the 8272.<commit_after>//
//  MFMDiskController.hpp
//  Clock Signal
//
//  Created by Thomas Harte on 05/08/2017.
//  Copyright © 2017 Thomas Harte. All rights reserved.
//

#ifndef MFMDiskController_hpp
#define MFMDiskController_hpp

#include "DiskController.hpp"
#include "../../NumberTheory/CRC.hpp"
#include "../../ClockReceiver/ClockReceiver.hpp"

namespace Storage {
namespace Disk {

/*!
	Extends Controller with a built-in shift register and FM/MFM decoding logic,
	being able to post event messages to subclasses.
*/
class MFMController: public Controller {
	public:
		MFMController(Cycles clock_rate, int clock_rate_multiplier, int revolutions_per_minute);

	protected:
		/// Indicates whether the controller should try to decode double-density MFM content, or single-density FM content.
		void set_is_double_density(bool);

		/// @returns @c true if currently decoding MFM content; @c false otherwise.
		bool get_is_double_density();

		enum DataMode {
			/// When the controller is scanning it will obey all synchronisation marks found, even if in the middle of data.
			Scanning,
			/// When the controller is reading it will ignore synchronisation marks and simply return a new token every sixteen PLL clocks.
			Reading,
			/// When the controller is writing, it will replace the underlying data with that which has been enqueued, posting Event::DataWritten when the queue is empty.
			Writing
		};
		/// Sets the current data mode.
		void set_data_mode(DataMode);

		/*!
			Describes a token found in the incoming PLL bit stream. Tokens can be one of:

				Index: the bit pattern usually encoded at the start of a track to denote the position of the index hole;
				ID: the pattern that begins an ID section, i.e. a sector header, announcing sector number, track number, etc.
				Data: the pattern that begins a data section, i.e. sector contents.
				DeletedData: the pattern that begins a deleted data section, i.e. deleted sector contents.

				Sync: MFM only; the same synchronisation mark is used in MFM to denote the bottom three of the four types
				of token listed above; this class combines notification of that mark and the distinct index sync mark.
				Both are followed by a byte to indicate type. When scanning an MFM stream, subclasses will receive an
				announcement of sync followed by an announcement of one of the above four types of token.

				Byte: reports reading of an ordinary byte, with expected timing bits.

			When the data mode is set to 'reading', only Byte tokens are returned; detection of the other kinds of token
			is suppressed. Controllers will likely want to switch data mode when receiving ID and sector contents, as
			spurious sync signals can otherwise be found in ordinary data, causing framing errors.
		*/
		struct Token {
			enum Type {
				Index, ID, Data, DeletedData, Sync, Byte
			} type;
			uint8_t byte_value;
		};
		/// @returns The most-recently read token from the surface of the disk.
		Token get_latest_token();

		// Events
		enum class Event: int {
			Token			= (1 << 0),	// Indicates recognition of a new token in the flux stream. Use get_latest_token() for more details.
			IndexHole		= (1 << 1),	// Indicates the passing of a physical index hole.
			DataWritten		= (1 << 2),	// Indicates that all queued bits have been written
		};

		/*!
			Subclasses should implement this. It is called every time a new @c Event is discovered in the incoming data stream.
			Therefore it is called to announce when:

				(i) a new token is discovered in the incoming stream: an index, ID, data or deleted data, a sync mark or a new byte of data.
				(ii) the index hole passes; or
				(iii) the queue of data to be written has been exhausted.
		*/
		virtual void posit_event(Event type) = 0;

	private:
		// Storage::Disk::Controller
		virtual void process_input_bit(int value, unsigned int cycles_since_index_hole);
		virtual void process_index_hole();
		virtual void process_write_completed();

		// PLL input state
		int bits_since_token_;
		int shift_register_;
		bool is_awaiting_marker_value_;

		// input configuration
		bool is_double_density_;
		DataMode data_mode_;

		// output
		Token latest_token_;

		// CRC generator
		NumberTheory::CRC16 crc_generator_;
};

}
}

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


<commit_before>//
//  lexer_stage.cpp
//  Parse
//
//  Created by Andrew Hunter on 21/08/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

// TODO: it'd be nice to have a way of designing this so it's not dependent on the language_stage stage
//       (we don't do this at the moment to keep things reasonably simple, there's a lot of dependencies that means that DI
//       wouldn't really fix the problem, and would just create a new 'giant constructor of doom' problem)

#include <sstream>
#include "TameParse/Compiler/lexer_stage.h"

using namespace std;
using namespace dfa;
using namespace contextfree;
using namespace lr;
using namespace compiler;

/// \brief Creates a new lexer compiler
///
/// The compiler will not 'own' the objects passed in to this constructor; however, they must have a lifespan
/// that is at least as long as the compiler itself (it's safe to call the destructor but no other call if they
/// have been destroyed)
lexer_stage::lexer_stage(console_container& console, const std::wstring& filename, language_stage* languageCompiler)
: compilation_stage(console, filename)
, m_Language(languageCompiler)
, m_WeakSymbols(languageCompiler->grammar())
, m_Dfa(NULL)
, m_Lexer(NULL) {
}

/// \brief Destroys the lexer compiler
lexer_stage::~lexer_stage() {
    // Destroy the DFA if it exists
    if (m_Dfa) {
        delete m_Dfa;
    }

    if (m_Lexer) {
        delete m_Lexer;
    }
}

/// \brief Compiles the lexer
void lexer_stage::compile() {
    // Grab the input
    const lexer_data*       lex             = m_Language->lexer();
    terminal_dictionary*    terminals       = m_Language->terminals();
    const set<int>*         weakSymbolIds   = m_Language->weak_symbols();

    // Reset the weak symbols
    m_WeakSymbols = lr::weak_symbols(m_Language->grammar());

    // Sanity check
    if (!lex || !terminals || !weakSymbolIds) {
        cons().report_error(error(error::sev_bug, filename(), L"BUG_LEXER_BAD_PARAMETERS", L"Missing input for the lexer stage", position(-1, -1, -1)));
        return;
    }

    // Output a staging message
    cons().verbose_stream() << L"  = Constructing final lexer" << endl;

    // Create the ndfa
    typedef lexer_data::item_list item_list;

    dfa::ndfa_regex* stage0 = new ndfa_regex();

    // Iterate through the definition lists for each item
    for (lexer_data::iterator itemList = lex->begin(); itemList != lex->end(); itemList++) {
        // Iterate through the individual definitions for this item
        for (item_list::const_iterator item = itemList->second.begin(); item != itemList->second.end(); item++) {
            // Add the corresponding items
            switch (item->type) {
                case lexer_item::regex:
                    stage0->set_case_insensitive(item->case_insensitive);
                    stage0->add_regex(0, item->definition, *item->accept);
                    break;

                case lexer_item::literal:
                    stage0->set_case_insensitive(item->case_insensitive);
                    stage0->add_literal(0, item->definition, *item->accept);
                    break;
            }
        }
    }

    // Write out some stats about the ndfa
    cons().verbose_stream() << L"    Number states in the NDFA:              " << stage0->count_states() << endl;

    // Compile the NDFA to a NDFA without overlapping symbol sets
    dfa::ndfa* stage1 = stage0->to_ndfa_with_unique_symbols();

    if (!stage1) {
        cons().report_error(error(error::sev_bug, filename(), L"BUG_DFA_FAILED_TO_CONVERT", L"Failed to create an NDFA with unique symbols", position(-1, -1, -1)));
        return;
    }

    // Write some information about the first stage
    cons().verbose_stream() << L"    Initial number of character sets:       " << stage0->symbols().count_sets() << endl;
    cons().verbose_stream() << L"    Final number of character sets:         " << stage1->symbols().count_sets() << endl;

    delete stage0;
    stage0 = NULL;

    // Compile the NDFA to a DFA
    dfa::ndfa* stage2 = stage1->to_dfa();
    delete stage1;
    stage1 = NULL;

    if (!stage2) {
        cons().report_error(error(error::sev_bug, filename(), L"BUG_DFA_FAILED_TO_COMPILE", L"Failed to compile DFA", position(-1, -1, -1)));
        return;
    }

    // Identify any terminals that are always replaced by other terminals (warning)
    set<int>            unusedTerminals;
    map<int, set<int> > clashes;
    for (int terminalId = 0; terminalId < m_Language->terminals()->count_symbols(); terminalId++) {
        unusedTerminals.insert(terminalId);
    }

    for (int stateId = 0; stateId < stage2->count_states(); stateId++) {
        // Get the actions for this state
        const ndfa::accept_action_list& acceptActions = stage2->actions_for_state(stateId);

        // Ignore empty action sets
        if (acceptActions.empty()) continue;

        // Pick the highest action
        ndfa::accept_action_list::const_iterator action = acceptActions.begin();
        accept_action* highest = *action;

        action++;
        for (; action != acceptActions.end(); action++) {
            if (*highest < **action) {
                clashes[highest->symbol()].insert((*action)->symbol());
                highest = *action;
            } else {
                clashes[(*action)->symbol()].insert(highest->symbol());
            }
        }

        // Remove from the set of unused terminals
        unusedTerminals.erase(highest->symbol());
    }

    // Report warnings for any terminals that are never generated by the lexer
    for (set<int>::const_iterator unusedSymbol = unusedTerminals.begin(); unusedSymbol != unusedTerminals.end(); unusedSymbol++) {
        // Get the position of this terminal
        position        pos     = m_Language->terminal_definition_pos(*unusedSymbol);
        const wstring&  file    = m_Language->terminal_definition_file(*unusedSymbol);

        // Get the name of the terminal
        const wstring& name = m_Language->terminals()->name_for_symbol(*unusedSymbol);

        // Build the warning message
        wstringstream msg;
        msg << L"Lexer symbol can never be generated: " << name;

        cons().report_error(error(error::sev_warning, file, L"SYMBOL_CANNOT_BE_GENERATED", msg.str(), pos));

        // Get the symbols that clash with this one
        set<int>& clashSet = clashes[*unusedSymbol];
        if (!clashSet.empty()) {
            // Write out the symbols that are generated instead
            for (set<int>::iterator clashSymbol = clashSet.begin(); clashSymbol != clashSet.end(); clashSymbol++) {
                wstringstream msg2;
                msg2 << L"'" << name << L"' clashes with: " << m_Language->terminals()->name_for_symbol(*clashSymbol);
                cons().report_error(error(error::sev_detail, m_Language->terminal_definition_file(*clashSymbol), L"SYMBOL_CLASHES_WITH", msg2.str(), m_Language->terminal_definition_pos(*clashSymbol)));
            }
        }
    }

    // TODO: also identify any terminals that clash with terminals at the same level (warning)

    // Build up the weak symbols set if there are any
    if (weakSymbolIds->size() > 0) {
        // Build up the weak symbol set as a series of items
        item_set weakSymSet(m_Language->grammar());

        // Count how many symbols there were initially
        int initialSymCount = terminals->count_symbols();

        // Iterate through the symbol IDs
        for (set<int>::const_iterator weakSymId = weakSymbolIds->begin(); weakSymId != weakSymbolIds->end(); weakSymId++) {
            weakSymSet.insert(item_container(new terminal(*weakSymId), true));
        }

        // Add these symbols to the weak symbols object
        m_WeakSymbols.add_symbols(*stage2, weakSymSet, *terminals);

        // Display how many new terminal symbols were added
        int finalSymCount = terminals->count_symbols();

        cons().verbose_stream() << L"    Number of extra weak symbols:           " << finalSymCount - initialSymCount << endl;
    }

    // Compact the resulting DFA
    cons().verbose_stream() << L"    Number of states in the lexer DFA:      " << stage2->count_states() << endl;
    dfa::ndfa* stage3 = stage2->to_compact_dfa();
    delete stage2;
    stage2 = NULL;

    // Write some information about the DFA we just produced
    cons().verbose_stream() << L"    Number of states in the compacted DFA:  " << stage3->count_states() << endl;

    // Eliminate any unnecessary symbol sets
    dfa::ndfa* stage4 = stage3->to_ndfa_with_merged_symbols();
    delete stage3;
    stage3 = NULL;

    // Write some information about the DFA we just produced
    cons().verbose_stream() << L"    Number of symbols in the compacted DFA: " << stage4->symbols().count_sets() << endl;

    m_Dfa = stage4;

    // Build the final lexer
    m_Lexer = new lexer(*m_Dfa);

    // Write some parting words
    // (Well, this is really kibibytes but I can't take blibblebytes seriously as a unit of measurement)
    cons().verbose_stream() << L"    Approximate size of final lexer:        " << (m_Lexer->size() + 512) / 1024 << L" kilobytes" << endl;
}
<commit_msg>Added detection for a particular kind of bug with the new way of generating lexer data<commit_after>//
//  lexer_stage.cpp
//  Parse
//
//  Created by Andrew Hunter on 21/08/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

// TODO: it'd be nice to have a way of designing this so it's not dependent on the language_stage stage
//       (we don't do this at the moment to keep things reasonably simple, there's a lot of dependencies that means that DI
//       wouldn't really fix the problem, and would just create a new 'giant constructor of doom' problem)

#include <sstream>
#include "TameParse/Compiler/lexer_stage.h"

using namespace std;
using namespace dfa;
using namespace contextfree;
using namespace lr;
using namespace compiler;

/// \brief Creates a new lexer compiler
///
/// The compiler will not 'own' the objects passed in to this constructor; however, they must have a lifespan
/// that is at least as long as the compiler itself (it's safe to call the destructor but no other call if they
/// have been destroyed)
lexer_stage::lexer_stage(console_container& console, const std::wstring& filename, language_stage* languageCompiler)
: compilation_stage(console, filename)
, m_Language(languageCompiler)
, m_WeakSymbols(languageCompiler->grammar())
, m_Dfa(NULL)
, m_Lexer(NULL) {
}

/// \brief Destroys the lexer compiler
lexer_stage::~lexer_stage() {
    // Destroy the DFA if it exists
    if (m_Dfa) {
        delete m_Dfa;
    }

    if (m_Lexer) {
        delete m_Lexer;
    }
}

/// \brief Compiles the lexer
void lexer_stage::compile() {
    // Grab the input
    const lexer_data*       lex             = m_Language->lexer();
    terminal_dictionary*    terminals       = m_Language->terminals();
    const set<int>*         weakSymbolIds   = m_Language->weak_symbols();

    // Reset the weak symbols
    m_WeakSymbols = lr::weak_symbols(m_Language->grammar());

    // Sanity check
    if (!lex || !terminals || !weakSymbolIds) {
        cons().report_error(error(error::sev_bug, filename(), L"BUG_LEXER_BAD_PARAMETERS", L"Missing input for the lexer stage", position(-1, -1, -1)));
        return;
    }

    // Output a staging message
    cons().verbose_stream() << L"  = Constructing final lexer" << endl;

    // Create the ndfa
    typedef lexer_data::item_list item_list;

    dfa::ndfa_regex* stage0 = new ndfa_regex();

    // Iterate through the definition lists for each item
    for (lexer_data::iterator itemList = lex->begin(); itemList != lex->end(); itemList++) {
        // Iterate through the individual definitions for this item
        for (item_list::const_iterator item = itemList->second.begin(); item != itemList->second.end(); item++) {
            // Ignore items without a valid accept action (this is a bug)
            if (!item->accept) {
                cons().report_error(error(error::sev_bug, filename(), L"BUG_MISSING_ACTION", L"Missing action for lexer symbol", position(-1, -1, -1)));
                continue;
            }

            // Add the corresponding items
            switch (item->type) {
                case lexer_item::regex:
                    stage0->set_case_insensitive(item->case_insensitive);
                    stage0->add_regex(0, item->definition, *item->accept);
                    break;

                case lexer_item::literal:
                    stage0->set_case_insensitive(item->case_insensitive);
                    stage0->add_literal(0, item->definition, *item->accept);
                    break;
            }
        }
    }

    // Write out some stats about the ndfa
    cons().verbose_stream() << L"    Number states in the NDFA:              " << stage0->count_states() << endl;

    // Compile the NDFA to a NDFA without overlapping symbol sets
    dfa::ndfa* stage1 = stage0->to_ndfa_with_unique_symbols();

    if (!stage1) {
        cons().report_error(error(error::sev_bug, filename(), L"BUG_DFA_FAILED_TO_CONVERT", L"Failed to create an NDFA with unique symbols", position(-1, -1, -1)));
        return;
    }

    // Write some information about the first stage
    cons().verbose_stream() << L"    Initial number of character sets:       " << stage0->symbols().count_sets() << endl;
    cons().verbose_stream() << L"    Final number of character sets:         " << stage1->symbols().count_sets() << endl;

    delete stage0;
    stage0 = NULL;

    // Compile the NDFA to a DFA
    dfa::ndfa* stage2 = stage1->to_dfa();
    delete stage1;
    stage1 = NULL;

    if (!stage2) {
        cons().report_error(error(error::sev_bug, filename(), L"BUG_DFA_FAILED_TO_COMPILE", L"Failed to compile DFA", position(-1, -1, -1)));
        return;
    }

    // Identify any terminals that are always replaced by other terminals (warning)
    set<int>            unusedTerminals;
    map<int, set<int> > clashes;
    for (int terminalId = 0; terminalId < m_Language->terminals()->count_symbols(); terminalId++) {
        unusedTerminals.insert(terminalId);
    }

    for (int stateId = 0; stateId < stage2->count_states(); stateId++) {
        // Get the actions for this state
        const ndfa::accept_action_list& acceptActions = stage2->actions_for_state(stateId);

        // Ignore empty action sets
        if (acceptActions.empty()) continue;

        // Pick the highest action
        ndfa::accept_action_list::const_iterator action = acceptActions.begin();
        accept_action* highest = *action;

        action++;
        for (; action != acceptActions.end(); action++) {
            if (*highest < **action) {
                clashes[highest->symbol()].insert((*action)->symbol());
                highest = *action;
            } else {
                clashes[(*action)->symbol()].insert(highest->symbol());
            }
        }

        // Remove from the set of unused terminals
        unusedTerminals.erase(highest->symbol());
    }

    // Report warnings for any terminals that are never generated by the lexer
    for (set<int>::const_iterator unusedSymbol = unusedTerminals.begin(); unusedSymbol != unusedTerminals.end(); unusedSymbol++) {
        // Get the position of this terminal
        position        pos     = m_Language->terminal_definition_pos(*unusedSymbol);
        const wstring&  file    = m_Language->terminal_definition_file(*unusedSymbol);

        // Get the name of the terminal
        const wstring& name = m_Language->terminals()->name_for_symbol(*unusedSymbol);

        // Build the warning message
        wstringstream msg;
        msg << L"Lexer symbol can never be generated: " << name;

        cons().report_error(error(error::sev_warning, file, L"SYMBOL_CANNOT_BE_GENERATED", msg.str(), pos));

        // Get the symbols that clash with this one
        set<int>& clashSet = clashes[*unusedSymbol];
        if (!clashSet.empty()) {
            // Write out the symbols that are generated instead
            for (set<int>::iterator clashSymbol = clashSet.begin(); clashSymbol != clashSet.end(); clashSymbol++) {
                wstringstream msg2;
                msg2 << L"'" << name << L"' clashes with: " << m_Language->terminals()->name_for_symbol(*clashSymbol);
                cons().report_error(error(error::sev_detail, m_Language->terminal_definition_file(*clashSymbol), L"SYMBOL_CLASHES_WITH", msg2.str(), m_Language->terminal_definition_pos(*clashSymbol)));
            }
        }
    }

    // TODO: also identify any terminals that clash with terminals at the same level (warning)

    // Build up the weak symbols set if there are any
    if (weakSymbolIds->size() > 0) {
        // Build up the weak symbol set as a series of items
        item_set weakSymSet(m_Language->grammar());

        // Count how many symbols there were initially
        int initialSymCount = terminals->count_symbols();

        // Iterate through the symbol IDs
        for (set<int>::const_iterator weakSymId = weakSymbolIds->begin(); weakSymId != weakSymbolIds->end(); weakSymId++) {
            weakSymSet.insert(item_container(new terminal(*weakSymId), true));
        }

        // Add these symbols to the weak symbols object
        m_WeakSymbols.add_symbols(*stage2, weakSymSet, *terminals);

        // Display how many new terminal symbols were added
        int finalSymCount = terminals->count_symbols();

        cons().verbose_stream() << L"    Number of extra weak symbols:           " << finalSymCount - initialSymCount << endl;
    }

    // Compact the resulting DFA
    cons().verbose_stream() << L"    Number of states in the lexer DFA:      " << stage2->count_states() << endl;
    dfa::ndfa* stage3 = stage2->to_compact_dfa();
    delete stage2;
    stage2 = NULL;

    // Write some information about the DFA we just produced
    cons().verbose_stream() << L"    Number of states in the compacted DFA:  " << stage3->count_states() << endl;

    // Eliminate any unnecessary symbol sets
    dfa::ndfa* stage4 = stage3->to_ndfa_with_merged_symbols();
    delete stage3;
    stage3 = NULL;

    // Write some information about the DFA we just produced
    cons().verbose_stream() << L"    Number of symbols in the compacted DFA: " << stage4->symbols().count_sets() << endl;

    m_Dfa = stage4;

    // Build the final lexer
    m_Lexer = new lexer(*m_Dfa);

    // Write some parting words
    // (Well, this is really kibibytes but I can't take blibblebytes seriously as a unit of measurement)
    cons().verbose_stream() << L"    Approximate size of final lexer:        " << (m_Lexer->size() + 512) / 1024 << L" kilobytes" << endl;
}
<|endoftext|>


<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

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

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

You should have received a copy of the
GNU Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/

#include <string>
#include <stdexcept>
#include <boost/algorithm/string/predicate.hpp> //For iequals()
#include <bh.h>
#include "bh_fuse.h"

using namespace std;

namespace bohrium {

/* The possible fuse models */
enum fuse_model
{
/* The broadest possible model. I.e. a SIMD machine can
 * theoretically execute the two instructions in a single operation,
 * thus accepts broadcast, reduction, extension methods, etc. */
    BROADEST,

/* A very simple mode that only fuses same shaped arrays thus no
 * broadcast, reduction, extension methods, etc. */
    SAME_SHAPE,

/* The sentinel */
    NONE
};

/* The default fuse model */
static const fuse_model default_fuse_model = BROADEST;

/* The current selected fuse model */
static fuse_model selected_fuse_model = NONE;

/************************************************************************/
/*************** Specific fuse model implementations ********************/
/************************************************************************/

static bool fuse_broadest(const bh_instruction *a, const bh_instruction *b)
{
    if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
        return true;

    const int a_nop = bh_operands(a->opcode);
    for(int i=0; i<a_nop; ++i)
    {
        if(not bh_view_disjoint(&b->operand[0], &a->operand[i])
           && not bh_view_aligned(&b->operand[0], &a->operand[i]))
            return false;
    }
    const int b_nop = bh_operands(b->opcode);
    for(int i=0; i<b_nop; ++i)
    {
        if(not bh_view_disjoint(&a->operand[0], &b->operand[i])
           && not bh_view_aligned(&a->operand[0], &b->operand[i]))
            return false;
    }
    return true;
}

static bool fuse_same_shape(const bh_instruction *a, const bh_instruction *b)
{
    if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
        return true;

    if(!bh_opcode_is_elementwise(a->opcode) || !bh_opcode_is_elementwise(b->opcode))
        return false;

    const int a_nop = bh_operands(a->opcode);
    for(int i=0; i<a_nop; ++i)
    {
        if(not bh_view_disjoint(&b->operand[0], &a->operand[i])
           && not bh_view_aligned_and_same_shape(&b->operand[0], &a->operand[i]))
            return false;
    }
    const int b_nop = bh_operands(b->opcode);
    for(int i=0; i<b_nop; ++i)
    {
        if(not bh_view_disjoint(&a->operand[0], &b->operand[i])
           && not bh_view_aligned_and_same_shape(&a->operand[0], &b->operand[i]))
            return false;
    }
    return true;
}

/************************************************************************/
/*************** The public interface implementation ********************/
/************************************************************************/

/* Get the selected fuse model by reading the environment
 * variable 'BH_FUSE_MODEL' */
static fuse_model get_selected_fuse_model()
{
    using namespace boost;

    //Check enviroment variable
    const char *env = getenv("BH_FUSE_MODEL");
    if(env != NULL)
    {
        string e(env);
        if(iequals(e, string("broadest")))
        {
            cout << "[FUSE] info: selected fuse model: 'BROADEST'" << endl;
            return BROADEST;
        }
        else if(iequals(e, string("same_shape")))
        {
            cout << "[FUSE] info: selected fuse model: 'SAME_SHAPE'" << endl;
            return SAME_SHAPE;
        }
        else
        {
            cerr << "[FUSE] WARNING: unknown fuse model: '" << e;
            cerr << "', using the default model instead" << endl;
        }
    }
    cout << "[FUSE] info: selected fuse model: 'BROADEST'" << endl;
    return default_fuse_model;
}

/* Determines whether it is legal to fuse two instructions into one
 * kernel using the 'selected_fuse_model'.
 *
 * @a The first instruction
 * @b The second instruction
 * @return The boolean answer
 */
bool check_fusible(const bh_instruction *a, const bh_instruction *b)
{
    switch(selected_fuse_model)
    {
        case NONE:
            selected_fuse_model = get_selected_fuse_model();
            return check_fusible(a, b);
        case BROADEST:
            return fuse_broadest(a,b);
        case SAME_SHAPE:
            return fuse_same_shape(a,b);
        default:
            throw runtime_error("No fuse module is selected!");
    }
}

} //namespace bohrium
<commit_msg>core-fuse: Commented out verbose notifying about selected fuser.<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

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

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

You should have received a copy of the
GNU Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/

#include <string>
#include <stdexcept>
#include <boost/algorithm/string/predicate.hpp> //For iequals()
#include <bh.h>
#include "bh_fuse.h"

using namespace std;

namespace bohrium {

/* The possible fuse models */
enum fuse_model
{
/* The broadest possible model. I.e. a SIMD machine can
 * theoretically execute the two instructions in a single operation,
 * thus accepts broadcast, reduction, extension methods, etc. */
    BROADEST,

/* A very simple mode that only fuses same shaped arrays thus no
 * broadcast, reduction, extension methods, etc. */
    SAME_SHAPE,

/* The sentinel */
    NONE
};

/* The default fuse model */
static const fuse_model default_fuse_model = BROADEST;

/* The current selected fuse model */
static fuse_model selected_fuse_model = NONE;

/************************************************************************/
/*************** Specific fuse model implementations ********************/
/************************************************************************/

static bool fuse_broadest(const bh_instruction *a, const bh_instruction *b)
{
    if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
        return true;

    const int a_nop = bh_operands(a->opcode);
    for(int i=0; i<a_nop; ++i)
    {
        if(not bh_view_disjoint(&b->operand[0], &a->operand[i])
           && not bh_view_aligned(&b->operand[0], &a->operand[i]))
            return false;
    }
    const int b_nop = bh_operands(b->opcode);
    for(int i=0; i<b_nop; ++i)
    {
        if(not bh_view_disjoint(&a->operand[0], &b->operand[i])
           && not bh_view_aligned(&a->operand[0], &b->operand[i]))
            return false;
    }
    return true;
}

static bool fuse_same_shape(const bh_instruction *a, const bh_instruction *b)
{
    if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
        return true;

    if(!bh_opcode_is_elementwise(a->opcode) || !bh_opcode_is_elementwise(b->opcode))
        return false;

    const int a_nop = bh_operands(a->opcode);
    for(int i=0; i<a_nop; ++i)
    {
        if(not bh_view_disjoint(&b->operand[0], &a->operand[i])
           && not bh_view_aligned_and_same_shape(&b->operand[0], &a->operand[i]))
            return false;
    }
    const int b_nop = bh_operands(b->opcode);
    for(int i=0; i<b_nop; ++i)
    {
        if(not bh_view_disjoint(&a->operand[0], &b->operand[i])
           && not bh_view_aligned_and_same_shape(&a->operand[0], &b->operand[i]))
            return false;
    }
    return true;
}

/************************************************************************/
/*************** The public interface implementation ********************/
/************************************************************************/

/* Get the selected fuse model by reading the environment
 * variable 'BH_FUSE_MODEL' */
static fuse_model get_selected_fuse_model()
{
    using namespace boost;

    //Check enviroment variable
    const char *env = getenv("BH_FUSE_MODEL");
    if(env != NULL)
    {
        string e(env);
        if(iequals(e, string("broadest")))
        {
            //cout << "[FUSE] info: selected fuse model: 'BROADEST'" << endl;
            return BROADEST;
        }
        else if(iequals(e, string("same_shape")))
        {
            //cout << "[FUSE] info: selected fuse model: 'SAME_SHAPE'" << endl;
            return SAME_SHAPE;
        }
        else
        {
            cerr << "[FUSE] WARNING: unknown fuse model: '" << e;
            cerr << "', using the default model instead" << endl;
        }
    }
    //cout << "[FUSE] info: selected fuse model: 'BROADEST'" << endl;
    return default_fuse_model;
}

/* Determines whether it is legal to fuse two instructions into one
 * kernel using the 'selected_fuse_model'.
 *
 * @a The first instruction
 * @b The second instruction
 * @return The boolean answer
 */
bool check_fusible(const bh_instruction *a, const bh_instruction *b)
{
    switch(selected_fuse_model)
    {
        case NONE:
            selected_fuse_model = get_selected_fuse_model();
            return check_fusible(a, b);
        case BROADEST:
            return fuse_broadest(a,b);
        case SAME_SHAPE:
            return fuse_same_shape(a,b);
        default:
            throw runtime_error("No fuse module is selected!");
    }
}

} //namespace bohrium
<|endoftext|>


<commit_before>#include "unit_tests.h"
#include "universal_crc.h"

//------------- tests for CRC_Type_helper -------------

int test_crc_type_helper_uint8(struct test_info_t  *test_info)
{

    TEST_INIT;

    if(
        sizeof(CRC_Type_helper< (1-1)/8 >::value_type) != sizeof(uint8_t) ||
        sizeof(CRC_Type_helper< (2-1)/8 >::value_type) != sizeof(uint8_t) ||
        sizeof(CRC_Type_helper< (3-1)/8 >::value_type) != sizeof(uint8_t) ||
        sizeof(CRC_Type_helper< (4-1)/8 >::value_type) != sizeof(uint8_t) ||
        sizeof(CRC_Type_helper< (5-1)/8 >::value_type) != sizeof(uint8_t) ||
        sizeof(CRC_Type_helper< (6-1)/8 >::value_type) != sizeof(uint8_t) ||
        sizeof(CRC_Type_helper< (7-1)/8 >::value_type) != sizeof(uint8_t) ||
        sizeof(CRC_Type_helper< (8-1)/8 >::value_type) != sizeof(uint8_t)
      )
        return TEST_BROKEN;

    return TEST_PASSED;
}

int test_crc_type_helper_uint16(struct test_info_t  *test_info)
{

    TEST_INIT;

    if(
        sizeof(CRC_Type_helper< (9 -1)/8 >::value_type) != sizeof(uint16_t) ||
        sizeof(CRC_Type_helper< (10-1)/8 >::value_type) != sizeof(uint16_t) ||
        sizeof(CRC_Type_helper< (11-1)/8 >::value_type) != sizeof(uint16_t) ||
        sizeof(CRC_Type_helper< (12-1)/8 >::value_type) != sizeof(uint16_t) ||
        sizeof(CRC_Type_helper< (13-1)/8 >::value_type) != sizeof(uint16_t) ||
        sizeof(CRC_Type_helper< (14-1)/8 >::value_type) != sizeof(uint16_t) ||
        sizeof(CRC_Type_helper< (15-1)/8 >::value_type) != sizeof(uint16_t) ||
        sizeof(CRC_Type_helper< (16-1)/8 >::value_type) != sizeof(uint16_t)
      )
        return TEST_BROKEN;

    return TEST_PASSED;
}

int test_crc_type_helper_uint32(struct test_info_t  *test_info)
{

    TEST_INIT;

    if(
        sizeof(CRC_Type_helper< (17-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (18-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (19-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (20-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (21-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (22-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (23-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (24-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (25-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (26-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (27-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (28-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (29-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (30-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (31-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (32-1)/8 >::value_type) != sizeof(uint32_t)
      )
        return TEST_BROKEN;

    return TEST_PASSED;
}

int test_crc_type_helper_uint64(struct test_info_t  *test_info)
{

    TEST_INIT;

    //Template CRC_Type_helper default is uint64_t
    if( sizeof(CRC_Type_helper<100>::value_type) != sizeof(uint64_t) )
        return TEST_BROKEN;

    return TEST_PASSED;
}

//------------- tests for Universal_CRC methods -------------

int test_universal_crc_name(struct test_info_t  *test_info)
{

    TEST_INIT;

    Universal_CRC<1, 0, 0, true, true, 0>  ucrc;

    if( ucrc.name != "" )
        return TEST_BROKEN;

    return TEST_PASSED;
}

int test_universal_crc_name_2(struct test_info_t  *test_info)
{

    TEST_INIT;

    const char* name = "some_name";

    Universal_CRC<1, 0, 0, true, true, 0>  ucrc(name);

    if( ucrc.name != name )
        return TEST_BROKEN;

    return TEST_PASSED;
}

int test_universal_crc_get_bits(struct test_info_t  *test_info)
{

    TEST_INIT;

    Universal_CRC<1, 0, 0, true, true, 0>  ucrc_1;

    if( ucrc_1.get_bits() != 1 )
        return TEST_BROKEN;

    return TEST_PASSED;
}

ptest_func tests[] =
{

    //CRC_Type_Helper
    test_crc_type_helper_uint8,
    test_crc_type_helper_uint16,
    test_crc_type_helper_uint32,
    test_crc_type_helper_uint64,

    //Universal_CRC methods
    test_universal_crc_name,
    test_universal_crc_name_2,

    test_universal_crc_get_bits
};

int main(void)
{

    RUN_TESTS(tests);

    return 0;
}
<commit_msg>add test for get_poly()<commit_after>#include "unit_tests.h"
#include "universal_crc.h"

//------------- tests for CRC_Type_helper -------------

int test_crc_type_helper_uint8(struct test_info_t  *test_info)
{

    TEST_INIT;

    if(
        sizeof(CRC_Type_helper< (1-1)/8 >::value_type) != sizeof(uint8_t) ||
        sizeof(CRC_Type_helper< (2-1)/8 >::value_type) != sizeof(uint8_t) ||
        sizeof(CRC_Type_helper< (3-1)/8 >::value_type) != sizeof(uint8_t) ||
        sizeof(CRC_Type_helper< (4-1)/8 >::value_type) != sizeof(uint8_t) ||
        sizeof(CRC_Type_helper< (5-1)/8 >::value_type) != sizeof(uint8_t) ||
        sizeof(CRC_Type_helper< (6-1)/8 >::value_type) != sizeof(uint8_t) ||
        sizeof(CRC_Type_helper< (7-1)/8 >::value_type) != sizeof(uint8_t) ||
        sizeof(CRC_Type_helper< (8-1)/8 >::value_type) != sizeof(uint8_t)
      )
        return TEST_BROKEN;

    return TEST_PASSED;
}

int test_crc_type_helper_uint16(struct test_info_t  *test_info)
{

    TEST_INIT;

    if(
        sizeof(CRC_Type_helper< (9 -1)/8 >::value_type) != sizeof(uint16_t) ||
        sizeof(CRC_Type_helper< (10-1)/8 >::value_type) != sizeof(uint16_t) ||
        sizeof(CRC_Type_helper< (11-1)/8 >::value_type) != sizeof(uint16_t) ||
        sizeof(CRC_Type_helper< (12-1)/8 >::value_type) != sizeof(uint16_t) ||
        sizeof(CRC_Type_helper< (13-1)/8 >::value_type) != sizeof(uint16_t) ||
        sizeof(CRC_Type_helper< (14-1)/8 >::value_type) != sizeof(uint16_t) ||
        sizeof(CRC_Type_helper< (15-1)/8 >::value_type) != sizeof(uint16_t) ||
        sizeof(CRC_Type_helper< (16-1)/8 >::value_type) != sizeof(uint16_t)
      )
        return TEST_BROKEN;

    return TEST_PASSED;
}

int test_crc_type_helper_uint32(struct test_info_t  *test_info)
{

    TEST_INIT;

    if(
        sizeof(CRC_Type_helper< (17-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (18-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (19-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (20-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (21-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (22-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (23-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (24-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (25-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (26-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (27-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (28-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (29-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (30-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (31-1)/8 >::value_type) != sizeof(uint32_t) ||
        sizeof(CRC_Type_helper< (32-1)/8 >::value_type) != sizeof(uint32_t)
      )
        return TEST_BROKEN;

    return TEST_PASSED;
}

int test_crc_type_helper_uint64(struct test_info_t  *test_info)
{

    TEST_INIT;

    //Template CRC_Type_helper default is uint64_t
    if( sizeof(CRC_Type_helper<100>::value_type) != sizeof(uint64_t) )
        return TEST_BROKEN;

    return TEST_PASSED;
}

//------------- tests for Universal_CRC methods -------------

int test_universal_crc_name(struct test_info_t  *test_info)
{

    TEST_INIT;

    Universal_CRC<1, 0, 0, true, true, 0>  ucrc;

    if( ucrc.name != "" )
        return TEST_BROKEN;

    return TEST_PASSED;
}

int test_universal_crc_name_2(struct test_info_t  *test_info)
{

    TEST_INIT;

    const char* name = "some_name";

    Universal_CRC<1, 0, 0, true, true, 0>  ucrc(name);

    if( ucrc.name != name )
        return TEST_BROKEN;

    return TEST_PASSED;
}

int test_universal_crc_get_bits(struct test_info_t  *test_info)
{

    TEST_INIT;

    Universal_CRC<1, 0, 0, true, true, 0>  ucrc_1;

    if( ucrc_1.get_bits() != 1 )
        return TEST_BROKEN;

    return TEST_PASSED;
}

int test_universal_crc_get_poly(struct test_info_t  *test_info)
{

    TEST_INIT;

    Universal_CRC<16, 1234, 0, true, true, 0>  ucrc;

    if( ucrc.get_poly() != 1234 )
        return TEST_BROKEN;

    return TEST_PASSED;
}

ptest_func tests[] =
{

    //CRC_Type_Helper
    test_crc_type_helper_uint8,
    test_crc_type_helper_uint16,
    test_crc_type_helper_uint32,
    test_crc_type_helper_uint64,

    //Universal_CRC methods
    test_universal_crc_name,
    test_universal_crc_name_2,

    test_universal_crc_get_bits,
    test_universal_crc_get_poly
};

int main(void)
{

    RUN_TESTS(tests);

    return 0;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(int argc, char* argv[])
{
	int sum = 0;
	int i = 0;

	for (i; i < 1000; i++)
	{
		if (i % 3 == 0 || i % 5 == 0)
		{
			sum += i;
		}
	}

	printf("%d\n", sum);

	return 0;
}

<commit_msg>Fix warnings<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(int argc, char* argv[])
{
	int sum = 0;
	int i;

	for (i = 0; i < 1000; i++)
	{
		if (i % 3 == 0 || i % 5 == 0)
		{
			sum += i;
		}
	}

	printf("%d\n", sum);

	return 0;
}

<|endoftext|>


<commit_before>#include <unistd.h>
#include <sys/time.h>
#include <cstring>
#include "sess.h"

IUINT32 iclock();

int main() {
    struct timeval time;
    gettimeofday(&time, NULL);
    srand((time.tv_sec * 1000) + (time.tv_usec / 1000));

    UDPSession *sess = UDPSession::DialWithOptions("127.0.0.1", 9999, 2,2);
    sess->NoDelay(1, 20, 2, 1);
    sess->WndSize(128, 128);
    sess->SetMtu(1400);
    sess->SetStreamMode(true);
    sess->SetDSCP(46);

    assert(sess != nullptr);
    ssize_t nsent = 0;
    ssize_t nrecv = 0;
    char *buf = (char *) malloc(128);

    for (int i = 0; i < 10; i++) {
        sprintf(buf, "message:%d", i);
        auto sz = strlen(buf);
        sess->Write(buf, sz);
        sess->Update(iclock());
        memset(buf, 0, 128);
        ssize_t n = 0;
        do {
            n = sess->Read(buf, 128);
            if (n > 0) { printf("%s\n", buf); }
            usleep(33000);
            sess->Update(iclock());
        } while(n==0);
    }

    UDPSession::Destroy(sess);
}

void
itimeofday(long *sec, long *usec) {
    struct timeval time;
    gettimeofday(&time, NULL);
    if (sec) *sec = time.tv_sec;
    if (usec) *usec = time.tv_usec;
}

IUINT64 iclock64(void) {
    long s, u;
    IUINT64 value;
    itimeofday(&s, &u);
    value = ((IUINT64) s) * 1000 + (u / 1000);
    return value;
}

IUINT32 iclock() {
    return (IUINT32) (iclock64() & 0xfffffffful);
}

<commit_msg>upd import<commit_after>#include <unistd.h>
#include <sys/time.h>
#include <cstring>
#include <cstdio>
#include "sess.h"

IUINT32 iclock();

int main() {
    struct timeval time;
    gettimeofday(&time, NULL);
    srand((time.tv_sec * 1000) + (time.tv_usec / 1000));

    UDPSession *sess = UDPSession::DialWithOptions("127.0.0.1", 9999, 2,2);
    sess->NoDelay(1, 20, 2, 1);
    sess->WndSize(128, 128);
    sess->SetMtu(1400);
    sess->SetStreamMode(true);
    sess->SetDSCP(46);

    assert(sess != nullptr);
    ssize_t nsent = 0;
    ssize_t nrecv = 0;
    char *buf = (char *) malloc(128);

    for (int i = 0; i < 10; i++) {
        sprintf(buf, "message:%d", i);
        auto sz = strlen(buf);
        sess->Write(buf, sz);
        sess->Update(iclock());
        memset(buf, 0, 128);
        ssize_t n = 0;
        do {
            n = sess->Read(buf, 128);
            if (n > 0) { printf("%s\n", buf); }
            usleep(33000);
            sess->Update(iclock());
        } while(n==0);
    }

    UDPSession::Destroy(sess);
}

void
itimeofday(long *sec, long *usec) {
    struct timeval time;
    gettimeofday(&time, NULL);
    if (sec) *sec = time.tv_sec;
    if (usec) *usec = time.tv_usec;
}

IUINT64 iclock64(void) {
    long s, u;
    IUINT64 value;
    itimeofday(&s, &u);
    value = ((IUINT64) s) * 1000 + (u / 1000);
    return value;
}

IUINT32 iclock() {
    return (IUINT32) (iclock64() & 0xfffffffful);
}

<|endoftext|>