<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/disk_cache/file.h"

#include <fcntl.h>

#include "base/logging.h"
#include "net/disk_cache/disk_cache.h"

namespace disk_cache {

File::File(OSFile file)
    : init_(true), os_file_(file) {
}

bool File::Init(const std::wstring& name) {
  if (init_)
    return false;

  os_file_ = CreateOSFile(name, OS_FILE_OPEN | OS_FILE_READ | OS_FILE_WRITE,
                          NULL);
  if (os_file_ < 0) {
    os_file_ = 0;
    return false;
  }

  init_ = true;
  return true;
}

File::~File() {
  if (os_file_)
    close(os_file_);
}

OSFile File::os_file() const {
  return os_file_;
}

bool File::IsValid() const {
  if (!init_)
    return false;
  return (INVALID_HANDLE_VALUE != os_file_);
}

bool File::Read(void* buffer, size_t buffer_len, size_t offset) {
  DCHECK(init_);
  if (buffer_len > ULONG_MAX || offset > LONG_MAX)
    return false;

  int ret = pread(os_file_, buffer, buffer_len, offset);
  return (static_cast<size_t>(ret) == buffer_len);
}

bool File::Write(const void* buffer, size_t buffer_len, size_t offset) {
  DCHECK(init_);
  if (buffer_len > ULONG_MAX || offset > ULONG_MAX)
    return false;

  int ret = pwrite(os_file_, buffer, buffer_len, offset);
  return (static_cast<size_t>(ret) == buffer_len);
}

// We have to increase the ref counter of the file before performing the IO to
// prevent the completion to happen with an invalid handle (if the file is
// closed while the IO is in flight).
bool File::Read(void* buffer, size_t buffer_len, size_t offset,
                FileIOCallback* callback, bool* completed) {
  DCHECK(init_);
  if (buffer_len > ULONG_MAX || offset > ULONG_MAX)
    return false;

  // TODO: Implement async IO.
  bool ret = Read(buffer, buffer_len, offset);
  if (ret && completed)
    *completed = true;
  return ret;
}

bool File::Write(const void* buffer, size_t buffer_len, size_t offset,
                 FileIOCallback* callback, bool* completed) {
  DCHECK(init_);
  return AsyncWrite(buffer, buffer_len, offset, true, callback, completed);
}

bool File::PostWrite(const void* buffer, size_t buffer_len, size_t offset) {
  DCHECK(init_);
  return AsyncWrite(buffer, buffer_len, offset, false, NULL, NULL);
}

bool File::AsyncWrite(const void* buffer, size_t buffer_len, size_t offset,
                      bool notify, FileIOCallback* callback, bool* completed) {
  DCHECK(init_);
  if (buffer_len > ULONG_MAX || offset > ULONG_MAX)
    return false;

  // TODO: Implement async IO.
  bool ret = Write(buffer, buffer_len, offset);
  if (ret && completed)
    *completed = true;
  return ret;
}

bool File::SetLength(size_t length) {
  DCHECK(init_);
  if (length > ULONG_MAX)
    return false;

  return 0 == ftruncate(os_file_, length);
}

size_t File::GetLength() {
  DCHECK(init_);
  size_t ret = lseek(os_file_, 0, SEEK_END);
  return ret;
}

}  // namespace disk_cache
<commit_msg>Fix a memory leak on the disk cache for posix.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/disk_cache/file.h"

#include <fcntl.h>

#include "base/logging.h"
#include "net/disk_cache/disk_cache.h"

namespace disk_cache {

File::File(OSFile file)
    : init_(true), os_file_(file) {
}

bool File::Init(const std::wstring& name) {
  if (init_)
    return false;

  os_file_ = CreateOSFile(name, OS_FILE_OPEN | OS_FILE_READ | OS_FILE_WRITE,
                          NULL);
  if (os_file_ < 0) {
    os_file_ = 0;
    return false;
  }

  init_ = true;
  return true;
}

File::~File() {
  if (os_file_)
    close(os_file_);
}

OSFile File::os_file() const {
  return os_file_;
}

bool File::IsValid() const {
  if (!init_)
    return false;
  return (INVALID_HANDLE_VALUE != os_file_);
}

bool File::Read(void* buffer, size_t buffer_len, size_t offset) {
  DCHECK(init_);
  if (buffer_len > ULONG_MAX || offset > LONG_MAX)
    return false;

  int ret = pread(os_file_, buffer, buffer_len, offset);
  return (static_cast<size_t>(ret) == buffer_len);
}

bool File::Write(const void* buffer, size_t buffer_len, size_t offset) {
  DCHECK(init_);
  if (buffer_len > ULONG_MAX || offset > ULONG_MAX)
    return false;

  int ret = pwrite(os_file_, buffer, buffer_len, offset);
  return (static_cast<size_t>(ret) == buffer_len);
}

// We have to increase the ref counter of the file before performing the IO to
// prevent the completion to happen with an invalid handle (if the file is
// closed while the IO is in flight).
bool File::Read(void* buffer, size_t buffer_len, size_t offset,
                FileIOCallback* callback, bool* completed) {
  DCHECK(init_);
  if (buffer_len > ULONG_MAX || offset > ULONG_MAX)
    return false;

  // TODO: Implement async IO.
  bool ret = Read(buffer, buffer_len, offset);
  if (ret && completed)
    *completed = true;
  return ret;
}

bool File::Write(const void* buffer, size_t buffer_len, size_t offset,
                 FileIOCallback* callback, bool* completed) {
  DCHECK(init_);
  return AsyncWrite(buffer, buffer_len, offset, true, callback, completed);
}

bool File::PostWrite(const void* buffer, size_t buffer_len, size_t offset) {
  DCHECK(init_);
  return AsyncWrite(buffer, buffer_len, offset, false, NULL, NULL);
}

bool File::AsyncWrite(const void* buffer, size_t buffer_len, size_t offset,
                      bool notify, FileIOCallback* callback, bool* completed) {
  DCHECK(init_);
  if (buffer_len > ULONG_MAX || offset > ULONG_MAX)
    return false;

  // TODO: Implement async IO.
  bool ret = Write(buffer, buffer_len, offset);
  if (ret && completed)
    *completed = true;

  // If we supply our own async callback, and the caller is not asking to be
  // notified when completed, we are supposed to delete the buffer.
  if (ret && !callback && !notify)
    delete[] reinterpret_cast<const char*>(buffer);

  return ret;
}

bool File::SetLength(size_t length) {
  DCHECK(init_);
  if (length > ULONG_MAX)
    return false;

  return 0 == ftruncate(os_file_, length);
}

size_t File::GetLength() {
  DCHECK(init_);
  size_t ret = lseek(os_file_, 0, SEEK_END);
  return ret;
}

}  // namespace disk_cache
<|endoftext|>


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

#include "TaskPaneFocusManager.hxx"
#include "taskpane/TitleBar.hxx"
#include "taskpane/TitledControl.hxx"
#include "taskpane/ControlContainer.hxx"
#include "AccessibleTreeNode.hxx"

#ifndef _SV_DECOVIEW_HXX
#include <vcl/decoview.hxx>
#endif
#include <vcl/svapp.hxx>

namespace sd { namespace toolpanel {

SubToolPanel::SubToolPanel (
    TreeNode* pParent)
    : Control (pParent->GetWindow(), WB_DIALOGCONTROL),
      TreeNode(pParent),
      maWindowFiller(this),
      mbIsRearrangePending(true),
      mbIsLayoutPending(true),
      mnChildrenWidth(0),
      mnVerticalBorder(0),
      mnVerticalGap(3),
      mnHorizontalBorder(2)
{
    SetAccessibleName (
        ::rtl::OUString::createFromAscii("Sub Task Panel"));
    mpControlContainer->SetMultiSelection (true);

    SetBorderStyle (WINDOW_BORDER_NORMAL);
    SetMapMode (MapMode(MAP_PIXEL));

    // To reduce flickering during repaints make the container windows
    // transparent and rely on their children to paint the whole area.
    SetBackground(Wallpaper());
    maWindowFiller.SetBackground(
        Application::GetSettings().GetStyleSettings().GetWindowColor());
}

SubToolPanel::~SubToolPanel (void)
{
    sal_uInt32 nCount = mpControlContainer->GetControlCount();
    for (sal_uInt32 nIndex=0; nIndex<nCount; nIndex++)
    {
        TitledControl* pControl = static_cast<TitledControl*>(
            mpControlContainer->GetControl(nIndex));
        pControl->GetControl()->GetWindow()->RemoveEventListener(
            LINK(this,SubToolPanel,WindowEventListener));
    }
    mpControlContainer->DeleteChildren();
}

void SubToolPanel::ListHasChanged (void)
{
    mpControlContainer->ListHasChanged ();
    RequestResize ();
}

void SubToolPanel::AddControl (
    ::std::auto_ptr<TreeNode> pControl,
    const String& rTitle,
    ULONG nHelpId)
{
    pControl->GetWindow()->AddEventListener (
        LINK(this,SubToolPanel,WindowEventListener));

    // We are interested only in the title.  The control itself is
    // managed by the content object.
    TitledControl* pTitledControl = new TitledControl(
        this,
        pControl,
        rTitle,
        TitleBar::TBT_SUB_CONTROL_HEADLINE);
    pTitledControl->GetWindow()->SetParent(this);
    pTitledControl->GetWindow()->SetHelpId(nHelpId);
    ::std::auto_ptr<TreeNode> pChild (pTitledControl);

    // Add a down link only for the first control so that when
    // entering the sub tool panel the focus is set to the first control.
    if (mpControlContainer->GetControlCount() == 0)
        FocusManager::Instance().RegisterDownLink(GetParent(), pTitledControl->GetWindow());
    FocusManager::Instance().RegisterUpLink(pTitledControl->GetWindow(), GetParent());

    mpControlContainer->AddControl (pChild);
}

void SubToolPanel::AddControl (::std::auto_ptr<TreeNode> pControl)
{
    pControl->GetWindow()->AddEventListener (
        LINK(this,SubToolPanel,WindowEventListener));

    // Add a down link only for the first control so that when
    // entering the sub tool panel the focus is set to the first control.
    if (mpControlContainer->GetControlCount() == 0)
        FocusManager::Instance().RegisterDownLink(GetParent(), pControl->GetWindow());
    FocusManager::Instance().RegisterUpLink(pControl->GetWindow(), GetParent());

    mpControlContainer->AddControl (pControl);
}

void SubToolPanel::Paint (const Rectangle& rRect)
{
    if (mbIsRearrangePending)
        Rearrange();
    if (mbIsLayoutPending)
        LayoutChildren();
    ::Window::Paint (rRect);

    // Paint the outer border and the space between every two children.
    Color aOriginalLineColor (GetLineColor());
    Color aOriginalFillColor (GetFillColor());

    SetLineColor ();
    SetFillColor (GetSettings().GetStyleSettings().GetWindowColor());

    Size aSize (GetOutputSizePixel());
    // Paint left and right vertical border.
    Rectangle aVerticalArea (
        Point(0,0),
        Size(mnHorizontalBorder,aSize.Height()));
    DrawRect (aVerticalArea);
    aVerticalArea.Right() += mnHorizontalBorder + mnChildrenWidth - 1;
    aVerticalArea.Left() = aVerticalArea.Right() + mnHorizontalBorder;
    DrawRect (aVerticalArea);

    // Paint horizontal stripes.
    Rectangle aStripeArea (
        Point (mnHorizontalBorder,0),
        Size(mnChildrenWidth,0));
    StripeList::const_iterator iStripe;
    for (iStripe=maStripeList.begin(); iStripe!=maStripeList.end(); iStripe++)
    {
        aStripeArea.Top() = iStripe->first;
        aStripeArea.Bottom() = iStripe->second;
        if (aStripeArea.Bottom() < 0)
            continue;
        if (aStripeArea.Top() >= aSize.Height())
            break;
        DrawRect (aStripeArea);
    }

    SetLineColor (aOriginalLineColor);
    SetFillColor (aOriginalFillColor);
}

void SubToolPanel::Resize (void)
{
    ::Window::Resize();
    mbIsRearrangePending = true;
    mbIsLayoutPending = true;
}

void SubToolPanel::RequestResize (void)
{
    mbIsRearrangePending = true;
    mbIsLayoutPending = true;
    Invalidate();
}

Size SubToolPanel::GetPreferredSize (void)
{
    return GetRequiredSize();
}

sal_Int32 SubToolPanel::GetPreferredWidth (sal_Int32 )
{
    return GetPreferredSize().Width();
}

sal_Int32 SubToolPanel::GetPreferredHeight (sal_Int32 )
{
    return GetPreferredSize().Height();
}

bool SubToolPanel::IsResizable (void)
{
    return true;
}

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

sal_Int32 SubToolPanel::GetMinimumWidth (void)
{
    return TreeNode::GetMinimumWidth();
}

void SubToolPanel::ExpandControl (
    TreeNode* pControl,
    bool bExpansionState)
{
    // Toggle expand status.
    pControl->Expand (bExpansionState);

    Rearrange ();
    Invalidate ();
}

/** This control shows an expansion bar for every control and in a
    separate area below that expansion area it shows all controls each
    with its title bar.  When there is not enough space then show a
    scroll bar in the control area.
*/
void SubToolPanel::Rearrange (void)
{
    Size aRequiredSize (GetRequiredSize());
    if (aRequiredSize.Width()>0 && aRequiredSize.Height()>0)
    {
        Size aAvailableSize (GetOutputSizePixel());

        // Make the children at least as wide as the sub tool panel.
        if (aRequiredSize.Width() < aAvailableSize.Width())
            aRequiredSize.Width() = aAvailableSize.Width();
        mnChildrenWidth = -2*mnHorizontalBorder;
        mnChildrenWidth += aAvailableSize.Width();

        LayoutChildren();

        mbIsRearrangePending = false;
    }
}

Size SubToolPanel::GetRequiredSize (void)
{
    // First determine the width of the children.  This is the maximum of
    // the current window width and the individual minimum widths of the
    // children.
    int nChildrenWidth (GetSizePixel().Width());
    unsigned int nCount = mpControlContainer->GetControlCount();
    unsigned int nIndex;
    for (nIndex=0; nIndex<nCount; nIndex++)
    {
        TreeNode* pChild = mpControlContainer->GetControl (nIndex);
        int nMinimumWidth (pChild->GetMinimumWidth());
        if (nMinimumWidth > nChildrenWidth)
            nChildrenWidth = nMinimumWidth;
    }

    // Determine the accumulated width of all children when scaled to the
    // minimum width.
    nChildrenWidth -= 2*mnHorizontalBorder;
    Size aTotalSize (nChildrenWidth,
        2*mnVerticalBorder + (nCount-1) * mnVerticalGap);
    for (nIndex=0; nIndex<nCount; nIndex++)
    {
        TreeNode* pChild = mpControlContainer->GetControl (nIndex);
        sal_Int32 nHeight = pChild->GetPreferredHeight(nChildrenWidth);
        aTotalSize.Height() += nHeight;
    }

    return aTotalSize;
}

sal_Int32 SubToolPanel::LayoutChildren (void)
{
    // Determine vertical space that can be distributed to sizable children.
    unsigned int nCount (mpControlContainer->GetControlCount());
    unsigned int nResizableCount = 0;
    int nAvailableHeight = GetSizePixel().Height() - 2*mnVerticalBorder;
    unsigned int nIndex;
    for (nIndex=0; nIndex<nCount; nIndex++)
    {
        TreeNode* pChild = mpControlContainer->GetControl (nIndex);
        int nControlHeight = pChild->GetPreferredHeight(mnChildrenWidth);
        if (pChild->IsResizable())
            nResizableCount++;
        else
            nAvailableHeight -= nControlHeight;
    }

    maStripeList.clear();

    Point aPosition (0,0);
    aPosition.X() += mnHorizontalBorder;
    maStripeList.push_back( ::std::pair<int,int>(
        aPosition.Y(),
        aPosition.Y() + mnVerticalBorder - 1));
    aPosition.Y() += mnVerticalBorder;

    // Place the controls one over the other.
    for (nIndex=0; nIndex<nCount; nIndex++)
    {
        if (nIndex > 0)
        {
            maStripeList.push_back( ::std::pair<int,int>(
                aPosition.Y(),
                aPosition.Y() + mnVerticalGap - 1));
            aPosition.Y() += mnVerticalGap;
        }
        TreeNode* pChild = mpControlContainer->GetControl (nIndex);
        int nControlHeight = pChild->GetPreferredHeight(mnChildrenWidth);
        if (pChild->IsResizable())
        {
            nControlHeight = nAvailableHeight / nResizableCount;
            nResizableCount--;
        }
        nAvailableHeight -= nControlHeight;
        pChild->GetWindow()->SetPosSizePixel(
            aPosition,
            Size(mnChildrenWidth, nControlHeight));
        aPosition.Y() += nControlHeight;
    }

    // If the children do not cover their parent window completely
    // (regarding the height) we put a filler below that is responsible for
    // painting the remaining space.
    int nWindowHeight = GetSizePixel().Height();
    if (aPosition.Y() < nWindowHeight)
    {
        maWindowFiller.SetPosSizePixel (
            aPosition,
            Size(mnChildrenWidth, nWindowHeight-aPosition.Y()));
        maStripeList.push_back( ::std::pair<int,int>(
            aPosition.Y(),
            nWindowHeight-1));
        //        maScrollWindowFiller.Show();
        aPosition.Y() = nWindowHeight;
    }
    else
        maWindowFiller.Hide();

    aPosition.Y() += mnVerticalBorder;
    mbIsLayoutPending = false;

    return aPosition.Y();
}

IMPL_LINK(SubToolPanel, WindowEventListener, VclSimpleEvent*, pEvent)
{
    if (pEvent!=NULL && pEvent->ISA(VclWindowEvent))
    {
        VclWindowEvent* pWindowEvent = static_cast<VclWindowEvent*>(pEvent);
        switch (pWindowEvent->GetId())
        {
            case VCLEVENT_WINDOW_SHOW:
            case VCLEVENT_WINDOW_HIDE:
            case VCLEVENT_WINDOW_ACTIVATE:
            case VCLEVENT_WINDOW_RESIZE:
                RequestResize();
                break;
        }
    }
    return 0;
}

::com::sun::star::uno::Reference<
    ::com::sun::star::accessibility::XAccessible> SubToolPanel::CreateAccessibleObject (
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>& )
{
    return new ::accessibility::AccessibleTreeNode (
        *this,
        ::rtl::OUString::createFromAscii("Sub Task Panel"),
        ::rtl::OUString::createFromAscii("Sub Task Panel"),
        ::com::sun::star::accessibility::AccessibleRole::PANEL);
}

} } // end of namespace ::sd::toolpanel
<commit_msg>INTEGRATION: CWS components1 (1.8.14); FILE MERGED 2007/01/25 15:22:45 af 1.8.14.2: RESYNC: (1.8-1.9); FILE MERGED 2007/01/24 17:48:59 af 1.8.14.1: #i68075# The click handler can now be supplied along with a control.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SubToolPanel.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-03 16:20:22 $
 *
 *  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 "taskpane/SubToolPanel.hxx"

#include "TaskPaneFocusManager.hxx"
#include "taskpane/TitleBar.hxx"
#include "taskpane/TitledControl.hxx"
#include "taskpane/ControlContainer.hxx"
#include "AccessibleTreeNode.hxx"

#ifndef _SV_DECOVIEW_HXX
#include <vcl/decoview.hxx>
#endif
#include <vcl/svapp.hxx>

namespace sd { namespace toolpanel {

SubToolPanel::SubToolPanel (
    TreeNode* pParent)
    : Control (pParent->GetWindow(), WB_DIALOGCONTROL),
      TreeNode(pParent),
      maWindowFiller(this),
      mbIsRearrangePending(true),
      mbIsLayoutPending(true),
      mnChildrenWidth(0),
      mnVerticalBorder(0),
      mnVerticalGap(3),
      mnHorizontalBorder(2)
{
    SetAccessibleName (
        ::rtl::OUString::createFromAscii("Sub Task Panel"));
    mpControlContainer->SetMultiSelection (true);

    SetBorderStyle (WINDOW_BORDER_NORMAL);
    SetMapMode (MapMode(MAP_PIXEL));

    // To reduce flickering during repaints make the container windows
    // transparent and rely on their children to paint the whole area.
    SetBackground(Wallpaper());
    maWindowFiller.SetBackground(
        Application::GetSettings().GetStyleSettings().GetWindowColor());
}

SubToolPanel::~SubToolPanel (void)
{
    sal_uInt32 nCount = mpControlContainer->GetControlCount();
    for (sal_uInt32 nIndex=0; nIndex<nCount; nIndex++)
    {
        TitledControl* pControl = static_cast<TitledControl*>(
            mpControlContainer->GetControl(nIndex));
        pControl->GetControl()->GetWindow()->RemoveEventListener(
            LINK(this,SubToolPanel,WindowEventListener));
    }
    mpControlContainer->DeleteChildren();
}

void SubToolPanel::ListHasChanged (void)
{
    mpControlContainer->ListHasChanged ();
    RequestResize ();
}

void SubToolPanel::AddControl (
    ::std::auto_ptr<TreeNode> pControl,
    const String& rTitle,
    ULONG nHelpId)
{
    pControl->GetWindow()->AddEventListener (
        LINK(this,SubToolPanel,WindowEventListener));

    // We are interested only in the title.  The control itself is
    // managed by the content object.
    TitledControl* pTitledControl = new TitledControl(
        this,
        pControl,
        rTitle,
        TitledControlStandardClickHandler(GetControlContainer(), ControlContainer::ES_TOGGLE),
        TitleBar::TBT_SUB_CONTROL_HEADLINE);
    pTitledControl->GetWindow()->SetParent(this);
    pTitledControl->GetWindow()->SetHelpId(nHelpId);
    ::std::auto_ptr<TreeNode> pChild (pTitledControl);

    // Add a down link only for the first control so that when
    // entering the sub tool panel the focus is set to the first control.
    if (mpControlContainer->GetControlCount() == 0)
        FocusManager::Instance().RegisterDownLink(GetParent(), pTitledControl->GetWindow());
    FocusManager::Instance().RegisterUpLink(pTitledControl->GetWindow(), GetParent());

    mpControlContainer->AddControl (pChild);
}

void SubToolPanel::AddControl (::std::auto_ptr<TreeNode> pControl)
{
    pControl->GetWindow()->AddEventListener (
        LINK(this,SubToolPanel,WindowEventListener));

    // Add a down link only for the first control so that when
    // entering the sub tool panel the focus is set to the first control.
    if (mpControlContainer->GetControlCount() == 0)
        FocusManager::Instance().RegisterDownLink(GetParent(), pControl->GetWindow());
    FocusManager::Instance().RegisterUpLink(pControl->GetWindow(), GetParent());

    mpControlContainer->AddControl (pControl);
}

void SubToolPanel::Paint (const Rectangle& rRect)
{
    if (mbIsRearrangePending)
        Rearrange();
    if (mbIsLayoutPending)
        LayoutChildren();
    ::Window::Paint (rRect);

    // Paint the outer border and the space between every two children.
    Color aOriginalLineColor (GetLineColor());
    Color aOriginalFillColor (GetFillColor());

    SetLineColor ();
    SetFillColor (GetSettings().GetStyleSettings().GetWindowColor());

    Size aSize (GetOutputSizePixel());
    // Paint left and right vertical border.
    Rectangle aVerticalArea (
        Point(0,0),
        Size(mnHorizontalBorder,aSize.Height()));
    DrawRect (aVerticalArea);
    aVerticalArea.Right() += mnHorizontalBorder + mnChildrenWidth - 1;
    aVerticalArea.Left() = aVerticalArea.Right() + mnHorizontalBorder;
    DrawRect (aVerticalArea);

    // Paint horizontal stripes.
    Rectangle aStripeArea (
        Point (mnHorizontalBorder,0),
        Size(mnChildrenWidth,0));
    StripeList::const_iterator iStripe;
    for (iStripe=maStripeList.begin(); iStripe!=maStripeList.end(); iStripe++)
    {
        aStripeArea.Top() = iStripe->first;
        aStripeArea.Bottom() = iStripe->second;
        if (aStripeArea.Bottom() < 0)
            continue;
        if (aStripeArea.Top() >= aSize.Height())
            break;
        DrawRect (aStripeArea);
    }

    SetLineColor (aOriginalLineColor);
    SetFillColor (aOriginalFillColor);
}

void SubToolPanel::Resize (void)
{
    ::Window::Resize();
    mbIsRearrangePending = true;
    mbIsLayoutPending = true;
}

void SubToolPanel::RequestResize (void)
{
    mbIsRearrangePending = true;
    mbIsLayoutPending = true;
    Invalidate();
}

Size SubToolPanel::GetPreferredSize (void)
{
    return GetRequiredSize();
}

sal_Int32 SubToolPanel::GetPreferredWidth (sal_Int32 )
{
    return GetPreferredSize().Width();
}

sal_Int32 SubToolPanel::GetPreferredHeight (sal_Int32 )
{
    return GetPreferredSize().Height();
}

bool SubToolPanel::IsResizable (void)
{
    return true;
}

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

sal_Int32 SubToolPanel::GetMinimumWidth (void)
{
    return TreeNode::GetMinimumWidth();
}

void SubToolPanel::ExpandControl (
    TreeNode* pControl,
    bool bExpansionState)
{
    // Toggle expand status.
    pControl->Expand (bExpansionState);

    Rearrange ();
    Invalidate ();
}

/** This control shows an expansion bar for every control and in a
    separate area below that expansion area it shows all controls each
    with its title bar.  When there is not enough space then show a
    scroll bar in the control area.
*/
void SubToolPanel::Rearrange (void)
{
    Size aRequiredSize (GetRequiredSize());
    if (aRequiredSize.Width()>0 && aRequiredSize.Height()>0)
    {
        Size aAvailableSize (GetOutputSizePixel());

        // Make the children at least as wide as the sub tool panel.
        if (aRequiredSize.Width() < aAvailableSize.Width())
            aRequiredSize.Width() = aAvailableSize.Width();
        mnChildrenWidth = -2*mnHorizontalBorder;
        mnChildrenWidth += aAvailableSize.Width();

        LayoutChildren();

        mbIsRearrangePending = false;
    }
}

Size SubToolPanel::GetRequiredSize (void)
{
    // First determine the width of the children.  This is the maximum of
    // the current window width and the individual minimum widths of the
    // children.
    int nChildrenWidth (GetSizePixel().Width());
    unsigned int nCount = mpControlContainer->GetControlCount();
    unsigned int nIndex;
    for (nIndex=0; nIndex<nCount; nIndex++)
    {
        TreeNode* pChild = mpControlContainer->GetControl (nIndex);
        int nMinimumWidth (pChild->GetMinimumWidth());
        if (nMinimumWidth > nChildrenWidth)
            nChildrenWidth = nMinimumWidth;
    }

    // Determine the accumulated width of all children when scaled to the
    // minimum width.
    nChildrenWidth -= 2*mnHorizontalBorder;
    Size aTotalSize (nChildrenWidth,
        2*mnVerticalBorder + (nCount-1) * mnVerticalGap);
    for (nIndex=0; nIndex<nCount; nIndex++)
    {
        TreeNode* pChild = mpControlContainer->GetControl (nIndex);
        sal_Int32 nHeight = pChild->GetPreferredHeight(nChildrenWidth);
        aTotalSize.Height() += nHeight;
    }

    return aTotalSize;
}

sal_Int32 SubToolPanel::LayoutChildren (void)
{
    // Determine vertical space that can be distributed to sizable children.
    unsigned int nCount (mpControlContainer->GetControlCount());
    unsigned int nResizableCount = 0;
    int nAvailableHeight = GetSizePixel().Height() - 2*mnVerticalBorder;
    unsigned int nIndex;
    for (nIndex=0; nIndex<nCount; nIndex++)
    {
        TreeNode* pChild = mpControlContainer->GetControl (nIndex);
        int nControlHeight = pChild->GetPreferredHeight(mnChildrenWidth);
        if (pChild->IsResizable())
            nResizableCount++;
        else
            nAvailableHeight -= nControlHeight;
    }

    maStripeList.clear();

    Point aPosition (0,0);
    aPosition.X() += mnHorizontalBorder;
    maStripeList.push_back( ::std::pair<int,int>(
        aPosition.Y(),
        aPosition.Y() + mnVerticalBorder - 1));
    aPosition.Y() += mnVerticalBorder;

    // Place the controls one over the other.
    for (nIndex=0; nIndex<nCount; nIndex++)
    {
        if (nIndex > 0)
        {
            maStripeList.push_back( ::std::pair<int,int>(
                aPosition.Y(),
                aPosition.Y() + mnVerticalGap - 1));
            aPosition.Y() += mnVerticalGap;
        }
        TreeNode* pChild = mpControlContainer->GetControl (nIndex);
        int nControlHeight = pChild->GetPreferredHeight(mnChildrenWidth);
        if (pChild->IsResizable())
        {
            nControlHeight = nAvailableHeight / nResizableCount;
            nResizableCount--;
        }
        nAvailableHeight -= nControlHeight;
        pChild->GetWindow()->SetPosSizePixel(
            aPosition,
            Size(mnChildrenWidth, nControlHeight));
        aPosition.Y() += nControlHeight;
    }

    // If the children do not cover their parent window completely
    // (regarding the height) we put a filler below that is responsible for
    // painting the remaining space.
    int nWindowHeight = GetSizePixel().Height();
    if (aPosition.Y() < nWindowHeight)
    {
        maWindowFiller.SetPosSizePixel (
            aPosition,
            Size(mnChildrenWidth, nWindowHeight-aPosition.Y()));
        maStripeList.push_back( ::std::pair<int,int>(
            aPosition.Y(),
            nWindowHeight-1));
        //        maScrollWindowFiller.Show();
        aPosition.Y() = nWindowHeight;
    }
    else
        maWindowFiller.Hide();

    aPosition.Y() += mnVerticalBorder;
    mbIsLayoutPending = false;

    return aPosition.Y();
}

IMPL_LINK(SubToolPanel, WindowEventListener, VclSimpleEvent*, pEvent)
{
    if (pEvent!=NULL && pEvent->ISA(VclWindowEvent))
    {
        VclWindowEvent* pWindowEvent = static_cast<VclWindowEvent*>(pEvent);
        switch (pWindowEvent->GetId())
        {
            case VCLEVENT_WINDOW_SHOW:
            case VCLEVENT_WINDOW_HIDE:
            case VCLEVENT_WINDOW_ACTIVATE:
            case VCLEVENT_WINDOW_RESIZE:
                RequestResize();
                break;
        }
    }
    return 0;
}

::com::sun::star::uno::Reference<
    ::com::sun::star::accessibility::XAccessible> SubToolPanel::CreateAccessibleObject (
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>& )
{
    return new ::accessibility::AccessibleTreeNode (
        *this,
        ::rtl::OUString::createFromAscii("Sub Task Panel"),
        ::rtl::OUString::createFromAscii("Sub Task Panel"),
        ::com::sun::star::accessibility::AccessibleRole::PANEL);
}

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


<commit_before><commit_msg>loplugin:passstuffbyref<commit_after><|endoftext|>


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

// C Includes

// C++ Includes

// Other libraries and framework includes

// Project includes
#include "lldb/DataFormatters/TypeValidator.h"
#include "lldb/Core/StreamString.h"

using namespace lldb;
using namespace lldb_private;

TypeValidatorImpl::TypeValidatorImpl(const Flags &flags)
    : m_flags(flags)
    , m_my_revision(0)
{
}

TypeValidatorImpl::ValidationResult
TypeValidatorImpl::Success ()
{
    return ValidationResult { TypeValidatorResult::Success, "" };
}

TypeValidatorImpl::ValidationResult
TypeValidatorImpl::Failure (std::string message)
{
    return ValidationResult { TypeValidatorResult::Failure, message };
}

TypeValidatorImpl_CXX::TypeValidatorImpl_CXX (ValidatorFunction f, std::string d, const TypeValidatorImpl::Flags& flags) :
    TypeValidatorImpl(flags),
    m_description(d),
    m_validator_function(f)
{
}

TypeValidatorImpl_CXX::~TypeValidatorImpl_CXX()
{
}

TypeValidatorImpl::ValidationResult
TypeValidatorImpl_CXX::FormatObject (ValueObject *valobj) const
{
    if (!valobj)
        return Success(); // I guess there's nothing wrong with a null valueobject..

    return m_validator_function(valobj);
}

std::string
TypeValidatorImpl_CXX::GetDescription()
{
    StreamString sstr;
    sstr.Printf ("%s%s%s%s",
                 m_description.c_str(),
                 Cascades() ? "" : " (not cascading)",
                 SkipsPointers() ? " (skip pointers)" : "",
                 SkipsReferences() ? " (skip references)" : "");
    return sstr.GetString();
}
<commit_msg>DataFormatters: add missing destructor implementation<commit_after>//===-- TypeValidator.cpp ---------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// C Includes

// C++ Includes

// Other libraries and framework includes

// Project includes
#include "lldb/DataFormatters/TypeValidator.h"
#include "lldb/Core/StreamString.h"

using namespace lldb;
using namespace lldb_private;

TypeValidatorImpl::TypeValidatorImpl(const Flags &flags)
    : m_flags(flags)
    , m_my_revision(0)
{
}

TypeValidatorImpl::~TypeValidatorImpl()
{
}

TypeValidatorImpl::ValidationResult
TypeValidatorImpl::Success ()
{
    return ValidationResult { TypeValidatorResult::Success, "" };
}

TypeValidatorImpl::ValidationResult
TypeValidatorImpl::Failure (std::string message)
{
    return ValidationResult { TypeValidatorResult::Failure, message };
}

TypeValidatorImpl_CXX::TypeValidatorImpl_CXX (ValidatorFunction f, std::string d, const TypeValidatorImpl::Flags& flags) :
    TypeValidatorImpl(flags),
    m_description(d),
    m_validator_function(f)
{
}

TypeValidatorImpl_CXX::~TypeValidatorImpl_CXX()
{
}

TypeValidatorImpl::ValidationResult
TypeValidatorImpl_CXX::FormatObject (ValueObject *valobj) const
{
    if (!valobj)
        return Success(); // I guess there's nothing wrong with a null valueobject..

    return m_validator_function(valobj);
}

std::string
TypeValidatorImpl_CXX::GetDescription()
{
    StreamString sstr;
    sstr.Printf ("%s%s%s%s",
                 m_description.c_str(),
                 Cascades() ? "" : " (not cascading)",
                 SkipsPointers() ? " (skip pointers)" : "",
                 SkipsReferences() ? " (skip references)" : "");
    return sstr.GetString();
}
<|endoftext|>


<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * 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
 * OpenSceneGraph Public License for more details.
*/
#include <osg/BoundingSphere>
#include <osg/BoundingBox>

using namespace osg;

void BoundingSphere::expandBy(const Vec3& v)
{
    if (valid())
    {
        Vec3 dv = v-_center;
        float r = dv.length();
        if (r>_radius)
        {
            float dr = (r-_radius)*0.5f;
            _center += dv*(dr/r);
            _radius += dr;
        } // else do nothing as vertex is within sphere.
    }
    else
    {
        _center = v;
        _radius = 0.0f;
    }
}

void BoundingSphere::expandRadiusBy(const Vec3& v)
{
    if (valid())
    {
        float r = (v-_center).length();
        if (r>_radius) _radius = r;
        // else do nothing as vertex is within sphere.
    }
    else
    {
        _center = v;
        _radius = 0.0f;
    }
}

void BoundingSphere::expandBy(const BoundingSphere& sh)
{
    if (sh.valid())
    {
        if (valid())
        {
            Vec3 dv = sh._center-_center;
            float dv_len = dv.length();
            if (dv_len+sh._radius>_radius)
            {
                Vec3 e1 = _center-(dv*(_radius/dv_len));
                Vec3 e2 = sh._center+(dv*(sh._radius/dv_len));
                _center = (e1+e2)*0.5f;
                _radius = (e2-_center).length();

            }                    // else do nothing as vertex is within sphere.
        }
        else
        {
            _center = sh._center;
            _radius = sh._radius;
        }
    }
}

void BoundingSphere::expandRadiusBy(const BoundingSphere& sh)
{
    if (sh.valid())
    {
        if (valid())
        {
            float r = (sh._center-_center).length()+sh._radius;
            if (r>_radius) _radius = r;
            // else do nothing as vertex is within sphere.
        }
        else
        {
            _center = sh._center;
            _radius = sh._radius;
        }
    }
}

void BoundingSphere::expandBy(const BoundingBox& bb)
{
    if (bb.valid())
    {
        if (valid())
        {
            BoundingBox newbb(bb);

            for(unsigned int c=0;c<8;++c)
            {
                Vec3 v = bb.corner(c)-_center; // get the direction vector from corner
                v.normalize(); // normalise it.
                v *= -_radius; // move the vector in the opposite direction distance radius.
                v += _center; // move to absolute position.
                newbb.expandBy(v); // add it into the new bounding box.
            }

            _center = newbb.center();
            _radius = newbb.radius();

        }
        else
        {
            _center = bb.center();
            _radius = bb.radius();
        }
    }
}

void BoundingSphere::expandRadiusBy(const BoundingBox& bb)
{
    if (bb.valid())
    {
        if (valid())
        {
            for(unsigned int c=0;c<8;++c)
            {
                expandRadiusBy(bb.corner(c));
            }
        }
        else
        {
            _center = bb.center();
            _radius = bb.radius();
        }
    }
}
<commit_msg>From Brad Christiansen, fix expandBy(const BoundingSphere&) method to properly handle the instance of when the two bounding sphere's have a coincident center.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * 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
 * OpenSceneGraph Public License for more details.
*/
#include <osg/BoundingSphere>
#include <osg/BoundingBox>

using namespace osg;

void BoundingSphere::expandBy(const Vec3& v)
{
    if (valid())
    {
        Vec3 dv = v-_center;
        float r = dv.length();
        if (r>_radius)
        {
            float dr = (r-_radius)*0.5f;
            _center += dv*(dr/r);
            _radius += dr;
        } // else do nothing as vertex is within sphere.
    }
    else
    {
        _center = v;
        _radius = 0.0f;
    }
}

void BoundingSphere::expandRadiusBy(const Vec3& v)
{
    if (valid())
    {
        float r = (v-_center).length();
        if (r>_radius) _radius = r;
        // else do nothing as vertex is within sphere.
    }
    else
    {
        _center = v;
        _radius = 0.0f;
    }
}

void BoundingSphere::expandBy(const BoundingSphere& sh)
{
    if (sh.valid())
    {
        if (valid())
        {
            Vec3 dv = sh._center-_center;
            float dv_len = dv.length();

            if(dv_len == 0 && sh._radius>_radius) {
               _radius = sh._radius;
            }
            else if (dv_len+sh._radius>_radius)
            {
                Vec3 e1 = _center-(dv*(_radius/dv_len));
                Vec3 e2 = sh._center+(dv*(sh._radius/dv_len));
                _center = (e1+e2)*0.5f;
                _radius = (e2-_center).length();

            }                    // else do nothing as vertex is within sphere.
        }
        else
        {
            _center = sh._center;
            _radius = sh._radius;
        }
    }
}

void BoundingSphere::expandRadiusBy(const BoundingSphere& sh)
{
    if (sh.valid())
    {
        if (valid())
        {
            float r = (sh._center-_center).length()+sh._radius;
            if (r>_radius) _radius = r;
            // else do nothing as vertex is within sphere.
        }
        else
        {
            _center = sh._center;
            _radius = sh._radius;
        }
    }
}

void BoundingSphere::expandBy(const BoundingBox& bb)
{
    if (bb.valid())
    {
        if (valid())
        {
            BoundingBox newbb(bb);

            for(unsigned int c=0;c<8;++c)
            {
                Vec3 v = bb.corner(c)-_center; // get the direction vector from corner
                v.normalize(); // normalise it.
                v *= -_radius; // move the vector in the opposite direction distance radius.
                v += _center; // move to absolute position.
                newbb.expandBy(v); // add it into the new bounding box.
            }

            _center = newbb.center();
            _radius = newbb.radius();

        }
        else
        {
            _center = bb.center();
            _radius = bb.radius();
        }
    }
}

void BoundingSphere::expandRadiusBy(const BoundingBox& bb)
{
    if (bb.valid())
    {
        if (valid())
        {
            for(unsigned int c=0;c<8;++c)
            {
                expandRadiusBy(bb.corner(c));
            }
        }
        else
        {
            _center = bb.center();
            _radius = bb.radius();
        }
    }
}
<|endoftext|>


<commit_before>/**********************************************************************
 *
 *    FILE:            LOD.cpp
 *
 *    DESCRIPTION:    Read/Write osg::LOD in binary format to disk.
 *
 *    CREATED BY:        Auto generated by iveGenerate
 *                    and later modified by Rune Schmidt Jensen.
 *
 *    HISTORY:        Created 24.3.2003
 *
 *    Copyright 2003 VR-C
 **********************************************************************/

#include "Exception.h"
#include "LOD.h"
#include "Group.h"

using namespace ive;

void LOD::write(DataOutputStream* out){
    // Write LOD's identification.
    out->writeInt(IVELOD);
    // If the osg class is inherited by any other class we should also write this to file.
    osg::Group*  group = dynamic_cast<osg::Group*>(this);
    if(group){
        ((ive::Group*)(group))->write(out);
    }
    else
        out_THROW_EXCEPTION("LOD::write(): Could not cast this osg::LOD to an osg::Group.");
    // Write LOD's properties.

        out->writeFloat(getRadius());

    // Write centermode
    out->writeInt(getCenterMode());
    out->writeVec3(getCenter());

        out->writeInt(getRangeMode());

    // Write rangelist
    int size = getNumRanges();
    out->writeInt(size);
    for(int i=0;i<size;i++){
        out->writeFloat(getMinRange(i));
        out->writeFloat(getMaxRange(i));
    }
}

void LOD::read(DataInputStream* in){
    // Peek on LOD's identification.
    int id = in->peekInt();
    if(id == IVELOD){
        // Read LOD's identification.
        id = in->readInt();

        // If the osg class is inherited by any other class we should also read this from file.
        osg::Group*  group = dynamic_cast<osg::Group*>(this);
        if(group){
            ((ive::Group*)(group))->read(in);
        }
        else
            in_THROW_EXCEPTION("LOD::read(): Could not cast this osg::LOD to an osg::Group.");
        // Read LOD's properties

                if ( in->getVersion() > VERSION_0002 )
                    setRadius(in->readFloat());

        // Read centermode
        setCenterMode((osg::LOD::CenterMode)in->readInt());
        setCenter(in->readVec3());

                if ( in->getVersion() > VERSION_0002 )
                    setRangeMode((RangeMode)in->readInt());

        // Read rangelist
        int size = in->readInt();;
        for(int i=0;i<size;i++){
            float min = in->readFloat();
            float max = in->readFloat();
            setRange(i, min, max);
        }
    }
    else{
        in_THROW_EXCEPTION("LOD::read(): Expected LOD identification.");
    }
}
<commit_msg>Fixed the order of setting of CenterMode<commit_after>/**********************************************************************
 *
 *    FILE:            LOD.cpp
 *
 *    DESCRIPTION:    Read/Write osg::LOD in binary format to disk.
 *
 *    CREATED BY:        Auto generated by iveGenerate
 *                    and later modified by Rune Schmidt Jensen.
 *
 *    HISTORY:        Created 24.3.2003
 *
 *    Copyright 2003 VR-C
 **********************************************************************/

#include "Exception.h"
#include "LOD.h"
#include "Group.h"

using namespace ive;

void LOD::write(DataOutputStream* out){
    // Write LOD's identification.
    out->writeInt(IVELOD);
    // If the osg class is inherited by any other class we should also write this to file.
    osg::Group*  group = dynamic_cast<osg::Group*>(this);
    if(group){
        ((ive::Group*)(group))->write(out);
    }
    else
        out_THROW_EXCEPTION("LOD::write(): Could not cast this osg::LOD to an osg::Group.");
    // Write LOD's properties.

        out->writeFloat(getRadius());

    // Write centermode
    out->writeInt(getCenterMode());
    out->writeVec3(getCenter());

    out->writeInt(getRangeMode());

    // Write rangelist
    int size = getNumRanges();
    out->writeInt(size);
    for(int i=0;i<size;i++){
        out->writeFloat(getMinRange(i));
        out->writeFloat(getMaxRange(i));
    }
}

void LOD::read(DataInputStream* in){
    // Peek on LOD's identification.
    int id = in->peekInt();
    if(id == IVELOD){
        // Read LOD's identification.
        id = in->readInt();

        // If the osg class is inherited by any other class we should also read this from file.
        osg::Group*  group = dynamic_cast<osg::Group*>(this);
        if(group){
            ((ive::Group*)(group))->read(in);
        }
        else
            in_THROW_EXCEPTION("LOD::read(): Could not cast this osg::LOD to an osg::Group.");
        // Read LOD's properties

                if ( in->getVersion() > VERSION_0002 )
                    setRadius(in->readFloat());

        // Read centermode and center
        osg::LOD::CenterMode centerMode = (osg::LOD::CenterMode)in->readInt();
        osg::Vec3 center = in->readVec3();
        setCenter(center);
        setCenterMode(centerMode);

        if ( in->getVersion() > VERSION_0002 )
            setRangeMode((RangeMode)in->readInt());

        // Read rangelist
        int size = in->readInt();;
        for(int i=0;i<size;i++){
            float min = in->readFloat();
            float max = in->readFloat();
            setRange(i, min, max);
        }
    }
    else{
        in_THROW_EXCEPTION("LOD::read(): Expected LOD identification.");
    }
}
<|endoftext|>


<commit_before>#pragma once

// C

#include <stdint.h>

// STL

#include <chrono>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <vector>

// utf8rewind

#include "utf8rewind.h"

// Google Test

#include "gtest/internal/gtest-port.h"
#include "gtest/gtest.h"

namespace testing {
namespace internal {

	extern bool ParseBoolFlag(
		const char* str,
		const char* flag,
		bool* value);

	extern bool ParseInt32Flag(
		const char* str,
		const char* flag,
		Int32* value);

	extern bool ParseStringFlag(
		const char* str,
		const char* flag,
		std::string* value);

};
};

namespace performance {

	class Suite
	{

	public:

		virtual void setup() { }
		virtual void body() = 0;
		virtual void tearDown() { }

	};

	class BaseSuiteFactory
	{

	public:

		virtual Suite* create() = 0;

	};

	template <class SuiteType>
	class SuiteFactory
		: public BaseSuiteFactory
	{

	public:

		virtual Suite* create() override { return new SuiteType(); }

	};

	class Collection
	{

	public:

		static Collection& get()
		{
			static Collection instance;
			return instance;
		}

		void addFactory(
			const std::string& name,
			BaseSuiteFactory* factory)
		{
			m_factories.push_back(std::make_pair(name, factory));
		}

		int run(int argc, char** argv)
		{
			using testing::internal::ParseBoolFlag;
			using testing::internal::ParseInt32Flag;
			using testing::internal::ParseStringFlag;

			testing::internal::Int32 repeat_count = 100;
			bool display_individual = false;
			std::string filter = "*";
			bool show_help = false;

			for (int i = 1; i < argc; ++i)
			{
				std::string arg_help = argv[i];

				if (arg_help == "--help" ||
					arg_help == "-h" ||
					arg_help == "-?" ||
					arg_help == "/?")
				{
					show_help = true;

					break;
				}

				if (!ParseInt32Flag(argv[i], "repeat_count", &repeat_count) &&
					!ParseBoolFlag(argv[i], "display_individual", &display_individual) &&
					!ParseStringFlag(argv[i], "filter", &filter))
				{
					show_help = true;

					break;
				}
			}

			if (show_help)
			{
				std::cout
					<< "--" GTEST_FLAG_PREFIX_ "repeat_count=[COUNT]" << std::endl
					<< "    How many times to repeat the performance tests. The default is " << std::endl
					<< "    100 times." << std::endl
					<< "--" GTEST_FLAG_PREFIX_ "display_invidual" << std::endl
					<< "    Display individual timings, instead of just the total time, worst," << std::endl
					<< "    best and average case." << std::endl
					<< "--" GTEST_FLAG_PREFIX_ "filter=POSITIVE_PATTERNS[-NEGATIVE_PATTERNS]" << std::endl
					<< "    Run only the tests whose name matches one of the positive patterns but" << std::endl
					<< "    none of the negative patterns. '?' matches any single character; '*'" << std::endl
					<< "    matches any substring; ':' separates two patterns." << std::endl;

				return 0;
			}

			std::cout
				<< "Running " << repeat_count << " iterations."
				<< std::endl;

			typedef std::chrono::steady_clock clock;
			typedef std::chrono::microseconds ms;

			clock::time_point time_start = clock::now();

			typedef
				std::vector<std::pair<std::string, BaseSuiteFactory*>>::iterator
				factory_it;

			for (factory_it it = m_factories.begin();
				it != m_factories.end();
				++it)
			{
				Suite* suite = it->second->create();

				std::cout
					<< "[" << it->first << "]"
					<< std::endl;

				std::vector<uint32_t> timings;

				clock::time_point total_start = clock::now();

				suite->setup();

				for (size_t i = 0; i < repeat_count; ++i)
				{
					clock::time_point test_start = clock::now();

					suite->body();

					uint32_t test_duration = (uint32_t)(
						std::chrono::duration_cast<ms>(
							clock::now() - test_start
						)).count() / 1000;

					if (display_individual)
					{
						std::cout
							<< std::setw(10) << i << ": "
							<< std::setw(8) << test_duration << " ms"
							<< std::endl;
					}

					timings.push_back(test_duration);
				}

				suite->tearDown();

				uint32_t total_duration = (uint32_t)(
						std::chrono::duration_cast<ms>(
							clock::now() - total_start
						)).count() / 1000;

				uint32_t worst_case = 0;
				uint32_t best_case = std::numeric_limits<uint32_t>::max();
				double average = 0.0;

				for (std::vector<uint32_t>::iterator it = timings.begin();
					it != timings.end();
					++it)
				{
					worst_case = std::max(worst_case, *it);
					best_case = std::min(best_case, *it);
					average += (double)*it;
				}

				average /= (double)timings.size();

				std::cout
					<< "     Total: "
					<< std::setw(8) << total_duration << " ms"
					<< std::endl;

				std::cout
					<< " Best case: "
					<< std::setw(8) << best_case << " ms"
					<< std::endl;

				std::cout
					<< "Worst case: "
					<< std::setw(8) << worst_case << " ms"
					<< std::endl;

				std::cout
					<< "   Average: "
					<< std::setw(8) << average << " ms"
					<< std::endl;

				std::cout << std::endl;
			}

			return 0;
		}

	private:

		std::vector<std::pair<std::string, BaseSuiteFactory*>> m_factories;

	};

	inline bool registerTest(
		const char* caseName,
		const char* testName,
		BaseSuiteFactory* factory)
	{
		std::string name = caseName;
		name += ".";
		name += testName;

		Collection::get().addFactory(name, factory);

		return true;
	}

}

#define PERF_RUN_ALL(_argc, _argv) \
	performance::Collection::get().run(_argc, _argv)

#define PERF_TEST_CLASS_NAME(_caseName, _testName) \
	_caseName ## _ ## _testName ## _Test

#define PERF_TEST_IMPL(_caseName, _testName, _parentClass) \
	class PERF_TEST_CLASS_NAME(_caseName, _testName) \
		: public _parentClass { \
	private: \
		virtual void body() override; \
		static bool m_registered; \
	}; \
	bool PERF_TEST_CLASS_NAME(_caseName, _testName)::m_registered = \
		performance::registerTest( \
			#_caseName, #_testName, \
			new performance::SuiteFactory< \
				PERF_TEST_CLASS_NAME(_caseName, _testName)>); \
	void PERF_TEST_CLASS_NAME(_caseName, _testName)::body()

#define PERF_TEST(_caseName, _testName) \
	PERF_TEST_IMPL(_caseName, _testName, performance::Suite)

#define PERF_TEST_F(_caseName, _testName) \
	PERF_TEST_IMPL(_caseName, _testName, _caseName)<commit_msg>Add filter matching based on command line.<commit_after>#pragma once

// C

#include <stdint.h>

// STL

#include <chrono>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <vector>

// utf8rewind

#include "utf8rewind.h"

// Google Test

#include "gtest/internal/gtest-port.h"
#include "gtest/gtest.h"

namespace testing {
namespace internal {

	extern bool ParseBoolFlag(
		const char* str,
		const char* flag,
		bool* value);

	extern bool ParseInt32Flag(
		const char* str,
		const char* flag,
		Int32* value);

	extern bool ParseStringFlag(
		const char* str,
		const char* flag,
		std::string* value);

	static bool PatternMatchesString(
		const char* pattern,
		const char* text)
	{
		switch (*pattern)
		{
			case '\0':
			case ':':  // Either ':' or '\0' marks the end of the pattern.
				return *text == '\0';
			case '?':  // Matches any single character.
				return
					*text != '\0'
					&& PatternMatchesString(pattern + 1, text + 1);
			case '*':  // Matches any string (possibly empty) of characters.
				return (
					*text != '\0' &&
					PatternMatchesString(pattern, text + 1)) ||
					PatternMatchesString(pattern + 1, text);
			default:  // Non-special character.  Matches itself.
				return
					*pattern == *text &&
					PatternMatchesString(pattern + 1, text + 1);
		}
	}

	static bool MatchesFilter(
		const std::string& name,
		const std::string& filter)
	{
		const char *cur_pattern = filter.c_str();
		while (1)
		{
			if (PatternMatchesString(cur_pattern, name.c_str()))
			{
				return true;
			}

			cur_pattern = strchr(cur_pattern, ':');
			if (cur_pattern == NULL)
			{
				return false;
			}

			// Skip the pattern separator (the ':' character).
			cur_pattern++;
		}
	}

};
};

namespace performance {

	class Suite
	{

	public:

		virtual void setup() { }
		virtual void body() = 0;
		virtual void tearDown() { }

	};

	class BaseSuiteFactory
	{

	public:

		virtual Suite* create() = 0;

	};

	template <class SuiteType>
	class SuiteFactory
		: public BaseSuiteFactory
	{

	public:

		virtual Suite* create() override { return new SuiteType(); }

	};

	class Collection
	{

	public:

		static Collection& get()
		{
			static Collection instance;
			return instance;
		}

		void addFactory(
			const std::string& name,
			BaseSuiteFactory* factory)
		{
			m_factories.push_back(std::make_pair(name, factory));
		}

		int run(int argc, char** argv)
		{
			using testing::internal::ParseBoolFlag;
			using testing::internal::ParseInt32Flag;
			using testing::internal::ParseStringFlag;

			testing::internal::Int32 repeat_count = 10;
			bool display_individual = false;
			std::string filter = "*";
			bool show_help = false;

			for (int i = 1; i < argc; ++i)
			{
				std::string arg_help = argv[i];

				if (arg_help == "--help" ||
					arg_help == "-h" ||
					arg_help == "-?" ||
					arg_help == "/?")
				{
					show_help = true;

					break;
				}

				if (!ParseInt32Flag(argv[i], "repeat_count", &repeat_count) &&
					!ParseBoolFlag(argv[i], "display_individual", &display_individual) &&
					!ParseStringFlag(argv[i], "filter", &filter))
				{
					show_help = true;

					break;
				}
			}

			if (show_help)
			{
				std::cout
					<< "--" GTEST_FLAG_PREFIX_ "repeat_count=[COUNT]" << std::endl
					<< "    How many times to repeat the performance tests. The default is " << std::endl
					<< "    100 times." << std::endl
					<< "--" GTEST_FLAG_PREFIX_ "display_invidual" << std::endl
					<< "    Display individual timings, instead of just the total time, worst," << std::endl
					<< "    best and average case." << std::endl
					<< "--" GTEST_FLAG_PREFIX_ "filter=POSITIVE_PATTERNS[-NEGATIVE_PATTERNS]" << std::endl
					<< "    Run only the tests whose name matches one of the positive patterns but" << std::endl
					<< "    none of the negative patterns. '?' matches any single character; '*'" << std::endl
					<< "    matches any substring; ':' separates two patterns." << std::endl;

				return 0;
			}

			if (filter != "*")
			{
				std::cout
					<< "NOTE: Filter is \"" << filter << "\""
					<< std::endl;
			}

			std::string positive_filter;
			std::string negative_filter;
			const char* dash = strchr(filter.c_str(), '-');
			if (dash != nullptr)
			{
				positive_filter = std::string(filter.c_str(), dash);
				if (positive_filter.empty())
				{
					positive_filter = "*";
				}
				negative_filter = std::string(dash + 1);
			}
			else
			{
				positive_filter = filter;
			}

			std::cout
				<< "Running " << repeat_count << " iterations."
				<< std::endl;

			typedef std::chrono::steady_clock clock;
			typedef std::chrono::microseconds ms;

			clock::time_point time_start = clock::now();

			typedef
				std::vector<std::pair<std::string, BaseSuiteFactory*>>::iterator
				factory_it;

			for (factory_it it = m_factories.begin();
				it != m_factories.end();
				++it)
			{
				using testing::internal::MatchesFilter;

				Suite* suite = it->second->create();

				if (!MatchesFilter(it->first, positive_filter) ||
					MatchesFilter(it->first, negative_filter))
				{
					continue;
				}

				std::cout
					<< "[" << it->first << "]"
					<< std::endl;

				std::vector<uint32_t> timings;

				clock::time_point total_start = clock::now();

				suite->setup();

				for (size_t i = 0; i < repeat_count; ++i)
				{
					clock::time_point test_start = clock::now();

					suite->body();

					uint32_t test_duration = (uint32_t)(
						std::chrono::duration_cast<ms>(
							clock::now() - test_start
						)).count() / 1000;

					if (display_individual)
					{
						std::cout
							<< std::setw(10) << i << ": "
							<< std::setw(8) << test_duration << " ms"
							<< std::endl;
					}

					timings.push_back(test_duration);
				}

				suite->tearDown();

				uint32_t total_duration = (uint32_t)(
						std::chrono::duration_cast<ms>(
							clock::now() - total_start
						)).count() / 1000;

				uint32_t worst_case = 0;
				uint32_t best_case = std::numeric_limits<uint32_t>::max();
				double average = 0.0;

				for (std::vector<uint32_t>::iterator it = timings.begin();
					it != timings.end();
					++it)
				{
					worst_case = std::max(worst_case, *it);
					best_case = std::min(best_case, *it);
					average += (double)*it;
				}

				average /= (double)timings.size();

				std::cout
					<< "     Total: "
					<< std::setw(8) << total_duration << " ms"
					<< std::endl;

				std::cout
					<< " Best case: "
					<< std::setw(8) << best_case << " ms"
					<< std::endl;

				std::cout
					<< "Worst case: "
					<< std::setw(8) << worst_case << " ms"
					<< std::endl;

				std::cout
					<< "   Average: "
					<< std::setw(8) << average << " ms"
					<< std::endl;

				std::cout << std::endl;
			}

			return 0;
		}

	private:

		std::vector<std::pair<std::string, BaseSuiteFactory*>> m_factories;

	};

	inline bool registerTest(
		const char* caseName,
		const char* testName,
		BaseSuiteFactory* factory)
	{
		std::string name = caseName;
		name += ".";
		name += testName;

		Collection::get().addFactory(name, factory);

		return true;
	}

}

#define PERF_RUN_ALL(_argc, _argv) \
	performance::Collection::get().run(_argc, _argv)

#define PERF_TEST_CLASS_NAME(_caseName, _testName) \
	_caseName ## _ ## _testName ## _Test

#define PERF_TEST_IMPL(_caseName, _testName, _parentClass) \
	class PERF_TEST_CLASS_NAME(_caseName, _testName) \
		: public _parentClass { \
	private: \
		virtual void body() override; \
		static bool m_registered; \
	}; \
	bool PERF_TEST_CLASS_NAME(_caseName, _testName)::m_registered = \
		performance::registerTest( \
			#_caseName, #_testName, \
			new performance::SuiteFactory< \
				PERF_TEST_CLASS_NAME(_caseName, _testName)>); \
	void PERF_TEST_CLASS_NAME(_caseName, _testName)::body()

#define PERF_TEST(_caseName, _testName) \
	PERF_TEST_IMPL(_caseName, _testName, performance::Suite)

#define PERF_TEST_F(_caseName, _testName) \
	PERF_TEST_IMPL(_caseName, _testName, _caseName)<|endoftext|>


<commit_before>#include "qcan_interface_widget.hpp"

#include <QDebug>
#include <QPainter>
#include <QPaintEvent>
#include <QPalette>

#include <QMessageBox>
#include <QDir>
#include <QMenu>
#include <QPluginLoader>
#include <QPoint>

/*----------------------------------------------------------------------------*\
** Class methods                                                              **
**                                                                            **
\*----------------------------------------------------------------------------*/

//----------------------------------------------------------------------------//
// QCanInterfaceWidget()                                                      //
// constructor                                                                //
//----------------------------------------------------------------------------//
QCanInterfaceWidget::QCanInterfaceWidget()
 : QWidget()
{
   clIconP = QIcon(":images/network-icon.png");
   pclQCanInterfaceP = NULL;
}

//----------------------------------------------------------------------------//
// QCanInterfaceWidget::mousePressEvent()                                     //
// handle mouse press events on window areas                                  //
//----------------------------------------------------------------------------//
void QCanInterfaceWidget::mousePressEvent(QMouseEvent * pclEventV)
{
   QList<QAction *> apclListActionsT;
   QAction * pclActionT;
   QPoint pos(this->mapFromParent(QCursor::pos()));
   QMenu clContextMenuT(tr("CAN interface selection"), this);

   //----------------------------------------------------------------
   // check there are any plugins available
   //
   if (!loadPlugin())
   {
       QMessageBox::information(this, "ERROR", "Could not load the any plugins!");
   }

   //----------------------------------------------------------------
   // create context menu with all available plugins
   //
   pclActionT = new QAction("Virtual", this);
   pclActionT->setIcon(QIcon(":images/network-icon.png"));
   apclListActionsT.append(pclActionT);
   clContextMenuT.addAction(apclListActionsT.at(0));

   quint32 ulCntrT = 0;
   while (ulCntrT < aclPluginNameListP.count())
   {
      pclActionT = new QAction(aclPluginNameListP.at(ulCntrT), this);
      pclActionT->setIcon(aclIconListP.at(ulCntrT));
      apclListActionsT.append(pclActionT);
      clContextMenuT.addAction(apclListActionsT.at(ulCntrT+1));
      ulCntrT++;
   }

   //----------------------------------------------------------------
   // evaluate click operation
   //
   switch(pclEventV->button())
   {
      case Qt::LeftButton:

         qDebug() << "Left button pressed";
         //-----------------------------------------------------
         // show context menu
         //
         pclActionT = clContextMenuT.exec(pos);

         //-----------------------------------------------------
         // evaluate selection
         //
         if (pclActionT != 0)
         {
            qint32 slIdxT = aclPluginNameListP.indexOf(pclActionT->text());
            qDebug() << "mousePressEvent(): select index ..." << slIdxT;

            pclQCanInterfaceP = NULL;
            if (slIdxT > 0)
            {
               QPluginLoader clPluginLoaderT(aclPluginListP.at(slIdxT));
               QObject *pclPluginT = clPluginLoaderT.instance();
               if (pclPluginT)
               {
                   pclQCanInterfaceP = qobject_cast<QCanInterface *>(pclPluginT);
               }
            }

            emit interfaceChanged(pclQCanInterfaceP);
         } else
         {
            qDebug() << "mousePressEvent(): no index selected";
         }
         break;

      case Qt::RightButton:
         qDebug() << "Right button pressed";

         break;

      default:

         break;
   }
   clicked(0);
}

//----------------------------------------------------------------------------//
// loadPlugin()                                                               //
//                                                                            //
//----------------------------------------------------------------------------//
bool QCanInterfaceWidget::loadPlugin()
{
   QCanInterface *pclQCanIfT;

   qInfo() << "loadPlugin(): used plugin path" << clPluginPathP.absolutePath();

   //----------------------------------------------------------------
   // check plugin path
   //
   if (!clPluginPathP.exists())
   {
      qWarning() << "loadPlugin(): plugin path does not exist!";
      return false;
   }

   //----------------------------------------------------------------
   // check plugins and create a list with valid plugins
   //
   aclPluginNameListP.clear();
   aclPluginListP.clear();
   aclIconListP.clear();
   foreach (QString clFileNameT, clPluginPathP.entryList(QDir::Files))
   {
      if (QLibrary::isLibrary(clPluginPathP.absoluteFilePath(clFileNameT)))
      {
         QPluginLoader clPluginLoaderT(clPluginPathP.absoluteFilePath(clFileNameT));
         QObject *pclPluginT = clPluginLoaderT.instance();
         if (pclPluginT)
         {
            pclQCanIfT = qobject_cast<QCanInterface *>(pclPluginT);
            if (pclQCanIfT)
            {
               qInfo() << "loadPlugin(): found" << clPluginPathP.absoluteFilePath(clFileNameT) << "plugin.";

               //-------------------------------------
               // collect all information of valid plugin
               // \todo Get the PluginName and Icon
               //
               aclPluginNameListP.append(pclQCanIfT->name());
               aclIconListP.append(pclQCanIfT->icon());
               aclPluginListP.append(clPluginPathP.absoluteFilePath(clFileNameT));
            }
         } else
         {
            qWarning() << "loadPlugin(): plugin" << clPluginPathP.absoluteFilePath(clFileNameT) << "could NOT be loaded or the root component object could NOT be instantiated!";
         }
      } else
      {
         qWarning() << "loadPlugin(): plugin" << clPluginPathP.absoluteFilePath(clFileNameT) << "is NOT a library!";
      }
   }

   if (aclPluginNameListP.isEmpty())
   {
      qWarning() << "loadPlugin(): NONE plugins have been found!";
      return false;
   }

   qInfo() << "loadPlugin(): found" << QString::number(aclPluginNameListP.count(),10) << "available plugins.";

   return true;
}

//----------------------------------------------------------------------------//
// QCanInterfaceWidget::paintEvent()                                          //
//                                                                            //
//----------------------------------------------------------------------------//
void QCanInterfaceWidget::paintEvent(QPaintEvent * pclEventV)
{
   qDebug() << "Paint" << pclEventV->rect();

   QPalette clPaletteT(this->palette());
   QPainter clPainterT(this);
   QBrush brush = QBrush(Qt::transparent, Qt::NoBrush);
   qDebug() << "Brush" << brush;
   clPainterT.setPen((Qt::white));
   clPainterT.setBrush(brush);
   //clPainterT.eraseRect(pclEventV->rect());
   clPainterT.fillRect(pclEventV->rect(), QColor(0xE3, 0xE3, 0xE3)); //Qt::NoBrush);
   //clPainterT.drawLine(1, 1, 80, 80);

   clIconP.paint(&clPainterT, pclEventV->rect(), Qt::AlignCenter);
}

//----------------------------------------------------------------------------//
// setPluginPath()                                                            //
//                                                                            //
//----------------------------------------------------------------------------//
void QCanInterfaceWidget::setPluginPath(QDir clPluginPathV)
{
   clPluginPathP = clPluginPathV;
   qDebug() << "INFO: Plugin Path is set to" << clPluginPathP.absolutePath();
}
<commit_msg>Fix data type<commit_after>#include "qcan_interface_widget.hpp"

#include <QDebug>
#include <QPainter>
#include <QPaintEvent>
#include <QPalette>

#include <QMessageBox>
#include <QDir>
#include <QMenu>
#include <QPluginLoader>
#include <QPoint>

/*----------------------------------------------------------------------------*\
** Class methods                                                              **
**                                                                            **
\*----------------------------------------------------------------------------*/

//----------------------------------------------------------------------------//
// QCanInterfaceWidget()                                                      //
// constructor                                                                //
//----------------------------------------------------------------------------//
QCanInterfaceWidget::QCanInterfaceWidget()
 : QWidget()
{
   clIconP = QIcon(":images/network-icon.png");
   pclQCanInterfaceP = NULL;
}

//----------------------------------------------------------------------------//
// QCanInterfaceWidget::mousePressEvent()                                     //
// handle mouse press events on window areas                                  //
//----------------------------------------------------------------------------//
void QCanInterfaceWidget::mousePressEvent(QMouseEvent * pclEventV)
{
   QList<QAction *> apclListActionsT;
   QAction * pclActionT;
   QPoint pos(this->mapFromParent(QCursor::pos()));
   QMenu clContextMenuT(tr("CAN interface selection"), this);

   //----------------------------------------------------------------
   // check there are any plugins available
   //
   if (!loadPlugin())
   {
       QMessageBox::information(this, "ERROR", "Could not load the any plugins!");
   }

   //----------------------------------------------------------------
   // create context menu with all available plugins
   //
   pclActionT = new QAction("Virtual", this);
   pclActionT->setIcon(QIcon(":images/network-icon.png"));
   apclListActionsT.append(pclActionT);
   clContextMenuT.addAction(apclListActionsT.at(0));

   qint32 slCntrT = 0;
   while (slCntrT < aclPluginNameListP.count())
   {
      pclActionT = new QAction(aclPluginNameListP.at(slCntrT), this);
      pclActionT->setIcon(aclIconListP.at(slCntrT));
      apclListActionsT.append(pclActionT);
      clContextMenuT.addAction(apclListActionsT.at(slCntrT+1));
      slCntrT++;
   }

   //----------------------------------------------------------------
   // evaluate click operation
   //
   switch(pclEventV->button())
   {
      case Qt::LeftButton:

         qDebug() << "Left button pressed";
         //-----------------------------------------------------
         // show context menu
         //
         pclActionT = clContextMenuT.exec(pos);

         //-----------------------------------------------------
         // evaluate selection
         //
         if (pclActionT != 0)
         {
            qint32 slIdxT = aclPluginNameListP.indexOf(pclActionT->text());
            qDebug() << "mousePressEvent(): select index ..." << slIdxT;

            pclQCanInterfaceP = NULL;
            if (slIdxT > 0)
            {
               QPluginLoader clPluginLoaderT(aclPluginListP.at(slIdxT));
               QObject *pclPluginT = clPluginLoaderT.instance();
               if (pclPluginT)
               {
                   pclQCanInterfaceP = qobject_cast<QCanInterface *>(pclPluginT);
               }
            }

            emit interfaceChanged(pclQCanInterfaceP);
         } else
         {
            qDebug() << "mousePressEvent(): no index selected";
         }
         break;

      case Qt::RightButton:
         qDebug() << "Right button pressed";

         break;

      default:

         break;
   }
   clicked(0);
}

//----------------------------------------------------------------------------//
// loadPlugin()                                                               //
//                                                                            //
//----------------------------------------------------------------------------//
bool QCanInterfaceWidget::loadPlugin()
{
   QCanInterface *pclQCanIfT;

   qInfo() << "loadPlugin(): used plugin path" << clPluginPathP.absolutePath();

   //----------------------------------------------------------------
   // check plugin path
   //
   if (!clPluginPathP.exists())
   {
      qWarning() << "loadPlugin(): plugin path does not exist!";
      return false;
   }

   //----------------------------------------------------------------
   // check plugins and create a list with valid plugins
   //
   aclPluginNameListP.clear();
   aclPluginListP.clear();
   aclIconListP.clear();
   foreach (QString clFileNameT, clPluginPathP.entryList(QDir::Files))
   {
      if (QLibrary::isLibrary(clPluginPathP.absoluteFilePath(clFileNameT)))
      {
         QPluginLoader clPluginLoaderT(clPluginPathP.absoluteFilePath(clFileNameT));
         QObject *pclPluginT = clPluginLoaderT.instance();
         if (pclPluginT)
         {
            pclQCanIfT = qobject_cast<QCanInterface *>(pclPluginT);
            if (pclQCanIfT)
            {
               qInfo() << "loadPlugin(): found" << clPluginPathP.absoluteFilePath(clFileNameT) << "plugin.";

               //-------------------------------------
               // collect all information of valid plugin
               // \todo Get the PluginName and Icon
               //
               aclPluginNameListP.append(pclQCanIfT->name());
               aclIconListP.append(pclQCanIfT->icon());
               aclPluginListP.append(clPluginPathP.absoluteFilePath(clFileNameT));
            }
         } else
         {
            qWarning() << "loadPlugin(): plugin" << clPluginPathP.absoluteFilePath(clFileNameT) << "could NOT be loaded or the root component object could NOT be instantiated!";
         }
      } else
      {
         qWarning() << "loadPlugin(): plugin" << clPluginPathP.absoluteFilePath(clFileNameT) << "is NOT a library!";
      }
   }

   if (aclPluginNameListP.isEmpty())
   {
      qWarning() << "loadPlugin(): NONE plugins have been found!";
      return false;
   }

   qInfo() << "loadPlugin(): found" << QString::number(aclPluginNameListP.count(),10) << "available plugins.";

   return true;
}

//----------------------------------------------------------------------------//
// QCanInterfaceWidget::paintEvent()                                          //
//                                                                            //
//----------------------------------------------------------------------------//
void QCanInterfaceWidget::paintEvent(QPaintEvent * pclEventV)
{
   qDebug() << "Paint" << pclEventV->rect();

   QPalette clPaletteT(this->palette());
   QPainter clPainterT(this);
   QBrush brush = QBrush(Qt::transparent, Qt::NoBrush);
   qDebug() << "Brush" << brush;
   clPainterT.setPen((Qt::white));
   clPainterT.setBrush(brush);
   //clPainterT.eraseRect(pclEventV->rect());
   clPainterT.fillRect(pclEventV->rect(), QColor(0xE3, 0xE3, 0xE3)); //Qt::NoBrush);
   //clPainterT.drawLine(1, 1, 80, 80);

   clIconP.paint(&clPainterT, pclEventV->rect(), Qt::AlignCenter);
}

//----------------------------------------------------------------------------//
// setPluginPath()                                                            //
//                                                                            //
//----------------------------------------------------------------------------//
void QCanInterfaceWidget::setPluginPath(QDir clPluginPathV)
{
   clPluginPathP = clPluginPathV;
   qDebug() << "INFO: Plugin Path is set to" << clPluginPathP.absolutePath();
}
<|endoftext|>


<commit_before>#include "./labeller.h"
#include <Eigen/Geometry>
#include <QLoggingCategory>
#include <vector>
#include <map>
#include "../utils/cuda_array_provider.h"
#include "./summed_area_table.h"
#include "./apollonius.h"
#include "./occupancy_updater.h"
#include "./constraint_updater.h"

namespace Placement
{

QLoggingCategory plChan("Placement.Labeller");

Labeller::Labeller(std::shared_ptr<Labels> labels) : labels(labels)
{
}

void Labeller::initialize(
    std::shared_ptr<CudaArrayProvider> occupancyTextureMapper,
    std::shared_ptr<CudaArrayProvider> distanceTransformTextureMapper,
    std::shared_ptr<CudaArrayProvider> apolloniusTextureMapper,
    std::shared_ptr<ConstraintUpdater> constraintUpdater)
{
  qCInfo(plChan) << "Initialize";
  if (!occupancySummedAreaTable.get())
    occupancySummedAreaTable =
        std::make_shared<SummedAreaTable>(occupancyTextureMapper);
  occupancyUpdater = std::make_shared<OccupancyUpdater>(occupancyTextureMapper);

  this->distanceTransformTextureMapper = distanceTransformTextureMapper;
  this->apolloniusTextureMapper = apolloniusTextureMapper;
  this->constraintUpdater = constraintUpdater;

  costFunctionCalculator.setTextureSize(occupancyTextureMapper->getWidth(),
                                        occupancyTextureMapper->getHeight());
}

void Labeller::cleanup()
{
  occupancySummedAreaTable.reset();
  apolloniusTextureMapper.reset();
  occupancyUpdater.reset();
}

void Labeller::setInsertionOrder(std::vector<int> ids)
{
  insertionOrder = ids;
}

std::map<int, Eigen::Vector3f>
Labeller::update(const LabellerFrameData &frameData)
{
  newPositions.clear();
  if (!occupancySummedAreaTable.get())
    return newPositions;

  Eigen::Vector2i size(distanceTransformTextureMapper->getWidth(),
                       distanceTransformTextureMapper->getHeight());
  std::vector<Eigen::Vector4f> labelsSeed =
      createLabelSeeds(size, frameData.viewProjection);

  Apollonius apollonius(distanceTransformTextureMapper, apolloniusTextureMapper,
                        labelsSeed, labels->count());
  apollonius.run();
  setInsertionOrder(apollonius.calculateOrdering());

  Eigen::Matrix4f inverseViewProjection = frameData.viewProjection.inverse();

  // TODO(SIR): iterate through labels specific order according to apollonius.
  for (size_t i = 0; i < insertionOrder.size(); ++i)
  {
    int id = insertionOrder[i];
    occupancySummedAreaTable->runKernel();

    auto label = labels->getById(id);
    auto anchor2D = frameData.project(label.anchorPosition);
    float x = (anchor2D.x() * 0.5f + 0.5f) * width;
    float y = (anchor2D.y() * 0.5f + 0.5f) * height;

    std::cout << "x " << int(x) << " y " << int(y) << std::endl;
    Eigen::Vector2i labelSizeForBuffer =
        label.size.cast<int>().cwiseProduct(size).cwiseQuotient(
            Eigen::Vector2i(width, height));

    auto newPosition = costFunctionCalculator.calculateForLabel(
        occupancySummedAreaTable->getResults(), label.id, x, y, label.size.x(),
        label.size.y());

    float newXPosition = std::get<0>(newPosition);
    float newYPosition = std::get<1>(newPosition);

    occupancyUpdater->addLabel(newXPosition, newYPosition,
                               labelSizeForBuffer.x(), labelSizeForBuffer.y());

    if (i + 1 < insertionOrder.size())
    {
      int nextId = insertionOrder[i + 1];
      auto nextLabel = labels->getById(nextId);
      auto nextAnchor2D = frameData.project(nextLabel.anchorPosition);
      constraintUpdater->addLabel(
          nextAnchor2D.head<2>().cast<int>(), nextLabel.size.cast<int>(),
          anchor2D.head<2>().cast<int>(),
          Eigen::Vector2i(newXPosition, newYPosition), label.size.cast<int>());
    }

    float newXNDC = (newXPosition / size.x() - 0.5f) * 2.0f;
    float newYNDC = (newYPosition / size.y() - 0.5f) * 2.0f;
    Eigen::Vector4f reprojected =
        inverseViewProjection *
        Eigen::Vector4f(newXNDC, newYNDC, anchor2D.z(), 1);
    reprojected /= reprojected.w();

    newPositions[label.id] = toVector3f(reprojected);
  }

  return newPositions;
}

void Labeller::resize(int width, int height)
{
  this->width = width;
  this->height = height;

  costFunctionCalculator.resize(width, height);
}

std::map<int, Eigen::Vector3f> Labeller::getLastPlacementResult()
{
  return newPositions;
}

std::vector<Eigen::Vector4f>
Labeller::createLabelSeeds(Eigen::Vector2i size, Eigen::Matrix4f viewProjection)
{
  std::vector<Eigen::Vector4f> result;
  for (auto &label : labels->getLabels())
  {
    Eigen::Vector4f pos =
        viewProjection * Eigen::Vector4f(label.anchorPosition.x(),
                                         label.anchorPosition.y(),
                                         label.anchorPosition.z(), 1);
    float x = (pos.x() / pos.w() * 0.5f + 0.5f) * size.x();
    float y = (pos.y() / pos.w() * 0.5f + 0.5f) * size.y();
    result.push_back(Eigen::Vector4f(label.id, x, y, 1));
  }

  return result;
}

}  // namespace Placement
<commit_msg>Pass right label sizes to ConstraintUpdater.<commit_after>#include "./labeller.h"
#include <Eigen/Geometry>
#include <QLoggingCategory>
#include <vector>
#include <map>
#include "../utils/cuda_array_provider.h"
#include "./summed_area_table.h"
#include "./apollonius.h"
#include "./occupancy_updater.h"
#include "./constraint_updater.h"

namespace Placement
{

QLoggingCategory plChan("Placement.Labeller");

Labeller::Labeller(std::shared_ptr<Labels> labels) : labels(labels)
{
}

void Labeller::initialize(
    std::shared_ptr<CudaArrayProvider> occupancyTextureMapper,
    std::shared_ptr<CudaArrayProvider> distanceTransformTextureMapper,
    std::shared_ptr<CudaArrayProvider> apolloniusTextureMapper,
    std::shared_ptr<ConstraintUpdater> constraintUpdater)
{
  qCInfo(plChan) << "Initialize";
  if (!occupancySummedAreaTable.get())
    occupancySummedAreaTable =
        std::make_shared<SummedAreaTable>(occupancyTextureMapper);
  occupancyUpdater = std::make_shared<OccupancyUpdater>(occupancyTextureMapper);

  this->distanceTransformTextureMapper = distanceTransformTextureMapper;
  this->apolloniusTextureMapper = apolloniusTextureMapper;
  this->constraintUpdater = constraintUpdater;

  costFunctionCalculator.setTextureSize(occupancyTextureMapper->getWidth(),
                                        occupancyTextureMapper->getHeight());
}

void Labeller::cleanup()
{
  occupancySummedAreaTable.reset();
  apolloniusTextureMapper.reset();
  occupancyUpdater.reset();
}

void Labeller::setInsertionOrder(std::vector<int> ids)
{
  insertionOrder = ids;
}

std::map<int, Eigen::Vector3f>
Labeller::update(const LabellerFrameData &frameData)
{
  newPositions.clear();
  if (!occupancySummedAreaTable.get())
    return newPositions;

  Eigen::Vector2i size(distanceTransformTextureMapper->getWidth(),
                       distanceTransformTextureMapper->getHeight());
  std::vector<Eigen::Vector4f> labelsSeed =
      createLabelSeeds(size, frameData.viewProjection);

  Apollonius apollonius(distanceTransformTextureMapper, apolloniusTextureMapper,
                        labelsSeed, labels->count());
  apollonius.run();
  setInsertionOrder(apollonius.calculateOrdering());

  Eigen::Matrix4f inverseViewProjection = frameData.viewProjection.inverse();

  // TODO(SIR): iterate through labels specific order according to apollonius.
  for (size_t i = 0; i < insertionOrder.size(); ++i)
  {
    int id = insertionOrder[i];
    occupancySummedAreaTable->runKernel();

    auto label = labels->getById(id);
    auto anchor2D = frameData.project(label.anchorPosition);
    float x = (anchor2D.x() * 0.5f + 0.5f) * width;
    float y = (anchor2D.y() * 0.5f + 0.5f) * height;

    std::cout << "x " << int(x) << " y " << int(y) << std::endl;
    Eigen::Vector2i labelSizeForBuffer =
        label.size.cast<int>().cwiseProduct(size).cwiseQuotient(
            Eigen::Vector2i(width, height));

    auto newPosition = costFunctionCalculator.calculateForLabel(
        occupancySummedAreaTable->getResults(), label.id, x, y, label.size.x(),
        label.size.y());

    float newXPosition = std::get<0>(newPosition);
    float newYPosition = std::get<1>(newPosition);

    occupancyUpdater->addLabel(newXPosition, newYPosition,
                               labelSizeForBuffer.x(), labelSizeForBuffer.y());

    if (i + 1 < insertionOrder.size())
    {
      int nextId = insertionOrder[i + 1];
      auto nextLabel = labels->getById(nextId);
      auto nextAnchor2D = frameData.project(nextLabel.anchorPosition);
      Eigen::Vector2i nextLabelSizeForBuffer =
          nextLabel.size.cast<int>().cwiseProduct(size).cwiseQuotient(
              Eigen::Vector2i(width, height));
      constraintUpdater->addLabel(
          nextAnchor2D.head<2>().cast<int>(), nextLabelSizeForBuffer,
          anchor2D.head<2>().cast<int>(),
          Eigen::Vector2i(newXPosition, newYPosition), labelSizeForBuffer);
    }

    float newXNDC = (newXPosition / size.x() - 0.5f) * 2.0f;
    float newYNDC = (newYPosition / size.y() - 0.5f) * 2.0f;
    Eigen::Vector4f reprojected =
        inverseViewProjection *
        Eigen::Vector4f(newXNDC, newYNDC, anchor2D.z(), 1);
    reprojected /= reprojected.w();

    newPositions[label.id] = toVector3f(reprojected);
  }

  return newPositions;
}

void Labeller::resize(int width, int height)
{
  this->width = width;
  this->height = height;

  costFunctionCalculator.resize(width, height);
}

std::map<int, Eigen::Vector3f> Labeller::getLastPlacementResult()
{
  return newPositions;
}

std::vector<Eigen::Vector4f>
Labeller::createLabelSeeds(Eigen::Vector2i size, Eigen::Matrix4f viewProjection)
{
  std::vector<Eigen::Vector4f> result;
  for (auto &label : labels->getLabels())
  {
    Eigen::Vector4f pos =
        viewProjection * Eigen::Vector4f(label.anchorPosition.x(),
                                         label.anchorPosition.y(),
                                         label.anchorPosition.z(), 1);
    float x = (pos.x() / pos.w() * 0.5f + 0.5f) * size.x();
    float y = (pos.y() / pos.w() * 0.5f + 0.5f) * size.y();
    result.push_back(Eigen::Vector4f(label.id, x, y, 1));
  }

  return result;
}

}  // namespace Placement
<|endoftext|>