<commit_before>/*************************************************************************
 *
 *  $RCSfile: TitledControl.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2005-03-18 16:59:16 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "TitledControl.hxx"

#include "AccessibleTitledControl.hxx"
#include "ControlContainer.hxx"
#include "TaskPaneFocusManager.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"

#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

namespace sd { namespace toolpanel {

TitledControl::TitledControl (
    TreeNode* pParent,
    ::std::auto_ptr<TreeNode> pControl,
    const String& rTitle,
    TitleBar::TitleBarType eType)
    : ::Window (pParent->GetWindow(), WB_TABSTOP),
      TreeNode(pParent),
      msTitle (rTitle),
      mpUserData (NULL),
      mbVisible (true),
      mpControlFactory(NULL)
{
    if (pControl.get() != NULL)
    {
        mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
            new TitleBar (this, rTitle, eType, pControl->IsExpandable())));
        pControl->SetParentNode (this);
    }
    mpControlContainer->AddControl (pControl);

    FocusManager::Instance().RegisterLink (
        this,
        GetControl()->GetWindow());

    SetBackground (Wallpaper());

    GetTitleBar()->GetWindow()->Show ();
    GetTitleBar()->GetWindow()->AddEventListener (
        LINK(this,TitledControl,WindowEventListener));

    UpdateStates ();
}

TitledControl::TitledControl (
    TreeNode* pParent,
    ::std::auto_ptr<ControlFactory> pControlFactory,
    const String& rTitle,
    TitleBar::TitleBarType eType)
    : ::Window (pParent->GetWindow(), WB_TABSTOP),
      TreeNode(pParent),
      msTitle (rTitle),
      mpUserData (NULL),
      mbVisible (true),
      mpControlFactory(pControlFactory)
{
    mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
        new TitleBar (this, rTitle, eType, true)));

    // The second control is created on demand, i.e. when GetControl(true)
    // is called the first time.

    SetBackground (Wallpaper());

    GetTitleBar()->GetWindow()->Show ();
    GetTitleBar()->GetWindow()->AddEventListener (
        LINK(this,TitledControl,WindowEventListener));

    UpdateStates ();
}

TitledControl::~TitledControl (void)
{
    GetTitleBar()->GetWindow()->RemoveEventListener (
        LINK(this,TitledControl,WindowEventListener));
}

Size TitledControl::GetPreferredSize (void)
{
    Size aPreferredSize;
    if (GetControl(false) != NULL)
    {
        aPreferredSize = GetControl()->GetPreferredSize();
        if ( ! IsExpanded())
            aPreferredSize.Height() = 0;
    }
    else
        aPreferredSize = Size (GetSizePixel().Width(), 0);
    if (aPreferredSize.Width() == 0)
        aPreferredSize.Width() = 300;
    aPreferredSize.Height() += GetTitleBar()->GetPreferredHeight(
        aPreferredSize.Width());

    return aPreferredSize;
}

sal_Int32 TitledControl::GetPreferredWidth (sal_Int32 nHeight)
{
    int nPreferredWidth = 0;
    if (GetControl(false) != NULL)
        nPreferredWidth = GetControl()->GetPreferredWidth(
            nHeight - GetTitleBar()->GetWindow()->GetSizePixel().Height());
    else
        nPreferredWidth = GetSizePixel().Width();
    if (nPreferredWidth == 0)
        nPreferredWidth = 300;

    return nPreferredWidth;
}

sal_Int32 TitledControl::GetPreferredHeight (sal_Int32 nWidth)
{
    int nPreferredHeight = 0;
    if (IsExpanded() && GetControl(false)!=NULL)
        nPreferredHeight = GetControl()->GetPreferredHeight(nWidth);
    nPreferredHeight += GetTitleBar()->GetPreferredHeight(nWidth);

    return nPreferredHeight;
}

bool TitledControl::IsResizable (void)
{
    return IsExpanded()
        && GetControl()->IsResizable();
}

::Window* TitledControl::GetWindow (void)
{
    return this;
}

void TitledControl::Resize (void)
{
    Size aWindowSize (GetOutputSizePixel());

    int nTitleBarHeight
        = GetTitleBar()->GetPreferredHeight(aWindowSize.Width());
    GetTitleBar()->GetWindow()->SetPosSizePixel (
        Point (0,0),
        Size (aWindowSize.Width(), nTitleBarHeight));

    TreeNode* pControl = GetControl(false);
    if (pControl != NULL
        && pControl->GetWindow() != NULL
        && pControl->GetWindow()->IsVisible())
    {
        pControl->GetWindow()->SetPosSizePixel (
            Point (0,nTitleBarHeight),
            Size (aWindowSize.Width(), aWindowSize.Height()-nTitleBarHeight));
    }
}

void TitledControl::GetFocus (void)
{
    ::Window::GetFocus();
    if (GetTitleBar() != NULL)
        GetTitleBar()->SetFocus (true);
}

void TitledControl::LoseFocus (void)
{
    ::Window::LoseFocus();
    if (GetTitleBar() != NULL)
        GetTitleBar()->SetFocus (false);
}

void TitledControl::KeyInput (const KeyEvent& rEvent)
{
    KeyCode nCode = rEvent.GetKeyCode();
    if (nCode == KEY_SPACE)
    {
        // Toggle the expansion state of the control (when toggling is
        // supported.)  The focus remains on this control.
        GetParentNode()->GetControlContainer().SetExpansionState (
            this,
            ControlContainer::ES_TOGGLE);
    }
    else if (nCode == KEY_RETURN)
    {
        // Return, also called enter, enters the control and puts the
        // focus to the first child.  If the control is not yet
        // expanded then do that first.
        GetParentNode()->GetControlContainer().SetExpansionState (
            this,
            ControlContainer::ES_EXPAND);

        if ( ! FocusManager::Instance().TransferFocusDown (this))
        {
            // When already expanded then put focus on first child.
            TreeNode* pControl = GetControl(false);
            if (pControl!=NULL && IsExpanded())
                if (pControl->GetWindow() != NULL)
                    pControl->GetWindow()->GrabFocus();
        }
    }
    else if (nCode == KEY_ESCAPE)
    {
        if ( ! FocusManager::Instance().TransferFocusUp (this))
            // Put focus to parent.
            GetParent()->GrabFocus();
    }
    else
        Window::KeyInput (rEvent);
}

const String& TitledControl::GetTitle (void) const
{
    return msTitle;
}

void TitledControl::Expand (bool bExpanded)
{
    if (IsExpandable())
    {
        GetTitleBar()->Expand (bExpanded);
        // Get the control.  Use the bExpanded parameter as argument to
        // indicate that a control is created via its factory only when it
        // is to be expanded.  When it is collapsed this is not necessary.
        TreeNode* pControl = GetControl(bExpanded);
        if (pControl != NULL)
            pControl->Expand (bExpanded);
        UpdateStates();
    }
}

void TitledControl::Collapse (void)
{
    Expand (false);
}

bool TitledControl::IsExpandable (void) const
{
    const TreeNode* pControl = GetConstControl(false);
    if (pControl != NULL)
        return pControl->IsExpandable();
    else
        // When a control factory is given but the control has not yet been
        // created we assume that the control is expandable.
        return true;
}

bool TitledControl::IsExpanded (void) const
{
    const TreeNode* pControl = GetConstControl(false);
    if (pControl != NULL)
        return pControl->IsExpanded();
    else
        return false;
}

void TitledControl::SetUserData (void* pUserData)
{
    mpUserData = pUserData;
}

void* TitledControl::GetUserData (void) const
{
    return mpUserData;
}

bool TitledControl::IsShowing (void) const
{
    return mbVisible;
}

void TitledControl::Show (bool bVisible)
{
    if (mbVisible != bVisible)
    {
        mbVisible = bVisible;
        UpdateStates ();
    }
}

::com::sun::star::uno::Reference<
    ::com::sun::star::accessibility::XAccessible>
    TitledControl::CreateAccessible (void)
{
    AccessibleTitledControl* pAccessible = new AccessibleTitledControl (*this);
    ::com::sun::star::uno::Reference<
          ::com::sun::star::accessibility::XAccessible> xAccessible (
              pAccessible);
    pAccessible->Init ();
    return xAccessible;
}

void TitledControl::UpdateStates (void)
{
    if (mbVisible)
        GetWindow()->Show();
    else
        GetWindow()->Hide();

    TreeNode* pControl = GetControl(false);
    if (pControl!=NULL  &&  pControl->GetWindow() != NULL)
        if (IsVisible() && IsExpanded())
            pControl->GetWindow()->Show();
        else
            pControl->GetWindow()->Hide();
}

IMPL_LINK(TitledControl, WindowEventListener,
    VclSimpleEvent*, pEvent)
{
    if (pEvent!=NULL && pEvent->ISA(VclWindowEvent))
    {
        VclWindowEvent* pWindowEvent = static_cast<VclWindowEvent*>(pEvent);
        switch (pWindowEvent->GetId())
        {
            case VCLEVENT_WINDOW_MOUSEBUTTONUP:
                // Toggle expansion.
                GetParentNode()->GetControlContainer().SetExpansionState (
                    this,
                    ControlContainer::ES_TOGGLE);
                break;
        }
    }
    return 0;
}

TreeNode* TitledControl::GetControl (bool bCreate)
{
    TreeNode* pNode = mpControlContainer->GetControl(1);
    if (pNode==NULL && mpControlFactory.get()!=NULL && bCreate)
    {
        // We have to create the control with the factory object.
        ::std::auto_ptr<TreeNode> pControl (mpControlFactory->CreateControl(this));//GetParentNode()));
        if (pControl.get() != NULL)
        {
            pControl->SetParentNode(this);
            mpControlContainer->AddControl(pControl);

            pNode = mpControlContainer->GetControl(1);
            FocusManager::Instance().RegisterLink (
                this,
                pNode->GetWindow());
        }
    }

    return pNode;
}

const TreeNode* TitledControl::GetConstControl (bool bCreate) const
{
    return const_cast<TitledControl*>(this)->GetControl(bCreate);
}

TitleBar* TitledControl::GetTitleBar (void)
{
    return static_cast<TitleBar*>(mpControlContainer->GetControl(0));
}

} } // end of namespace ::sd::toolpanel
<commit_msg>INTEGRATION: CWS impress37 (1.4.54); FILE MERGED 2005/03/10 10:51:06 af 1.4.54.1: #i44484# Expand() returns bool.  Removed Collapse().  Added mbExpansionModeIsToggle.<commit_after>/*************************************************************************
 *
 *  $RCSfile: TitledControl.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-23 14:14:26 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "TitledControl.hxx"

#include "AccessibleTitledControl.hxx"
#include "ControlContainer.hxx"
#include "TaskPaneFocusManager.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"

#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

namespace sd { namespace toolpanel {

TitledControl::TitledControl (
    TreeNode* pParent,
    ::std::auto_ptr<TreeNode> pControl,
    const String& rTitle,
    TitleBar::TitleBarType eType)
    : ::Window (pParent->GetWindow(), WB_TABSTOP),
      TreeNode(pParent),
    mpControlFactory(NULL),
      mbExpansionModeIsToggle(eType!=TitleBar::TBT_CONTROL_TITLE)
{
    if (pControl.get() != NULL)
    {
        mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
            new TitleBar (this, rTitle, eType, pControl->IsExpandable())));
        pControl->SetParentNode (this);
    }
    mpControlContainer->AddControl (pControl);

    FocusManager::Instance().RegisterLink (
        this,
        GetControl()->GetWindow());

    SetBackground (Wallpaper());

    GetTitleBar()->GetWindow()->Show ();
    GetTitleBar()->GetWindow()->AddEventListener (
        LINK(this,TitledControl,WindowEventListener));

    UpdateStates ();
}

TitledControl::TitledControl (
    TreeNode* pParent,
    ::std::auto_ptr<ControlFactory> pControlFactory,
    const String& rTitle,
    TitleBar::TitleBarType eType)
    : ::Window (pParent->GetWindow(), WB_TABSTOP),
      TreeNode(pParent),
      msTitle (rTitle),
      mbVisible (true),
      mpUserData (NULL),
      mpControlFactory(pControlFactory)
{
    mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
        new TitleBar (this, rTitle, eType, true)));

    // The second control is created on demand, i.e. when GetControl(true)
    // is called the first time.

    SetBackground (Wallpaper());

    GetTitleBar()->GetWindow()->Show ();
    GetTitleBar()->GetWindow()->AddEventListener (
        LINK(this,TitledControl,WindowEventListener));

    UpdateStates ();
}

TitledControl::~TitledControl (void)
{
    GetTitleBar()->GetWindow()->RemoveEventListener (
        LINK(this,TitledControl,WindowEventListener));
}

Size TitledControl::GetPreferredSize (void)
{
    Size aPreferredSize;
    if (GetControl(false) != NULL)
    {
        aPreferredSize = GetControl()->GetPreferredSize();
        if ( ! IsExpanded())
            aPreferredSize.Height() = 0;
    }
    else
        aPreferredSize = Size (GetSizePixel().Width(), 0);
    if (aPreferredSize.Width() == 0)
        aPreferredSize.Width() = 300;
    aPreferredSize.Height() += GetTitleBar()->GetPreferredHeight(
        aPreferredSize.Width());

    return aPreferredSize;
}

sal_Int32 TitledControl::GetPreferredWidth (sal_Int32 nHeight)
{
    int nPreferredWidth = 0;
    if (GetControl(false) != NULL)
        nPreferredWidth = GetControl()->GetPreferredWidth(
            nHeight - GetTitleBar()->GetWindow()->GetSizePixel().Height());
    else
        nPreferredWidth = GetSizePixel().Width();
    if (nPreferredWidth == 0)
        nPreferredWidth = 300;

    return nPreferredWidth;
}

sal_Int32 TitledControl::GetPreferredHeight (sal_Int32 nWidth)
{
    int nPreferredHeight = 0;
    if (IsExpanded() && GetControl(false)!=NULL)
        nPreferredHeight = GetControl()->GetPreferredHeight(nWidth);
    nPreferredHeight += GetTitleBar()->GetPreferredHeight(nWidth);

    return nPreferredHeight;
}

bool TitledControl::IsResizable (void)
{
    return IsExpanded()
        && GetControl()->IsResizable();
}

::Window* TitledControl::GetWindow (void)
{
    return this;
}

void TitledControl::Resize (void)
{
    Size aWindowSize (GetOutputSizePixel());

    int nTitleBarHeight
        = GetTitleBar()->GetPreferredHeight(aWindowSize.Width());
    GetTitleBar()->GetWindow()->SetPosSizePixel (
        Point (0,0),
        Size (aWindowSize.Width(), nTitleBarHeight));

    TreeNode* pControl = GetControl(false);
    if (pControl != NULL
        && pControl->GetWindow() != NULL
        && pControl->GetWindow()->IsVisible())
    {
        pControl->GetWindow()->SetPosSizePixel (
            Point (0,nTitleBarHeight),
            Size (aWindowSize.Width(), aWindowSize.Height()-nTitleBarHeight));
    }
}

void TitledControl::GetFocus (void)
{
    ::Window::GetFocus();
    if (GetTitleBar() != NULL)
        GetTitleBar()->SetFocus (true);
}

void TitledControl::LoseFocus (void)
{
    ::Window::LoseFocus();
    if (GetTitleBar() != NULL)
        GetTitleBar()->SetFocus (false);
}

void TitledControl::KeyInput (const KeyEvent& rEvent)
{
    KeyCode nCode = rEvent.GetKeyCode();
    if (nCode == KEY_SPACE)
    {
        // Toggle the expansion state of the control (when toggling is
        // supported.)  The focus remains on this control.
        GetParentNode()->GetControlContainer().SetExpansionState (
            this,
            ControlContainer::ES_TOGGLE);
    }
    else if (nCode == KEY_RETURN)
    {
        // Return, also called enter, enters the control and puts the
        // focus to the first child.  If the control is not yet
        // expanded then do that first.
        GetParentNode()->GetControlContainer().SetExpansionState (
            this,
            ControlContainer::ES_EXPAND);

        if ( ! FocusManager::Instance().TransferFocusDown (this))
        {
            // When already expanded then put focus on first child.
            TreeNode* pControl = GetControl(false);
            if (pControl!=NULL && IsExpanded())
                if (pControl->GetWindow() != NULL)
                    pControl->GetWindow()->GrabFocus();
        }
    }
    else if (nCode == KEY_ESCAPE)
    {
        if ( ! FocusManager::Instance().TransferFocusUp (this))
            // Put focus to parent.
            GetParent()->GrabFocus();
    }
    else
        Window::KeyInput (rEvent);
}

const String& TitledControl::GetTitle (void) const
{
    return msTitle;
}

bool TitledControl::Expand (bool bExpanded)
{
    bool bExpansionStateChanged (false);

    if (IsExpandable())
    {
        if (GetTitleBar()->IsExpanded() != bExpanded)
            bExpansionStateChanged |= GetTitleBar()->Expand (bExpanded);
        // Get the control.  Use the bExpanded parameter as argument to
        // indicate that a control is created via its factory only when it
        // is to be expanded.  When it is collapsed this is not necessary.
        TreeNode* pControl = GetControl(bExpanded);
        if (pControl != NULL
            && GetControl()->IsExpanded() != bExpanded)
        {
            bExpansionStateChanged |= pControl->Expand (bExpanded);
        }
        if (bExpansionStateChanged)
            UpdateStates();
    }

    return bExpansionStateChanged;
}

bool TitledControl::IsExpandable (void) const
{
    const TreeNode* pControl = GetConstControl(false);
    if (pControl != NULL)
        return pControl->IsExpandable();
    else
        // When a control factory is given but the control has not yet been
        // created we assume that the control is expandable.
        return true;
}

bool TitledControl::IsExpanded (void) const
{
    const TreeNode* pControl = GetConstControl(false);
    if (pControl != NULL)
        return pControl->IsExpanded();
    else
        return false;
}

void TitledControl::SetUserData (void* pUserData)
{
    mpUserData = pUserData;
}

void* TitledControl::GetUserData (void) const
{
    return mpUserData;
}

bool TitledControl::IsShowing (void) const
{
    return mbVisible;
}

void TitledControl::Show (bool bVisible)
{
    if (mbVisible != bVisible)
    {
        mbVisible = bVisible;
        UpdateStates ();
    }
}

::com::sun::star::uno::Reference<
    ::com::sun::star::accessibility::XAccessible>
    TitledControl::CreateAccessible (void)
{
    AccessibleTitledControl* pAccessible = new AccessibleTitledControl (*this);
    ::com::sun::star::uno::Reference<
          ::com::sun::star::accessibility::XAccessible> xAccessible (
              pAccessible);
    pAccessible->Init ();
    return xAccessible;
}

void TitledControl::UpdateStates (void)
{
    if (mbVisible)
        GetWindow()->Show();
    else
        GetWindow()->Hide();

    TreeNode* pControl = GetControl(false);
    if (pControl!=NULL  &&  pControl->GetWindow() != NULL)
        if (IsVisible() && IsExpanded())
            pControl->GetWindow()->Show();
        else
            pControl->GetWindow()->Hide();
}

IMPL_LINK(TitledControl, WindowEventListener,
    VclSimpleEvent*, pEvent)
{
    if (pEvent!=NULL && pEvent->ISA(VclWindowEvent))
    {
        VclWindowEvent* pWindowEvent = static_cast<VclWindowEvent*>(pEvent);
        switch (pWindowEvent->GetId())
        {
            case VCLEVENT_WINDOW_MOUSEBUTTONUP:
                // Toggle expansion.
                GetParentNode()->GetControlContainer().SetExpansionState (
                    this,
                    mbExpansionModeIsToggle ? ControlContainer::ES_TOGGLE
                                            : ControlContainer::ES_EXPAND);
                break;
        }
    }
    return 0;
}

TreeNode* TitledControl::GetControl (bool bCreate)
{
    TreeNode* pNode = mpControlContainer->GetControl(1);
    if (pNode==NULL && mpControlFactory.get()!=NULL && bCreate)
    {
        // We have to create the control with the factory object.
        ::std::auto_ptr<TreeNode> pControl (mpControlFactory->CreateControl(this));//GetParentNode()));
        if (pControl.get() != NULL)
        {
            pControl->SetParentNode(this);
            mpControlContainer->AddControl(pControl);

            pNode = mpControlContainer->GetControl(1);
            FocusManager::Instance().RegisterLink (
                this,
                pNode->GetWindow());
        }
    }

    return pNode;
}

const TreeNode* TitledControl::GetConstControl (bool bCreate) const
{
    return const_cast<TitledControl*>(this)->GetControl(bCreate);
}

TitleBar* TitledControl::GetTitleBar (void)
{
    return static_cast<TitleBar*>(mpControlContainer->GetControl(0));
}

} } // end of namespace ::sd::toolpanel
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SdUnoOutlineView.cxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 18:55:12 $
 *
 *  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_sd.hxx"

#include "SdUnoOutlineView.hxx"

#include "DrawController.hxx"
#ifndef SD_OUTLINE_VIEW_SHELL_HXX
#include "OutlineViewShell.hxx"
#endif
#include "sdpage.hxx"
#include "unopage.hxx"

#include <cppuhelper/proptypehlp.hxx>
#include <svx/unopage.hxx>

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

using ::rtl::OUString;
using namespace ::vos;
using namespace ::cppu;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

namespace sd {

SdUnoOutlineView::SdUnoOutlineView(
    DrawController& rController,
    OutlineViewShell& rViewShell,
    View& rView) throw()
    :   DrawSubController(),
        mrController(rController),
        mrOutlineViewShell(rViewShell),
        mrView(rView)
{
}

SdUnoOutlineView::~SdUnoOutlineView (void) throw()
{
}

// XSelectionSupplier

sal_Bool SAL_CALL SdUnoOutlineView::select( const Any&  )
    throw(lang::IllegalArgumentException, RuntimeException)
{
    // todo: add selections for text ranges
    return sal_False;
}

Any SAL_CALL SdUnoOutlineView::getSelection()
    throw(RuntimeException)
{
    Any aAny;
    return aAny;
}

// XDrawView

void SAL_CALL SdUnoOutlineView::setCurrentPage (
    const Reference< drawing::XDrawPage >& xPage)
    throw(RuntimeException)
{
    SvxDrawPage* pDrawPage = SvxDrawPage::getImplementation( xPage );
    SdrPage *pSdrPage = pDrawPage ? pDrawPage->GetSdrPage() : NULL;

    if (pSdrPage != NULL)
        mrOutlineViewShell.SetCurrentPage(dynamic_cast<SdPage*>(pSdrPage));
}

Reference< drawing::XDrawPage > SAL_CALL SdUnoOutlineView::getCurrentPage (void)
    throw(RuntimeException)
{
    Reference<drawing::XDrawPage>  xPage;

    SdPage* pPage = mrOutlineViewShell.getCurrentPage();
    if (pPage != NULL)
        xPage = Reference<drawing::XDrawPage>::query(pPage->getUnoPage());

    return xPage;
}

// Return sal_True, value change
sal_Bool SdUnoOutlineView::convertFastPropertyValue (
    Any & rConvertedValue,
    Any & rOldValue,
    sal_Int32 nHandle,
    const Any& rValue)
    throw ( com::sun::star::lang::IllegalArgumentException)
{
    sal_Bool bResult = sal_False;

    switch( nHandle )
    {
        case DrawController::PROPERTY_CURRENTPAGE:
            {
                Reference< drawing::XDrawPage > xOldPage( getCurrentPage() );
                Reference< drawing::XDrawPage > xNewPage;
                ::cppu::convertPropertyValue( xNewPage, rValue );
                if( xOldPage != xNewPage )
                {
                    rConvertedValue <<= xNewPage;
                    rOldValue <<= xOldPage;
                    bResult = sal_True;
                }
            }
            break;

        default:
            break;
    }

    return bResult;
}

/**
 * only set the value.
 */
void SdUnoOutlineView::setFastPropertyValue_NoBroadcast (
    sal_Int32 nHandle,
    const Any& rValue)
    throw ( com::sun::star::uno::Exception)
{
    switch( nHandle )
    {
        case DrawController::PROPERTY_CURRENTPAGE:
        {
            Reference< drawing::XDrawPage > xPage;
            rValue >>= xPage;
            setCurrentPage( xPage );
        }
        break;

        default:
            break;
    }
}

void SAL_CALL SdUnoOutlineView::disposing (const ::com::sun::star::lang::EventObject& )
    throw (::com::sun::star::uno::RuntimeException)
{
}

void SdUnoOutlineView::getFastPropertyValue(
    Any & rRet,
    sal_Int32 nHandle ) const
{
    switch( nHandle )
    {
        case DrawController::PROPERTY_CURRENTPAGE:
        {
            SdPage* pPage = const_cast<OutlineViewShell&>(mrOutlineViewShell).GetActualPage();
            if (pPage != NULL)
                rRet <<= pPage->getUnoPage();
        }
        break;

        default:
            break;
    }
}

} // end of namespace sd
<commit_msg>INTEGRATION: CWS presenterview (1.19.54); FILE MERGED 2007/09/25 08:03:14 af 1.19.54.2: #i18486# Removed unreachable breaks.  Added disposing() method. 2007/09/11 11:22:49 af 1.19.54.1: #i18486# Turned SubControllers into components.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SdUnoOutlineView.cxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: kz $ $Date: 2008-04-03 14:55:28 $
 *
 *  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_sd.hxx"

#include "SdUnoOutlineView.hxx"

#include "DrawController.hxx"
#ifndef SD_OUTLINE_VIEW_SHELL_HXX
#include "OutlineViewShell.hxx"
#endif
#include "sdpage.hxx"
#include "unopage.hxx"

#include <cppuhelper/proptypehlp.hxx>
#include <svx/unopage.hxx>

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

using ::rtl::OUString;
using namespace ::vos;
using namespace ::cppu;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

namespace sd {

SdUnoOutlineView::SdUnoOutlineView(
    DrawController& rController,
    OutlineViewShell& rViewShell,
    View& rView) throw()
    :   DrawSubControllerInterfaceBase(m_aMutex),
        mrController(rController),
        mrOutlineViewShell(rViewShell),
        mrView(rView)
{
}

SdUnoOutlineView::~SdUnoOutlineView (void) throw()
{
}

void SAL_CALL SdUnoOutlineView::disposing (void)
{
}

//----- XSelectionSupplier ----------------------------------------------------

sal_Bool SAL_CALL SdUnoOutlineView::select( const Any&  )
    throw(lang::IllegalArgumentException, RuntimeException)
{
    // todo: add selections for text ranges
    return sal_False;
}

Any SAL_CALL SdUnoOutlineView::getSelection()
    throw(RuntimeException)
{
    Any aAny;
    return aAny;
}

void SAL_CALL SdUnoOutlineView::addSelectionChangeListener (
    const css::uno::Reference<css::view::XSelectionChangeListener>& rxListener)
    throw(css::uno::RuntimeException)
{
    (void)rxListener;
}

void SAL_CALL SdUnoOutlineView::removeSelectionChangeListener (
    const css::uno::Reference<css::view::XSelectionChangeListener>& rxListener)
    throw(css::uno::RuntimeException)
{
    (void)rxListener;
}

//----- XDrawView -------------------------------------------------------------

void SAL_CALL SdUnoOutlineView::setCurrentPage (
    const Reference< drawing::XDrawPage >& xPage)
    throw(RuntimeException)
{
    SvxDrawPage* pDrawPage = SvxDrawPage::getImplementation( xPage );
    SdrPage *pSdrPage = pDrawPage ? pDrawPage->GetSdrPage() : NULL;

    if (pSdrPage != NULL)
        mrOutlineViewShell.SetCurrentPage(dynamic_cast<SdPage*>(pSdrPage));
}

Reference< drawing::XDrawPage > SAL_CALL SdUnoOutlineView::getCurrentPage (void)
    throw(RuntimeException)
{
    Reference<drawing::XDrawPage>  xPage;

    SdPage* pPage = mrOutlineViewShell.getCurrentPage();
    if (pPage != NULL)
        xPage = Reference<drawing::XDrawPage>::query(pPage->getUnoPage());

    return xPage;
}

/*
// Return sal_True, value change
sal_Bool SdUnoOutlineView::convertFastPropertyValue (
    Any & rConvertedValue,
    Any & rOldValue,
    sal_Int32 nHandle,
    const Any& rValue)
    throw ( com::sun::star::lang::IllegalArgumentException)
{
    sal_Bool bResult = sal_False;

    switch( nHandle )
    {
        case DrawController::PROPERTY_CURRENTPAGE:
            {
                Reference< drawing::XDrawPage > xOldPage( getCurrentPage() );
                Reference< drawing::XDrawPage > xNewPage;
                ::cppu::convertPropertyValue( xNewPage, rValue );
                if( xOldPage != xNewPage )
                {
                    rConvertedValue <<= xNewPage;
                    rOldValue <<= xOldPage;
                    bResult = sal_True;
                }
            }
            break;

        default:
            break;
    }

    return bResult;
}
*/

void SdUnoOutlineView::setFastPropertyValue (
    sal_Int32 nHandle,
        const Any& rValue)
    throw(css::beans::UnknownPropertyException,
        css::beans::PropertyVetoException,
        css::lang::IllegalArgumentException,
        css::lang::WrappedTargetException,
        css::uno::RuntimeException)
{
    switch( nHandle )
    {
        case DrawController::PROPERTY_CURRENTPAGE:
        {
            Reference< drawing::XDrawPage > xPage;
            rValue >>= xPage;
            setCurrentPage( xPage );
        }
        break;

        default:
            throw beans::UnknownPropertyException();
    }
}

void SAL_CALL SdUnoOutlineView::disposing (const ::com::sun::star::lang::EventObject& )
    throw (::com::sun::star::uno::RuntimeException)
{
}

Any SAL_CALL SdUnoOutlineView::getFastPropertyValue (
    sal_Int32 nHandle)
    throw(css::beans::UnknownPropertyException,
        css::lang::WrappedTargetException,
        css::uno::RuntimeException)
{
    Any aValue;

    switch( nHandle )
    {
        case DrawController::PROPERTY_CURRENTPAGE:
        {
            SdPage* pPage = const_cast<OutlineViewShell&>(mrOutlineViewShell).GetActualPage();
            if (pPage != NULL)
                aValue <<= pPage->getUnoPage();
        }
        break;

        default:
            throw beans::UnknownPropertyException();
    }

    return aValue;
}

} // end of namespace sd
<|endoftext|>


<commit_before>//! Copyright (c) 2013 ASMlover. All rights reserved.
//!
//! Redistribution and use in source and binary forms, with or without
//! modification, are permitted provided that the following conditions
//! are met:
//!
//!  * Redistributions of source code must retain the above copyright
//!    notice, this list ofconditions and the following disclaimer.
//!
//!  * Redistributions in binary form must reproduce the above copyright
//!    notice, this list of conditions and the following disclaimer in
//!    the documentation and/or other materialsprovided with the
//!    distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#include "libnet_internal.h"
#include "tools.h"
#include "thread.h"
#include "socket.h"
#include "connector_dispatcher.h"
#include "worker.h"
#include "listener.h"
<commit_msg>finished the implementation of Listener module<commit_after>//! Copyright (c) 2013 ASMlover. All rights reserved.
//!
//! Redistribution and use in source and binary forms, with or without
//! modification, are permitted provided that the following conditions
//! are met:
//!
//!  * Redistributions of source code must retain the above copyright
//!    notice, this list ofconditions and the following disclaimer.
//!
//!  * Redistributions in binary form must reproduce the above copyright
//!    notice, this list of conditions and the following disclaimer in
//!    the documentation and/or other materialsprovided with the
//!    distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#include "libnet_internal.h"
#include "tools.h"
#include "thread.h"
#include "address.h"
#include "socket.h"
#include "connector_dispatcher.h"
#include "worker.h"
#include "listener.h"

Listener::Listener(void)
  : running_(false)
  , listener_(NULL)
  , thread_(NULL)
  , dispatcher_(NULL)
{
}

Listener::~Listener(void)
{
  Stop();
}

bool
Listener::Start(const char* ip, uint16_t port)
{
  if (NULL == dispatcher_)
    return false;

  listener_ = new Socket();
  if (NULL == listener_)
    return false;

  do {
    if (!listener_->Open()
        || !listener_->SetNonBlock()
        || !listener_->Bind(ip, port)
        || !listener_->Listen())
      break;

    thread_ = new Thread();
    if (NULL == thread_)
      break;

    running_ = true;
    thread_->Start(&Listener::Routine, this);

    return true;
  } while (0);

  Stop();
  return false;
}

void
Listener::Stop(void)
{
  running_ = false;

  if (NULL != thread_) {
    thread_->Stop();

    delete thread_;
    thread_ = NULL;
  }

  if (NULL != listener_) {
    listener_->Close();

    delete listener_;
    listener_ = NULL;
  }
}

void
Listener::Routine(void* argument)
{
  Listener* self = static_cast<Listener*>(argument);
  if (NULL == self || NULL == self->listener_
      || NULL == self->dispatcher_)
    return;

  Socket s;
  Address addr;
  while (self->running_) {
    if (!self->listener_->Accept(&s, &addr)) {
      tools::Sleep(1);
      continue;
    }
    else {
      Connector* conn = self->dispatcher_->Insert(s.fd());
      if (NULL != conn) {
        //! TODO:
        //! worker add connector
      }
      else {
        s.Close();
      }

      s.Detach();
      addr.Detach();
    }
  }
}
<|endoftext|>


<commit_before>#ifndef MJOLNIR_UNDERDAMPED_LANGEVIN_INTEGRATOR
#define MJOLNIR_UNDERDAMPED_LANGEVIN_INTEGRATOR
#include "constants.hpp"
#include "RandomNumberGenerator.hpp"
#include <mjolnir/util/zip_iterator.hpp>
#include <mjolnir/util/make_zip.hpp>

namespace mjolnir
{

template<typename traitsT>
class UnderdampedLangevinStepper
{
  public:
    typedef traitsT traits_type;
    typedef System<traits_type>     system_type;
    typedef ForceField<traits_type> forcefield_type;
    typedef RandomNumberGenerator<traits_type>    rng_type;
    typedef typename traits_type::boundary_type   boundary_type;
    typedef typename traits_type::real_type       real_type;
    typedef typename traits_type::coordinate_type coordinate_type;

  public:

    UnderdampedLangevinStepper(const real_type dt,
            std::vector<real_type>&& gamma, rng_type&& rng)
        : dt_(dt), halfdt_(dt * 0.5), halfdt2_(dt * dt * 0.5), rng_(std::move(rng)),
          gamma_(std::move(gamma)), noise_(gamma_.size()), accel_(gamma_.size())
    {}
    ~UnderdampedLangevinStepper() = default;

    void initialize(const system_type& sys);
    real_type step(const real_type time, system_type& sys, forcefield_type& ff);

    real_type delta_t() const noexcept {return dt_;}
    void  set_delta_t(const real_type dt) noexcept
    {
        dt_ = dt; halfdt_ = dt * 0.5; halfdt2_ = dt*dt*0.5;
    }

    rng_type&       random_number_generator()       noexcept {return rng_;}
    rng_type const& random_number_generator() const noexcept {return rng_;}

  private:

    coordinate_type gen_random_accel(const real_type m, const real_type g)
    {
        const real_type coef = this->noise_coef_ * std::sqrt(g / m);
        return coordinate_type(this->rng_.gaussian(0., coef),
                               this->rng_.gaussian(0., coef),
                               this->rng_.gaussian(0., coef));
    }

  private:
    real_type dt_;
    real_type halfdt_;
    real_type halfdt2_;
    real_type noise_coef_;
    rng_type  rng_;
    std::vector<real_type>       gamma_;
    std::vector<coordinate_type> noise_;
    std::vector<coordinate_type> accel_;
};

template<typename traitsT, typename randomT>
void UnderdampedLangevinStepper<traitsT, randomT>::initialize(
        const system_type& system)
{
    this->noise_coef =
        std::sqrt(2 * physics<real_type>::kB * sys.temperature() / dt_);

    for(auto iter = make_zip(system.cbegin(), gamma_.cbegin(),
                             noise_.begin(),  accel_.begin());
            iter != make_zip(system.cend(),   gamma_.cend(),
                             noise_.end(),    accel_.end()); ++iter)
    {
        *get<3>(iter) = get<0>(iter)->force / get<0>(iter)->mass;
        *get<2>(iter) = gen_random_accel(get<0>(iter)->mass,
                            /*gamma = */*get<1>(iter));
    }

    return;

}

template<typename traitsT, typename randomT>
typename UnderdampedLangevinStepper<traitsT, randomT>::real_type
UnderdampedLangevinStepper<traitsT, randomT>::step(
        const real_type time, system_type& sys, forcefield_type& ff)
{
    this->noise_coef =
        std::sqrt(2 * physics<real_type>::kB * sys.temperature() / dt_);

    for(auto iter(make_zip(sys.begin(),     gamma_.cbegin(),
                           noise_.cbegin(), accel_.cbegin())),
             end_(make_zip(sys.end(),       gamma_.cend(),
                           noise_.cend(),   accel_.cend())),
            iter != end_; ++iter)
    {
        const real_type hgdt   = (*get<1>(iter) * halfdt_);
        const real_type o_hgdt = 1. - hgdt;

        const coordinate_type noisy_force = ((*get<2>(iter)) + (*get<3>(iter)) / m);

        get<0>(iter)->position = boundary_type::adjust_absolute(
                get<0>(iter)->position +
                (dt_ * o_hgdt) * (get<0>(iter)->velocity) +
                halfdt2_ * noisy_force);

        get<0>(iter)->velocity *= o_hgdt * (o_hgdt * o_hgdt + hgdt);
        get<0>(iter)->velocity += (halfdt_ * o_hgdt) * noisy_force;
    }

    // calc f(t+dt)
    ff.calc_force(pcon);

    // calc a(t+dt) and v(t+dt), generate noise
    for(auto iter(make_zip(sys.begin(),    gamma_.cbegin(),
                           noise_.begin(), accel_.begin())),
             end_(make_zip(sys.end(),      gamma_.cend(),
                           noise_.end(),   accel_.end()));
            iter != end_; ++iter)
    {
        // consider cash 1/m
        const coordinate_type acc = get<0>(iter)->force / (get<0>(iter)->mass);
        *get<3>(iter) = acc;

        const coordinate_type noise =
            this->gen_random_accel(get<0>(iter)->mass, *get<1>(iter));
        *get<2>(iter) = noise;

        const real_type gm = (*get<1>(iter));
        get<0>(iter)->velocity +=
            halfdt_ * (1. - gm * halfdt_) * (acc + noise);
        get<0>(iter)->force = coordinate_type(0., 0., 0.);
    }

    return time + dt_;
}

} // mjolnir
#endif /* MJOLNIR_UNDERDAMPED_LANGEVIN_INTEGRATOR */
<commit_msg>fix invalid template arguments<commit_after>#ifndef MJOLNIR_UNDERDAMPED_LANGEVIN_INTEGRATOR
#define MJOLNIR_UNDERDAMPED_LANGEVIN_INTEGRATOR
#include "constants.hpp"
#include "RandomNumberGenerator.hpp"
#include <mjolnir/util/zip_iterator.hpp>
#include <mjolnir/util/make_zip.hpp>

namespace mjolnir
{

template<typename traitsT>
class UnderdampedLangevinStepper
{
  public:
    typedef traitsT traits_type;
    typedef System<traits_type>     system_type;
    typedef ForceField<traits_type> forcefield_type;
    typedef RandomNumberGenerator<traits_type>    rng_type;
    typedef typename traits_type::boundary_type   boundary_type;
    typedef typename traits_type::real_type       real_type;
    typedef typename traits_type::coordinate_type coordinate_type;

  public:

    UnderdampedLangevinStepper(const real_type dt,
            std::vector<real_type>&& gamma, rng_type&& rng)
        : dt_(dt), halfdt_(dt * 0.5), halfdt2_(dt * dt * 0.5), rng_(std::move(rng)),
          gamma_(std::move(gamma)), noise_(gamma_.size()), accel_(gamma_.size())
    {}
    ~UnderdampedLangevinStepper() = default;

    void initialize(const system_type& sys);
    real_type step(const real_type time, system_type& sys, forcefield_type& ff);

    real_type delta_t() const noexcept {return dt_;}
    void  set_delta_t(const real_type dt) noexcept
    {
        dt_ = dt; halfdt_ = dt * 0.5; halfdt2_ = dt*dt*0.5;
    }

    rng_type&       random_number_generator()       noexcept {return rng_;}
    rng_type const& random_number_generator() const noexcept {return rng_;}

  private:

    coordinate_type gen_random_accel(const real_type m, const real_type g)
    {
        const real_type coef = this->noise_coef_ * std::sqrt(g / m);
        return coordinate_type(this->rng_.gaussian(0., coef),
                               this->rng_.gaussian(0., coef),
                               this->rng_.gaussian(0., coef));
    }

  private:
    real_type dt_;
    real_type halfdt_;
    real_type halfdt2_;
    real_type noise_coef_;
    rng_type  rng_;
    std::vector<real_type>       gamma_;
    std::vector<coordinate_type> noise_;
    std::vector<coordinate_type> accel_;
};

template<typename traitsT>
void UnderdampedLangevinStepper<traitsT>::initialize(
        const system_type& system)
{
    this->noise_coef_ =
        std::sqrt(2 * physics<real_type>::kB * system.temperature() / dt_);

    for(auto iter = make_zip(system.cbegin(), gamma_.cbegin(),
                             noise_.begin(),  accel_.begin());
            iter != make_zip(system.cend(),   gamma_.cend(),
                             noise_.end(),    accel_.end()); ++iter)
    {
        *get<3>(iter) = get<0>(iter)->force / get<0>(iter)->mass;
        *get<2>(iter) = gen_random_accel(get<0>(iter)->mass,
                            /*gamma = */*get<1>(iter));
    }

    return;

}

template<typename traitsT>
typename UnderdampedLangevinStepper<traitsT>::real_type
UnderdampedLangevinStepper<traitsT>::step(
        const real_type time, system_type& sys, forcefield_type& ff)
{
    this->noise_coef_ =
        std::sqrt(2 * physics<real_type>::kB * sys.temperature() / dt_);

    for(auto iter(make_zip(sys.begin(),     gamma_.cbegin(),
                           noise_.cbegin(), accel_.cbegin())),
             end_(make_zip(sys.end(),       gamma_.cend(),
                           noise_.cend(),   accel_.cend()));
            iter != end_; ++iter)
    {
        const real_type hgdt   = (*get<1>(iter) * halfdt_);
        const real_type o_hgdt = 1. - hgdt;

        const coordinate_type noisy_force = (*get<2>(iter)) + (*get<3>(iter));

        get<0>(iter)->position = sys.adjust_position(
                get<0>(iter)->position +
                (dt_ * o_hgdt) * (get<0>(iter)->velocity) +
                halfdt2_ * noisy_force);

        get<0>(iter)->velocity *= o_hgdt * (o_hgdt * o_hgdt + hgdt);
        get<0>(iter)->velocity += (halfdt_ * o_hgdt) * noisy_force;
    }

    // calc f(t+dt)
    ff.calc_force(sys);

    // calc a(t+dt) and v(t+dt), generate noise
    for(auto iter(make_zip(sys.begin(),    gamma_.cbegin(),
                           noise_.begin(), accel_.begin())),
             end_(make_zip(sys.end(),      gamma_.cend(),
                           noise_.end(),   accel_.end()));
            iter != end_; ++iter)
    {
        // consider cash 1/m
        const coordinate_type acc = get<0>(iter)->force / (get<0>(iter)->mass);
        *get<3>(iter) = acc;

        const coordinate_type noise =
            this->gen_random_accel(get<0>(iter)->mass, *get<1>(iter));
        *get<2>(iter) = noise;

        const real_type gm = (*get<1>(iter));
        get<0>(iter)->velocity +=
            halfdt_ * (1. - gm * halfdt_) * (acc + noise);
        get<0>(iter)->force = coordinate_type(0., 0., 0.);
    }

    return time + dt_;
}

} // mjolnir
#endif /* MJOLNIR_UNDERDAMPED_LANGEVIN_INTEGRATOR */
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <sstream>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <sys/utsname.h>

static const char* const ANSI_COLOR_RESET_FG            = "\x1b[39m";

static const char* const ANSI_COLOR_TITLE_FG            = ANSI_COLOR_RESET_FG;
static const char* const ANSI_COLOR_EXPLANATION_FG      = ANSI_COLOR_RESET_FG;
static const char* const ANSI_COLOR_COMMENT_FG          = "\x1b[32m";

static const char* const ANSI_COLOR_CODE_FG             = "\x1b[31m";
static const char* const ANSI_COLOR_CODE_PLACEHOLDER_FG = "\x1b[34m";

static const char* const ANSI_BOLD_ON                   = "\x1b[1m";
static const char* const ANSI_BOLD_OFF                  = "\x1b[22m";

// Constants.
std::string const kBaseUrl =
    "http://raw.github.com/tldr-pages/tldr/master/pages";

void init_response(struct response* r);
size_t writeCallback(char* raw, size_t size, size_t nmemb, std::string* data);

// Fetching.
std::string getUrlForArgAndPlatform(std::string const& arg,
                                    std::string const& platform);
std::string getUrlForArg(std::string const& arg);
std::string getContentForUrl(std::string const& url);

// Utilities.
void replaceAll(std::string& str, std::string const& from,
                std::string const& to);

int main(int argc, char* argv[])
{
    struct utsname sys;
    uname(&sys);

    if (argc > 1)
    {
        std::string arg(argv[1]);
        std::string url = getUrlForArg(arg);
        std::string urlForPlatform = getUrlForArgAndPlatform(arg, sys.sysname);

        std::string response = getContentForUrl(urlForPlatform);
        if (response.empty()) { response = getContentForUrl(url); }

        replaceAll(response, "{{", ANSI_COLOR_CODE_PLACEHOLDER_FG);
        replaceAll(response, "}}", ANSI_COLOR_RESET_FG);

        std::string const stripPrefix("#");
        std::string const explainPrefix(">");
        std::string const commentPrefix("-");
        std::string const codePrefix("`");
        std::stringstream ss(response);
        std::string to;
        bool firstComment = true;

        while (std::getline(ss, to, '\n'))
        {
            // Title
            if (to.compare(0, stripPrefix.size(), stripPrefix) == 0)
            {
                replaceAll(to, "#", ANSI_COLOR_TITLE_FG);
                std::cout << std::endl
                          << ANSI_BOLD_ON
                          << to
                          << ANSI_BOLD_OFF
                          << ANSI_COLOR_RESET_FG
                          << std::endl;
            }
            // Command explanation
            else if (to.compare(0, explainPrefix.size(), explainPrefix) == 0)
            {
                replaceAll(to, explainPrefix, ANSI_COLOR_EXPLANATION_FG);
                std::cout << to << ANSI_COLOR_RESET_FG << std::endl;
            }
            // Example comment
            else if (to.compare(0, commentPrefix.size(), commentPrefix) == 0)
            {
                if (firstComment)
                {
                    std::cout << std::endl;
                    firstComment = false;
                }

                replaceAll(to, commentPrefix, ANSI_COLOR_COMMENT_FG);
                std::cout << to << ANSI_COLOR_RESET_FG << std::endl;
            }
            // Code example
            else if (to.compare(0, codePrefix.size(), codePrefix) == 0)
            {
                // Remove trailing backtick (`).
                to = to.substr(0, to.size() - 1);

                // Replace first backtick (`) with three spaces for aligned indentation.
                replaceAll(to, "`", "   ");
                std::cout << ANSI_COLOR_CODE_FG
                          << to
                          << ANSI_COLOR_RESET_FG
                          << std::endl
                          << std::endl;
            }
        }
    }
}

// =====================================
// URL determination.
// =====================================
std::string getUrlForArgAndPlatform(std::string const& arg,
                                    std::string const& platform)
{
    int isLinux = !platform.compare("Linux");
    int isOSX = !platform.compare("Darwin");

    std::string platformUrlDelimiter;
    if (isLinux) { platformUrlDelimiter = "linux"; }
    else if (isOSX) { platformUrlDelimiter = "osx"; }
    else { platformUrlDelimiter = "common"; }

    std::string url(kBaseUrl);
    url += "/" + platformUrlDelimiter + "/" + arg + ".md";

    return url;
}

std::string getUrlForArg(std::string const& arg)
{
    return getUrlForArgAndPlatform(arg, "common");
}

// =====================================
// Curl Fetching.
// =====================================
size_t writeCallback(char* raw, size_t size, size_t nmemb, std::string* data)
{
    if (data == NULL) { return 0; }

    data->append(raw, size * nmemb);
    return size * nmemb;
}

std::string getContentForUrl(std::string const& url)
{
    CURL* curl;
    CURLcode res;
    std::string response;

    curl = curl_easy_init();
    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

        res = curl_easy_perform(curl);
        if (res == CURLE_OK)
        {
            long httpCode = 0;
            curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);

            if (httpCode == 200)
            {
                curl_easy_cleanup(curl);
                return response;
            }
            else
            {
                curl_easy_cleanup(curl);
                return "";
            }
        }

        curl_easy_cleanup(curl);
    }

    return "";
}

// =====================================
// Utilities.
// =====================================
void replaceAll(std::string& str, std::string const& from,
                std::string const& to)
{
    if (from.empty()) { return; }

    size_t start_pos = 0;
    while ((start_pos = str.find(from, start_pos)) != std::string::npos)
    {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length();
    }
}

<commit_msg>improve variable naming<commit_after>#include <iostream>
#include <string>
#include <sstream>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <sys/utsname.h>

static const char* const ANSI_COLOR_RESET_FG            = "\x1b[39m";

static const char* const ANSI_COLOR_TITLE_FG            = ANSI_COLOR_RESET_FG;
static const char* const ANSI_COLOR_EXPLANATION_FG      = ANSI_COLOR_RESET_FG;
static const char* const ANSI_COLOR_COMMENT_FG          = "\x1b[32m";

static const char* const ANSI_COLOR_CODE_FG             = "\x1b[31m";
static const char* const ANSI_COLOR_CODE_PLACEHOLDER_FG = "\x1b[34m";

static const char* const ANSI_BOLD_ON                   = "\x1b[1m";
static const char* const ANSI_BOLD_OFF                  = "\x1b[22m";

// Constants.
std::string const kBaseUrl =
    "http://raw.github.com/tldr-pages/tldr/master/pages";

void init_response(struct response* r);
size_t writeCallback(char* raw, size_t size, size_t nmemb, std::string* data);

// Fetching.
std::string getUrlForArgAndPlatform(std::string const& arg,
                                    std::string const& platform);
std::string getUrlForArg(std::string const& arg);
std::string getContentForUrl(std::string const& url);

// Utilities.
void replaceAll(std::string& str, std::string const& from,
                std::string const& to);

int main(int argc, char* argv[])
{
    struct utsname sys;
    uname(&sys);

    if (argc > 1)
    {
        std::string arg(argv[1]);
        std::string url = getUrlForArg(arg);
        std::string urlForPlatform = getUrlForArgAndPlatform(arg, sys.sysname);

        std::string response = getContentForUrl(urlForPlatform);
        if (response.empty()) { response = getContentForUrl(url); }

        replaceAll(response, "{{", ANSI_COLOR_CODE_PLACEHOLDER_FG);
        replaceAll(response, "}}", ANSI_COLOR_RESET_FG);

        std::string const stripPrefix("#");
        std::string const explainPrefix(">");
        std::string const commentPrefix("-");
        std::string const codePrefix("`");
        std::stringstream ss(response);
        std::string line;
        bool firstComment = true;

        while (std::getline(ss, line, '\n'))
        {
            // Title
            if (line.compare(0, stripPrefix.size(), stripPrefix) == 0)
            {
                replaceAll(line, "#", ANSI_COLOR_TITLE_FG);
                std::cout << std::endl
                          << ANSI_BOLD_ON
                          << line
                          << ANSI_BOLD_OFF
                          << ANSI_COLOR_RESET_FG
                          << std::endl;
            }
            // Command explanation
            else if (line.compare(0, explainPrefix.size(), explainPrefix) == 0)
            {
                replaceAll(line, explainPrefix, ANSI_COLOR_EXPLANATION_FG);
                std::cout << line << ANSI_COLOR_RESET_FG << std::endl;
            }
            // Example comment
            else if (line.compare(0, commentPrefix.size(), commentPrefix) == 0)
            {
                if (firstComment)
                {
                    std::cout << std::endl;
                    firstComment = false;
                }

                replaceAll(line, commentPrefix, ANSI_COLOR_COMMENT_FG);
                std::cout << line << ANSI_COLOR_RESET_FG << std::endl;
            }
            // Code example
            else if (line.compare(0, codePrefix.size(), codePrefix) == 0)
            {
                // Remove trailing backtick (`).
                line = line.substr(0, line.size() - 1);

                // Replace first backtick (`) with three spaces for aligned indentation.
                replaceAll(line, "`", "   ");
                std::cout << ANSI_COLOR_CODE_FG
                          << line
                          << ANSI_COLOR_RESET_FG
                          << std::endl
                          << std::endl;
            }
        }
    }
}

// =====================================
// URL determination.
// =====================================
std::string getUrlForArgAndPlatform(std::string const& arg,
                                    std::string const& platform)
{
    int isLinux = !platform.compare("Linux");
    int isOSX = !platform.compare("Darwin");

    std::string platformUrlDelimiter;
    if (isLinux) { platformUrlDelimiter = "linux"; }
    else if (isOSX) { platformUrlDelimiter = "osx"; }
    else { platformUrlDelimiter = "common"; }

    std::string url(kBaseUrl);
    url += "/" + platformUrlDelimiter + "/" + arg + ".md";

    return url;
}

std::string getUrlForArg(std::string const& arg)
{
    return getUrlForArgAndPlatform(arg, "common");
}

// =====================================
// Curl Fetching.
// =====================================
size_t writeCallback(char* raw, size_t size, size_t nmemb, std::string* data)
{
    if (data == NULL) { return 0; }

    data->append(raw, size * nmemb);
    return size * nmemb;
}

std::string getContentForUrl(std::string const& url)
{
    CURL* curl;
    CURLcode res;
    std::string response;

    curl = curl_easy_init();
    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

        res = curl_easy_perform(curl);
        if (res == CURLE_OK)
        {
            long httpCode = 0;
            curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);

            if (httpCode == 200)
            {
                curl_easy_cleanup(curl);
                return response;
            }
            else
            {
                curl_easy_cleanup(curl);
                return "";
            }
        }

        curl_easy_cleanup(curl);
    }

    return "";
}

// =====================================
// Utilities.
// =====================================
void replaceAll(std::string& str, std::string const& from,
                std::string const& to)
{
    if (from.empty()) { return; }

    size_t start_pos = 0;
    while ((start_pos = str.find(from, start_pos)) != std::string::npos)
    {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length();
    }
}

<|endoftext|>


<commit_before>#include <vector>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <fstream>
#include "overlapgraph.h"

#define VERTEX_INACTIVE 0
#define VERTEX_ACTIVE 1
#define VERTEX_ELIMINATED -1
#define FUZZ 10

/*
Constructor for OverlapGraph class.
*/
OverlapGraph::OverlapGraph(std::vector<std::string> readvector, std::vector<overlap> overlapvector)
{
	reads = readvector;
	overlaps = overlapvector;
}

void OverlapGraph::initialize()
{
	int num_of_reads = reads.size();
	graph.resize(num_of_reads);
	completeGraph.resize(num_of_reads);
	reducedGraph.resize(num_of_reads);

	nonContainedReads.resize(num_of_reads);
	nonContainedReads.assign(num_of_reads, 1);

	overlap_flags = (bool *)malloc(num_of_reads*sizeof(bool));
	memset(overlap_flags, 0, num_of_reads*sizeof(bool));

	for(int i=0;i<overlaps.size();i++)
	{
		overlap o = overlaps[i];

		//removing contained reads
		if(o.ahg > 0 & o.bhg > 0)
			graph[o.read1].push_back(o);
		else if (o.ahg < 0 & o.bhg < 0)
			graph[o.read2].push_back(o);
		else if (o.ahg >= 0 & o.bhg <= 0)
			nonContainedReads[o.read2] = 0;
		else if (o.ahg <= 0 & o.bhg>=0)
			nonContainedReads[o.read1] = 0;

		completeGraph[o.read1].push_back(o);
		overlap_flags[o.read1] = true;
		overlap_flags[o.read2] = true;
	}

	int *indegree = (int *)malloc(num_of_reads*sizeof(int));
	memset(indegree, 0, num_of_reads*sizeof(int));
	for (int i = 0; i < graph.size(); i++)
	{
		for (int j = 0; j < graph[i].size(); j++)
		{
			indegree[graph[i][j].read2]++;
		}
	}

	for (int i = 0; i < reads.size(); i++)
	{
		if (indegree[i] == 0 & graph[i].size() == 0)
			nonContainedReads[i] = 0;
	}

	free(indegree);
}

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

void OverlapGraph::runUnitigging()
{
	using namespace std;
	int N = reads.size();

	initialize();

	int *vertexstatus = (int *)malloc(N*sizeof(int));
	memset(vertexstatus, VERTEX_INACTIVE, N*sizeof(int));
	vector< vector<bool> > reduceflags(N);

	for (int i = 0; i < N; i++)
		for (int j = 0; j < graph[i].size(); j++)
			reduceflags[i].push_back(false);

	for (int I = 0; I < N; I++)
	{
		if (graph[I].size() == 0)
			continue;

		for (int j = 0; j < graph[I].size(); j++)
			vertexstatus[graph[I][j].read2] = VERTEX_ACTIVE;

		int longest = 0;
		for (int j = 0; j < graph[I].size(); j++)
		{
			if (graph[I][j].bhg > longest)
				longest = graph[I][j].bhg;
		}

		longest += FUZZ;
		//cout << longest << endl;

		for (int j = 0; j < graph[I].size(); j++)
		{
			if (vertexstatus[graph[I][j].read2] == VERTEX_ACTIVE)
			{
				int x = graph[I][j].read2;
				for (int k = 0; k < graph[x].size(); k++)
				{
					if (graph[I][j].bhg + graph[x][k].bhg <= longest)
					{
						if (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)
							vertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;
					}
				}
			}
		}

		for (int j = 0; j < graph[I].size(); j++)
		{
			int x = graph[I][j].read2;
			for (int k = 0; k < graph[x].size(); k++)
			{
				if (graph[x][k].bhg < FUZZ)
				{
					if (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)
						vertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;
				}
			}
		}

		for (int j = 0; j < graph[I].size(); j++)
		{
			if (vertexstatus[graph[I][j].read2] == VERTEX_ELIMINATED)
			{
				reduceflags[I][j] = true;
			}
			vertexstatus[graph[I][j].read2] == VERTEX_INACTIVE;
		}
	}

	for(int i=0;i<graph.size();i++)
    {
        for(int j=0;j<graph[i].size();j++)
        {
			if (!reduceflags[i][j] & nonContainedReads[graph[i][j].read1] & nonContainedReads[graph[i][j].read2]){
				// Add edge to the reduced graph
				reducedGraph[i].push_back(graph[i][j]);
				cout << graph[i][j].read1 + 1<< " -> " << graph[i][j].read2 + 1<< endl;
			}
        }
    }

	uniqueJoinCollapsing();

	free(vertexstatus);
	return;
}

void OverlapGraph::unitigsPrinting()
{
	using namespace std;

	ofstream output("unitigsPrinting.afg");

	int counter = 1;

	output << "{unitigs" << endl;

	for (Chunk c : collapsedReducedGraph)
	{
		output << "{" << "unitig" << endl;
		output << "id: " << counter << endl;
		output << "members: ";
		for (int a : c.members)
		{
			output << a << ",";
		}

		output << endl;
		output << "}" << endl;
	}

	output << "}" << endl;
}

void OverlapGraph::printLayouts()
{
	using namespace std;

	ofstream output("layouts.afg");

	int *offsets = (int *)malloc(reads.size()*sizeof(int));
	memset(offsets, 0, reads.size()*sizeof(int));

	calculateOffsets(offsets);

	output << "{LAY" << endl;
	for (int i = 0; i < reads.size(); i++)
	{
		if (overlap_flags[i]){
			output << "{TLE" << endl;
			output << "clr:0," << reads[i].length() << endl;
			output << "off:" << offsets[i] << endl;
			output << "src:" << i + 1 << endl;
			output << "}" << endl;
		}
	}

	output << "}" << endl;
	output.close();

	free(offsets);
}

void OverlapGraph::calculateOffsets(int *offsets)
{
	//array that stores id of non-containted read to which
	//contained read is mapped. mapping[19] = 14 means that
	//contained read 19 is mapped to non-contained read 14.
	int *mapping = (int *)malloc(reads.size()*sizeof(int));

	//smallest right overhang for contained read
	int *bhglen = (int *)malloc(reads.size()*sizeof(int));
	memset(mapping, -1, reads.size() * sizeof(int));

	for (int i = 0; i < reads.size(); i++)
	{
		for (int j = 0; j < completeGraph[i].size(); j++)
		{
			overlap o = completeGraph[i][j];
			if (nonContainedReads[o.read1] & nonContainedReads[o.read2]) {
				//calculating offset for non-contained reads that are part of final contig.
				offsets[o.read2] = offsets[o.read1] + o.ahg;
			}
			else if (nonContainedReads[o.read1] & !nonContainedReads[o.read2])
			{
				//mapping contained read to smallest right overhang
				if ((mapping[o.read2] == -1 || abs(o.bhg) < bhglen[o.read2]) && o.bhg <= 0)
				{
					mapping[o.read2] = o.read1;
					bhglen[o.read2] = abs(o.bhg);
				}
			}
		}
	}

	for (int i = 0; i < reads.size(); i++)
	{
		if (!nonContainedReads[i] && overlap_flags[i])
		{
			int m = mapping[i];
			overlap *o = find_overlap(mapping[i], i);
			offsets[i] = offsets[m] + o->ahg;
		}
	}

	free(mapping);
	free(bhglen);
}

overlap* OverlapGraph::find_overlap(int read1, int read2)
{
	for (int j = 0; j < completeGraph[read1].size(); j++)
		if (completeGraph[read1][j].read2 == read2)
			return &completeGraph[read1][j];
}

void OverlapGraph::uniqueJoinCollapsing(){

	reducedGraphVertexReferenceCounter.assign(reducedGraph.size(), 0);

	// Calculate references to vertexes
	for (int i = 0; i < reducedGraph.size(); i++){
		for (int j = 0; j < reducedGraph[i].size(); j++){
			reducedGraphVertexReferenceCounter[reducedGraph[i][j].read2]++;
		}
	}

	// Find first "juncture" vertex
	int startingVertex = 0;
	bool startingVertexFound = false;
	while (startingVertex < reducedGraph.size()){
		if (reducedGraph[startingVertex].size() > 0){
			startingVertexFound = true;
			break;
		}
		startingVertex++;
	}
	if (startingVertexFound){
		calculateChunks(startingVertex);
	}
}

void OverlapGraph::calculateChunks(int chunkStartingVertexId){

	int currentVertexId = chunkStartingVertexId;

	if (vertexAlreadyInChunk(currentVertexId)){
		return;
	}

	// create new chunk
	Chunk chunk;

	while (true){
		if (reducedGraphVertexReferenceCounter[currentVertexId] > 1 && currentVertexId != chunkStartingVertexId){
			// special case: juncture vertex (not part of our chunk)
			calculateChunks(currentVertexId);
			break;
		}

		chunk.members.push_back(currentVertexId);

		if (reducedGraph[currentVertexId].size() < 1){
			// dead end
			break;
		}

		if (reducedGraph[currentVertexId].size() > 1){
			// juncture point - each path vertex represents a new chunk start
			for (int i = 0; i < reducedGraph[currentVertexId].size(); i++){
				calculateChunks(reducedGraph[currentVertexId][i].read2);
			}
			break;
		}

		currentVertexId = reducedGraph[currentVertexId][0].read2;
	}
	collapsedReducedGraph.push_back(chunk);

	return;
}

bool OverlapGraph::vertexAlreadyInChunk(int vertexId){
	for (int i = 0; i < collapsedReducedGraph.size(); ++i){
		for (int j = 0; j < collapsedReducedGraph[i].members.size(); ++j){
			if (vertexId == collapsedReducedGraph[i].members[j]){
				return true;
			}
		}
	}
	return false;
}<commit_msg>Minor refactoring and print improvment.<commit_after>#include <vector>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <fstream>
#include "overlapgraph.h"

#define VERTEX_INACTIVE 0
#define VERTEX_ACTIVE 1
#define VERTEX_ELIMINATED -1
#define FUZZ 10

/*
Constructor for OverlapGraph class.
*/
OverlapGraph::OverlapGraph(std::vector<std::string> readvector, std::vector<overlap> overlapvector)
{
	reads = readvector;
	overlaps = overlapvector;
}

void OverlapGraph::initialize()
{
	int num_of_reads = reads.size();
	graph.resize(num_of_reads);
	completeGraph.resize(num_of_reads);
	reducedGraph.resize(num_of_reads);

	nonContainedReads.resize(num_of_reads);
	nonContainedReads.assign(num_of_reads, 1);

	overlap_flags = (bool *)malloc(num_of_reads*sizeof(bool));
	memset(overlap_flags, 0, num_of_reads*sizeof(bool));

	for(int i=0;i<overlaps.size();i++)
	{
		overlap o = overlaps[i];

		//removing contained reads
		if(o.ahg > 0 & o.bhg > 0)
			graph[o.read1].push_back(o);
		else if (o.ahg < 0 & o.bhg < 0)
			graph[o.read2].push_back(o);
		else if (o.ahg >= 0 & o.bhg <= 0)
			nonContainedReads[o.read2] = 0;
		else if (o.ahg <= 0 & o.bhg>=0)
			nonContainedReads[o.read1] = 0;

		completeGraph[o.read1].push_back(o);
		overlap_flags[o.read1] = true;
		overlap_flags[o.read2] = true;
	}

	int *indegree = (int *)malloc(num_of_reads*sizeof(int));
	memset(indegree, 0, num_of_reads*sizeof(int));
	for (int i = 0; i < graph.size(); i++)
	{
		for (int j = 0; j < graph[i].size(); j++)
		{
			indegree[graph[i][j].read2]++;
		}
	}

	for (int i = 0; i < reads.size(); i++)
	{
		if (indegree[i] == 0 & graph[i].size() == 0)
			nonContainedReads[i] = 0;
	}

	free(indegree);
}

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

void OverlapGraph::runUnitigging()
{
	using namespace std;
	int N = reads.size();

	initialize();

	int *vertexstatus = (int *)malloc(N*sizeof(int));
	memset(vertexstatus, VERTEX_INACTIVE, N*sizeof(int));
	vector< vector<bool> > reduceflags(N);

	for (int i = 0; i < N; i++)
		for (int j = 0; j < graph[i].size(); j++)
			reduceflags[i].push_back(false);

	for (int I = 0; I < N; I++)
	{
		if (graph[I].size() == 0)
			continue;

		for (int j = 0; j < graph[I].size(); j++)
			vertexstatus[graph[I][j].read2] = VERTEX_ACTIVE;

		int longest = 0;
		for (int j = 0; j < graph[I].size(); j++)
		{
			if (graph[I][j].bhg > longest)
				longest = graph[I][j].bhg;
		}

		longest += FUZZ;
		//cout << longest << endl;

		for (int j = 0; j < graph[I].size(); j++)
		{
			if (vertexstatus[graph[I][j].read2] == VERTEX_ACTIVE)
			{
				int x = graph[I][j].read2;
				for (int k = 0; k < graph[x].size(); k++)
				{
					if (graph[I][j].bhg + graph[x][k].bhg <= longest)
					{
						if (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)
							vertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;
					}
				}
			}
		}

		for (int j = 0; j < graph[I].size(); j++)
		{
			int x = graph[I][j].read2;
			for (int k = 0; k < graph[x].size(); k++)
			{
				if (graph[x][k].bhg < FUZZ)
				{
					if (vertexstatus[graph[x][k].read2] == VERTEX_ACTIVE)
						vertexstatus[graph[x][k].read2] = VERTEX_ELIMINATED;
				}
			}
		}

		for (int j = 0; j < graph[I].size(); j++)
		{
			if (vertexstatus[graph[I][j].read2] == VERTEX_ELIMINATED)
			{
				reduceflags[I][j] = true;
			}
			vertexstatus[graph[I][j].read2] == VERTEX_INACTIVE;
		}
	}

	cout << "Vertices and edges in unitig:" << endl;
	for(int i=0;i<graph.size();i++)
    {
        for(int j=0;j<graph[i].size();j++)
        {
			if (!reduceflags[i][j] & nonContainedReads[graph[i][j].read1] & nonContainedReads[graph[i][j].read2]){
				// Add edge to the reduced graph
				reducedGraph[i].push_back(graph[i][j]);
				cout << graph[i][j].read1 + 1<< " -> " << graph[i][j].read2 + 1<< endl;
			}
        }
    }

	uniqueJoinCollapsing();

	free(vertexstatus);
	return;
}

void OverlapGraph::unitigsPrinting()
{
	using namespace std;

	ofstream output("unitigs.afg");

	int counter = 1;

	output << "{unitigs" << endl;

	for (Chunk c : collapsedReducedGraph)
	{
		output << "{" << "unitig" << endl;
		output << "id: " << counter << endl;
		output << "members: ";
		for (int i = 0; i < c.members.size();i++)
		{
			if (i < c.members.size() - 1)
				output << c.members[i] + 1 << ",";
			else
				output << c.members[i] + 1 << endl;
		}
		output << "}" << endl;
		counter++;
	}

	output << "}" << endl;
	output.close();
}

void OverlapGraph::printLayouts()
{
	using namespace std;

	ofstream output("layouts.afg");

	int *offsets = (int *)malloc(reads.size()*sizeof(int));
	memset(offsets, 0, reads.size()*sizeof(int));

	calculateOffsets(offsets);

	output << "{LAY" << endl;
	for (int i = 0; i < reads.size(); i++)
	{
		if (overlap_flags[i]){
			output << "{TLE" << endl;
			output << "clr:0," << reads[i].length() << endl;
			output << "off:" << offsets[i] << endl;
			output << "src:" << i + 1 << endl;
			output << "}" << endl;
		}
	}

	output << "}" << endl;
	output.close();

	free(offsets);
}

void OverlapGraph::calculateOffsets(int *offsets)
{
	//array that stores id of non-containted read to which
	//contained read is mapped. mapping[19] = 14 means that
	//contained read 19 is mapped to non-contained read 14.
	int *mapping = (int *)malloc(reads.size()*sizeof(int));

	//smallest right overhang for contained read
	int *bhglen = (int *)malloc(reads.size()*sizeof(int));
	memset(mapping, -1, reads.size() * sizeof(int));

	for (int i = 0; i < reads.size(); i++)
	{
		for (int j = 0; j < completeGraph[i].size(); j++)
		{
			overlap o = completeGraph[i][j];
			if (nonContainedReads[o.read1] & nonContainedReads[o.read2]) {
				//calculating offset for non-contained reads that are part of final contig.
				offsets[o.read2] = offsets[o.read1] + o.ahg;
			}
			else if (nonContainedReads[o.read1] & !nonContainedReads[o.read2])
			{
				//mapping contained read to smallest right overhang
				if ((mapping[o.read2] == -1 || abs(o.bhg) < bhglen[o.read2]) && o.bhg <= 0)
				{
					mapping[o.read2] = o.read1;
					bhglen[o.read2] = abs(o.bhg);
				}
			}
		}
	}

	for (int i = 0; i < reads.size(); i++)
	{
		if (!nonContainedReads[i] && overlap_flags[i])
		{
			int m = mapping[i];
			overlap *o = find_overlap(mapping[i], i);
			offsets[i] = offsets[m] + o->ahg;
		}
	}

	free(mapping);
	free(bhglen);
}

overlap* OverlapGraph::find_overlap(int read1, int read2)
{
	for (int j = 0; j < completeGraph[read1].size(); j++)
		if (completeGraph[read1][j].read2 == read2)
			return &completeGraph[read1][j];
}

void OverlapGraph::uniqueJoinCollapsing(){

	reducedGraphVertexReferenceCounter.assign(reducedGraph.size(), 0);

	// Calculate references to vertexes
	for (int i = 0; i < reducedGraph.size(); i++){
		for (int j = 0; j < reducedGraph[i].size(); j++){
			reducedGraphVertexReferenceCounter[reducedGraph[i][j].read2]++;
		}
	}

	// Find first "juncture" vertex
	int startingVertex = 0;
	bool startingVertexFound = false;
	while (startingVertex < reducedGraph.size()){
		if (reducedGraph[startingVertex].size() > 0){
			startingVertexFound = true;
			break;
		}
		startingVertex++;
	}
	if (startingVertexFound){
		calculateChunks(startingVertex);
	}
}

void OverlapGraph::calculateChunks(int chunkStartingVertexId){

	int currentVertexId = chunkStartingVertexId;

	if (vertexAlreadyInChunk(currentVertexId)){
		return;
	}

	// create new chunk
	Chunk chunk;

	while (true){
		if (reducedGraphVertexReferenceCounter[currentVertexId] > 1 && currentVertexId != chunkStartingVertexId){
			// special case: juncture vertex (not part of our chunk)
			calculateChunks(currentVertexId);
			break;
		}

		chunk.members.push_back(currentVertexId);

		if (reducedGraph[currentVertexId].size() < 1){
			// dead end
			break;
		}

		if (reducedGraph[currentVertexId].size() > 1){
			// juncture point - each path vertex represents a new chunk start
			for (int i = 0; i < reducedGraph[currentVertexId].size(); i++){
				calculateChunks(reducedGraph[currentVertexId][i].read2);
			}
			break;
		}

		currentVertexId = reducedGraph[currentVertexId][0].read2;
	}
	collapsedReducedGraph.push_back(chunk);

	return;
}

bool OverlapGraph::vertexAlreadyInChunk(int vertexId){
	for (int i = 0; i < collapsedReducedGraph.size(); ++i){
		for (int j = 0; j < collapsedReducedGraph[i].members.size(); ++j){
			if (vertexId == collapsedReducedGraph[i].members[j]){
				return true;
			}
		}
	}
	return false;
}<|endoftext|>


<commit_before>//===-- MICmnMIOutOfBandRecord.cpp ------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// In-house headers:
#include "MICmnMIOutOfBandRecord.h"
#include "MICmnResources.h"

// Instantiations:
static const char *
MapOutOfBandToText(CMICmnMIOutOfBandRecord::OutOfBand_e veType)
{
    switch (veType)
    {
        case CMICmnMIOutOfBandRecord::eOutOfBand_Running:
            return "running";
        case CMICmnMIOutOfBandRecord::eOutOfBand_Stopped:
            return "stopped";
        case CMICmnMIOutOfBandRecord::eOutOfBand_BreakPointCreated:
            return "breakpoint-created";
        case CMICmnMIOutOfBandRecord::eOutOfBand_BreakPointModified:
            return "breakpoint-modified";
        case CMICmnMIOutOfBandRecord::eOutOfBand_Thread:
            return ""; // "" Meant to be empty
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupAdded:
            return "thread-group-added";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupExited:
            return "thread-group-exited";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupRemoved:
            return "thread-group-removed";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupStarted:
            return "thread-group-started";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadCreated:
            return "thread-created";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadExited:
            return "thread-exited";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadSelected:
            return "thread-selected";
        case CMICmnMIOutOfBandRecord::eOutOfBand_TargetModuleLoaded:
            return "library-loaded";
        case CMICmnMIOutOfBandRecord::eOutOfBand_TargetModuleUnloaded:
            return "library-unloaded";
        case CMICmnMIOutOfBandRecord::eOutOfBand_TargetStreamOutput:
            return "";
    }
    assert(false && "unknown CMICmnMIOutofBandRecord::OutOfBand_e");
    return NULL;
}

static const char *
MapOutOfBandToToken(CMICmnMIOutOfBandRecord::OutOfBand_e veType)
{
    switch (veType)
    {
        case CMICmnMIOutOfBandRecord::eOutOfBand_Running:
            return "*";
        case CMICmnMIOutOfBandRecord::eOutOfBand_Stopped:
            return "*";
        case CMICmnMIOutOfBandRecord::eOutOfBand_BreakPointCreated:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_BreakPointModified:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_Thread:
            return "@";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupAdded:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupExited:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupRemoved:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupStarted:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadCreated:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadExited:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadSelected:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_TargetModuleLoaded:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_TargetModuleUnloaded:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_TargetStreamOutput:
            return "@";
    }
    assert(false && "unknown CMICmnMIOutofBandRecord::OutOfBand_e");
    return NULL;
}

//++ ------------------------------------------------------------------------------------
// Details: Build the Out-of-band record's mandatory data part. The part up to the first
//          (additional) result i.e. async-record ==>  "*" type.
// Args:    veType      - (R) A MI Out-of-Band enumeration.
// Return:  CMIUtilString - The async record text.
// Throws:  None.
//--
static CMIUtilString
BuildAsyncRecord(CMICmnMIOutOfBandRecord::OutOfBand_e veType)
{
    return CMIUtilString::Format("%s%s", MapOutOfBandToToken(veType), MapOutOfBandToText(veType));
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmnMIOutOfBandRecord constructor.
// Type:    Method.
// Args:    None.
// Return:  None.
// Throws:  None.
//--
CMICmnMIOutOfBandRecord::CMICmnMIOutOfBandRecord()
    : m_strAsyncRecord(MIRSRC(IDS_CMD_ERR_EVENT_HANDLED_BUT_NO_ACTION))
{
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmnMIOutOfBandRecord constructor.
// Type:    Method.
// Args:    veType      - (R) A MI Out-of-Bound enumeration.
// Return:  None.
// Throws:  None.
//--
CMICmnMIOutOfBandRecord::CMICmnMIOutOfBandRecord(OutOfBand_e veType)
    : m_strAsyncRecord(BuildAsyncRecord(veType))
{
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmnMIOutOfBandRecord constructor.
// Type:    Method.
// Args:    veType      - (R) A MI Out-of-Bound enumeration.
//          vConst      - (R) A MI const object.
// Return:  None.
// Throws:  None.
//--
CMICmnMIOutOfBandRecord::CMICmnMIOutOfBandRecord(OutOfBand_e veType, const CMICmnMIValueConst &vConst)
    : m_strAsyncRecord(BuildAsyncRecord(veType))
{
    m_strAsyncRecord += vConst.GetString();
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmnMIOutOfBandRecord constructor.
// Type:    Method.
// Args:    veType      - (R) A MI Out-of-Bound enumeration.
//          vResult     - (R) A MI result object.
// Return:  None.
// Throws:  None.
//--
CMICmnMIOutOfBandRecord::CMICmnMIOutOfBandRecord(OutOfBand_e veType, const CMICmnMIValueResult &vResult)
    : m_strAsyncRecord(BuildAsyncRecord(veType))
{
    Add(vResult);
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmnMIOutOfBandRecord destructor.
// Type:    Overrideable.
// Args:    None.
// Return:  None.
// Throws:  None.
//--
CMICmnMIOutOfBandRecord::~CMICmnMIOutOfBandRecord()
{
}

//++ ------------------------------------------------------------------------------------
// Details: Return the MI Out-of-band record as a string. The string is a direct result of
//          work done on *this Out-of-band record so if not enough data is added then it is
//          possible to return a malformed Out-of-band record. If nothing has been set or
//          added to *this MI Out-of-band record object then text "<Invalid>" will be returned.
// Type:    Method.
// Args:    None.
// Return:  CMIUtilString & - MI output text.
// Throws:  None.
//--
const CMIUtilString &
CMICmnMIOutOfBandRecord::GetString() const
{
    return m_strAsyncRecord;
}

//++ ------------------------------------------------------------------------------------
// Details: Add to *this Out-of-band record additional information.
// Type:    Method.
// Args:    vResult           - (R) A MI result object.
// Return:  None.
// Throws:  None.
//--
void
CMICmnMIOutOfBandRecord::Add(const CMICmnMIValueResult &vResult)
{
    m_strAsyncRecord += ",";
    m_strAsyncRecord += vResult.GetString();
}
<commit_msg>[lldb-mi] Fix non-OS X builds.<commit_after>//===-- MICmnMIOutOfBandRecord.cpp ------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// Third Party Headers:
#include <assert.h>

// In-house headers:
#include "MICmnMIOutOfBandRecord.h"
#include "MICmnResources.h"

// Instantiations:
static const char *
MapOutOfBandToText(CMICmnMIOutOfBandRecord::OutOfBand_e veType)
{
    switch (veType)
    {
        case CMICmnMIOutOfBandRecord::eOutOfBand_Running:
            return "running";
        case CMICmnMIOutOfBandRecord::eOutOfBand_Stopped:
            return "stopped";
        case CMICmnMIOutOfBandRecord::eOutOfBand_BreakPointCreated:
            return "breakpoint-created";
        case CMICmnMIOutOfBandRecord::eOutOfBand_BreakPointModified:
            return "breakpoint-modified";
        case CMICmnMIOutOfBandRecord::eOutOfBand_Thread:
            return ""; // "" Meant to be empty
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupAdded:
            return "thread-group-added";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupExited:
            return "thread-group-exited";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupRemoved:
            return "thread-group-removed";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupStarted:
            return "thread-group-started";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadCreated:
            return "thread-created";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadExited:
            return "thread-exited";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadSelected:
            return "thread-selected";
        case CMICmnMIOutOfBandRecord::eOutOfBand_TargetModuleLoaded:
            return "library-loaded";
        case CMICmnMIOutOfBandRecord::eOutOfBand_TargetModuleUnloaded:
            return "library-unloaded";
        case CMICmnMIOutOfBandRecord::eOutOfBand_TargetStreamOutput:
            return "";
    }
    assert(false && "unknown CMICmnMIOutofBandRecord::OutOfBand_e");
    return NULL;
}

static const char *
MapOutOfBandToToken(CMICmnMIOutOfBandRecord::OutOfBand_e veType)
{
    switch (veType)
    {
        case CMICmnMIOutOfBandRecord::eOutOfBand_Running:
            return "*";
        case CMICmnMIOutOfBandRecord::eOutOfBand_Stopped:
            return "*";
        case CMICmnMIOutOfBandRecord::eOutOfBand_BreakPointCreated:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_BreakPointModified:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_Thread:
            return "@";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupAdded:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupExited:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupRemoved:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadGroupStarted:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadCreated:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadExited:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_ThreadSelected:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_TargetModuleLoaded:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_TargetModuleUnloaded:
            return "=";
        case CMICmnMIOutOfBandRecord::eOutOfBand_TargetStreamOutput:
            return "@";
    }
    assert(false && "unknown CMICmnMIOutofBandRecord::OutOfBand_e");
    return NULL;
}

//++ ------------------------------------------------------------------------------------
// Details: Build the Out-of-band record's mandatory data part. The part up to the first
//          (additional) result i.e. async-record ==>  "*" type.
// Args:    veType      - (R) A MI Out-of-Band enumeration.
// Return:  CMIUtilString - The async record text.
// Throws:  None.
//--
static CMIUtilString
BuildAsyncRecord(CMICmnMIOutOfBandRecord::OutOfBand_e veType)
{
    return CMIUtilString::Format("%s%s", MapOutOfBandToToken(veType), MapOutOfBandToText(veType));
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmnMIOutOfBandRecord constructor.
// Type:    Method.
// Args:    None.
// Return:  None.
// Throws:  None.
//--
CMICmnMIOutOfBandRecord::CMICmnMIOutOfBandRecord()
    : m_strAsyncRecord(MIRSRC(IDS_CMD_ERR_EVENT_HANDLED_BUT_NO_ACTION))
{
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmnMIOutOfBandRecord constructor.
// Type:    Method.
// Args:    veType      - (R) A MI Out-of-Bound enumeration.
// Return:  None.
// Throws:  None.
//--
CMICmnMIOutOfBandRecord::CMICmnMIOutOfBandRecord(OutOfBand_e veType)
    : m_strAsyncRecord(BuildAsyncRecord(veType))
{
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmnMIOutOfBandRecord constructor.
// Type:    Method.
// Args:    veType      - (R) A MI Out-of-Bound enumeration.
//          vConst      - (R) A MI const object.
// Return:  None.
// Throws:  None.
//--
CMICmnMIOutOfBandRecord::CMICmnMIOutOfBandRecord(OutOfBand_e veType, const CMICmnMIValueConst &vConst)
    : m_strAsyncRecord(BuildAsyncRecord(veType))
{
    m_strAsyncRecord += vConst.GetString();
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmnMIOutOfBandRecord constructor.
// Type:    Method.
// Args:    veType      - (R) A MI Out-of-Bound enumeration.
//          vResult     - (R) A MI result object.
// Return:  None.
// Throws:  None.
//--
CMICmnMIOutOfBandRecord::CMICmnMIOutOfBandRecord(OutOfBand_e veType, const CMICmnMIValueResult &vResult)
    : m_strAsyncRecord(BuildAsyncRecord(veType))
{
    Add(vResult);
}

//++ ------------------------------------------------------------------------------------
// Details: CMICmnMIOutOfBandRecord destructor.
// Type:    Overrideable.
// Args:    None.
// Return:  None.
// Throws:  None.
//--
CMICmnMIOutOfBandRecord::~CMICmnMIOutOfBandRecord()
{
}

//++ ------------------------------------------------------------------------------------
// Details: Return the MI Out-of-band record as a string. The string is a direct result of
//          work done on *this Out-of-band record so if not enough data is added then it is
//          possible to return a malformed Out-of-band record. If nothing has been set or
//          added to *this MI Out-of-band record object then text "<Invalid>" will be returned.
// Type:    Method.
// Args:    None.
// Return:  CMIUtilString & - MI output text.
// Throws:  None.
//--
const CMIUtilString &
CMICmnMIOutOfBandRecord::GetString() const
{
    return m_strAsyncRecord;
}

//++ ------------------------------------------------------------------------------------
// Details: Add to *this Out-of-band record additional information.
// Type:    Method.
// Args:    vResult           - (R) A MI result object.
// Return:  None.
// Throws:  None.
//--
void
CMICmnMIOutOfBandRecord::Add(const CMICmnMIValueResult &vResult)
{
    m_strAsyncRecord += ",";
    m_strAsyncRecord += vResult.GetString();
}
<|endoftext|>