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

#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#ifndef _STATUS_HXX //autogen
#include <vcl/status.hxx>
#endif
#ifndef _MENU_HXX //autogen
#include <vcl/menu.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#include <tools/urlobj.hxx>
#pragma hdrstop

#include "dialogs.hrc"

#include "zoomctrl.hxx"
//CHINA001 #include "zoom.hxx"
#include "zoomitem.hxx"
#include "stbctrls.h"
#include "dialmgr.hxx"

SFX_IMPL_STATUSBAR_CONTROL(SvxZoomStatusBarControl,SvxZoomItem);

// class ZoomPopup_Impl --------------------------------------------------

class ZoomPopup_Impl : public PopupMenu
{
public:
    ZoomPopup_Impl( USHORT nZ, USHORT nValueSet );

    USHORT          GetZoom() const { return nZoom; }
    USHORT          GetCurId() const { return nCurId; }

private:
    USHORT          nZoom;
    USHORT          nCurId;

    virtual void    Select();
};

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

ZoomPopup_Impl::ZoomPopup_Impl( USHORT nZ, USHORT nValueSet )

:   PopupMenu( ResId( RID_SVXMNU_ZOOM, DIALOG_MGR() ) ),

    nZoom( nZ )
{
    static USHORT aTable[] =
    {
        SVX_ZOOM_ENABLE_50,         ZOOM_50,
        SVX_ZOOM_ENABLE_100,        ZOOM_100,
        SVX_ZOOM_ENABLE_150,        ZOOM_150,
        SVX_ZOOM_ENABLE_200,        ZOOM_200,
        SVX_ZOOM_ENABLE_OPTIMAL,    ZOOM_OPTIMAL,
        SVX_ZOOM_ENABLE_WHOLEPAGE,  ZOOM_WHOLE_PAGE,
        SVX_ZOOM_ENABLE_PAGEWIDTH,  ZOOM_PAGE_WIDTH
    };

    for ( USHORT nPos = 0; nPos < sizeof(aTable) / sizeof(USHORT); nPos += 2 )
        if ( ( aTable[nPos] != ( aTable[nPos] & nValueSet ) ) )
            EnableItem( aTable[nPos+1], FALSE );
}

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

void ZoomPopup_Impl::Select()
{
    nCurId = GetCurItemId();

    switch ( nCurId )
    {
        case ZOOM_200:          nZoom = 200; break;
        case ZOOM_150:          nZoom = 150; break;
        case ZOOM_100:          nZoom = 100; break;
        case ZOOM_75:           nZoom =  75; break;
        case ZOOM_50:           nZoom =  50; break;

        case ZOOM_OPTIMAL:
        case ZOOM_PAGE_WIDTH:
        case ZOOM_WHOLE_PAGE:   nZoom = 0; break;

    }
}

// class SvxZoomStatusBarControl ------------------------------------------

SvxZoomStatusBarControl::SvxZoomStatusBarControl( USHORT nSlotId,
                                                  USHORT nId,
                                                  StatusBar& rStb ) :

    SfxStatusBarControl( nSlotId, nId, rStb ),
    nZoom( 100 ),
    nValueSet( SVX_ZOOM_ENABLE_ALL )
{
}

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

void SvxZoomStatusBarControl::StateChanged( USHORT nSID, SfxItemState eState,
                                            const SfxPoolItem* pState )
{
    if( SFX_ITEM_AVAILABLE != eState )
    {
        GetStatusBar().SetItemText( GetId(), String() );
        nValueSet = 0;
    }
    else if ( pState->ISA( SfxUInt16Item) )
    {
        const SfxUInt16Item* pItem = (const SfxUInt16Item*)pState;
        nZoom = pItem->GetValue();
        String aStr( String::CreateFromInt32(nZoom) );
        aStr += '%';
        GetStatusBar().SetItemText( GetId(), aStr );

        if ( pState->ISA(SvxZoomItem) )
        {
            nValueSet = ((const SvxZoomItem*)pState)->GetValueSet();
            SvxZoomType eType = ((const SvxZoomItem*)pState)->GetType();

/*!!!
            switch ( eType )
            {
                case SVX_ZOOM_OPTIMAL:
                    GetStatusBar().SetItemText( GetId(), "Opt." );
                    break;
                case SVX_ZOOM_WHOLEPAGE:
                    GetStatusBar().SetItemText( GetId(), "Page" );
                    break;
                case SVX_ZOOM_PAGEWIDTH:
                    GetStatusBar().SetItemText( GetId(), "Width" );
                    break;
            }
*/
        }
        else
        {
            DBG_WARNING( "use SfxZoomItem for SID_ATTR_ZOOM" );
            nValueSet = SVX_ZOOM_ENABLE_ALL;
        }
    }
}

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

void SvxZoomStatusBarControl::Paint( const UserDrawEvent& rUsrEvt )
{
    String aStr( String::CreateFromInt32( nZoom ));
    aStr += '%';
    GetStatusBar().SetItemText( GetId(), aStr );
}

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

void SvxZoomStatusBarControl::Command( const CommandEvent& rCEvt )
{
    if ( COMMAND_CONTEXTMENU & rCEvt.GetCommand() && 0 != nValueSet )
    {
        CaptureMouse();
        ZoomPopup_Impl aPop( nZoom, nValueSet );
        StatusBar& rStatusbar = GetStatusBar();

        if ( aPop.Execute( &rStatusbar, rCEvt.GetMousePosPixel() ) && ( nZoom != aPop.GetZoom() || !nZoom ) )
        {
            nZoom = aPop.GetZoom();
            SvxZoomItem aZoom( SVX_ZOOM_PERCENT, nZoom, GetId() );

            USHORT nId = aPop.GetCurId();

            if ( ZOOM_OPTIMAL == nId )
                aZoom.SetType( SVX_ZOOM_OPTIMAL );
            else if ( ZOOM_PAGE_WIDTH == nId )
                aZoom.SetType( SVX_ZOOM_PAGEWIDTH );
            else if ( ZOOM_WHOLE_PAGE == nId )
                aZoom.SetType( SVX_ZOOM_WHOLEPAGE );

            ::com::sun::star::uno::Any a;
            INetURLObject aObj( m_aCommandURL );

            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aArgs( 1 );
            aArgs[0].Name  = aObj.GetURLPath();
            aZoom.QueryValue( a );
            aArgs[0].Value = a;

            execute( aArgs );
        }
        ReleaseMouse();
    }
    else
        SfxStatusBarControl::Command( rCEvt );
}

ULONG SvxZoomStatusBarControl::GetDefItemWidth(const StatusBar& rStb)
{
    long nWidth1 =  rStb.GetTextWidth(String::CreateFromAscii("XXXXX%"));
    return nWidth1;
}

<commit_msg>INTEGRATION: CWS warnings01 (1.5.220); FILE MERGED 2006/04/20 14:50:01 cl 1.5.220.1: warning free code changes<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: zoomctrl.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 16:32:52 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#ifndef _STATUS_HXX //autogen
#include <vcl/status.hxx>
#endif
#ifndef _MENU_HXX //autogen
#include <vcl/menu.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#include <tools/urlobj.hxx>

#include "dialogs.hrc"

#include "zoomctrl.hxx"
//CHINA001 #include "zoom.hxx"
#include "zoomitem.hxx"
#include "stbctrls.h"
#include "dialmgr.hxx"

SFX_IMPL_STATUSBAR_CONTROL(SvxZoomStatusBarControl,SvxZoomItem);

// class ZoomPopup_Impl --------------------------------------------------

class ZoomPopup_Impl : public PopupMenu
{
public:
    ZoomPopup_Impl( USHORT nZ, USHORT nValueSet );

    USHORT          GetZoom() const { return nZoom; }
    USHORT          GetCurId() const { return nCurId; }

private:
    USHORT          nZoom;
    USHORT          nCurId;

    virtual void    Select();
};

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

ZoomPopup_Impl::ZoomPopup_Impl( USHORT nZ, USHORT nValueSet )

:   PopupMenu( ResId( RID_SVXMNU_ZOOM, DIALOG_MGR() ) ),

    nZoom( nZ )
{
    static USHORT aTable[] =
    {
        SVX_ZOOM_ENABLE_50,         ZOOM_50,
        SVX_ZOOM_ENABLE_100,        ZOOM_100,
        SVX_ZOOM_ENABLE_150,        ZOOM_150,
        SVX_ZOOM_ENABLE_200,        ZOOM_200,
        SVX_ZOOM_ENABLE_OPTIMAL,    ZOOM_OPTIMAL,
        SVX_ZOOM_ENABLE_WHOLEPAGE,  ZOOM_WHOLE_PAGE,
        SVX_ZOOM_ENABLE_PAGEWIDTH,  ZOOM_PAGE_WIDTH
    };

    for ( USHORT nPos = 0; nPos < sizeof(aTable) / sizeof(USHORT); nPos += 2 )
        if ( ( aTable[nPos] != ( aTable[nPos] & nValueSet ) ) )
            EnableItem( aTable[nPos+1], FALSE );
}

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

void ZoomPopup_Impl::Select()
{
    nCurId = GetCurItemId();

    switch ( nCurId )
    {
        case ZOOM_200:          nZoom = 200; break;
        case ZOOM_150:          nZoom = 150; break;
        case ZOOM_100:          nZoom = 100; break;
        case ZOOM_75:           nZoom =  75; break;
        case ZOOM_50:           nZoom =  50; break;

        case ZOOM_OPTIMAL:
        case ZOOM_PAGE_WIDTH:
        case ZOOM_WHOLE_PAGE:   nZoom = 0; break;

    }
}

// class SvxZoomStatusBarControl ------------------------------------------

SvxZoomStatusBarControl::SvxZoomStatusBarControl( USHORT nSlotId,
                                                  USHORT nId,
                                                  StatusBar& rStb ) :

    SfxStatusBarControl( nSlotId, nId, rStb ),
    nZoom( 100 ),
    nValueSet( SVX_ZOOM_ENABLE_ALL )
{
}

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

void SvxZoomStatusBarControl::StateChanged( USHORT nSID, SfxItemState eState,
                                            const SfxPoolItem* pState )
{
    if( SFX_ITEM_AVAILABLE != eState )
    {
        GetStatusBar().SetItemText( GetId(), String() );
        nValueSet = 0;
    }
    else if ( pState->ISA( SfxUInt16Item) )
    {
        const SfxUInt16Item* pItem = (const SfxUInt16Item*)pState;
        nZoom = pItem->GetValue();
        String aStr( String::CreateFromInt32(nZoom) );
        aStr += '%';
        GetStatusBar().SetItemText( GetId(), aStr );

        if ( pState->ISA(SvxZoomItem) )
        {
            nValueSet = ((const SvxZoomItem*)pState)->GetValueSet();
            SvxZoomType eType = ((const SvxZoomItem*)pState)->GetType();

/*!!!
            switch ( eType )
            {
                case SVX_ZOOM_OPTIMAL:
                    GetStatusBar().SetItemText( GetId(), "Opt." );
                    break;
                case SVX_ZOOM_WHOLEPAGE:
                    GetStatusBar().SetItemText( GetId(), "Page" );
                    break;
                case SVX_ZOOM_PAGEWIDTH:
                    GetStatusBar().SetItemText( GetId(), "Width" );
                    break;
            }
*/
        }
        else
        {
            DBG_WARNING( "use SfxZoomItem for SID_ATTR_ZOOM" );
            nValueSet = SVX_ZOOM_ENABLE_ALL;
        }
    }
}

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

void SvxZoomStatusBarControl::Paint( const UserDrawEvent& rUsrEvt )
{
    String aStr( String::CreateFromInt32( nZoom ));
    aStr += '%';
    GetStatusBar().SetItemText( GetId(), aStr );
}

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

void SvxZoomStatusBarControl::Command( const CommandEvent& rCEvt )
{
    if ( COMMAND_CONTEXTMENU & rCEvt.GetCommand() && 0 != nValueSet )
    {
        CaptureMouse();
        ZoomPopup_Impl aPop( nZoom, nValueSet );
        StatusBar& rStatusbar = GetStatusBar();

        if ( aPop.Execute( &rStatusbar, rCEvt.GetMousePosPixel() ) && ( nZoom != aPop.GetZoom() || !nZoom ) )
        {
            nZoom = aPop.GetZoom();
            SvxZoomItem aZoom( SVX_ZOOM_PERCENT, nZoom, GetId() );

            USHORT nId = aPop.GetCurId();

            if ( ZOOM_OPTIMAL == nId )
                aZoom.SetType( SVX_ZOOM_OPTIMAL );
            else if ( ZOOM_PAGE_WIDTH == nId )
                aZoom.SetType( SVX_ZOOM_PAGEWIDTH );
            else if ( ZOOM_WHOLE_PAGE == nId )
                aZoom.SetType( SVX_ZOOM_WHOLEPAGE );

            ::com::sun::star::uno::Any a;
            INetURLObject aObj( m_aCommandURL );

            ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aArgs( 1 );
            aArgs[0].Name  = aObj.GetURLPath();
            aZoom.QueryValue( a );
            aArgs[0].Value = a;

            execute( aArgs );
        }
        ReleaseMouse();
    }
    else
        SfxStatusBarControl::Command( rCEvt );
}

ULONG SvxZoomStatusBarControl::GetDefItemWidth(const StatusBar& rStb)
{
    long nWidth1 =  rStb.GetTextWidth(String::CreateFromAscii("XXXXX%"));
    return nWidth1;
}

<|endoftext|>


<commit_before>/*
 * wlan Ljubljana firmware flasher
 */
#include "gui/wizard.h"

FlashWizard::FlashWizard()
  : QWizard()
{
  resize(640, 480);

  // Initialize the plan
  m_plan.append("init");
  m_currentStep = m_plan.begin();

  // Connect signals
  connect(this, SIGNAL(currentIdChanged(int)), this, SLOT(slotStepChanged(int)));
}

void FlashWizard::addPage(Step *page)
{
  int pageId = QWizard::addPage(page);
  m_steps[page->getId()] = pageId;

  // Ensure that we start with init
  if (page->getId() == "init")
    setStartId(pageId);
}

int FlashWizard::nextId() const
{
  if (m_currentStep + 1 == m_plan.end())
    return -1;

  return m_steps[*(m_currentStep + 1)];
}

Plan *FlashWizard::getPlan() const
{
  return const_cast<Plan*>(&m_plan);
}

void FlashWizard::slotStepChanged(int id)
{
  if (id == m_steps["init"]) {
    // Wizard started
    m_currentStep = m_plan.begin();
  } else if (id == -1) {
    // TODO Wizard aborted
  } else if (id == m_steps[*(m_currentStep + 1)]) {
    // We have moved forward
    m_currentStep++;
  } else if (id == m_steps[*(m_currentStep - 1)]) {
    // We have moved backward
    m_currentStep--;
  }
}

Step::Step(const QString &id)
  : QWizardPage(),
    m_id(id)
{
}

Step::~Step()
{
}

QString Step::getId() const
{
  return m_id;
}

FlashWizard *Step::flashWizard() const
{
  return static_cast<FlashWizard*>(QWizardPage::wizard());
}

Plan *Step::plan() const
{
  return flashWizard()->getPlan();
}

<commit_msg>Detect duplicate step identifiers and abort.<commit_after>/*
 * wlan Ljubljana firmware flasher
 */
#include "gui/wizard.h"

FlashWizard::FlashWizard()
  : QWizard()
{
  resize(640, 480);

  // Initialize the plan
  m_plan.append("init");
  m_currentStep = m_plan.begin();

  // Connect signals
  connect(this, SIGNAL(currentIdChanged(int)), this, SLOT(slotStepChanged(int)));
}

void FlashWizard::addPage(Step *page)
{
  if (m_steps.contains(page->getId()))
    qFatal("Attempted registration of step with duplicate identifier '%s'!", page->getId().toAscii().data());

  int pageId = QWizard::addPage(page);
  m_steps[page->getId()] = pageId;

  // Ensure that we start with init
  if (page->getId() == "init")
    setStartId(pageId);
}

int FlashWizard::nextId() const
{
  if (m_currentStep + 1 == m_plan.end())
    return -1;

  return m_steps[*(m_currentStep + 1)];
}

Plan *FlashWizard::getPlan() const
{
  return const_cast<Plan*>(&m_plan);
}

void FlashWizard::slotStepChanged(int id)
{
  if (id == m_steps["init"]) {
    // Wizard started
    m_currentStep = m_plan.begin();
  } else if (id == -1) {
    // TODO Wizard aborted
  } else if (id == m_steps[*(m_currentStep + 1)]) {
    // We have moved forward
    m_currentStep++;
  } else if (id == m_steps[*(m_currentStep - 1)]) {
    // We have moved backward
    m_currentStep--;
  }
}

Step::Step(const QString &id)
  : QWizardPage(),
    m_id(id)
{
}

Step::~Step()
{
}

QString Step::getId() const
{
  return m_id;
}

FlashWizard *Step::flashWizard() const
{
  return static_cast<FlashWizard*>(QWizardPage::wizard());
}

Plan *Step::plan() const
{
  return flashWizard()->getPlan();
}

<|endoftext|>


<commit_before>#include "CentralWidget.hpp"
#include <iostream>
#include <QMessageBox>

CentralWidget::CentralWidget(QWidget* parent):
    QWidget(parent){
    //sub dialogs
    addEnvdlg = new AddNewEnvDialog();
    changeDataDialog = new ChangeEnvDataDialog();

    connect(changeDataDialog,SIGNAL(changedData()),this,SLOT(update()));
    connect(addEnvdlg,SIGNAL(OKButtonIsPushed(AddNewEnvDialog_d*)),this,SLOT(AddNewEnvDialogIsSet(AddNewEnvDialog_d*)));
    connect(addEnvdlg,SIGNAL(CancelButtonIsPushed()),this,SLOT(setVisibleTrue()));
    currentEnvLabel = new QLabel("Current Environment ");
    currentEnvView = new QLineEdit();
    currentEnvView->setReadOnly(true);
    currentEnvView->setFrame(true);

    this->initEnvironments();
    this->initInformationViewer();
    this->initComboBox(this->mcenvs);
    this->initButtons();
    this->setupUI();
    this->update();
}

void CentralWidget::update(){
    MCEnv* cenv = mcenvs->getCurrentEnv();
    if(cenv == NULL){
        std::cerr<<"MCSwitch can't load current env."<<std::endl;
        exit(1);
    }
    cenv->open();
    currentEnvView->setText(cenv->getName());
    QString c = selectEnvBox->currentText();
    int i = -1;
    selectEnvBox->clear();
    for(int n = 0;n < mcenvs->getNumberOfEnvironments();n++){
      selectEnvBox->addItem(mcenvs->getMCEnv(n)->getName());
      if(mcenvs->getMCEnv(n)->getName() == c){
          i = n;
      }
    }
    if(i != -1){
        selectEnvBox->setCurrentIndex(i);
    }
}

void CentralWidget::initEnvironments(){
    mcenvs = new Environments();
}

void CentralWidget::initButtons(){
    OKButton = new QPushButton("OK");
    connect(OKButton,SIGNAL(clicked()),this,SLOT(OKButtonPushed()));
	AddButton = new QPushButton("Add");
    connect(AddButton,SIGNAL(clicked()),this,SLOT(addNewEnvironment()));
    ChangeDataButton = new QPushButton("Change Data");
    connect(ChangeDataButton,SIGNAL(clicked()),this,SLOT(callChangeEnvDataDialog()));
    ExitButton = new QPushButton("QUIT");
    connect(ExitButton,SIGNAL(clicked()),this,SLOT(ExitButtonPushed()));
}

void CentralWidget::initComboBox(Environments* e_obj){
    selectEnvBox = new QComboBox();
    connect(selectEnvBox,SIGNAL(currentIndexChanged(const QString&)),this,SLOT(selectEnvBoxChanged(const QString&)));
	MCEnv* e = mcenvs->getCurrentEnv();
	e->open();
	int b = 0;
    for(int i = 0;i < e_obj->getNumberOfEnvironments();i++){
        selectEnvBox->addItem(e_obj->getMCEnv(i)->getName());
		if(e_obj->getMCEnv(i)->getName() == e->getName()){
			b = i;
		}
    }
	delete e;
	selectEnvBox->setCurrentIndex(b);
}

void CentralWidget::initInformationViewer(){
    this->mViewer = new QLabel("");

    this->commentViewer = new QTextEdit();
    this->commentViewer->setReadOnly(true);

    this->versionViewer = new QLabel("VERSION ");
}

void CentralWidget::setupUI(){
    QHBoxLayout* currentEnvLayout = new QHBoxLayout();
    currentEnvLayout->addWidget(currentEnvLabel);
    currentEnvLayout->addWidget(currentEnvView);
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget(OKButton);
    buttonLayout->addWidget(ExitButton);

	QHBoxLayout* comboBoxLayout = new QHBoxLayout();
	comboBoxLayout->addWidget(selectEnvBox);
	comboBoxLayout->addWidget(AddButton);

    QVBoxLayout* mainLayout = new QVBoxLayout();
    mainLayout->addLayout(comboBoxLayout);
    mainLayout->addWidget(ChangeDataButton);
    mainLayout->addWidget(versionViewer);
    mainLayout->addWidget(mViewer);
    mainLayout->addWidget(commentViewer);
    mainLayout->addLayout(currentEnvLayout);
    mainLayout->addLayout(buttonLayout);

    setLayout(mainLayout);
}

void CentralWidget::AddNewEnvDialogIsSet(AddNewEnvDialog_d* data){
    Environments::createNewEnvironemnt(data->env_name,data->version,data->comment,data->mod);
    mcenvs->updateEnvData();
    if(data->copyFrom != COPYFROM_SELECT_NOTHING){
        if(!mcenvs->copyEnvContents(data->copyFrom,data->env_name)){
            QMessageBox::critical(this, "ERROR", "Failed to copy environment's contents.");
        }
    }
    emit requestToVisible();
    this->update();
}

void CentralWidget::ExitButtonPushed(){
    //If you want to excuse something before exit,you should write it here.
    emit exitSignal();
}

void CentralWidget::OKButtonPushed(){
    //When OKButton is pushed,this is called.
    if(!mcenvs->changeEnv(selectEnvBox->itemText(selectEnvBox->currentIndex()))){
        std::cerr<<"fail to change environment\n";
    }
    this->update();
}

void CentralWidget::selectEnvBoxChanged(const QString& env_name){
    for(int n = 0;n < mcenvs->getNumberOfEnvironments();n++){
        if(mcenvs->getMCEnv(n)->getName() == env_name){
            MCEnv *e = mcenvs->getMCEnv(n);
            if(e->getMods())
                this->mViewer->setText("Mods are being installed to this environment.");
            else
                this->mViewer->setText("Mods are not being installed to this environment.");
            this->commentViewer->setPlainText(e->getComment());//set commnet viewer's text.
            this->versionViewer->setText("VERSION " + e->getVersion());//set version info.
        }
    }
}

//When AddButton is clicked,this is called.
void CentralWidget::addNewEnvironment(){
    addEnvdlg->show();
    emit requestToInvisible();
}

void CentralWidget::callChangeEnvDataDialog(){
    MCEnv *env;
    for(int n = 0;n < mcenvs->getNumberOfEnvironments();n++){
        if(mcenvs->getMCEnv(n)->getName() == selectEnvBox->itemText(selectEnvBox->currentIndex())){
            env = mcenvs->getMCEnv(n);
            break;
        }
    }
    changeDataDialog->setTarget(env);
    changeDataDialog->setupDialog();
    changeDataDialog->show();
}

<commit_msg>いくつかのエラーメッセージをQMessageBoxで表示するようにしてみた<commit_after>#include "CentralWidget.hpp"
#include <iostream>
#include <QMessageBox>

CentralWidget::CentralWidget(QWidget* parent):
    QWidget(parent){
    //sub dialogs
    addEnvdlg = new AddNewEnvDialog();
    changeDataDialog = new ChangeEnvDataDialog();

    connect(changeDataDialog,SIGNAL(changedData()),this,SLOT(update()));
    connect(addEnvdlg,SIGNAL(OKButtonIsPushed(AddNewEnvDialog_d*)),this,SLOT(AddNewEnvDialogIsSet(AddNewEnvDialog_d*)));
    connect(addEnvdlg,SIGNAL(CancelButtonIsPushed()),this,SLOT(setVisibleTrue()));
    currentEnvLabel = new QLabel("Current Environment ");
    currentEnvView = new QLineEdit();
    currentEnvView->setReadOnly(true);
    currentEnvView->setFrame(true);

    this->initEnvironments();
    this->initInformationViewer();
    this->initComboBox(this->mcenvs);
    this->initButtons();
    this->setupUI();
    this->update();
}

void CentralWidget::update(){
    MCEnv* cenv = mcenvs->getCurrentEnv();
    if(cenv == NULL){
        QMessageBox::critical(this, "ERROR", "MCSwitch cannot load currnet environment.");
        exit(1);
    }
    cenv->open();
    currentEnvView->setText(cenv->getName());
    QString c = selectEnvBox->currentText();
    int i = -1;
    selectEnvBox->clear();
    for(int n = 0;n < mcenvs->getNumberOfEnvironments();n++){
      selectEnvBox->addItem(mcenvs->getMCEnv(n)->getName());
      if(mcenvs->getMCEnv(n)->getName() == c){
          i = n;
      }
    }
    if(i != -1){
        selectEnvBox->setCurrentIndex(i);
    }
}

void CentralWidget::initEnvironments(){
    mcenvs = new Environments();
}

void CentralWidget::initButtons(){
    OKButton = new QPushButton("OK");
    connect(OKButton,SIGNAL(clicked()),this,SLOT(OKButtonPushed()));
	AddButton = new QPushButton("Add");
    connect(AddButton,SIGNAL(clicked()),this,SLOT(addNewEnvironment()));
    ChangeDataButton = new QPushButton("Change Data");
    connect(ChangeDataButton,SIGNAL(clicked()),this,SLOT(callChangeEnvDataDialog()));
    ExitButton = new QPushButton("QUIT");
    connect(ExitButton,SIGNAL(clicked()),this,SLOT(ExitButtonPushed()));
}

void CentralWidget::initComboBox(Environments* e_obj){
    selectEnvBox = new QComboBox();
    connect(selectEnvBox,SIGNAL(currentIndexChanged(const QString&)),this,SLOT(selectEnvBoxChanged(const QString&)));
	MCEnv* e = mcenvs->getCurrentEnv();
	e->open();
	int b = 0;
    for(int i = 0;i < e_obj->getNumberOfEnvironments();i++){
        selectEnvBox->addItem(e_obj->getMCEnv(i)->getName());
		if(e_obj->getMCEnv(i)->getName() == e->getName()){
			b = i;
		}
    }
	delete e;
	selectEnvBox->setCurrentIndex(b);
}

void CentralWidget::initInformationViewer(){
    this->mViewer = new QLabel("");

    this->commentViewer = new QTextEdit();
    this->commentViewer->setReadOnly(true);

    this->versionViewer = new QLabel("VERSION ");
}

void CentralWidget::setupUI(){
    QHBoxLayout* currentEnvLayout = new QHBoxLayout();
    currentEnvLayout->addWidget(currentEnvLabel);
    currentEnvLayout->addWidget(currentEnvView);
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    buttonLayout->addWidget(OKButton);
    buttonLayout->addWidget(ExitButton);

	QHBoxLayout* comboBoxLayout = new QHBoxLayout();
	comboBoxLayout->addWidget(selectEnvBox);
	comboBoxLayout->addWidget(AddButton);

    QVBoxLayout* mainLayout = new QVBoxLayout();
    mainLayout->addLayout(comboBoxLayout);
    mainLayout->addWidget(ChangeDataButton);
    mainLayout->addWidget(versionViewer);
    mainLayout->addWidget(mViewer);
    mainLayout->addWidget(commentViewer);
    mainLayout->addLayout(currentEnvLayout);
    mainLayout->addLayout(buttonLayout);

    setLayout(mainLayout);
}

void CentralWidget::AddNewEnvDialogIsSet(AddNewEnvDialog_d* data){
    Environments::createNewEnvironemnt(data->env_name,data->version,data->comment,data->mod);
    mcenvs->updateEnvData();
    if(data->copyFrom != COPYFROM_SELECT_NOTHING){
        if(!mcenvs->copyEnvContents(data->copyFrom,data->env_name)){
            QMessageBox::critical(this, "ERROR", "Failed to copy environment's contents.");
        }
    }
    emit requestToVisible();
    this->update();
}

void CentralWidget::ExitButtonPushed(){
    //If you want to excuse something before exit,you should write it here.
    emit exitSignal();
}

void CentralWidget::OKButtonPushed(){
    //When OKButton is pushed,this is called.
    if(!mcenvs->changeEnv(selectEnvBox->itemText(selectEnvBox->currentIndex()))){
        QMessageBox::critical(this, "ERROR", "Failed to change environment.");
    }
    this->update();
}

void CentralWidget::selectEnvBoxChanged(const QString& env_name){
    for(int n = 0;n < mcenvs->getNumberOfEnvironments();n++){
        if(mcenvs->getMCEnv(n)->getName() == env_name){
            MCEnv *e = mcenvs->getMCEnv(n);
            if(e->getMods())
                this->mViewer->setText("Mods are being installed to this environment.");
            else
                this->mViewer->setText("Mods are not being installed to this environment.");
            this->commentViewer->setPlainText(e->getComment());//set commnet viewer's text.
            this->versionViewer->setText("VERSION " + e->getVersion());//set version info.
        }
    }
}

//When AddButton is clicked,this is called.
void CentralWidget::addNewEnvironment(){
    addEnvdlg->show();
    emit requestToInvisible();
}

void CentralWidget::callChangeEnvDataDialog(){
    MCEnv *env;
    for(int n = 0;n < mcenvs->getNumberOfEnvironments();n++){
        if(mcenvs->getMCEnv(n)->getName() == selectEnvBox->itemText(selectEnvBox->currentIndex())){
            env = mcenvs->getMCEnv(n);
            break;
        }
    }
    changeDataDialog->setTarget(env);
    changeDataDialog->setupDialog();
    changeDataDialog->show();
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: lboxctrl.cxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: obo $ $Date: 2004-07-06 13:19:31 $
 *
 *  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   _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif
#ifndef _SV_EVENT_HXX
#include <vcl/event.hxx>
#endif
#ifndef _SFXAPP_HXX
#include <sfx2/app.hxx>
#endif
#ifndef _SFXTBXCTRL_HXX
#include <sfx2/tbxctrl.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXDISPATCH_HXX
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXVIEWSH_HXX
#include <sfx2/viewsh.hxx>
#endif
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _STDCTRL_HXX
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SFXSLSTITM_HXX
#include <svtools/slstitm.hxx>
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif

#ifndef _SVX_DIALMGR_HXX
#include <dialmgr.hxx>
#endif
#ifndef _SVX_LBOXCTRL_HXX_
#include <lboxctrl.hxx>
#endif
#ifndef _VCL_MNEMONIC_HXX_
#include <vcl/mnemonic.hxx>
#endif
#include <tools/urlobj.hxx>

#include <svxids.hrc>
#include <dialogs.hrc>

#include "lboxctrl.hrc"

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;

class SvxPopupWindowListBox;

/////////////////////////////////////////////////////////////////

class SvxPopupWindowListBox : public SfxPopupWindow
{
    FixedInfo       aInfo;
    ListBox *       pListBox;
    ToolBox &       rToolBox;
    BOOL            bUserSel;
    USHORT          nTbxId;
    rtl::OUString   maCommandURL;
    // disallow copy-constructor and assignment-operator

    SvxPopupWindowListBox(const int& );
    SvxPopupWindowListBox & operator = (const int& );

//  SvxPopupWindowListBox( USHORT nSlotId, ToolBox& rTbx, USHORT nTbxItemId );

public:
    SvxPopupWindowListBox( USHORT nSlotId, const rtl::OUString& rCommandURL, USHORT nTbxId, ToolBox& rTbx );
    virtual ~SvxPopupWindowListBox();

    // SfxPopupWindow
    virtual SfxPopupWindow *    Clone() const;
    virtual void                PopupModeEnd();
    virtual void                StateChanged( USHORT nSID, SfxItemState eState,
                                              const SfxPoolItem* pState );

    void                        StartSelection();
    inline ListBox &            GetListBox()    { return *pListBox; }
    inline FixedInfo &          GetInfo()       { return aInfo; }

    BOOL                        IsUserSelected() const          { return bUserSel; }
    void                        SetUserSelected( BOOL bVal )    { bUserSel = bVal; }
    /*virtual*/Window*                     GetPreferredKeyInputWindow();
};

/////////////////////////////////////////////////////////////////

SvxPopupWindowListBox::SvxPopupWindowListBox( USHORT nSlotId, const rtl::OUString& rCommandURL, USHORT nId, ToolBox& rTbx ) :
    SfxPopupWindow( nSlotId, Reference< XFrame >(), SVX_RES( RID_SVXTBX_UNDO_REDO_CTRL ) ),
    aInfo       ( this, ResId( FT_NUM_OPERATIONS ) ),
    rToolBox    ( rTbx ),
    bUserSel    ( FALSE ),
    nTbxId      ( nId ),
    maCommandURL( rCommandURL )
{
    DBG_ASSERT( nSlotId == GetId(), "id mismatch" );
    pListBox = new ListBox( this, SVX_RES( LB_SVXTBX_UNDO_REDO_CTRL ) );
    FreeResource();
    pListBox->EnableMultiSelection( TRUE, TRUE );
    SetBackground( GetSettings().GetStyleSettings().GetDialogColor() );
    AddStatusListener( rCommandURL );
}

SvxPopupWindowListBox::~SvxPopupWindowListBox()
{
    delete pListBox;
}

SfxPopupWindow* SvxPopupWindowListBox::Clone() const
{
    return new SvxPopupWindowListBox( GetId(), maCommandURL, nTbxId, rToolBox );
}

void SvxPopupWindowListBox::PopupModeEnd()
{
    rToolBox.EndSelection();
    SfxPopupWindow::PopupModeEnd();
    //FloatingWindow::PopupModeEnd();

    Window* pShellWnd = SfxViewShell::Current()->GetWindow();
    if (pShellWnd)
        pShellWnd->GrabFocus();
}

void SvxPopupWindowListBox::StateChanged(
        USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
    rToolBox.EnableItem( nTbxId, ( SfxToolBoxControl::GetItemState( pState ) != SFX_ITEM_DISABLED) );
    SfxPopupWindow::StateChanged( nSID, eState, pState );
}

void SvxPopupWindowListBox::StartSelection()
{
    rToolBox.StartSelection();
}

Window* SvxPopupWindowListBox::GetPreferredKeyInputWindow()
{
    // allows forwarding key events in the correct window
    // without setting the focus
    return pListBox->GetPreferredKeyInputWindow();
}

/////////////////////////////////////////////////////////////////

SFX_IMPL_TOOLBOX_CONTROL( SvxListBoxControl, SfxStringItem );

SvxListBoxControl::SvxListBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx )
    :SfxToolBoxControl( nSlotId, nId, rTbx ),
    pPopupWin   ( 0 )
{
    rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );
    rTbx.Invalidate();
}

SvxListBoxControl::~SvxListBoxControl()
{
}

SfxPopupWindow* SvxListBoxControl::CreatePopupWindow()
{
    DBG_ERROR( "not implemented" );
    return 0;
}

SfxPopupWindowType SvxListBoxControl::GetPopupWindowType() const
{
    return SFX_POPUPWINDOW_ONTIMEOUT;
}

void SvxListBoxControl::StateChanged(
        USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
    GetToolBox().EnableItem( GetId(),
                            SFX_ITEM_DISABLED != GetItemState(pState) );
}

IMPL_LINK( SvxListBoxControl, PopupModeEndHdl, void *, EMPTYARG )
{
    if( pPopupWin && 0 == pPopupWin->GetPopupModeFlags()  &&
        pPopupWin->IsUserSelected() )
    {
        USHORT nCount = pPopupWin->GetListBox().GetSelectEntryCount();

        INetURLObject aObj( m_aCommandURL );

        Sequence< PropertyValue > aArgs( 1 );
        aArgs[0].Name   = aObj.GetURLPath();
        aArgs[0].Value  = makeAny( sal_Int16( nCount ));
        SfxToolBoxControl::Dispatch( m_aCommandURL, aArgs );
    }
    return 0;
}

void SvxListBoxControl::Impl_SetInfo( USHORT nCount )
{
    DBG_ASSERT( pPopupWin, "NULL pointer, PopupWindow missing" );

    ListBox &rListBox = pPopupWin->GetListBox();

    USHORT nId;
    if (nCount == 1)
        nId = SID_UNDO == GetSlotId() ? RID_SVXSTR_NUM_UNDO_ACTION : RID_SVXSTR_NUM_REDO_ACTION;
    else
        nId = SID_UNDO == GetSlotId() ? RID_SVXSTR_NUM_UNDO_ACTIONS : RID_SVXSTR_NUM_REDO_ACTIONS;

    aActionStr = String(SVX_RES(nId));

    String aText( aActionStr );
    aText.SearchAndReplaceAllAscii( "$(ARG1)", String::CreateFromInt32( nCount ) );
    pPopupWin->GetInfo().SetText( aText );
}

IMPL_LINK( SvxListBoxControl, SelectHdl, void *, EMPTYARG )
{
    if (pPopupWin)
    {
        //pPopupWin->SetUserSelected( FALSE );

        ListBox &rListBox = pPopupWin->GetListBox();
        if (rListBox.IsTravelSelect())
            Impl_SetInfo( rListBox.GetSelectEntryCount() );
        else
        {
            pPopupWin->SetUserSelected( TRUE );
            pPopupWin->EndPopupMode( 0 );
        }
    }
    return 0;
}

/////////////////////////////////////////////////////////////////

SFX_IMPL_TOOLBOX_CONTROL( SvxUndoRedoControl, SfxStringItem );

SvxUndoRedoControl::SvxUndoRedoControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx )
    : SvxListBoxControl( nSlotId, nId, rTbx )
{
    rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );
    rTbx.Invalidate();
}

SvxUndoRedoControl::~SvxUndoRedoControl()
{
}

void SvxUndoRedoControl::StateChanged(
    USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
    if ( nSID == SID_UNDO || nSID == SID_REDO )
    {
        if ( pState && pState->ISA( SfxStringItem ))
        {
            SfxStringItem& rItem = *(SfxStringItem *)pState;
            ToolBox& rBox = GetToolBox();
            String aQuickHelpText = MnemonicGenerator::EraseAllMnemonicChars( rItem.GetValue() );
            rBox.SetQuickHelpText( GetId(), aQuickHelpText );
        }
        SvxListBoxControl::StateChanged( nSID, eState, pState );
    }
    else
    {
        aUndoRedoList.clear();

        SfxStringListItem &rItem = *(SfxStringListItem *)pState;
        const List* pLst = rItem.GetList();
        DBG_ASSERT( pLst, "no undo actions available" );
        if ( pLst )
        {
            for( long nI = 0, nEnd = pLst->Count(); nI < nEnd; ++nI )
                aUndoRedoList.push_back( rtl::OUString( *(String *)pLst->GetObject( nI )));
        }
    }
}

SfxPopupWindow* SvxUndoRedoControl::CreatePopupWindow()
{
    DBG_ASSERT(( SID_UNDO == GetSlotId() || SID_REDO == GetSlotId() ), "mismatching ids" );

    if ( m_aCommandURL.equalsAscii( ".uno:Undo" ))
        updateStatus( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:GetUndoStrings" )));
    else
        updateStatus( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:GetRedoStrings" )));

    ToolBox& rBox = GetToolBox();

    pPopupWin = new SvxPopupWindowListBox( GetSlotId(), m_aCommandURL, GetId(), rBox );
    pPopupWin->SetPopupModeEndHdl( LINK( this, SvxUndoRedoControl,
                                            PopupModeEndHdl ) );
    ListBox &rListBox = pPopupWin->GetListBox();
    rListBox.SetSelectHdl( LINK( this, SvxUndoRedoControl, SelectHdl ) );

    for( sal_uInt32 n = 0; n < aUndoRedoList.size(); n++ )
        rListBox.InsertEntry( String( aUndoRedoList[n] ));

    rListBox.SelectEntryPos( 0 );
    aActionStr = String( SVX_RES( SID_UNDO == GetSlotId() ?
                                  RID_SVXSTR_NUM_UNDO_ACTIONS : RID_SVXSTR_NUM_REDO_ACTIONS ) );
    Impl_SetInfo( rListBox.GetSelectEntryCount() );

    // move focus in floating window without
    // closing it (GrabFocus() would close it!)
    pPopupWin->StartPopupMode( &rBox, FLOATWIN_POPUPMODE_GRABFOCUS );
    //pPopupWin->GetListBox().GrabFocus();

    return pPopupWin;
}
<commit_msg>INTEGRATION: CWS tbe19 (1.20.448); FILE MERGED 2005/01/27 17:01:49 tbe 1.20.448.1: #i40118# undo & restore in basic<commit_after>/*************************************************************************
 *
 *  $RCSfile: lboxctrl.cxx,v $
 *
 *  $Revision: 1.21 $
 *
 *  last change: $Author: vg $ $Date: 2005-02-24 16:55:56 $
 *
 *  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   _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif
#ifndef _SV_EVENT_HXX
#include <vcl/event.hxx>
#endif
#ifndef _SFXAPP_HXX
#include <sfx2/app.hxx>
#endif
#ifndef _SFXTBXCTRL_HXX
#include <sfx2/tbxctrl.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXDISPATCH_HXX
#include <sfx2/dispatch.hxx>
#endif
#ifndef _SFXVIEWSH_HXX
#include <sfx2/viewsh.hxx>
#endif
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _STDCTRL_HXX
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SFXSLSTITM_HXX
#include <svtools/slstitm.hxx>
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif

#ifndef _SVX_DIALMGR_HXX
#include <dialmgr.hxx>
#endif
#ifndef _SVX_LBOXCTRL_HXX_
#include <lboxctrl.hxx>
#endif
#ifndef _VCL_MNEMONIC_HXX_
#include <vcl/mnemonic.hxx>
#endif
#include <tools/urlobj.hxx>

#include <svxids.hrc>
#include <dialogs.hrc>

#include "lboxctrl.hrc"

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;

class SvxPopupWindowListBox;

/////////////////////////////////////////////////////////////////

class SvxPopupWindowListBox : public SfxPopupWindow
{
    FixedInfo       aInfo;
    ListBox *       pListBox;
    ToolBox &       rToolBox;
    BOOL            bUserSel;
    USHORT          nTbxId;
    rtl::OUString   maCommandURL;
    // disallow copy-constructor and assignment-operator

    SvxPopupWindowListBox(const int& );
    SvxPopupWindowListBox & operator = (const int& );

//  SvxPopupWindowListBox( USHORT nSlotId, ToolBox& rTbx, USHORT nTbxItemId );

public:
    SvxPopupWindowListBox( USHORT nSlotId, const rtl::OUString& rCommandURL, USHORT nTbxId, ToolBox& rTbx );
    virtual ~SvxPopupWindowListBox();

    // SfxPopupWindow
    virtual SfxPopupWindow *    Clone() const;
    virtual void                PopupModeEnd();
    virtual void                StateChanged( USHORT nSID, SfxItemState eState,
                                              const SfxPoolItem* pState );

    void                        StartSelection();
    inline ListBox &            GetListBox()    { return *pListBox; }
    inline FixedInfo &          GetInfo()       { return aInfo; }

    BOOL                        IsUserSelected() const          { return bUserSel; }
    void                        SetUserSelected( BOOL bVal )    { bUserSel = bVal; }
    /*virtual*/Window*                     GetPreferredKeyInputWindow();
};

/////////////////////////////////////////////////////////////////

SvxPopupWindowListBox::SvxPopupWindowListBox( USHORT nSlotId, const rtl::OUString& rCommandURL, USHORT nId, ToolBox& rTbx ) :
    SfxPopupWindow( nSlotId, Reference< XFrame >(), SVX_RES( RID_SVXTBX_UNDO_REDO_CTRL ) ),
    aInfo       ( this, ResId( FT_NUM_OPERATIONS ) ),
    rToolBox    ( rTbx ),
    bUserSel    ( FALSE ),
    nTbxId      ( nId ),
    maCommandURL( rCommandURL )
{
    DBG_ASSERT( nSlotId == GetId(), "id mismatch" );
    pListBox = new ListBox( this, SVX_RES( LB_SVXTBX_UNDO_REDO_CTRL ) );
    FreeResource();
    pListBox->EnableMultiSelection( TRUE, TRUE );
    SetBackground( GetSettings().GetStyleSettings().GetDialogColor() );
    AddStatusListener( rCommandURL );
}

SvxPopupWindowListBox::~SvxPopupWindowListBox()
{
    delete pListBox;
}

SfxPopupWindow* SvxPopupWindowListBox::Clone() const
{
    return new SvxPopupWindowListBox( GetId(), maCommandURL, nTbxId, rToolBox );
}

void SvxPopupWindowListBox::PopupModeEnd()
{
    rToolBox.EndSelection();
    SfxPopupWindow::PopupModeEnd();
    //FloatingWindow::PopupModeEnd();

    Window* pShellWnd = SfxViewShell::Current()->GetWindow();
    if (pShellWnd)
        pShellWnd->GrabFocus();
}

void SvxPopupWindowListBox::StateChanged(
        USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
    rToolBox.EnableItem( nTbxId, ( SfxToolBoxControl::GetItemState( pState ) != SFX_ITEM_DISABLED) );
    SfxPopupWindow::StateChanged( nSID, eState, pState );
}

void SvxPopupWindowListBox::StartSelection()
{
    rToolBox.StartSelection();
}

Window* SvxPopupWindowListBox::GetPreferredKeyInputWindow()
{
    // allows forwarding key events in the correct window
    // without setting the focus
    return pListBox->GetPreferredKeyInputWindow();
}

/////////////////////////////////////////////////////////////////

SFX_IMPL_TOOLBOX_CONTROL( SvxListBoxControl, SfxStringItem );

SvxListBoxControl::SvxListBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx )
    :SfxToolBoxControl( nSlotId, nId, rTbx ),
    pPopupWin   ( 0 )
{
    rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );
    rTbx.Invalidate();
}

SvxListBoxControl::~SvxListBoxControl()
{
}

SfxPopupWindow* SvxListBoxControl::CreatePopupWindow()
{
    DBG_ERROR( "not implemented" );
    return 0;
}

SfxPopupWindowType SvxListBoxControl::GetPopupWindowType() const
{
    return SFX_POPUPWINDOW_ONTIMEOUT;
}

void SvxListBoxControl::StateChanged(
        USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
    GetToolBox().EnableItem( GetId(),
                            SFX_ITEM_DISABLED != GetItemState(pState) );
}

IMPL_LINK( SvxListBoxControl, PopupModeEndHdl, void *, EMPTYARG )
{
    if( pPopupWin && 0 == pPopupWin->GetPopupModeFlags()  &&
        pPopupWin->IsUserSelected() )
    {
        USHORT nCount = pPopupWin->GetListBox().GetSelectEntryCount();

        INetURLObject aObj( m_aCommandURL );

        Sequence< PropertyValue > aArgs( 1 );
        aArgs[0].Name   = aObj.GetURLPath();
        aArgs[0].Value  = makeAny( sal_Int16( nCount ));
        SfxToolBoxControl::Dispatch( m_aCommandURL, aArgs );
    }
    return 0;
}

void SvxListBoxControl::Impl_SetInfo( USHORT nCount )
{
    DBG_ASSERT( pPopupWin, "NULL pointer, PopupWindow missing" );

    ListBox &rListBox = pPopupWin->GetListBox();

    USHORT nId;
    if (nCount == 1)
        nId = SID_UNDO == GetSlotId() ? RID_SVXSTR_NUM_UNDO_ACTION : RID_SVXSTR_NUM_REDO_ACTION;
    else
        nId = SID_UNDO == GetSlotId() ? RID_SVXSTR_NUM_UNDO_ACTIONS : RID_SVXSTR_NUM_REDO_ACTIONS;

    aActionStr = String(SVX_RES(nId));

    String aText( aActionStr );
    aText.SearchAndReplaceAllAscii( "$(ARG1)", String::CreateFromInt32( nCount ) );
    pPopupWin->GetInfo().SetText( aText );
}

IMPL_LINK( SvxListBoxControl, SelectHdl, void *, EMPTYARG )
{
    if (pPopupWin)
    {
        //pPopupWin->SetUserSelected( FALSE );

        ListBox &rListBox = pPopupWin->GetListBox();
        if (rListBox.IsTravelSelect())
            Impl_SetInfo( rListBox.GetSelectEntryCount() );
        else
        {
            pPopupWin->SetUserSelected( TRUE );
            pPopupWin->EndPopupMode( 0 );
        }
    }
    return 0;
}

/////////////////////////////////////////////////////////////////

SFX_IMPL_TOOLBOX_CONTROL( SvxUndoRedoControl, SfxStringItem );

SvxUndoRedoControl::SvxUndoRedoControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx )
    : SvxListBoxControl( nSlotId, nId, rTbx )
{
    rTbx.SetItemBits( nId, TIB_DROPDOWN | rTbx.GetItemBits( nId ) );
    rTbx.Invalidate();
    aDefaultText = MnemonicGenerator::EraseAllMnemonicChars( rTbx.GetItemText( nId ) );
}

SvxUndoRedoControl::~SvxUndoRedoControl()
{
}

void SvxUndoRedoControl::StateChanged(
    USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
    if ( nSID == SID_UNDO || nSID == SID_REDO )
    {
        if ( eState == SFX_ITEM_DISABLED )
        {
            ToolBox& rBox = GetToolBox();
            rBox.SetQuickHelpText( GetId(), aDefaultText );
        }
        else if ( pState && pState->ISA( SfxStringItem ) )
        {
            SfxStringItem& rItem = *(SfxStringItem *)pState;
            ToolBox& rBox = GetToolBox();
            String aQuickHelpText = MnemonicGenerator::EraseAllMnemonicChars( rItem.GetValue() );
            rBox.SetQuickHelpText( GetId(), aQuickHelpText );
        }
        SvxListBoxControl::StateChanged( nSID, eState, pState );
    }
    else
    {
        aUndoRedoList.clear();

        SfxStringListItem &rItem = *(SfxStringListItem *)pState;
        const List* pLst = rItem.GetList();
        DBG_ASSERT( pLst, "no undo actions available" );
        if ( pLst )
        {
            for( long nI = 0, nEnd = pLst->Count(); nI < nEnd; ++nI )
                aUndoRedoList.push_back( rtl::OUString( *(String *)pLst->GetObject( nI )));
        }
    }
}

SfxPopupWindow* SvxUndoRedoControl::CreatePopupWindow()
{
    DBG_ASSERT(( SID_UNDO == GetSlotId() || SID_REDO == GetSlotId() ), "mismatching ids" );

    if ( m_aCommandURL.equalsAscii( ".uno:Undo" ))
        updateStatus( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:GetUndoStrings" )));
    else
        updateStatus( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:GetRedoStrings" )));

    ToolBox& rBox = GetToolBox();

    pPopupWin = new SvxPopupWindowListBox( GetSlotId(), m_aCommandURL, GetId(), rBox );
    pPopupWin->SetPopupModeEndHdl( LINK( this, SvxUndoRedoControl,
                                            PopupModeEndHdl ) );
    ListBox &rListBox = pPopupWin->GetListBox();
    rListBox.SetSelectHdl( LINK( this, SvxUndoRedoControl, SelectHdl ) );

    for( sal_uInt32 n = 0; n < aUndoRedoList.size(); n++ )
        rListBox.InsertEntry( String( aUndoRedoList[n] ));

    rListBox.SelectEntryPos( 0 );
    aActionStr = String( SVX_RES( SID_UNDO == GetSlotId() ?
                                  RID_SVXSTR_NUM_UNDO_ACTIONS : RID_SVXSTR_NUM_REDO_ACTIONS ) );
    Impl_SetInfo( rListBox.GetSelectEntryCount() );

    // move focus in floating window without
    // closing it (GrabFocus() would close it!)
    pPopupWin->StartPopupMode( &rBox, FLOATWIN_POPUPMODE_GRABFOCUS );
    //pPopupWin->GetListBox().GrabFocus();

    return pPopupWin;
}
<|endoftext|>


<commit_before><commit_msg>break out text drawing bit as UserDrawEntry<commit_after><|endoftext|>


<commit_before><commit_msg>sw: oops, forgot to commit that<commit_after><|endoftext|>


<commit_before><commit_msg>Fix (again) angular velocity.<commit_after><|endoftext|>


<commit_before><commit_msg>Hack to suppress warnings from MSL compiler<commit_after><|endoftext|>


<commit_before><commit_msg>fdo#75757: remove inheritance to std::map<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: swatrset.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 08:25:59 $
 *
 *  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"

#include <hintids.hxx>
#include <svtools/whiter.hxx>
#ifndef _SVX_COLRITEM_HXX //autogen
#include <svx/colritem.hxx>
#endif
#ifndef _SVX_BRSHITEM_HXX //autogen
#include <svx/brshitem.hxx>
#endif
#ifndef _SVX_BOLNITEM_HXX //autogen
#include <svx/bolnitem.hxx>
#endif
#ifndef _SVX_BOXITEM_HXX //autogen
#include <svx/boxitem.hxx>
#endif
#ifndef _XTABLE_HXX //autogen
#include <svx/xtable.hxx>
#endif
#ifndef _FMTPDSC_HXX //autogen
#include <fmtpdsc.hxx>
#endif
#ifndef _PAGEDESC_HXX //autogen
#include <pagedesc.hxx>
#endif
#ifndef _CHARFMT_HXX
#include <charfmt.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _NODE_HXX //autogen
#include <node.hxx>
#endif
#ifndef _PARATR_HXX
#include <paratr.hxx>       // fuer SetModifyAtAttr
#endif
#ifndef _CELLATR_HXX
#include <cellatr.hxx>      // fuer SetModifyAtAttr
#endif
#ifndef _CMDID_H
#include <cmdid.h>
#endif
#include <istyleaccess.hxx>

SwAttrPool::SwAttrPool( SwDoc* pD )
    : SfxItemPool( String::CreateFromAscii(
                                RTL_CONSTASCII_STRINGPARAM( "SWG" )),
                    POOLATTR_BEGIN, POOLATTR_END-1,
                    aSlotTab, aAttrTab ),
    pDoc( pD )
{
    SetVersionMap( 1, 1, 60, pVersionMap1 );
    SetVersionMap( 2, 1, 75, pVersionMap2 );
    SetVersionMap( 3, 1, 86, pVersionMap3 );
    SetVersionMap( 4, 1,121, pVersionMap4 );
    // OD 2004-01-21 #i18732# - apply new version map
    SetVersionMap( 5, 1,130, pVersionMap5 );
}

SwAttrSet::SwAttrSet( SwAttrPool& rPool, USHORT nWh1, USHORT nWh2 )
    : SfxItemSet( rPool, nWh1, nWh2 ), pOldSet( 0 ), pNewSet( 0 )
{
}

SwAttrSet::SwAttrSet( SwAttrPool& rPool, const USHORT* nWhichPairTable )
    : SfxItemSet( rPool, nWhichPairTable ), pOldSet( 0 ), pNewSet( 0 )
{
}

SwAttrSet::SwAttrSet( const SwAttrSet& rSet )
    : SfxItemSet( rSet ), pOldSet( 0 ), pNewSet( 0 )
{
}

SfxItemSet* SwAttrSet::Clone( BOOL bItems, SfxItemPool *pToPool ) const
{
    if ( pToPool && pToPool != GetPool() )
    {
        SwAttrPool* pAttrPool = dynamic_cast< SwAttrPool* >(pToPool);
        SfxItemSet* pTmpSet = 0;
        if ( !pAttrPool )
            pTmpSet = SfxItemSet::Clone( bItems, pToPool );
        else
        {
            pTmpSet = new SwAttrSet( *pAttrPool, GetRanges() );
            if ( bItems )
            {
                SfxWhichIter aIter(*pTmpSet);
                USHORT nWhich = aIter.FirstWhich();
                while ( nWhich )
                {
                    const SfxPoolItem* pItem;
                    if ( SFX_ITEM_SET == GetItemState( nWhich, FALSE, &pItem ) )
                        pTmpSet->Put( *pItem, pItem->Which() );
                    nWhich = aIter.NextWhich();
                }
            }
        }
        return pTmpSet;
    }
    else
        return bItems
                ? new SwAttrSet( *this )
                : new SwAttrSet( *GetPool(), GetRanges() );
}

int SwAttrSet::Put_BC( const SfxPoolItem& rAttr,
                    SwAttrSet* pOld, SwAttrSet* pNew )
{
    pNewSet = pNew;
    pOldSet = pOld;
    int nRet = 0 != SfxItemSet::Put( rAttr );
    pOldSet = pNewSet = 0;
    return nRet;
}

int SwAttrSet::Put_BC( const SfxItemSet& rSet,
                    SwAttrSet* pOld, SwAttrSet* pNew )
{
    pNewSet = pNew;
    pOldSet = pOld;
    int nRet = 0 != SfxItemSet::Put( rSet );
    pOldSet = pNewSet = 0;
    return nRet;
}

USHORT SwAttrSet::ClearItem_BC( USHORT nWhich,
                        SwAttrSet* pOld, SwAttrSet* pNew )
{
    pNewSet = pNew;
    pOldSet = pOld;
    USHORT nRet = SfxItemSet::ClearItem( nWhich );
    pOldSet = pNewSet = 0;
    return nRet;
}

USHORT SwAttrSet::ClearItem_BC( USHORT nWhich1, USHORT nWhich2,
                        SwAttrSet* pOld, SwAttrSet* pNew )
{
    ASSERT( nWhich1 <= nWhich2, "kein gueltiger Bereich" );
    pNewSet = pNew;
    pOldSet = pOld;
    USHORT nRet = 0;
    for( ; nWhich1 <= nWhich2; ++nWhich1 )
        nRet = nRet + SfxItemSet::ClearItem( nWhich1 );
    pOldSet = pNewSet = 0;
    return nRet;
}

int SwAttrSet::Intersect_BC( const SfxItemSet& rSet,
                            SwAttrSet* pOld, SwAttrSet* pNew )
{
    pNewSet = pNew;
    pOldSet = pOld;
    SfxItemSet::Intersect( rSet );
    pOldSet = pNewSet = 0;
    return pNew ? pNew->Count() : ( pOld ? pOld->Count() : 0 );
}

// Notification-Callback
void  SwAttrSet::Changed( const SfxPoolItem& rOld,
                                const SfxPoolItem& rNew )
{
    if( pOldSet )
        pOldSet->PutChgd( rOld );

    if( pNewSet )
        pNewSet->PutChgd( rNew );
}

// ----------------------------------------------------------------
// Sonderbehandlung fuer einige Attribute
// Setze den Modify-Pointer (alten pDefinedIn) bei folgenden Attributen:
//  - SwFmtDropCaps
//  - SwFmtPageDesc
// (Wird beim Einfuegen in Formate/Nodes gerufen)
// ----------------------------------------------------------------

bool SwAttrSet::SetModifyAtAttr( const SwModify* pModify )
{
    bool bSet = false;

    const SfxPoolItem* pItem;
    if( SFX_ITEM_SET == GetItemState( RES_PAGEDESC, FALSE, &pItem ) &&
        ((SwFmtPageDesc*)pItem)->GetDefinedIn() != pModify  )
    {
        ((SwFmtPageDesc*)pItem)->ChgDefinedIn( pModify );
        bSet = true;
    }

    if( SFX_ITEM_SET == GetItemState( RES_PARATR_NUMRULE, FALSE, &pItem ) &&
        ((SwNumRuleItem*)pItem)->GetDefinedIn() != pModify  )
    {
        ((SwNumRuleItem*)pItem)->ChgDefinedIn( pModify );
        bSet = true;
    }

    if( SFX_ITEM_SET == GetItemState( RES_PARATR_DROP, FALSE, &pItem ) &&
        ((SwFmtDrop*)pItem)->GetDefinedIn() != pModify )
    {
        // CharFormat gesetzt und dann noch in unterschiedlichen
        // Attribut Pools, dann muss das CharFormat kopiert werden!
        SwCharFmt* pCharFmt;
        if( 0 != ( pCharFmt = ((SwFmtDrop*)pItem)->GetCharFmt() )
            && GetPool() != pCharFmt->GetAttrSet().GetPool() )
        {
           pCharFmt = GetDoc()->CopyCharFmt( *pCharFmt );
           ((SwFmtDrop*)pItem)->SetCharFmt( pCharFmt );
        }
        ((SwFmtDrop*)pItem)->ChgDefinedIn( pModify );
        bSet = true;
    }

    if( SFX_ITEM_SET == GetItemState( RES_BOXATR_FORMULA, FALSE, &pItem ) &&
        ((SwTblBoxFormula*)pItem)->GetDefinedIn() != pModify )
    {
        ((SwTblBoxFormula*)pItem)->ChgDefinedIn( pModify );
        bSet = true;
    }

    return bSet;
}

void SwAttrSet::CopyToModify( SwModify& rMod ) const
{
    // kopiere die Attribute ggfs. ueber Dokumentgrenzen
    SwCntntNode* pCNd = PTR_CAST( SwCntntNode, &rMod );
    SwFmt* pFmt = PTR_CAST( SwFmt, &rMod );

    if( pCNd || pFmt )
    {
        if( Count() )
        {
            const SfxPoolItem* pItem;
            const SwDoc *pSrcDoc = GetDoc();
            SwDoc *pDstDoc = pCNd ? pCNd->GetDoc() : pFmt->GetDoc();

            // muss die NumRule kopiert werden?
            if( pSrcDoc != pDstDoc && SFX_ITEM_SET == GetItemState(
                                    RES_PARATR_NUMRULE, FALSE, &pItem ) )
            {
                const String& rNm = ((SwNumRuleItem*)pItem)->GetValue();
                if( rNm.Len() )
                {
                    SwNumRule* pDestRule = pDstDoc->FindNumRulePtr( rNm );
                    if( pDestRule )
                        pDestRule->SetInvalidRule( TRUE );
                    else
                        pDstDoc->MakeNumRule( rNm,
                                            pSrcDoc->FindNumRulePtr( rNm ) );
                }
            }

            // JP 04.02.99: Task #61467# Seitenvorlagenwechsel mit kopieren
            //              Gegenueber dem alten Verhalten, sie zu entfernen
            const SwPageDesc* pPgDesc;
            if( pSrcDoc != pDstDoc && SFX_ITEM_SET == GetItemState(
                                            RES_PAGEDESC, FALSE, &pItem ) &&
                0 != ( pPgDesc = ((SwFmtPageDesc*)pItem)->GetPageDesc()) )
            {
                SfxItemSet aTmpSet( *this );

                // JP 09.02.99: und jetzt doch wieder nur entfernen
                aTmpSet.ClearItem( RES_PAGEDESC );

/*************************************************************************
                SwPageDesc* pDstPgDesc = pDstDoc->FindPageDescByName(
                                                    pPgDesc->GetName() );
                if( !pDstPgDesc )
                {
                    // dann kopieren, ansonsten den benutzen
                    pDstPgDesc = &pDstDoc->_GetPageDesc( pDstDoc->MakePageDesc(
                                                    pPgDesc->GetName() ));
                    pDstDoc->CopyPageDesc( *pPgDesc, *pDstPgDesc );
                }
                SwFmtPageDesc aDesc( pDstPgDesc );
                aDesc.SetNumOffset( ((SwFmtPageDesc*)pItem)->GetNumOffset() );
                aTmpSet.Put( aDesc );
************************************************************************/

                if( pCNd )
                    pCNd->SetAttr( aTmpSet );
                else
                    pFmt->SetAttr( aTmpSet );
            }
            else if( pCNd )
                pCNd->SetAttr( *this );
            else
                pFmt->SetAttr( *this );
        }
    }
#ifndef PRODUCT
    else
        ASSERT( !this, "weder Format noch ContentNode - keine Attribute kopiert");
#endif
}

// check if ID is InRange of AttrSet-Ids
BOOL IsInRange( const USHORT* pRange, const USHORT nId )
{
    while( *pRange )
    {
        if( *pRange <= nId && nId <= *(pRange+1) )
            return TRUE;
        pRange += 2;
    }
    return FALSE;
}

<commit_msg>INTEGRATION: CWS swnewlistlevelattrs_DEV300 (1.12.142); FILE MERGED 2008/01/31 12:39:23 od 1.12.142.1: #i85348# refactoring: adjust includes<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: swatrset.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-05 16:52: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"

#include <hintids.hxx>
#include <svtools/whiter.hxx>
#ifndef _SVX_COLRITEM_HXX //autogen
#include <svx/colritem.hxx>
#endif
#ifndef _SVX_BRSHITEM_HXX //autogen
#include <svx/brshitem.hxx>
#endif
#ifndef _SVX_BOLNITEM_HXX //autogen
#include <svx/bolnitem.hxx>
#endif
#ifndef _SVX_BOXITEM_HXX //autogen
#include <svx/boxitem.hxx>
#endif
#ifndef _XTABLE_HXX //autogen
#include <svx/xtable.hxx>
#endif
#ifndef _FMTPDSC_HXX //autogen
#include <fmtpdsc.hxx>
#endif
#ifndef _PAGEDESC_HXX //autogen
#include <pagedesc.hxx>
#endif
#ifndef _CHARFMT_HXX
#include <charfmt.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _NODE_HXX //autogen
#include <node.hxx>
#endif
#ifndef _PARATR_HXX
#include <paratr.hxx>       // fuer SetModifyAtAttr
#endif
#ifndef _CELLATR_HXX
#include <cellatr.hxx>      // fuer SetModifyAtAttr
#endif
#ifndef _CMDID_H
#include <cmdid.h>
#endif
#include <istyleaccess.hxx>
#ifndef _NUMRULE_HXX
#include <numrule.hxx>
#endif

SwAttrPool::SwAttrPool( SwDoc* pD )
    : SfxItemPool( String::CreateFromAscii(
                                RTL_CONSTASCII_STRINGPARAM( "SWG" )),
                    POOLATTR_BEGIN, POOLATTR_END-1,
                    aSlotTab, aAttrTab ),
    pDoc( pD )
{
    SetVersionMap( 1, 1, 60, pVersionMap1 );
    SetVersionMap( 2, 1, 75, pVersionMap2 );
    SetVersionMap( 3, 1, 86, pVersionMap3 );
    SetVersionMap( 4, 1,121, pVersionMap4 );
    // OD 2004-01-21 #i18732# - apply new version map
    SetVersionMap( 5, 1,130, pVersionMap5 );
}

SwAttrSet::SwAttrSet( SwAttrPool& rPool, USHORT nWh1, USHORT nWh2 )
    : SfxItemSet( rPool, nWh1, nWh2 ), pOldSet( 0 ), pNewSet( 0 )
{
}

SwAttrSet::SwAttrSet( SwAttrPool& rPool, const USHORT* nWhichPairTable )
    : SfxItemSet( rPool, nWhichPairTable ), pOldSet( 0 ), pNewSet( 0 )
{
}

SwAttrSet::SwAttrSet( const SwAttrSet& rSet )
    : SfxItemSet( rSet ), pOldSet( 0 ), pNewSet( 0 )
{
}

SfxItemSet* SwAttrSet::Clone( BOOL bItems, SfxItemPool *pToPool ) const
{
    if ( pToPool && pToPool != GetPool() )
    {
        SwAttrPool* pAttrPool = dynamic_cast< SwAttrPool* >(pToPool);
        SfxItemSet* pTmpSet = 0;
        if ( !pAttrPool )
            pTmpSet = SfxItemSet::Clone( bItems, pToPool );
        else
        {
            pTmpSet = new SwAttrSet( *pAttrPool, GetRanges() );
            if ( bItems )
            {
                SfxWhichIter aIter(*pTmpSet);
                USHORT nWhich = aIter.FirstWhich();
                while ( nWhich )
                {
                    const SfxPoolItem* pItem;
                    if ( SFX_ITEM_SET == GetItemState( nWhich, FALSE, &pItem ) )
                        pTmpSet->Put( *pItem, pItem->Which() );
                    nWhich = aIter.NextWhich();
                }
            }
        }
        return pTmpSet;
    }
    else
        return bItems
                ? new SwAttrSet( *this )
                : new SwAttrSet( *GetPool(), GetRanges() );
}

int SwAttrSet::Put_BC( const SfxPoolItem& rAttr,
                    SwAttrSet* pOld, SwAttrSet* pNew )
{
    pNewSet = pNew;
    pOldSet = pOld;
    int nRet = 0 != SfxItemSet::Put( rAttr );
    pOldSet = pNewSet = 0;
    return nRet;
}

int SwAttrSet::Put_BC( const SfxItemSet& rSet,
                    SwAttrSet* pOld, SwAttrSet* pNew )
{
    pNewSet = pNew;
    pOldSet = pOld;
    int nRet = 0 != SfxItemSet::Put( rSet );
    pOldSet = pNewSet = 0;
    return nRet;
}

USHORT SwAttrSet::ClearItem_BC( USHORT nWhich,
                        SwAttrSet* pOld, SwAttrSet* pNew )
{
    pNewSet = pNew;
    pOldSet = pOld;
    USHORT nRet = SfxItemSet::ClearItem( nWhich );
    pOldSet = pNewSet = 0;
    return nRet;
}

USHORT SwAttrSet::ClearItem_BC( USHORT nWhich1, USHORT nWhich2,
                        SwAttrSet* pOld, SwAttrSet* pNew )
{
    ASSERT( nWhich1 <= nWhich2, "kein gueltiger Bereich" );
    pNewSet = pNew;
    pOldSet = pOld;
    USHORT nRet = 0;
    for( ; nWhich1 <= nWhich2; ++nWhich1 )
        nRet = nRet + SfxItemSet::ClearItem( nWhich1 );
    pOldSet = pNewSet = 0;
    return nRet;
}

int SwAttrSet::Intersect_BC( const SfxItemSet& rSet,
                            SwAttrSet* pOld, SwAttrSet* pNew )
{
    pNewSet = pNew;
    pOldSet = pOld;
    SfxItemSet::Intersect( rSet );
    pOldSet = pNewSet = 0;
    return pNew ? pNew->Count() : ( pOld ? pOld->Count() : 0 );
}

// Notification-Callback
void  SwAttrSet::Changed( const SfxPoolItem& rOld,
                                const SfxPoolItem& rNew )
{
    if( pOldSet )
        pOldSet->PutChgd( rOld );

    if( pNewSet )
        pNewSet->PutChgd( rNew );
}

// ----------------------------------------------------------------
// Sonderbehandlung fuer einige Attribute
// Setze den Modify-Pointer (alten pDefinedIn) bei folgenden Attributen:
//  - SwFmtDropCaps
//  - SwFmtPageDesc
// (Wird beim Einfuegen in Formate/Nodes gerufen)
// ----------------------------------------------------------------

bool SwAttrSet::SetModifyAtAttr( const SwModify* pModify )
{
    bool bSet = false;

    const SfxPoolItem* pItem;
    if( SFX_ITEM_SET == GetItemState( RES_PAGEDESC, FALSE, &pItem ) &&
        ((SwFmtPageDesc*)pItem)->GetDefinedIn() != pModify  )
    {
        ((SwFmtPageDesc*)pItem)->ChgDefinedIn( pModify );
        bSet = true;
    }

    if( SFX_ITEM_SET == GetItemState( RES_PARATR_NUMRULE, FALSE, &pItem ) &&
        ((SwNumRuleItem*)pItem)->GetDefinedIn() != pModify  )
    {
        ((SwNumRuleItem*)pItem)->ChgDefinedIn( pModify );
        bSet = true;
    }

    if( SFX_ITEM_SET == GetItemState( RES_PARATR_DROP, FALSE, &pItem ) &&
        ((SwFmtDrop*)pItem)->GetDefinedIn() != pModify )
    {
        // CharFormat gesetzt und dann noch in unterschiedlichen
        // Attribut Pools, dann muss das CharFormat kopiert werden!
        SwCharFmt* pCharFmt;
        if( 0 != ( pCharFmt = ((SwFmtDrop*)pItem)->GetCharFmt() )
            && GetPool() != pCharFmt->GetAttrSet().GetPool() )
        {
           pCharFmt = GetDoc()->CopyCharFmt( *pCharFmt );
           ((SwFmtDrop*)pItem)->SetCharFmt( pCharFmt );
        }
        ((SwFmtDrop*)pItem)->ChgDefinedIn( pModify );
        bSet = true;
    }

    if( SFX_ITEM_SET == GetItemState( RES_BOXATR_FORMULA, FALSE, &pItem ) &&
        ((SwTblBoxFormula*)pItem)->GetDefinedIn() != pModify )
    {
        ((SwTblBoxFormula*)pItem)->ChgDefinedIn( pModify );
        bSet = true;
    }

    return bSet;
}

void SwAttrSet::CopyToModify( SwModify& rMod ) const
{
    // kopiere die Attribute ggfs. ueber Dokumentgrenzen
    SwCntntNode* pCNd = PTR_CAST( SwCntntNode, &rMod );
    SwFmt* pFmt = PTR_CAST( SwFmt, &rMod );

    if( pCNd || pFmt )
    {
        if( Count() )
        {
            const SfxPoolItem* pItem;
            const SwDoc *pSrcDoc = GetDoc();
            SwDoc *pDstDoc = pCNd ? pCNd->GetDoc() : pFmt->GetDoc();

            // muss die NumRule kopiert werden?
            if( pSrcDoc != pDstDoc && SFX_ITEM_SET == GetItemState(
                                    RES_PARATR_NUMRULE, FALSE, &pItem ) )
            {
                const String& rNm = ((SwNumRuleItem*)pItem)->GetValue();
                if( rNm.Len() )
                {
                    SwNumRule* pDestRule = pDstDoc->FindNumRulePtr( rNm );
                    if( pDestRule )
                        pDestRule->SetInvalidRule( TRUE );
                    else
                        pDstDoc->MakeNumRule( rNm,
                                            pSrcDoc->FindNumRulePtr( rNm ) );
                }
            }

            // JP 04.02.99: Task #61467# Seitenvorlagenwechsel mit kopieren
            //              Gegenueber dem alten Verhalten, sie zu entfernen
            const SwPageDesc* pPgDesc;
            if( pSrcDoc != pDstDoc && SFX_ITEM_SET == GetItemState(
                                            RES_PAGEDESC, FALSE, &pItem ) &&
                0 != ( pPgDesc = ((SwFmtPageDesc*)pItem)->GetPageDesc()) )
            {
                SfxItemSet aTmpSet( *this );

                // JP 09.02.99: und jetzt doch wieder nur entfernen
                aTmpSet.ClearItem( RES_PAGEDESC );

/*************************************************************************
                SwPageDesc* pDstPgDesc = pDstDoc->FindPageDescByName(
                                                    pPgDesc->GetName() );
                if( !pDstPgDesc )
                {
                    // dann kopieren, ansonsten den benutzen
                    pDstPgDesc = &pDstDoc->_GetPageDesc( pDstDoc->MakePageDesc(
                                                    pPgDesc->GetName() ));
                    pDstDoc->CopyPageDesc( *pPgDesc, *pDstPgDesc );
                }
                SwFmtPageDesc aDesc( pDstPgDesc );
                aDesc.SetNumOffset( ((SwFmtPageDesc*)pItem)->GetNumOffset() );
                aTmpSet.Put( aDesc );
************************************************************************/

                if( pCNd )
                    pCNd->SetAttr( aTmpSet );
                else
                    pFmt->SetAttr( aTmpSet );
            }
            else if( pCNd )
                pCNd->SetAttr( *this );
            else
                pFmt->SetAttr( *this );
        }
    }
#ifndef PRODUCT
    else
        ASSERT( !this, "weder Format noch ContentNode - keine Attribute kopiert");
#endif
}

// check if ID is InRange of AttrSet-Ids
BOOL IsInRange( const USHORT* pRange, const USHORT nId )
{
    while( *pRange )
    {
        if( *pRange <= nId && nId <= *(pRange+1) )
            return TRUE;
        pRange += 2;
    }
    return FALSE;
}

<|endoftext|>


<commit_before>#include "VulkanHandler.hpp"

// Includes
//----------
//   3rd Party Libraries
//  ---------------------

#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>

//   Standard Libary
//  -----------------

#include <algorithm>
#include <set>
#include <string>
#include <vector>

// Weird crap (see README.md to see my justification)
//----------------------------------------------------

#define WHOLE(container) std::begin(container), std::end(container)
#define CWHOLE(container) std::cbegin(container), std::cend(container)
using namespace std;

// Constants
//-----------

const vector<const char*> VulkanHandler::k_validation_layers{
    "VK_LAYER_KHRONOS_validation"};

// Method Definitions
//--------------------

vk::UniqueInstance createInstance();
// is used by:
VulkanHandler::VulkanHandler() : vk_instance_{createInstance()}
{
}

// Helpers
//---------

bool checkValidationLayerSupport();
vector<const char*> getExtensions();
// are used by:
vk::UniqueInstance createInstance()
{
  if (VulkanHandler::k_enable_validation_layers
      && !checkValidationLayerSupport()) {
    throw std::runtime_error("validation layers requested, but not available!");
  }

  vk::ApplicationInfo app_info{ //
      "Hello Triangle",         // pApplicationName
      VK_MAKE_VERSION(1, 0, 0), // application version
      "No Engine",              //
      VK_MAKE_VERSION(1, 0, 0), // engine version
      VK_API_VERSION_1_0};      //

  auto extensions = getExtensions();

  vk::InstanceCreateInfo create_info{{}, &app_info, 0, {},
      static_cast<uint32_t>(extensions.size()), extensions.data()};
  if (VulkanHandler::k_enable_validation_layers) {
    create_info.enabledLayerCount =
        static_cast<uint32_t>(VulkanHandler::k_validation_layers.size());
    create_info.ppEnabledLayerNames = VulkanHandler::k_validation_layers.data();
  }

  return vk::createInstanceUnique(create_info);
}

bool checkValidationLayerSupport()
{
  // set<string> is sorted, and its elements are trivially comparable.
  std::set<string> available_layer_names{};
  for (const auto& layer_properties : vk::enumerateInstanceLayerProperties()) {
    available_layer_names.emplace(layer_properties.layerName);
  }

  std::set<string> validation_layers_sorted{};
  for (const auto& layer : VulkanHandler::k_validation_layers) {
    validation_layers_sorted.emplace(layer);
  }

  return std::includes(
      CWHOLE(available_layer_names), CWHOLE(validation_layers_sorted));
}

vector<const char*> getExtensions()
{
  uint32_t glfw_extension_count{};
  const char** glfw_extensions =
      glfwGetRequiredInstanceExtensions(&glfw_extension_count);

  vector<const char*> extensions(glfw_extension_count);
  std::copy_n(glfw_extensions, glfw_extension_count, begin(extensions));

  return extensions;
}

// vim:set et ts=2 sw=0 sts=0:

<commit_msg>Assure that k_validation_layers is sorted<commit_after>#include "VulkanHandler.hpp"

// Includes
//----------
//   3rd Party Libraries
//  ---------------------

#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>

//   Standard Libary
//  -----------------

#include <algorithm>
#include <cstring>
#include <set>
#include <string>
#include <vector>

// Weird crap (see README.md to see my justification)
//----------------------------------------------------

#define WHOLE(container) std::begin(container), std::end(container)
#define CWHOLE(container) std::cbegin(container), std::cend(container)
using namespace std;

// Constants
//-----------

const vector<const char*> VulkanHandler::k_validation_layers = []() {
  const vector<const char*> value{"VK_LAYER_KHRONOS_validation"};

  // Easier to compare. Same name makes the assertion fail output more readable.
  vector<string> k_validation_layers(CWHOLE(value));
  assert(std::is_sorted(CWHOLE(k_validation_layers)));

  return value;
}();

// Method Definitions
//--------------------

vk::UniqueInstance createInstance();
// is used by:
VulkanHandler::VulkanHandler() : vk_instance_{createInstance()}
{
}

// Helpers
//---------

bool checkValidationLayerSupport();
vector<const char*> getExtensions();
// are used by:
vk::UniqueInstance createInstance()
{
  if (VulkanHandler::k_enable_validation_layers
      && !checkValidationLayerSupport()) {
    throw std::runtime_error("validation layers requested, but not available!");
  }

  vk::ApplicationInfo app_info{ //
      "Hello Triangle",         // pApplicationName
      VK_MAKE_VERSION(1, 0, 0), // application version
      "No Engine",              //
      VK_MAKE_VERSION(1, 0, 0), // engine version
      VK_API_VERSION_1_0};      //

  auto extensions = getExtensions();

  vk::InstanceCreateInfo create_info{{}, &app_info, 0, {},
      static_cast<uint32_t>(extensions.size()), extensions.data()};
  if (VulkanHandler::k_enable_validation_layers) {
    create_info.enabledLayerCount =
        static_cast<uint32_t>(VulkanHandler::k_validation_layers.size());
    create_info.ppEnabledLayerNames = VulkanHandler::k_validation_layers.data();
  }

  return vk::createInstanceUnique(create_info);
}

bool checkValidationLayerSupport()
{
  // set<string> is sorted, and its elements are trivially comparable.
  std::set<string> available_layer_names{};
  for (const auto& layer_properties : vk::enumerateInstanceLayerProperties()) {
    available_layer_names.emplace(layer_properties.layerName);
  }

  return std::includes(CWHOLE(available_layer_names),
      CWHOLE(VulkanHandler::k_validation_layers));
}

vector<const char*> getExtensions()
{
  uint32_t glfw_extension_count{};
  const char** glfw_extensions =
      glfwGetRequiredInstanceExtensions(&glfw_extension_count);

  vector<const char*> extensions(glfw_extension_count);
  std::copy_n(glfw_extensions, glfw_extension_count, begin(extensions));

  return extensions;
}

// vim:set et ts=2 sw=0 sts=0:

<|endoftext|>


<commit_before>//
//#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <ctime>
#include <algorithm>
#include <cmath>
#include "GPIOClass.h"

using namespace std;

void Pulse(GPIOClass* pin, double cycles);
void Wait(double seconds);
clock_t timer;
double time_to_complete;
double resolution = 1000;

#define PI 4*atan(1)

int main (int argc, char *argv[]) {
	string type = argv[1];
	transform(type.begin(), type.end(), type.begin(), :: tolower);
	// lets assume that the way to run this is
	// pwm.exe [rising/falling/sine/constant]
	if (argc != 2) {
		cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl;
		return -1;
	}

	while (time_to_complete <= 0) {
		cout << "Input How Long To Run (in seconds)" << endl;
		cin >> time_to_complete;
	}

	GPIOClass* out1 = new GPIOClass("4");
	GPIOClass* in2 = new GPIOClass("17");

	out1->export_gpio();
	in2->export_gpio();

	out1->setdir_gpio("out");
	in2->setdir_gpio("in");

	cout << "Pins are setup." << endl;
	// avoiding flickering will be at 100hz
	// aka turn on and off 100 times a sec
	// a cycle of 0 is off
	// a cycle of 100 is on

	if (type == "rising") {
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			for(int i = 0 ; i < time_to_complete; i++ ){
				Pulse(out1, sin((PI/2) * (i/time_to_complete)));
				Wait(sin((PI/2) * (i/time_to_complete)));
			}
		}
	}
	if (type == "falling") {

	}
	if (type == "sine") {

	}
	if (type == "constant") {
		out1->setval_gpio("1"); // turn the pin on
		Wait(time_to_complete); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		out1->setval_gpio("0"); // turn the pin off
	}
	if (type == "blink") { // aka. TESTR
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			Pulse(out1, 1 * resolution);
			Wait(0.5);
		}
	}
	cout << "Done." << endl;
}

//1 cycle is 1/100th of a second
//100 cycles is 1 sec
void Pulse(GPIOClass* pin, double cycles) {
	bool running = true;
	while (running) {
		pin->setval_gpio("1"); // turn the pin on
		Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		pin->setval_gpio("0"); // turn the pin off
		running = false; // this is unnessesary but could be useful if modified a bit.
	}
}

void Wait ( double seconds )
{
	clock_t endwait;
	endwait = clock () + seconds * CLOCKS_PER_SEC ;
	while (clock() < endwait) {}
}
<commit_msg>Update pwm.cpp<commit_after>//
//#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <ctime>
#include <algorithm>
#include <cmath>
#include "GPIOClass.h"

using namespace std;

void Pulse(GPIOClass* pin, double cycles);
void Wait(double seconds);
clock_t timer;
double time_to_complete;
double resolution = 1000;

#define PI 4*atan(1)

int main (int argc, char *argv[]) {
	string type = argv[1];
	transform(type.begin(), type.end(), type.begin(), :: tolower);
	// lets assume that the way to run this is
	// pwm.exe [rising/falling/sine/constant]
	if (argc != 2) {
		cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl;
		return -1;
	}

	while (time_to_complete <= 0) {
		cout << "Input How Long To Run (in seconds)" << endl;
		cin >> time_to_complete;
	}

	GPIOClass* out1 = new GPIOClass("4");
	GPIOClass* in2 = new GPIOClass("17");

	out1->export_gpio();
	in2->export_gpio();

	out1->setdir_gpio("out");
	in2->setdir_gpio("in");

	cout << "Pins are setup." << endl;
	// avoiding flickering will be at 100hz
	// aka turn on and off 100 times a sec
	// a cycle of 0 is off
	// a cycle of 100 is on

	if (type == "rising") {
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
				Pulse(out1, sin((PI/2) * (time_to_complete/finish)));
				Wait(sin((PI/2) * (time_to_complete/finish)));
		}
	}
	if (type == "falling") {

	}
	if (type == "sine") {

	}
	if (type == "constant") {
		out1->setval_gpio("1"); // turn the pin on
		Wait(time_to_complete); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		out1->setval_gpio("0"); // turn the pin off
	}
	if (type == "blink") { // aka. TESTR
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			Pulse(out1, 1 * resolution);
			Wait(0.5);
		}
	}
	cout << "Done." << endl;
}

//1 cycle is 1/100th of a second
//100 cycles is 1 sec
void Pulse(GPIOClass* pin, double cycles) {
	bool running = true;
	while (running) {
		pin->setval_gpio("1"); // turn the pin on
		Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		pin->setval_gpio("0"); // turn the pin off
		running = false; // this is unnessesary but could be useful if modified a bit.
	}
}

void Wait ( double seconds )
{
	clock_t endwait;
	endwait = clock () + seconds * CLOCKS_PER_SEC ;
	while (clock() < endwait) {}
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_ARR_FUN_VALUE_OF_HPP
#define STAN_MATH_PRIM_ARR_FUN_VALUE_OF_HPP

#include <stan/math/prim/scal/fun/value_of.hpp>
#include <stan/math/prim/scal/meta/child_type.hpp>
#include <vector>
#include <cstddef>

namespace stan {
namespace math {

/**
 * Convert a std::vector of type T to a std::vector of
 * child_type<T>::type.
 *
 * @tparam T Scalar type in std::vector
 * @param[in] x std::vector to be converted
 * @return std::vector of values
 **/
template <typename T>
inline std::vector<typename child_type<T>::type> value_of(
    const std::vector<T>& x) {
  size_t size = x.size();
  std::vector<typename child_type<T>::type> result(size);
  for (size_t i = 0; i < size; i++)
    result[i] = value_of(x[i]);
  return result;
}

/**
 * Return the specified argument.
 *
 *
See value_of(T) for a polymorphic
 * implementation using static casts.
 *
 *
This inline pass-through no-op should be compiled away.
 *
 * @param x Specified std::vector.
 * @return Specified std::vector.
 */
template <>
inline const std::vector<double>& value_of(const std::vector<double>& x) {
  return x;
}

}  // namespace math
}  // namespace stan

#endif
<commit_msg>value_of for std::vector<double>s didn't have a template to specialize from, so I made it just a plain overload and not a template specialization (Issue #968)<commit_after>#ifndef STAN_MATH_PRIM_ARR_FUN_VALUE_OF_HPP
#define STAN_MATH_PRIM_ARR_FUN_VALUE_OF_HPP

#include <stan/math/prim/scal/fun/value_of.hpp>
#include <stan/math/prim/scal/meta/child_type.hpp>
#include <vector>
#include <cstddef>

namespace stan {
namespace math {

/**
 * Convert a std::vector of type T to a std::vector of
 * child_type<T>::type.
 *
 * @tparam T Scalar type in std::vector
 * @param[in] x std::vector to be converted
 * @return std::vector of values
 **/
template <typename T>
inline std::vector<typename child_type<T>::type> value_of(
    const std::vector<T>& x) {
  size_t size = x.size();
  std::vector<typename child_type<T>::type> result(size);
  for (size_t i = 0; i < size; i++)
    result[i] = value_of(x[i]);
  return result;
}

/**
 * Return the specified argument.
 *
 *
See value_of(T) for a polymorphic
 * implementation using static casts.
 *
 *
This inline pass-through no-op should be compiled away.
 *
 * @param x Specified std::vector.
 * @return Specified std::vector.
 */
inline const std::vector<double>& value_of(const std::vector<double>& x) {
  return x;
}

}  // namespace math
}  // namespace stan

#endif
<|endoftext|>


<commit_before>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include "config.h"

#include <cmath>
#include <sys/time.h>

#include <dune/stuff/test/gtest/gtest.h>

#include "common.hh"

void busywait(const int ms)
{
  // "round" up to next full 10 ms to align with native timer res
  const int milliseconds = (ms/10)*10 + 10;
  timeval start, end;
  gettimeofday(&start, NULL);
  do {
   gettimeofday(&end, NULL);
  } while (((end.tv_sec - start.tv_sec)*1e6) + ((end.tv_usec - start.tv_usec)) < milliseconds*1000);
} // ... busywait(...)

namespace Dune {
namespace Stuff {
namespace Test {
namespace internal {

std::pair< size_t, ssize_t > convert_to_scientific(const double number, const size_t precision)
{
  // see http://www.mathworks.com/matlabcentral/newsreader/view_thread/151859
  const double sign = (number > 0.0) ? 1.0 : -1.0;
  const double tmp = std::log10(std::abs(number));
  ssize_t exponent = ((tmp > 0) ? 1 : -1) * std::floor(std::abs(tmp));
  double coefficient = sign * std::pow(10.0, tmp - exponent);
  if (std::abs(coefficient) < 1.0) {
    coefficient *= 10.0;
    exponent -= 1;
  }
  const double factor = std::pow(10, precision);
//  std::cout << "number      = " << number << std::endl;
//  std::cout << "exponent    = " << exponent << std::endl;
//  std::cout << "coefficient = " << coefficient << std::endl;
//  std::cout << "scaled         = " << std::round(factor * coefficient) << std::endl;
//  std::cout << "size_t(scaled) = " << size_t(std::round(factor * coefficient)) << std::endl << std::endl;

  return std::make_pair(size_t(std::round(factor * coefficient)), exponent);
} // ... convert_to_scientific(...)

} // namespace internal

void check_eoc_study_for_success(const Dune::Stuff::Common::ConvergenceStudy& study,
                                 const std::map< std::string, std::vector< double > >& results_map)
{
  for (const auto& norm : study.used_norms()) {
    const auto expected_results = study.expected_results(norm);
    const auto results_search = results_map.find(norm);
    EXPECT_NE(results_search, results_map.end())
        << "          norm = " << norm;
    const auto& actual_results = results_search->second;
    EXPECT_LE(actual_results.size(), expected_results.size())
        << "          norm = " << norm;
    for (size_t ii = 0; ii < actual_results.size(); ++ii) {
      const auto actual_result   = internal::convert_to_scientific(actual_results[ii], 2);
      const auto expected_result = internal::convert_to_scientific(expected_results[ii], 2);
      const auto actual_exponent = actual_result.second;
      const auto expected_exponent = expected_result.second;
      EXPECT_EQ(actual_exponent, expected_exponent)
          << "          Exponent comparison (in scientific notation, precision 2) failed for\n"
          << "          norm: " << norm << "\n"
          << "          actual_results[" << ii << "]   = " << actual_results[ii] << "\n"
          << "          expected_results[" << ii << "] = " << expected_results[ii];
      const auto actual_coefficient = actual_result.first;
      const auto expected_coefficient = expected_result.first;
      EXPECT_EQ(actual_coefficient, expected_coefficient)
          << "          Coefficient comparison (in scientific notation, precision 2) failed for\n"
          << "          norm: " << norm << "\n"
          << "          actual_results[" << ii << "]   = " << actual_results[ii] << "\n"
          << "          expected_results[" << ii << "] = " << expected_results[ii];
    }
  }
} // ... check_for_success(...)

} // namespace Test
} // namespace Stuff
} // namespace Dune
<commit_msg>[test.common] prevent check_eoc_study_for_success() from segfaulting<commit_after>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include "config.h"

#include <cmath>
#include <sys/time.h>

#include <dune/stuff/test/gtest/gtest.h>

#include "common.hh"

void busywait(const int ms)
{
  // "round" up to next full 10 ms to align with native timer res
  const int milliseconds = (ms/10)*10 + 10;
  timeval start, end;
  gettimeofday(&start, NULL);
  do {
   gettimeofday(&end, NULL);
  } while (((end.tv_sec - start.tv_sec)*1e6) + ((end.tv_usec - start.tv_usec)) < milliseconds*1000);
} // ... busywait(...)

namespace Dune {
namespace Stuff {
namespace Test {
namespace internal {

std::pair< size_t, ssize_t > convert_to_scientific(const double number, const size_t precision)
{
  // see http://www.mathworks.com/matlabcentral/newsreader/view_thread/151859
  const double sign = (number > 0.0) ? 1.0 : -1.0;
  const double tmp = std::log10(std::abs(number));
  ssize_t exponent = ((tmp > 0) ? 1 : -1) * std::floor(std::abs(tmp));
  double coefficient = sign * std::pow(10.0, tmp - exponent);
  if (std::abs(coefficient) < 1.0) {
    coefficient *= 10.0;
    exponent -= 1;
  }
  const double factor = std::pow(10, precision);
//  std::cout << "number      = " << number << std::endl;
//  std::cout << "exponent    = " << exponent << std::endl;
//  std::cout << "coefficient = " << coefficient << std::endl;
//  std::cout << "scaled         = " << std::round(factor * coefficient) << std::endl;
//  std::cout << "size_t(scaled) = " << size_t(std::round(factor * coefficient)) << std::endl << std::endl;

  return std::make_pair(size_t(std::round(factor * coefficient)), exponent);
} // ... convert_to_scientific(...)

} // namespace internal

void check_eoc_study_for_success(const Dune::Stuff::Common::ConvergenceStudy& study,
                                 const std::map< std::string, std::vector< double > >& results_map)
{
  for (const auto& norm : study.used_norms()) {
    const auto expected_results = study.expected_results(norm);
    const auto results_search = results_map.find(norm);
    EXPECT_NE(results_search, results_map.end())
        << "          norm = " << norm;
    if (results_search == results_map.end())
      return;
    const auto& actual_results = results_search->second;
    EXPECT_LE(actual_results.size(), expected_results.size())
        << "          norm = " << norm;
    if (actual_results.size() > expected_results.size())
      return;
    for (size_t ii = 0; ii < actual_results.size(); ++ii) {
      const auto actual_result   = internal::convert_to_scientific(actual_results[ii], 2);
      const auto expected_result = internal::convert_to_scientific(expected_results[ii], 2);
      const auto actual_exponent = actual_result.second;
      const auto expected_exponent = expected_result.second;
      EXPECT_EQ(actual_exponent, expected_exponent)
          << "          Exponent comparison (in scientific notation, precision 2) failed for\n"
          << "          norm: " << norm << "\n"
          << "          actual_results[" << ii << "]   = " << actual_results[ii] << "\n"
          << "          expected_results[" << ii << "] = " << expected_results[ii];
      if (actual_exponent != expected_exponent)
        return;
      const auto actual_coefficient = actual_result.first;
      const auto expected_coefficient = expected_result.first;
      EXPECT_EQ(actual_coefficient, expected_coefficient)
          << "          Coefficient comparison (in scientific notation, precision 2) failed for\n"
          << "          norm: " << norm << "\n"
          << "          actual_results[" << ii << "]   = " << actual_results[ii] << "\n"
          << "          expected_results[" << ii << "] = " << expected_results[ii];
    }
  }
} // ... check_for_success(...)

} // namespace Test
} // namespace Stuff
} // namespace Dune
<|endoftext|>