<commit_before>/////////////////////////////////////////////////////////////////////////////
// Name:        paravermain.cpp
// Purpose:
// Author:      Eloy Martinez
// Modified by:
// Created:     Wed 25 Jun 2008 15:58:35 CEST
// RCS-ID:
// Copyright:
// Licence:
/////////////////////////////////////////////////////////////////////////////

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

////@begin includes
////@end includes

#include "wx/imaglist.h"
#include "paravermain.h"
#include "paraverkernelexception.h"
#include "cfg.h"
#include "window.h"
#include "histogram.h"
#include "gtimeline.h"
#include "ghistogram.h"

////@begin XPM images
////@end XPM images

#include "table.xpm"

/*!
 * paraverMain type definition
 */

IMPLEMENT_CLASS( paraverMain, wxFrame )

/*!
 * paraverMain event table definition
 */

BEGIN_EVENT_TABLE( paraverMain, wxFrame )

////@begin paraverMain event table entries
  EVT_MENU( wxID_OPEN, paraverMain::OnOpenClick )

  EVT_MENU( ID_MENULOADCFG, paraverMain::OnMenuloadcfgClick )
  EVT_UPDATE_UI( ID_MENULOADCFG, paraverMain::OnMenuloadcfgUpdate )

  EVT_MENU( wxID_EXIT, paraverMain::OnExitClick )

////@end paraverMain event table entries

END_EVENT_TABLE()

/*!
 * paraverMain constructors
 */

paraverMain::paraverMain()
{
  Init();
}

paraverMain::paraverMain( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
  Init();
  Create( parent, id, caption, pos, size, style );
}

/*!
 * paraverMain creator
 */

bool paraverMain::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
  imageList = new wxImageList( 16, 16 );
  imageList->Add( wxIcon( table_xpm ) );

////@begin paraverMain creation
  wxFrame::Create( parent, id, caption, pos, size, style );

  CreateControls();
////@end paraverMain creation

  LocalKernel::init();
  localKernel = new LocalKernel();
  paraverConfig = ParaverConfig::getInstance();
  paraverConfig->readParaverConfigFile();

  return true;
}

/*!
 * paraverMain destructor
 */

paraverMain::~paraverMain()
{
////@begin paraverMain destruction
  GetAuiManager().UnInit();
////@end paraverMain destruction

  for( vector<Trace *>::iterator it = loadedTraces.begin(); it != loadedTraces.end(); it++ )
    delete *it;
  delete localKernel;

  delete imageList;
}

/*!
 * Member initialisation
 */

void paraverMain::Init()
{
////@begin paraverMain member initialisation
  currentTrace = -1;
  menuFile = NULL;
  menuHelp = NULL;
  tbarMain = NULL;
  choiceWindowBrowser = NULL;
////@end paraverMain member initialisation
}

/*!
 * Control creation for paraverMain
 */

void paraverMain::CreateControls()
{
////@begin paraverMain content construction
  paraverMain* itemFrame1 = this;

  GetAuiManager().SetManagedWindow(this);

  wxMenuBar* menuBar = new wxMenuBar;
  menuFile = new wxMenu;
  menuFile->Append(wxID_OPEN, _("Load &Trace"), _T(""), wxITEM_NORMAL);
  menuFile->AppendSeparator();
  menuFile->Append(ID_MENULOADCFG, _("Load &Configuration"), _T(""), wxITEM_NORMAL);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT, _("&Quit"), _T(""), wxITEM_NORMAL);
  menuBar->Append(menuFile, _("&File"));
  menuHelp = new wxMenu;
  menuHelp->Append(wxID_ABOUT, _("&About..."), _T(""), wxITEM_NORMAL);
  menuBar->Append(menuHelp, _("&Help"));
  itemFrame1->SetMenuBar(menuBar);

  tbarMain = new wxToolBar( itemFrame1, ID_TOOLBAR, wxDefaultPosition, wxDefaultSize, wxTB_FLAT|wxTB_HORIZONTAL|wxTB_NODIVIDER );
  tbarMain->Realize();
  itemFrame1->GetAuiManager().AddPane(tbarMain, wxAuiPaneInfo()
    .ToolbarPane().Name(_T("auiTBarMain")).Top().Layer(10).CaptionVisible(false).CloseButton(false).DestroyOnClose(false).Resizable(false).Floatable(false).Gripper(true));

  choiceWindowBrowser = new wxChoicebook( itemFrame1, ID_CHOICEWINBROWSER, wxDefaultPosition, wxDefaultSize, wxBK_DEFAULT );

  itemFrame1->GetAuiManager().AddPane(choiceWindowBrowser, wxAuiPaneInfo()
    .Name(_T("auiWindowBrowser")).Caption(_T("Window browser")).Centre().DestroyOnClose(false).Resizable(true).MaximizeButton(true));

  GetAuiManager().Update();

////@end paraverMain content construction
  wxTreeCtrl* tmpTree = new wxTreeCtrl( choiceWindowBrowser, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTR_HAS_BUTTONS |wxTR_HIDE_ROOT|wxTR_SINGLE );
  tmpTree->SetImageList( imageList );
  tmpTree->AddRoot( wxT( "Root" ), 0, -1, new TreeBrowserItemData( "Root", NULL ) );
  choiceWindowBrowser->AddPage( tmpTree, "All Traces" );
}

/*!
 * wxEVT_COMMAND_MENU_SELECTED event handler for wxID_OPEN
 */

void paraverMain::OnOpenClick( wxCommandEvent& event )
{
  wxFileDialog dialog( this, "Load Trace", "", "",
    "Paraver trace (*.prv;*.prv.gz)|*.prv;*.prv.gz|All files (*.*)|*.*",
    wxOPEN|wxFILE_MUST_EXIST );
  if( dialog.ShowModal() == wxID_OK )
  {
    Trace *tr = NULL;
    wxString path = dialog.GetPath();
    for( vector<Trace *>::iterator it = loadedTraces.begin(); it != loadedTraces.end(); it++ )
    {
      if( (*it)->getFileName().compare( path.c_str() ) == 0 )
        return;
    }

    try
    {
      tr = Trace::create( localKernel, path.c_str() );
      loadedTraces.push_back( tr );
      currentTrace = loadedTraces.size() - 1;
      wxTreeCtrl *newTree =  new wxTreeCtrl( choiceWindowBrowser, wxID_ANY,
        wxDefaultPosition, wxDefaultSize, wxTR_HAS_BUTTONS |wxTR_HIDE_ROOT|wxTR_SINGLE );
      newTree->SetImageList( imageList );
      newTree->AddRoot( wxT( "Root" ), 0, -1, new TreeBrowserItemData( "Root", NULL ) );
      choiceWindowBrowser->AddPage( newTree, path );
    }
    catch( ParaverKernelException& ex )
    {
      wxMessageDialog message( this, ex.what(), "Error loading trace", wxOK );
      message.ShowModal();
    }
  }
}

/*!
 * wxEVT_COMMAND_MENU_SELECTED event handler for ID_MENULOADCFG
 */

void paraverMain::OnMenuloadcfgClick( wxCommandEvent& event )
{
  wxFileDialog dialog( this, "Load Configuration", "", "",
    "Paraver configuration file (*.cfg)|*.cfg|All files (*.*)|*.*",
    wxOPEN|wxFILE_MUST_EXIST );
  if( dialog.ShowModal() == wxID_OK )
  {
    wxString path = dialog.GetPath();
    if( !CFGLoader::isCFGFile( path.c_str() ) )
    {
      wxString errMessage = path + " isn't a valid cfg.";
      wxMessageDialog message( this, errMessage.c_str(), "Invalid file", wxOK );
      message.ShowModal();
    }
    else
    {
      vector<Window *> newWindows;
      vector<Histogram *> newHistograms;

      if( !CFGLoader::loadCFG( localKernel, path.c_str(), loadedTraces[ currentTrace ], newWindows, newHistograms ) )
      {
        wxString errMessage = path + " failed to load.";
        wxMessageDialog message( this, errMessage.c_str(), "Loading error", wxOK );
        message.ShowModal();
      }
      else
      {
        for( vector<Window *>::iterator it = newWindows.begin(); it != newWindows.end(); it++ )
        {
          gTimeline* tmpTimeline = new gTimeline( this, wxID_ANY, (*it)->getName() );

          wxTreeCtrl *allTracesPage = (wxTreeCtrl *) choiceWindowBrowser->GetPage( 0 );
          allTracesPage->AppendItem( allTracesPage->GetRootItem(), (*it)->getName(), -1, -1,
            new TreeBrowserItemData( (*it)->getName(), tmpTimeline ) );

          wxTreeCtrl *currentPage = (wxTreeCtrl *) choiceWindowBrowser->GetPage( currentTrace + 1 );
          currentPage->AppendItem( currentPage->GetRootItem(), (*it)->getName(), -1, -1,
            new TreeBrowserItemData( (*it)->getName(), tmpTimeline ) );

          tmpTimeline->SetWindow( *it );
          tmpTimeline->Show();
          tmpTimeline->redraw();
        }

        for( vector<Histogram *>::iterator it = newHistograms.begin(); it != newHistograms.end(); it++ )
        {
          gHistogram* tmpHisto = new gHistogram( this, wxID_ANY, (*it)->getName() );

          wxTreeCtrl *allTracesPage = (wxTreeCtrl *) choiceWindowBrowser->GetPage( 0 );
          allTracesPage->AppendItem( allTracesPage->GetRootItem(), (*it)->getName(), 0, -1,
            new TreeBrowserItemData( (*it)->getName(), tmpHisto ) );

          wxTreeCtrl *currentPage = (wxTreeCtrl *) choiceWindowBrowser->GetPage( currentTrace + 1 );
          currentPage->AppendItem( currentPage->GetRootItem(), (*it)->getName(), 0, -1,
            new TreeBrowserItemData( (*it)->getName(), tmpHisto ) );

          tmpHisto->SetHistogram( *it );
          tmpHisto->Show();
          tmpHisto->execute();
        }
      }
    }
  }
}

/*!
 * wxEVT_COMMAND_MENU_SELECTED event handler for wxID_EXIT
 */

void paraverMain::OnExitClick( wxCommandEvent& event )
{
////@begin wxEVT_COMMAND_MENU_SELECTED event handler for wxID_EXIT in paraverMain.
  // Before editing this code, remove the block markers.
  Destroy();
////@end wxEVT_COMMAND_MENU_SELECTED event handler for wxID_EXIT in paraverMain.
}

/*!
 * Should we show tooltips?
 */

bool paraverMain::ShowToolTips()
{
  return true;
}

/*!
 * Get bitmap resources
 */

wxBitmap paraverMain::GetBitmapResource( const wxString& name )
{
  // Bitmap retrieval
////@begin paraverMain bitmap retrieval
  wxUnusedVar(name);
  return wxNullBitmap;
////@end paraverMain bitmap retrieval
}

/*!
 * Get icon resources
 */

wxIcon paraverMain::GetIconResource( const wxString& name )
{
  // Icon retrieval
////@begin paraverMain icon retrieval
  wxUnusedVar(name);
  return wxNullIcon;
////@end paraverMain icon retrieval
}

/*!
 * wxEVT_UPDATE_UI event handler for ID_MENULOADCFG
 */

void paraverMain::OnMenuloadcfgUpdate( wxUpdateUIEvent& event )
{
  if( currentTrace == -1 )
    menuFile->Enable( ID_MENULOADCFG, false );
  else
    menuFile->Enable( ID_MENULOADCFG, true );
}

<commit_msg>*** empty log message ***<commit_after>/////////////////////////////////////////////////////////////////////////////
// Name:        paravermain.cpp
// Purpose:
// Author:      Eloy Martinez
// Modified by:
// Created:     Wed 25 Jun 2008 15:58:35 CEST
// RCS-ID:
// Copyright:
// Licence:
/////////////////////////////////////////////////////////////////////////////

// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif

#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif

////@begin includes
////@end includes

#include "wx/imaglist.h"
#include "paravermain.h"
#include "paraverkernelexception.h"
#include "cfg.h"
#include "window.h"
#include "histogram.h"
#include "gtimeline.h"
#include "ghistogram.h"

////@begin XPM images
////@end XPM images

#include "table.xpm"

/*!
 * paraverMain type definition
 */

IMPLEMENT_CLASS( paraverMain, wxFrame )

/*!
 * paraverMain event table definition
 */

BEGIN_EVENT_TABLE( paraverMain, wxFrame )

////@begin paraverMain event table entries
  EVT_MENU( wxID_OPEN, paraverMain::OnOpenClick )

  EVT_MENU( ID_MENULOADCFG, paraverMain::OnMenuloadcfgClick )
  EVT_UPDATE_UI( ID_MENULOADCFG, paraverMain::OnMenuloadcfgUpdate )

  EVT_MENU( wxID_EXIT, paraverMain::OnExitClick )

////@end paraverMain event table entries

END_EVENT_TABLE()

/*!
 * paraverMain constructors
 */

paraverMain::paraverMain()
{
  Init();
}

paraverMain::paraverMain( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
  Init();
  Create( parent, id, caption, pos, size, style );
}

/*!
 * paraverMain creator
 */

bool paraverMain::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
  imageList = new wxImageList( 16, 16 );
  imageList->Add( wxIcon( table_xpm ) );

////@begin paraverMain creation
  wxFrame::Create( parent, id, caption, pos, size, style );

  CreateControls();
////@end paraverMain creation

  LocalKernel::init();
  localKernel = new LocalKernel();
  paraverConfig = ParaverConfig::getInstance();
  paraverConfig->readParaverConfigFile();

  return true;
}

/*!
 * paraverMain destructor
 */

paraverMain::~paraverMain()
{
////@begin paraverMain destruction
  GetAuiManager().UnInit();
////@end paraverMain destruction

  for( vector<Trace *>::iterator it = loadedTraces.begin(); it != loadedTraces.end(); it++ )
    delete *it;
  delete localKernel;

  delete imageList;
}

/*!
 * Member initialisation
 */

void paraverMain::Init()
{
////@begin paraverMain member initialisation
  currentTrace = -1;
  menuFile = NULL;
  menuHelp = NULL;
  tbarMain = NULL;
  choiceWindowBrowser = NULL;
////@end paraverMain member initialisation
}

/*!
 * Control creation for paraverMain
 */

void paraverMain::CreateControls()
{
////@begin paraverMain content construction
  paraverMain* itemFrame1 = this;

  GetAuiManager().SetManagedWindow(this);

  wxMenuBar* menuBar = new wxMenuBar;
  menuFile = new wxMenu;
  menuFile->Append(wxID_OPEN, _("Load &Trace"), _T(""), wxITEM_NORMAL);
  menuFile->AppendSeparator();
  menuFile->Append(ID_MENULOADCFG, _("Load &Configuration"), _T(""), wxITEM_NORMAL);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT, _("&Quit"), _T(""), wxITEM_NORMAL);
  menuBar->Append(menuFile, _("&File"));
  menuHelp = new wxMenu;
  menuHelp->Append(wxID_ABOUT, _("&About..."), _T(""), wxITEM_NORMAL);
  menuBar->Append(menuHelp, _("&Help"));
  itemFrame1->SetMenuBar(menuBar);

  tbarMain = new wxToolBar( itemFrame1, ID_TOOLBAR, wxDefaultPosition, wxDefaultSize, wxTB_FLAT|wxTB_HORIZONTAL|wxTB_NODIVIDER );
  tbarMain->Realize();
  itemFrame1->GetAuiManager().AddPane(tbarMain, wxAuiPaneInfo()
    .ToolbarPane().Name(_T("auiTBarMain")).Top().Layer(10).CaptionVisible(false).CloseButton(false).DestroyOnClose(false).Resizable(false).Floatable(false).Gripper(true));

  choiceWindowBrowser = new wxChoicebook( itemFrame1, ID_CHOICEWINBROWSER, wxDefaultPosition, wxDefaultSize, wxBK_DEFAULT );

  itemFrame1->GetAuiManager().AddPane(choiceWindowBrowser, wxAuiPaneInfo()
    .Name(_T("auiWindowBrowser")).Caption(_T("Window browser")).Centre().DestroyOnClose(false).Resizable(true).MaximizeButton(true));

  GetAuiManager().Update();

////@end paraverMain content construction
  wxTreeCtrl* tmpTree = new wxTreeCtrl( choiceWindowBrowser, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTR_HAS_BUTTONS |wxTR_HIDE_ROOT|wxTR_SINGLE );
  tmpTree->SetImageList( imageList );
  tmpTree->AddRoot( wxT( "Root" ), 0, -1, new TreeBrowserItemData( "Root", NULL ) );
  choiceWindowBrowser->AddPage( tmpTree, "All Traces" );
}

/*!
 * wxEVT_COMMAND_MENU_SELECTED event handler for wxID_OPEN
 */

void paraverMain::OnOpenClick( wxCommandEvent& event )
{
  wxFileDialog dialog( this, "Load Trace", "", "",
    "Paraver trace (*.prv;*.prv.gz)|*.prv;*.prv.gz|All files (*.*)|*.*",
    wxOPEN|wxFILE_MUST_EXIST );
  if( dialog.ShowModal() == wxID_OK )
  {
    Trace *tr = NULL;
    wxString path = dialog.GetPath();
    for( vector<Trace *>::iterator it = loadedTraces.begin(); it != loadedTraces.end(); it++ )
    {
      if( (*it)->getFileName().compare( path.c_str() ) == 0 )
        return;
    }

    try
    {
      tr = Trace::create( localKernel, path.c_str() );
      loadedTraces.push_back( tr );
      currentTrace = loadedTraces.size() - 1;
      wxTreeCtrl *newTree =  new wxTreeCtrl( choiceWindowBrowser, wxID_ANY,
        wxDefaultPosition, wxDefaultSize, wxTR_HAS_BUTTONS |wxTR_HIDE_ROOT|wxTR_SINGLE );
      newTree->SetImageList( imageList );
      newTree->AddRoot( wxT( "Root" ), 0, -1, new TreeBrowserItemData( "Root", NULL ) );
      choiceWindowBrowser->AddPage( newTree, path );
    }
    catch( ParaverKernelException& ex )
    {
      wxMessageDialog message( this, ex.what(), "Error loading trace", wxOK );
      message.ShowModal();
    }
  }
}

/*!
 * wxEVT_COMMAND_MENU_SELECTED event handler for ID_MENULOADCFG
 */

void paraverMain::OnMenuloadcfgClick( wxCommandEvent& event )
{
  wxFileDialog dialog( this, "Load Configuration", "", "",
    "Paraver configuration file (*.cfg)|*.cfg|All files (*.*)|*.*",
    wxOPEN|wxFILE_MUST_EXIST );
  if( dialog.ShowModal() == wxID_OK )
  {
    wxString path = dialog.GetPath();
    if( !CFGLoader::isCFGFile( path.c_str() ) )
    {
      wxString errMessage = path + " isn't a valid cfg.";
      wxMessageDialog message( this, errMessage.c_str(), "Invalid file", wxOK );
      message.ShowModal();
    }
    else
    {
      vector<Window *> newWindows;
      vector<Histogram *> newHistograms;

      if( !CFGLoader::loadCFG( localKernel, path.c_str(), loadedTraces[ currentTrace ], newWindows, newHistograms ) )
      {
        wxString errMessage = path + " failed to load.";
        wxMessageDialog message( this, errMessage.c_str(), "Loading error", wxOK );
        message.ShowModal();
      }
      else
      {
        for( vector<Window *>::iterator it = newWindows.begin(); it != newWindows.end(); it++ )
        {
          gTimeline* tmpTimeline = new gTimeline( this, wxID_ANY, (*it)->getName() );

          wxTreeCtrl *allTracesPage = (wxTreeCtrl *) choiceWindowBrowser->GetPage( 0 );
          allTracesPage->AppendItem( allTracesPage->GetRootItem(), (*it)->getName(), -1, -1,
            new TreeBrowserItemData( (*it)->getName(), tmpTimeline ) );

          wxTreeCtrl *currentPage = (wxTreeCtrl *) choiceWindowBrowser->GetPage( currentTrace + 1 );
          currentPage->AppendItem( currentPage->GetRootItem(), (*it)->getName(), -1, -1,
            new TreeBrowserItemData( (*it)->getName(), tmpTimeline ) );

          tmpTimeline->SetWindow( *it );
          tmpTimeline->SetSize( (*it)->getPosX(), (*it)->getPosY(), (*it)->getWidth(), (*it)->getHeight() );
          tmpTimeline->Show();
          tmpTimeline->redraw();
        }

        for( vector<Histogram *>::iterator it = newHistograms.begin(); it != newHistograms.end(); it++ )
        {
          gHistogram* tmpHisto = new gHistogram( this, wxID_ANY, (*it)->getName() );

          wxTreeCtrl *allTracesPage = (wxTreeCtrl *) choiceWindowBrowser->GetPage( 0 );
          allTracesPage->AppendItem( allTracesPage->GetRootItem(), (*it)->getName(), 0, -1,
            new TreeBrowserItemData( (*it)->getName(), tmpHisto ) );

          wxTreeCtrl *currentPage = (wxTreeCtrl *) choiceWindowBrowser->GetPage( currentTrace + 1 );
          currentPage->AppendItem( currentPage->GetRootItem(), (*it)->getName(), 0, -1,
            new TreeBrowserItemData( (*it)->getName(), tmpHisto ) );

          tmpHisto->SetHistogram( *it );
          tmpHisto->SetSize( (*it)->getPosX(), (*it)->getPosY(), (*it)->getWidth(), (*it)->getHeight() );
          tmpHisto->Show();
          tmpHisto->execute();
        }
      }
    }
  }
}

/*!
 * wxEVT_COMMAND_MENU_SELECTED event handler for wxID_EXIT
 */

void paraverMain::OnExitClick( wxCommandEvent& event )
{
////@begin wxEVT_COMMAND_MENU_SELECTED event handler for wxID_EXIT in paraverMain.
  // Before editing this code, remove the block markers.
  Destroy();
////@end wxEVT_COMMAND_MENU_SELECTED event handler for wxID_EXIT in paraverMain.
}

/*!
 * Should we show tooltips?
 */

bool paraverMain::ShowToolTips()
{
  return true;
}

/*!
 * Get bitmap resources
 */

wxBitmap paraverMain::GetBitmapResource( const wxString& name )
{
  // Bitmap retrieval
////@begin paraverMain bitmap retrieval
  wxUnusedVar(name);
  return wxNullBitmap;
////@end paraverMain bitmap retrieval
}

/*!
 * Get icon resources
 */

wxIcon paraverMain::GetIconResource( const wxString& name )
{
  // Icon retrieval
////@begin paraverMain icon retrieval
  wxUnusedVar(name);
  return wxNullIcon;
////@end paraverMain icon retrieval
}

/*!
 * wxEVT_UPDATE_UI event handler for ID_MENULOADCFG
 */

void paraverMain::OnMenuloadcfgUpdate( wxUpdateUIEvent& event )
{
  if( currentTrace == -1 )
    menuFile->Enable( ID_MENULOADCFG, false );
  else
    menuFile->Enable( ID_MENULOADCFG, true );
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: VPolarGrid.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: iha $ $Date: 2004-01-22 19:20:35 $
 *
 *  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: 2003 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include "VPolarGrid.hxx"
#include "VCartesianGrid.hxx"
#include "TickmarkHelper.hxx"
#include "PlottingPositionHelper.hxx"
#include "ShapeFactory.hxx"
#include "chartview/ObjectIdentifier.hxx"
#include "macros.hxx"
#include "CommonConverters.hxx"

#ifndef _DRAFTS_COM_SUN_STAR_CHART2_XIDENTIFIABLE_HPP_
#include <drafts/com/sun/star/chart2/XIdentifiable.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_
#include <com/sun/star/drawing/LineStyle.hpp>
#endif

#include <vector>
#include <memory>

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::chart2;

VPolarGrid::VPolarGrid( const uno::Reference< XGrid >& xGrid, sal_Int32 nDimensionCount )
            : VMeterBase( uno::Reference<XMeter>::query(xGrid), nDimensionCount )
            , m_pPosHelper( new PolarPlottingPositionHelper(false) )
            , m_aIncrements()
{
    PlotterBase::m_pPosHelper = m_pPosHelper;
}

VPolarGrid::~VPolarGrid()
{
    delete m_pPosHelper;
    m_pPosHelper = NULL;
}

void VPolarGrid::setIncrements( const uno::Sequence< ExplicitIncrementData >& rIncrements )
{
    m_aIncrements = rIncrements;
}

void VPolarGrid::getAllTickInfos( sal_Int32 nDimensionIndex, ::std::vector< ::std::vector< TickInfo > >& rAllTickInfos ) const
{
    TickmarkHelper aTickmarkHelper(
            m_pPosHelper->getScales()[nDimensionIndex], m_aIncrements[nDimensionIndex] );
    aTickmarkHelper.getAllTicks( rAllTickInfos );
}

//static
void VPolarGrid::createLinePointSequence_ForAngleAxis(
        drawing::PointSequenceSequence& rPoints
        , ::std::vector< ::std::vector< TickInfo > >& rAllTickInfos
        , const ExplicitIncrementData& rIncrement
        , const ExplicitScaleData& rScale
        , PolarPlottingPositionHelper* pPosHelper
        , double fLogicRadius, double fLogicZ )
{
    uno::Reference< XScaling > xInverseScaling( NULL );
    if( rScale.Scaling.is() )
        xInverseScaling = rScale.Scaling->getInverseScaling();

    sal_Int32 nTick = 0;
    TickIter aIter( rAllTickInfos, rIncrement, 0, 0 );
    for( TickInfo* pTickInfo = aIter.firstInfo()
        ; pTickInfo
        ; pTickInfo = aIter.nextInfo(), nTick++ )
    {
        if(nTick>=rPoints[0].getLength())
            rPoints[0].realloc(rPoints[0].getLength()+30);

        pTickInfo->updateUnscaledValue( xInverseScaling );
        double fLogicAngle = pTickInfo->fUnscaledTickValue;

        drawing::Position3D aScenePosition3D( pPosHelper->transformLogicToScene( fLogicAngle, fLogicRadius, fLogicZ ) );
        rPoints[0][nTick].X = static_cast<sal_Int32>(aScenePosition3D.PositionX);
        rPoints[0][nTick].Y = static_cast<sal_Int32>(aScenePosition3D.PositionY);
    }
    if(rPoints.getLength()>1)
    {
        rPoints[0].realloc(nTick+1);
        rPoints[0][nTick].X = rPoints[0][0].X;
        rPoints[0][nTick].Y = rPoints[0][0].Y;
    }
    else
        rPoints[0].realloc(nTick);
}

void VPolarGrid::create2DAngleGrid( const uno::Reference< drawing::XShapes >& xTarget
        , ::std::vector< ::std::vector< TickInfo > >& rRadiusTickInfos
        , ::std::vector< ::std::vector< TickInfo > >& rAngleTickInfos
        , const ::std::vector<VLineProperties>& rLinePropertiesList )
{
    const ExplicitScaleData&     rAngleScale = m_pPosHelper->getScales()[0];
    const ExplicitIncrementData& rAngleIncrement = m_aIncrements[0];
    uno::Reference< XScaling > xInverseScaling( NULL );
    if( rAngleScale.Scaling.is() )
        xInverseScaling = rAngleScale.Scaling->getInverseScaling();

    double fLogicInnerRadius = m_pPosHelper->getInnerLogicRadius();
    double fLogicOuterRadius = m_pPosHelper->getOuterLogicRadius();
    double fLogicZ      = -0.5;//as defined

    sal_Int32 nLinePropertiesCount = rLinePropertiesList.size();
    ::std::vector< ::std::vector< TickInfo > >::iterator aDepthIter             = rAngleTickInfos.begin();
    sal_Int32 nDepth=0;
    /*
    //no subgrids so far for polar angle grid (need different radii)
    const ::std::vector< ::std::vector< TickInfo > >::const_iterator aDepthEnd  = rAngleTickInfos.end();
    for( ; aDepthIter != aDepthEnd && nDepth < nLinePropertiesCount
         ; aDepthIter++, nDepth++ )
    */
    if(nLinePropertiesCount)
    {
        //create axis main lines
        drawing::PointSequenceSequence aAllPoints(1);
        ::std::vector< TickInfo >::iterator             aTickIter = (*aDepthIter).begin();
        const ::std::vector< TickInfo >::const_iterator aTickEnd  = (*aDepthIter).end();
        sal_Int32 nRealPointCount = 0;
        for( ; aTickIter != aTickEnd; aTickIter++ )
        {
            TickInfo& rTickInfo = *aTickIter;
            if( !rTickInfo.bPaintIt )
                continue;

            rTickInfo.updateUnscaledValue( xInverseScaling );
            double fLogicAngle = rTickInfo.fUnscaledTickValue;

            drawing::PointSequenceSequence aPoints(1);
            aPoints[0].realloc(2);
            drawing::Position3D aScenePositionStart( m_pPosHelper->transformLogicToScene( fLogicAngle, fLogicInnerRadius, fLogicZ ) );
            drawing::Position3D aScenePositionEnd(   m_pPosHelper->transformLogicToScene( fLogicAngle, fLogicOuterRadius, fLogicZ ) );
            aPoints[0][0].X = static_cast<sal_Int32>(aScenePositionStart.PositionX);
            aPoints[0][0].Y = static_cast<sal_Int32>(aScenePositionStart.PositionY);
            aPoints[0][1].X = static_cast<sal_Int32>(aScenePositionEnd.PositionX);
            aPoints[0][1].Y = static_cast<sal_Int32>(aScenePositionEnd.PositionY);
            appendPointSequence( aAllPoints, aPoints );
        }

        uno::Reference< drawing::XShape > xShape = m_pShapeFactory->createLine2D(
                xTarget, aAllPoints, rLinePropertiesList[nDepth] );
        //because of this name this line will be used for marking
        m_pShapeFactory->setShapeName( xShape, C2U("MarkHandles") );
    }
}

void VPolarGrid::create2DRadiusGrid( const uno::Reference< drawing::XShapes >& xTarget
        , ::std::vector< ::std::vector< TickInfo > >& rRadiusTickInfos
        , ::std::vector< ::std::vector< TickInfo > >& rAngleTickInfos
        , const ::std::vector<VLineProperties>& rLinePropertiesList )
{
    const ExplicitScaleData&     rRadiusScale = m_pPosHelper->getScales()[1];
    const ExplicitScaleData&     rAngleScale = m_pPosHelper->getScales()[0];
    const ExplicitIncrementData& rAngleIncrement = m_aIncrements[0];
    uno::Reference< XScaling > xInverseRadiusScaling( NULL );
    if( rRadiusScale.Scaling.is() )
        xInverseRadiusScaling = rRadiusScale.Scaling->getInverseScaling();

    sal_Int32 nLinePropertiesCount = rLinePropertiesList.size();
    ::std::vector< ::std::vector< TickInfo > >::iterator aDepthIter             = rRadiusTickInfos.begin();
    const ::std::vector< ::std::vector< TickInfo > >::const_iterator aDepthEnd  = rRadiusTickInfos.end();
    for( sal_Int32 nDepth=0
        ; aDepthIter != aDepthEnd && nDepth < nLinePropertiesCount
        ; aDepthIter++, nDepth++ )
    {
        //create axis main lines
        drawing::PointSequenceSequence aAllPoints(1);
        ::std::vector< TickInfo >::iterator             aTickIter = (*aDepthIter).begin();
        const ::std::vector< TickInfo >::const_iterator aTickEnd  = (*aDepthIter).end();
        sal_Int32 nRealPointCount = 0;
        for( ; aTickIter != aTickEnd; aTickIter++ )
        {
            TickInfo& rTickInfo = *aTickIter;
            if( !rTickInfo.bPaintIt )
                continue;

            rTickInfo.updateUnscaledValue( xInverseRadiusScaling );
            double fLogicRadius = rTickInfo.fUnscaledTickValue;
            double fLogicZ      = -0.5;//as defined

            drawing::PointSequenceSequence aPoints(1);
            VPolarGrid::createLinePointSequence_ForAngleAxis( aPoints, rAngleTickInfos
                , rAngleIncrement, rAngleScale, m_pPosHelper, fLogicRadius, fLogicZ );
            appendPointSequence( aAllPoints, aPoints );
        }

        uno::Reference< drawing::XShape > xShape = m_pShapeFactory->createLine2D(
                xTarget, aAllPoints, rLinePropertiesList[nDepth] );
        //because of this name this line will be used for marking
        m_pShapeFactory->setShapeName( xShape, C2U("MarkHandles") );
    }
}

void SAL_CALL VPolarGrid::createShapes()
{
    DBG_ASSERT(m_pShapeFactory&&m_xLogicTarget.is()&&m_xFinalTarget.is(),"Axis is not proper initialized");
    if(!(m_pShapeFactory&&m_xLogicTarget.is()&&m_xFinalTarget.is()))
        return;
    if( !m_xMeter.is())
        return;
    uno::Reference< beans::XPropertySet > xGridProps( m_xMeter, uno::UNO_QUERY );
    if(!xGridProps.is())
        return;

    //-----------------------------------------
    //create named group shape
    uno::Reference< XIdentifiable > xIdent( m_xMeter, uno::UNO_QUERY );
    if( ! xIdent.is())
        return;

    uno::Reference< drawing::XShapes > xTarget(
        this->createGroupShape( m_xLogicTarget
        , ObjectIdentifier::createClassifiedIdentifier(
                OBJECTTYPE_GRID, xIdent->getIdentifier() )
        ) );

    //-----------------------------------------
    //create all scaled tickmark values
    ::std::vector< ::std::vector< TickInfo > > aAngleTickInfos;
    ::std::vector< ::std::vector< TickInfo > > aRadiusTickInfos;
    getAllTickInfos( 0, aAngleTickInfos );
    getAllTickInfos( 1, aRadiusTickInfos );

    //-----------------------------------------
    ::std::vector<VLineProperties> aLinePropertiesList;
    VCartesianGrid::fillLinePropertiesFromGridModel( aLinePropertiesList, xGridProps );

    //-----------------------------------------
    //create tick mark line shapes
    sal_Int32 nDimensionIndex = m_xMeter->getRepresentedDimension();
    if(nDimensionIndex==1)
        this->create2DRadiusGrid( xTarget, aRadiusTickInfos, aAngleTickInfos, aLinePropertiesList );
    else
        this->create2DAngleGrid( xTarget, aRadiusTickInfos, aAngleTickInfos, aLinePropertiesList );
}

//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>no 3D polar grid<commit_after>/*************************************************************************
 *
 *  $RCSfile: VPolarGrid.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: iha $ $Date: 2004-01-23 10:27:32 $
 *
 *  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: 2003 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include "VPolarGrid.hxx"
#include "VCartesianGrid.hxx"
#include "TickmarkHelper.hxx"
#include "PlottingPositionHelper.hxx"
#include "ShapeFactory.hxx"
#include "chartview/ObjectIdentifier.hxx"
#include "macros.hxx"
#include "CommonConverters.hxx"

#ifndef _DRAFTS_COM_SUN_STAR_CHART2_XIDENTIFIABLE_HPP_
#include <drafts/com/sun/star/chart2/XIdentifiable.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_
#include <com/sun/star/drawing/LineStyle.hpp>
#endif

#include <vector>
#include <memory>

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::chart2;

VPolarGrid::VPolarGrid( const uno::Reference< XGrid >& xGrid, sal_Int32 nDimensionCount )
            : VMeterBase( uno::Reference<XMeter>::query(xGrid), nDimensionCount )
            , m_pPosHelper( new PolarPlottingPositionHelper(false) )
            , m_aIncrements()
{
    PlotterBase::m_pPosHelper = m_pPosHelper;
}

VPolarGrid::~VPolarGrid()
{
    delete m_pPosHelper;
    m_pPosHelper = NULL;
}

void VPolarGrid::setIncrements( const uno::Sequence< ExplicitIncrementData >& rIncrements )
{
    m_aIncrements = rIncrements;
}

void VPolarGrid::getAllTickInfos( sal_Int32 nDimensionIndex, ::std::vector< ::std::vector< TickInfo > >& rAllTickInfos ) const
{
    TickmarkHelper aTickmarkHelper(
            m_pPosHelper->getScales()[nDimensionIndex], m_aIncrements[nDimensionIndex] );
    aTickmarkHelper.getAllTicks( rAllTickInfos );
}

//static
void VPolarGrid::createLinePointSequence_ForAngleAxis(
        drawing::PointSequenceSequence& rPoints
        , ::std::vector< ::std::vector< TickInfo > >& rAllTickInfos
        , const ExplicitIncrementData& rIncrement
        , const ExplicitScaleData& rScale
        , PolarPlottingPositionHelper* pPosHelper
        , double fLogicRadius, double fLogicZ )
{
    uno::Reference< XScaling > xInverseScaling( NULL );
    if( rScale.Scaling.is() )
        xInverseScaling = rScale.Scaling->getInverseScaling();

    sal_Int32 nTick = 0;
    TickIter aIter( rAllTickInfos, rIncrement, 0, 0 );
    for( TickInfo* pTickInfo = aIter.firstInfo()
        ; pTickInfo
        ; pTickInfo = aIter.nextInfo(), nTick++ )
    {
        if(nTick>=rPoints[0].getLength())
            rPoints[0].realloc(rPoints[0].getLength()+30);

        pTickInfo->updateUnscaledValue( xInverseScaling );
        double fLogicAngle = pTickInfo->fUnscaledTickValue;

        drawing::Position3D aScenePosition3D( pPosHelper->transformLogicToScene( fLogicAngle, fLogicRadius, fLogicZ ) );
        rPoints[0][nTick].X = static_cast<sal_Int32>(aScenePosition3D.PositionX);
        rPoints[0][nTick].Y = static_cast<sal_Int32>(aScenePosition3D.PositionY);
    }
    if(rPoints.getLength()>1)
    {
        rPoints[0].realloc(nTick+1);
        rPoints[0][nTick].X = rPoints[0][0].X;
        rPoints[0][nTick].Y = rPoints[0][0].Y;
    }
    else
        rPoints[0].realloc(nTick);
}

void VPolarGrid::create2DAngleGrid( const uno::Reference< drawing::XShapes >& xTarget
        , ::std::vector< ::std::vector< TickInfo > >& rRadiusTickInfos
        , ::std::vector< ::std::vector< TickInfo > >& rAngleTickInfos
        , const ::std::vector<VLineProperties>& rLinePropertiesList )
{
    const ExplicitScaleData&     rAngleScale = m_pPosHelper->getScales()[0];
    const ExplicitIncrementData& rAngleIncrement = m_aIncrements[0];
    uno::Reference< XScaling > xInverseScaling( NULL );
    if( rAngleScale.Scaling.is() )
        xInverseScaling = rAngleScale.Scaling->getInverseScaling();

    double fLogicInnerRadius = m_pPosHelper->getInnerLogicRadius();
    double fLogicOuterRadius = m_pPosHelper->getOuterLogicRadius();
    double fLogicZ      = -0.5;//as defined

    sal_Int32 nLinePropertiesCount = rLinePropertiesList.size();
    ::std::vector< ::std::vector< TickInfo > >::iterator aDepthIter             = rAngleTickInfos.begin();
    sal_Int32 nDepth=0;
    /*
    //no subgrids so far for polar angle grid (need different radii)
    const ::std::vector< ::std::vector< TickInfo > >::const_iterator aDepthEnd  = rAngleTickInfos.end();
    for( ; aDepthIter != aDepthEnd && nDepth < nLinePropertiesCount
         ; aDepthIter++, nDepth++ )
    */
    if(nLinePropertiesCount)
    {
        //create axis main lines
        drawing::PointSequenceSequence aAllPoints(1);
        ::std::vector< TickInfo >::iterator             aTickIter = (*aDepthIter).begin();
        const ::std::vector< TickInfo >::const_iterator aTickEnd  = (*aDepthIter).end();
        sal_Int32 nRealPointCount = 0;
        for( ; aTickIter != aTickEnd; aTickIter++ )
        {
            TickInfo& rTickInfo = *aTickIter;
            if( !rTickInfo.bPaintIt )
                continue;

            rTickInfo.updateUnscaledValue( xInverseScaling );
            double fLogicAngle = rTickInfo.fUnscaledTickValue;

            drawing::PointSequenceSequence aPoints(1);
            aPoints[0].realloc(2);
            drawing::Position3D aScenePositionStart( m_pPosHelper->transformLogicToScene( fLogicAngle, fLogicInnerRadius, fLogicZ ) );
            drawing::Position3D aScenePositionEnd(   m_pPosHelper->transformLogicToScene( fLogicAngle, fLogicOuterRadius, fLogicZ ) );
            aPoints[0][0].X = static_cast<sal_Int32>(aScenePositionStart.PositionX);
            aPoints[0][0].Y = static_cast<sal_Int32>(aScenePositionStart.PositionY);
            aPoints[0][1].X = static_cast<sal_Int32>(aScenePositionEnd.PositionX);
            aPoints[0][1].Y = static_cast<sal_Int32>(aScenePositionEnd.PositionY);
            appendPointSequence( aAllPoints, aPoints );
        }

        uno::Reference< drawing::XShape > xShape = m_pShapeFactory->createLine2D(
                xTarget, aAllPoints, rLinePropertiesList[nDepth] );
        //because of this name this line will be used for marking
        m_pShapeFactory->setShapeName( xShape, C2U("MarkHandles") );
    }
}

void VPolarGrid::create2DRadiusGrid( const uno::Reference< drawing::XShapes >& xTarget
        , ::std::vector< ::std::vector< TickInfo > >& rRadiusTickInfos
        , ::std::vector< ::std::vector< TickInfo > >& rAngleTickInfos
        , const ::std::vector<VLineProperties>& rLinePropertiesList )
{
    const ExplicitScaleData&     rRadiusScale = m_pPosHelper->getScales()[1];
    const ExplicitScaleData&     rAngleScale = m_pPosHelper->getScales()[0];
    const ExplicitIncrementData& rAngleIncrement = m_aIncrements[0];
    uno::Reference< XScaling > xInverseRadiusScaling( NULL );
    if( rRadiusScale.Scaling.is() )
        xInverseRadiusScaling = rRadiusScale.Scaling->getInverseScaling();

    sal_Int32 nLinePropertiesCount = rLinePropertiesList.size();
    ::std::vector< ::std::vector< TickInfo > >::iterator aDepthIter             = rRadiusTickInfos.begin();
    const ::std::vector< ::std::vector< TickInfo > >::const_iterator aDepthEnd  = rRadiusTickInfos.end();
    for( sal_Int32 nDepth=0
        ; aDepthIter != aDepthEnd && nDepth < nLinePropertiesCount
        ; aDepthIter++, nDepth++ )
    {
        //create axis main lines
        drawing::PointSequenceSequence aAllPoints(1);
        ::std::vector< TickInfo >::iterator             aTickIter = (*aDepthIter).begin();
        const ::std::vector< TickInfo >::const_iterator aTickEnd  = (*aDepthIter).end();
        sal_Int32 nRealPointCount = 0;
        for( ; aTickIter != aTickEnd; aTickIter++ )
        {
            TickInfo& rTickInfo = *aTickIter;
            if( !rTickInfo.bPaintIt )
                continue;

            rTickInfo.updateUnscaledValue( xInverseRadiusScaling );
            double fLogicRadius = rTickInfo.fUnscaledTickValue;
            double fLogicZ      = -0.5;//as defined

            drawing::PointSequenceSequence aPoints(1);
            VPolarGrid::createLinePointSequence_ForAngleAxis( aPoints, rAngleTickInfos
                , rAngleIncrement, rAngleScale, m_pPosHelper, fLogicRadius, fLogicZ );
            appendPointSequence( aAllPoints, aPoints );
        }

        uno::Reference< drawing::XShape > xShape = m_pShapeFactory->createLine2D(
                xTarget, aAllPoints, rLinePropertiesList[nDepth] );
        //because of this name this line will be used for marking
        m_pShapeFactory->setShapeName( xShape, C2U("MarkHandles") );
    }
}

void SAL_CALL VPolarGrid::createShapes()
{
    DBG_ASSERT(m_pShapeFactory&&m_xLogicTarget.is()&&m_xFinalTarget.is(),"Axis is not proper initialized");
    if(!(m_pShapeFactory&&m_xLogicTarget.is()&&m_xFinalTarget.is()))
        return;
    if( !m_xMeter.is())
        return;
    uno::Reference< beans::XPropertySet > xGridProps( m_xMeter, uno::UNO_QUERY );
    if(!xGridProps.is())
        return;

    //-----------------------------------------
    //create named group shape
    uno::Reference< XIdentifiable > xIdent( m_xMeter, uno::UNO_QUERY );
    if( ! xIdent.is())
        return;

    uno::Reference< drawing::XShapes > xTarget(
        this->createGroupShape( m_xLogicTarget
        , ObjectIdentifier::createClassifiedIdentifier(
                OBJECTTYPE_GRID, xIdent->getIdentifier() )
        ) );

    //-----------------------------------------
    //create all scaled tickmark values
    ::std::vector< ::std::vector< TickInfo > > aAngleTickInfos;
    ::std::vector< ::std::vector< TickInfo > > aRadiusTickInfos;
    getAllTickInfos( 0, aAngleTickInfos );
    getAllTickInfos( 1, aRadiusTickInfos );

    //-----------------------------------------
    ::std::vector<VLineProperties> aLinePropertiesList;
    VCartesianGrid::fillLinePropertiesFromGridModel( aLinePropertiesList, xGridProps );

    //-----------------------------------------
    //create tick mark line shapes
    if(2==m_nDimension)
    {
        sal_Int32 nDimensionIndex = m_xMeter->getRepresentedDimension();
        if(nDimensionIndex==1)
            this->create2DRadiusGrid( xTarget, aRadiusTickInfos, aAngleTickInfos, aLinePropertiesList );
        else
            this->create2DAngleGrid( xTarget, aRadiusTickInfos, aAngleTickInfos, aLinePropertiesList );
    }
}

//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>


<commit_before>/*
 * This file is a part of Xpiks - cross platform application for
 * keywording and uploading images for microstocks
 * Copyright (C) 2014-2016 Taras Kushnir <kushnirTV@gmail.com>
 *
 * Xpiks is distributed under the GNU General Public License, version 3.0
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "imagecachingworker.h"
#include <QDir>
#include <QFile>
#include <QImage>
#include <QString>
#include <QFileInfo>
#include <QByteArray>
#include <QDataStream>
#include <QReadLocker>
#include <QWriteLocker>
#include <QCryptographicHash>
#include "../Common/defines.h"
#include "../Helpers/constants.h"
#include "imagecacherequest.h"

namespace QMLExtensions {
    QString getPathHash(const QString &path) {
        return QString::fromLatin1(QCryptographicHash::hash(path.toUtf8(), QCryptographicHash::Sha256).toHex());
    }

    QDataStream &operator<<(QDataStream &out, const CachedImage &v) {
        out << v.m_Filename << v.m_LastModified << v.m_Size;
        return out;
    }

    QDataStream &operator>>(QDataStream &in, CachedImage &v) {
        in >> v.m_Filename >> v.m_LastModified >> v.m_Size;
        return in;
    }

    bool ImageCachingWorker::initWorker() {
        LOG_DEBUG << "#";

        m_ProcessedItemsCount = 0;
        QString appDataPath = XPIKS_USERDATA_PATH;

        if (!appDataPath.isEmpty()) {
            m_ImagesCacheDir = QDir::cleanPath(appDataPath + QDir::separator() + Constants::IMAGES_CACHE_DIR);
            QDir appDataDir(appDataPath);
            m_IndexFilepath = appDataDir.filePath(Constants::IMAGES_CACHE_INDEX);

            QDir imagesCacheDir(m_ImagesCacheDir);
            if (!imagesCacheDir.exists()) {
                LOG_DEBUG << "Creating cache dir" << m_ImagesCacheDir;
                QDir().mkpath(m_ImagesCacheDir);
            }
        } else {
            m_ImagesCacheDir = QDir::currentPath();
            m_IndexFilepath = Constants::IMAGES_CACHE_INDEX;
        }

        LOG_INFO << "Using" << m_ImagesCacheDir << "for images cache";

        readIndex();

        return true;
    }

    bool ImageCachingWorker::processOneItem(ImageCacheRequest *item) {
        if (isProcessed(item)) { return true; }

        const QString &originalPath = item->getFilepath();
        QSize requestedSize = item->getRequestedSize();

        if (!requestedSize.isValid()) {
            LOG_WARNING << "Invalid requestedSize for" << originalPath;
            requestedSize.setHeight(300);
            requestedSize.setWidth(300);
        }

        QImage img(originalPath);
        QImage resizedImage = img.scaled(requestedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);

        QFileInfo fi(originalPath);
        QString pathHash = getPathHash(originalPath) + "." + fi.completeSuffix();
        QString cachedFilepath = QDir::cleanPath(m_ImagesCacheDir + QDir::separator() + pathHash);

        if (resizedImage.save(cachedFilepath)) {
            CachedImage cachedImage;
            cachedImage.m_Filename = pathHash;
            cachedImage.m_LastModified = fi.lastModified();
            cachedImage.m_Size = requestedSize;

            {
                QWriteLocker locker(&m_CacheLock);
                Q_UNUSED(locker);

                m_CacheIndex.insert(originalPath, cachedImage);
            }

            m_ProcessedItemsCount++;
        } else {
            LOG_WARNING << "Failed to save image. Path:" << cachedFilepath << "size" << requestedSize;
        }

        if (m_ProcessedItemsCount % 50 == 0) {
            saveIndex();
        }

        return true;
    }

    bool ImageCachingWorker::tryGetCachedImage(const QString &key, const QSize &requestedSize,
                                               QString &cachedPath, bool &needsUpdate) {
        bool found = false;
        QReadLocker locker(&m_CacheLock);
        Q_UNUSED(locker);

        if (m_CacheIndex.contains(key)) {
            const CachedImage &cachedImage = m_CacheIndex[key];
            QString cachedValue = QDir::cleanPath(m_ImagesCacheDir + QDir::separator() + cachedImage.m_Filename);

            QFileInfo fi(cachedValue);

            if (fi.exists()) {
                cachedPath = cachedValue;
                needsUpdate = (fi.lastModified() >= cachedImage.m_LastModified) || (cachedImage.m_Size != requestedSize);
                found = true;
            }
        }

        return found;
    }

    void ImageCachingWorker::readIndex() {
        QFile file(m_IndexFilepath);
        if (file.exists() && file.open(QIODevice::ReadOnly)) {
            QHash<QString, CachedImage> cacheIndex;

            QDataStream in(&file);   // read the data
            in >> cacheIndex;
            file.close();

            m_CacheIndex.swap(cacheIndex);
            LOG_DEBUG << "Images cache index read";
        } else {
            LOG_WARNING << "File not found:" << m_IndexFilepath;
        }
    }

    void ImageCachingWorker::saveIndex() {
        LOG_DEBUG << "#";

        QFile file(m_IndexFilepath);

        if (file.open(QIODevice::WriteOnly)) {
            QReadLocker locker(&m_CacheLock);
            Q_UNUSED(locker);

            QDataStream out(&file);   // write the data
            out << m_CacheIndex;
            file.close();
        }
    }

    bool ImageCachingWorker::isProcessed(ImageCacheRequest *item) {
        if (item->getNeedRecache()) { return false; }

        const QString &originalPath = item->getFilepath();
        const QSize &requestedSize = item->getRequestedSize();

        bool isDone = false;

        QString cachedPath;
        bool needsUpdate = false;
        if (this->tryGetCachedImage(originalPath, requestedSize, cachedPath, needsUpdate)) {
            isDone = !needsUpdate;
        }

        return isDone;
    }
}
<commit_msg>More logging for tests<commit_after>/*
 * This file is a part of Xpiks - cross platform application for
 * keywording and uploading images for microstocks
 * Copyright (C) 2014-2016 Taras Kushnir <kushnirTV@gmail.com>
 *
 * Xpiks is distributed under the GNU General Public License, version 3.0
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "imagecachingworker.h"
#include <QDir>
#include <QFile>
#include <QImage>
#include <QString>
#include <QFileInfo>
#include <QByteArray>
#include <QDataStream>
#include <QReadLocker>
#include <QWriteLocker>
#include <QCryptographicHash>
#include "../Common/defines.h"
#include "../Helpers/constants.h"
#include "imagecacherequest.h"

namespace QMLExtensions {
    QString getPathHash(const QString &path) {
        return QString::fromLatin1(QCryptographicHash::hash(path.toUtf8(), QCryptographicHash::Sha256).toHex());
    }

    QDataStream &operator<<(QDataStream &out, const CachedImage &v) {
        out << v.m_Filename << v.m_LastModified << v.m_Size;
        return out;
    }

    QDataStream &operator>>(QDataStream &in, CachedImage &v) {
        in >> v.m_Filename >> v.m_LastModified >> v.m_Size;
        return in;
    }

    bool ImageCachingWorker::initWorker() {
        LOG_DEBUG << "#";

        m_ProcessedItemsCount = 0;
        QString appDataPath = XPIKS_USERDATA_PATH;

        if (!appDataPath.isEmpty()) {
            m_ImagesCacheDir = QDir::cleanPath(appDataPath + QDir::separator() + Constants::IMAGES_CACHE_DIR);
            QDir appDataDir(appDataPath);
            m_IndexFilepath = appDataDir.filePath(Constants::IMAGES_CACHE_INDEX);

            QDir imagesCacheDir(m_ImagesCacheDir);
            if (!imagesCacheDir.exists()) {
                LOG_DEBUG << "Creating cache dir" << m_ImagesCacheDir;
                QDir().mkpath(m_ImagesCacheDir);
            }
        } else {
            m_ImagesCacheDir = QDir::currentPath();
            m_IndexFilepath = Constants::IMAGES_CACHE_INDEX;
        }

        LOG_INFO << "Using" << m_ImagesCacheDir << "for images cache";

        readIndex();

        return true;
    }

    bool ImageCachingWorker::processOneItem(ImageCacheRequest *item) {
        if (isProcessed(item)) { return true; }

        const QString &originalPath = item->getFilepath();
        QSize requestedSize = item->getRequestedSize();

#ifdef INTEGRATION_TESTS
        LOG_INFO << originalPath << requestedSize;
#endif

        if (!requestedSize.isValid()) {
            LOG_WARNING << "Invalid requestedSize for" << originalPath;
            requestedSize.setHeight(300);
            requestedSize.setWidth(300);
        }

        QImage img(originalPath);
        QImage resizedImage = img.scaled(requestedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);

        QFileInfo fi(originalPath);
        QString pathHash = getPathHash(originalPath) + "." + fi.completeSuffix();
        QString cachedFilepath = QDir::cleanPath(m_ImagesCacheDir + QDir::separator() + pathHash);

        if (resizedImage.save(cachedFilepath)) {
            CachedImage cachedImage;
            cachedImage.m_Filename = pathHash;
            cachedImage.m_LastModified = fi.lastModified();
            cachedImage.m_Size = requestedSize;

            {
                QWriteLocker locker(&m_CacheLock);
                Q_UNUSED(locker);

                m_CacheIndex.insert(originalPath, cachedImage);
            }

            m_ProcessedItemsCount++;
        } else {
            LOG_WARNING << "Failed to save image. Path:" << cachedFilepath << "size" << requestedSize;
        }

        if (m_ProcessedItemsCount % 50 == 0) {
            saveIndex();
        }

        return true;
    }

    bool ImageCachingWorker::tryGetCachedImage(const QString &key, const QSize &requestedSize,
                                               QString &cachedPath, bool &needsUpdate) {
        bool found = false;
        QReadLocker locker(&m_CacheLock);
        Q_UNUSED(locker);

        if (m_CacheIndex.contains(key)) {
            const CachedImage &cachedImage = m_CacheIndex[key];
            QString cachedValue = QDir::cleanPath(m_ImagesCacheDir + QDir::separator() + cachedImage.m_Filename);

            QFileInfo fi(cachedValue);

            if (fi.exists()) {
                cachedPath = cachedValue;
                needsUpdate = (fi.lastModified() >= cachedImage.m_LastModified) || (cachedImage.m_Size != requestedSize);
                found = true;
            }
        }

        return found;
    }

    void ImageCachingWorker::readIndex() {
        QFile file(m_IndexFilepath);
        if (file.exists() && file.open(QIODevice::ReadOnly)) {
            QHash<QString, CachedImage> cacheIndex;

            QDataStream in(&file);   // read the data
            in >> cacheIndex;
            file.close();

            m_CacheIndex.swap(cacheIndex);
            LOG_DEBUG << "Images cache index read";
        } else {
            LOG_WARNING << "File not found:" << m_IndexFilepath;
        }
    }

    void ImageCachingWorker::saveIndex() {
        LOG_DEBUG << "#";

        QFile file(m_IndexFilepath);

        if (file.open(QIODevice::WriteOnly)) {
            QReadLocker locker(&m_CacheLock);
            Q_UNUSED(locker);

            QDataStream out(&file);   // write the data
            out << m_CacheIndex;
            file.close();
        }
    }

    bool ImageCachingWorker::isProcessed(ImageCacheRequest *item) {
        if (item->getNeedRecache()) { return false; }

        const QString &originalPath = item->getFilepath();
        const QSize &requestedSize = item->getRequestedSize();

        bool isDone = false;

        QString cachedPath;
        bool needsUpdate = false;
        if (this->tryGetCachedImage(originalPath, requestedSize, cachedPath, needsUpdate)) {
            isDone = !needsUpdate;
        }

        return isDone;
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 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 <EGL/egl.h>

#if defined(OS_LINUX)
extern "C" {
#include <X11/Xlib.h>
}
#define EGL_HAS_PBUFFERS 1
#endif

#include "build/build_config.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "app/gfx/gl/gl_bindings.h"
#include "app/gfx/gl/gl_context_egl.h"

namespace gfx {

namespace {

// The EGL configuration to use.
EGLDisplay g_display;
EGLConfig g_config;

// Returns the last EGL error as a string.
const char* GetLastEGLErrorString() {
  EGLint error = eglGetError();
  switch (error) {
    case EGL_SUCCESS:
      return "EGL_SUCCESS";
    case EGL_BAD_ACCESS:
      return "EGL_BAD_ACCESS";
    case EGL_BAD_ALLOC:
      return "EGL_BAD_ALLOC";
    case EGL_BAD_ATTRIBUTE:
      return "EGL_BAD_ATTRIBUTE";
    case EGL_BAD_CONTEXT:
      return "EGL_BAD_CONTEXT";
    case EGL_BAD_CONFIG:
      return "EGL_BAD_CONFIG";
    case EGL_BAD_CURRENT_SURFACE:
      return "EGL_BAD_CURRENT_SURFACE";
    case EGL_BAD_DISPLAY:
      return "EGL_BAD_DISPLAY";
    case EGL_BAD_SURFACE:
      return "EGL_BAD_SURFACE";
    case EGL_BAD_MATCH:
      return "EGL_BAD_MATCH";
    case EGL_BAD_PARAMETER:
      return "EGL_BAD_PARAMETER";
    case EGL_BAD_NATIVE_PIXMAP:
      return "EGL_BAD_NATIVE_PIXMAP";
    case EGL_BAD_NATIVE_WINDOW:
      return "EGL_BAD_NATIVE_WINDOW";
    default:
      return "UNKNOWN";
  }
}
}  // namespace anonymous

SharedEGLSurface::SharedEGLSurface(EGLSurface surface) : surface_(surface) {
}

SharedEGLSurface::~SharedEGLSurface() {
  if (surface_) {
    if (!eglDestroySurface(g_display, surface_)) {
      LOG(ERROR) << "eglDestroySurface failed with error "
                 << GetLastEGLErrorString();
    }
  }
}

EGLSurface SharedEGLSurface::egl_surface() const {
  return surface_;
}

bool BaseEGLContext::InitializeOneOff() {
  static bool initialized = false;
  if (initialized)
    return true;

#ifdef OS_LINUX
  EGLNativeDisplayType native_display = XOpenDisplay(NULL);
#else
  EGLNativeDisplayType native_display = EGL_DEFAULT_DISPLAY;
#endif
  g_display = eglGetDisplay(native_display);
  if (!g_display) {
    LOG(ERROR) << "eglGetDisplay failed with error " << GetLastEGLErrorString();
    return false;
  }

  if (!eglInitialize(g_display, NULL, NULL)) {
    LOG(ERROR) << "eglInitialize failed with error " << GetLastEGLErrorString();
    return false;
  }

  // Choose an EGL configuration.
  static const EGLint kConfigAttribs[] = {
    EGL_BUFFER_SIZE, 32,
    EGL_ALPHA_SIZE, 8,
    EGL_BLUE_SIZE, 8,
    EGL_RED_SIZE, 8,
    EGL_DEPTH_SIZE, 16,
    EGL_STENCIL_SIZE, 8,
    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
#ifdef EGL_HAS_PBUFFERS
    EGL_SURFACE_TYPE, EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
#else
    EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
#endif
    EGL_NONE
  };

  EGLint num_configs;
  if (!eglChooseConfig(g_display,
                       kConfigAttribs,
                       NULL,
                       0,
                       &num_configs)) {
    LOG(ERROR) << "eglChooseConfig failed failed with error "
               << GetLastEGLErrorString();
    return false;
  }

  if (num_configs == 0) {
    LOG(ERROR) << "No suitable EGL configs found.";
    return false;
  }

  scoped_array<EGLConfig> configs(new EGLConfig[num_configs]);
  if (!eglChooseConfig(g_display,
                       kConfigAttribs,
                       configs.get(),
                       num_configs,
                       &num_configs)) {
    LOG(ERROR) << "eglChooseConfig failed with error "
               << GetLastEGLErrorString();
    return false;
  }

  g_config = configs[0];

  initialized = true;
  return true;
}

EGLDisplay BaseEGLContext::GetDisplay() {
  return g_display;
}

std::string BaseEGLContext::GetExtensions() {
  const char* extensions = eglQueryString(g_display, EGL_EXTENSIONS);
  if (!extensions)
    return GLContext::GetExtensions();

  return GLContext::GetExtensions() + " " + extensions;
}

NativeViewEGLContext::NativeViewEGLContext(void* window)
    : window_(window),
      context_(NULL)
{
}

NativeViewEGLContext::~NativeViewEGLContext() {
}

bool NativeViewEGLContext::Initialize() {
  DCHECK(!context_);

  // Create a surface for the native window.
  EGLNativeWindowType native_window =
      reinterpret_cast<EGLNativeWindowType>(window_);
  surface_ = new SharedEGLSurface(eglCreateWindowSurface(g_display,
                                                         g_config,
                                                         native_window,
                                                         NULL));

  if (!surface_->egl_surface()) {
    LOG(ERROR) << "eglCreateWindowSurface failed with error "
               << GetLastEGLErrorString();
    Destroy();
    return false;
  }

  static const EGLint kContextAttributes[] = {
    EGL_CONTEXT_CLIENT_VERSION, 2,
    EGL_NONE
  };

  context_ = eglCreateContext(g_display, g_config, NULL, kContextAttributes);
  if (!context_) {
    LOG(ERROR) << "eglCreateContext failed with error "
               << GetLastEGLErrorString();
    Destroy();
    return false;
  }

  if (!MakeCurrent()) {
    LOG(ERROR) << "MakeCurrent failed.";
    Destroy();
    return false;
  }

  if (!InitializeCommon()) {
    LOG(ERROR) << "GLContext::InitializeCommon failed.";
    Destroy();
    return false;
  }

  return true;
}

void NativeViewEGLContext::Destroy() {
  if (context_) {
    if (!eglDestroyContext(g_display, context_)) {
      LOG(ERROR) << "eglDestroyContext failed with error "
                 << GetLastEGLErrorString();
    }

    context_ = NULL;
  }

  surface_ = NULL;
}

bool NativeViewEGLContext::MakeCurrent() {
  DCHECK(context_);
  if (!eglMakeCurrent(g_display,
                      surface_->egl_surface(),
                      surface_->egl_surface(),
                      context_)) {
    VLOG(1) << "eglMakeCurrent failed with error "
            << GetLastEGLErrorString();
    return false;
  }

  return true;
}

bool NativeViewEGLContext::IsCurrent() {
  DCHECK(context_);
  return context_ == eglGetCurrentContext();
}

bool NativeViewEGLContext::IsOffscreen() {
  return false;
}

bool NativeViewEGLContext::SwapBuffers() {
  if (!eglSwapBuffers(g_display, surface_->egl_surface())) {
    VLOG(1) << "eglSwapBuffers failed with error "
            << GetLastEGLErrorString();
    return false;
  }

  return true;
}

gfx::Size NativeViewEGLContext::GetSize() {
#if defined(OS_WIN)
  RECT rect;
  if (!GetClientRect(static_cast<HWND>(window_), &rect)) {
    DCHECK(false) << "GetClientRect failed.";
    return gfx::Size();
  }

  return gfx::Size(rect.right - rect.left, rect.bottom - rect.top);
#else
  // TODO(piman): This doesn't work correctly on Windows yet, the size doesn't
  // get updated on resize. When it does, we can share the code.
  EGLint width;
  EGLint height;
  if (!eglQuerySurface(
          g_display, surface_->egl_surface(), EGL_WIDTH, &width) ||
      !eglQuerySurface(
          g_display, surface_->egl_surface(), EGL_HEIGHT, &height)) {
    NOTREACHED() << "eglQuerySurface failed with error "
                 << GetLastEGLErrorString();
    return gfx::Size();
  }

  return gfx::Size(width, height);
#endif
}

void* NativeViewEGLContext::GetHandle() {
  return context_;
}

void NativeViewEGLContext::SetSwapInterval(int interval) {
  DCHECK(IsCurrent());
  if (!eglSwapInterval(g_display, interval)) {
    LOG(ERROR) << "eglSwapInterval failed with error "
               << GetLastEGLErrorString();
  }
}

SharedEGLSurface* NativeViewEGLContext::GetSurface() {
  return surface_;
}

SecondaryEGLContext::SecondaryEGLContext()
    : context_(NULL)
{
}

SecondaryEGLContext::~SecondaryEGLContext() {
}

bool SecondaryEGLContext::Initialize(GLContext* shared_context) {
  DCHECK(!context_);

  static const EGLint kContextAttributes[] = {
    EGL_CONTEXT_CLIENT_VERSION, 2,
    EGL_NONE
  };

  if (shared_context) {
    surface_ = static_cast<BaseEGLContext*>(shared_context)->GetSurface();

    // Create a context.
    context_ = eglCreateContext(g_display,
                                g_config,
                                shared_context->GetHandle(),
                                kContextAttributes);
  } else {
#ifdef EGL_HAS_PBUFFERS
    static const EGLint kPbufferAttribs[] = {
      EGL_WIDTH, 1,
      EGL_HEIGHT, 1,
      EGL_NONE
    };

    surface_ = new SharedEGLSurface(eglCreatePbufferSurface(g_display,
                                                            g_config,
                                                            kPbufferAttribs));
    if (!surface_->egl_surface()) {
      LOG(ERROR) << "eglCreatePbufferSurface failed with error "
                 << GetLastEGLErrorString();
      Destroy();
      return false;
    }

    context_ = eglCreateContext(g_display, g_config, NULL, kContextAttributes);
#else
    NOTIMPLEMENTED() << "Offscreen non-shared GLES context";
    return false;
#endif
  }

  if (!context_) {
    LOG(ERROR) << "eglCreateContext failed with error "
               << GetLastEGLErrorString();
    Destroy();
    return false;
  }

  return true;
}

void SecondaryEGLContext::Destroy() {
  if (context_) {
    if (!eglDestroyContext(g_display, context_)) {
      LOG(ERROR) << "eglDestroyContext failed with error "
                 << GetLastEGLErrorString();
    }

    context_ = NULL;
  }

  surface_ = NULL;
}

bool SecondaryEGLContext::MakeCurrent() {
  DCHECK(context_);
  if (!eglMakeCurrent(g_display,
                      surface_->egl_surface(),
                      surface_->egl_surface(),
                      context_)) {
    VLOG(1) << "eglMakeCurrent failed with error "
            << GetLastEGLErrorString();
    return false;
  }

  return true;
}

bool SecondaryEGLContext::IsCurrent() {
  DCHECK(context_);
  return context_ == eglGetCurrentContext();
}

bool SecondaryEGLContext::IsOffscreen() {
  return true;
}

bool SecondaryEGLContext::SwapBuffers() {
  NOTREACHED() << "Attempted to call SwapBuffers on a SecondaryEGLContext.";
  return false;
}

gfx::Size SecondaryEGLContext::GetSize() {
  NOTREACHED() << "Should not be requesting size of this SecondaryEGLContext.";
  return gfx::Size(1, 1);
}

void* SecondaryEGLContext::GetHandle() {
  return context_;
}

void SecondaryEGLContext::SetSwapInterval(int interval) {
  DCHECK(IsCurrent());
  NOTREACHED() << "Attempt to call SetSwapInterval on a SecondaryEGLContext.";
}

SharedEGLSurface* SecondaryEGLContext::GetSurface() {
  return surface_;
}

}  // namespace gfx
<commit_msg>linux: fix gl_context_egl header order<commit_after>// Copyright (c) 2010 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 "app/gfx/gl/gl_context_egl.h"

#include "build/build_config.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "third_party/angle/include/EGL/egl.h"

// This header must come after the above third-party include, as
// it brings in #defines that cause conflicts.
#include "app/gfx/gl/gl_bindings.h"

#if defined(OS_LINUX)
extern "C" {
#include <X11/Xlib.h>
}
#define EGL_HAS_PBUFFERS 1
#endif

namespace gfx {

namespace {

// The EGL configuration to use.
EGLDisplay g_display;
EGLConfig g_config;

// Returns the last EGL error as a string.
const char* GetLastEGLErrorString() {
  EGLint error = eglGetError();
  switch (error) {
    case EGL_SUCCESS:
      return "EGL_SUCCESS";
    case EGL_BAD_ACCESS:
      return "EGL_BAD_ACCESS";
    case EGL_BAD_ALLOC:
      return "EGL_BAD_ALLOC";
    case EGL_BAD_ATTRIBUTE:
      return "EGL_BAD_ATTRIBUTE";
    case EGL_BAD_CONTEXT:
      return "EGL_BAD_CONTEXT";
    case EGL_BAD_CONFIG:
      return "EGL_BAD_CONFIG";
    case EGL_BAD_CURRENT_SURFACE:
      return "EGL_BAD_CURRENT_SURFACE";
    case EGL_BAD_DISPLAY:
      return "EGL_BAD_DISPLAY";
    case EGL_BAD_SURFACE:
      return "EGL_BAD_SURFACE";
    case EGL_BAD_MATCH:
      return "EGL_BAD_MATCH";
    case EGL_BAD_PARAMETER:
      return "EGL_BAD_PARAMETER";
    case EGL_BAD_NATIVE_PIXMAP:
      return "EGL_BAD_NATIVE_PIXMAP";
    case EGL_BAD_NATIVE_WINDOW:
      return "EGL_BAD_NATIVE_WINDOW";
    default:
      return "UNKNOWN";
  }
}
}  // namespace anonymous

SharedEGLSurface::SharedEGLSurface(EGLSurface surface) : surface_(surface) {
}

SharedEGLSurface::~SharedEGLSurface() {
  if (surface_) {
    if (!eglDestroySurface(g_display, surface_)) {
      LOG(ERROR) << "eglDestroySurface failed with error "
                 << GetLastEGLErrorString();
    }
  }
}

EGLSurface SharedEGLSurface::egl_surface() const {
  return surface_;
}

bool BaseEGLContext::InitializeOneOff() {
  static bool initialized = false;
  if (initialized)
    return true;

#ifdef OS_LINUX
  EGLNativeDisplayType native_display = XOpenDisplay(NULL);
#else
  EGLNativeDisplayType native_display = EGL_DEFAULT_DISPLAY;
#endif
  g_display = eglGetDisplay(native_display);
  if (!g_display) {
    LOG(ERROR) << "eglGetDisplay failed with error " << GetLastEGLErrorString();
    return false;
  }

  if (!eglInitialize(g_display, NULL, NULL)) {
    LOG(ERROR) << "eglInitialize failed with error " << GetLastEGLErrorString();
    return false;
  }

  // Choose an EGL configuration.
  static const EGLint kConfigAttribs[] = {
    EGL_BUFFER_SIZE, 32,
    EGL_ALPHA_SIZE, 8,
    EGL_BLUE_SIZE, 8,
    EGL_RED_SIZE, 8,
    EGL_DEPTH_SIZE, 16,
    EGL_STENCIL_SIZE, 8,
    EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
#ifdef EGL_HAS_PBUFFERS
    EGL_SURFACE_TYPE, EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
#else
    EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
#endif
    EGL_NONE
  };

  EGLint num_configs;
  if (!eglChooseConfig(g_display,
                       kConfigAttribs,
                       NULL,
                       0,
                       &num_configs)) {
    LOG(ERROR) << "eglChooseConfig failed failed with error "
               << GetLastEGLErrorString();
    return false;
  }

  if (num_configs == 0) {
    LOG(ERROR) << "No suitable EGL configs found.";
    return false;
  }

  scoped_array<EGLConfig> configs(new EGLConfig[num_configs]);
  if (!eglChooseConfig(g_display,
                       kConfigAttribs,
                       configs.get(),
                       num_configs,
                       &num_configs)) {
    LOG(ERROR) << "eglChooseConfig failed with error "
               << GetLastEGLErrorString();
    return false;
  }

  g_config = configs[0];

  initialized = true;
  return true;
}

EGLDisplay BaseEGLContext::GetDisplay() {
  return g_display;
}

std::string BaseEGLContext::GetExtensions() {
  const char* extensions = eglQueryString(g_display, EGL_EXTENSIONS);
  if (!extensions)
    return GLContext::GetExtensions();

  return GLContext::GetExtensions() + " " + extensions;
}

NativeViewEGLContext::NativeViewEGLContext(void* window)
    : window_(window),
      context_(NULL)
{
}

NativeViewEGLContext::~NativeViewEGLContext() {
}

bool NativeViewEGLContext::Initialize() {
  DCHECK(!context_);

  // Create a surface for the native window.
  EGLNativeWindowType native_window =
      reinterpret_cast<EGLNativeWindowType>(window_);
  surface_ = new SharedEGLSurface(eglCreateWindowSurface(g_display,
                                                         g_config,
                                                         native_window,
                                                         NULL));

  if (!surface_->egl_surface()) {
    LOG(ERROR) << "eglCreateWindowSurface failed with error "
               << GetLastEGLErrorString();
    Destroy();
    return false;
  }

  static const EGLint kContextAttributes[] = {
    EGL_CONTEXT_CLIENT_VERSION, 2,
    EGL_NONE
  };

  context_ = eglCreateContext(g_display, g_config, NULL, kContextAttributes);
  if (!context_) {
    LOG(ERROR) << "eglCreateContext failed with error "
               << GetLastEGLErrorString();
    Destroy();
    return false;
  }

  if (!MakeCurrent()) {
    LOG(ERROR) << "MakeCurrent failed.";
    Destroy();
    return false;
  }

  if (!InitializeCommon()) {
    LOG(ERROR) << "GLContext::InitializeCommon failed.";
    Destroy();
    return false;
  }

  return true;
}

void NativeViewEGLContext::Destroy() {
  if (context_) {
    if (!eglDestroyContext(g_display, context_)) {
      LOG(ERROR) << "eglDestroyContext failed with error "
                 << GetLastEGLErrorString();
    }

    context_ = NULL;
  }

  surface_ = NULL;
}

bool NativeViewEGLContext::MakeCurrent() {
  DCHECK(context_);
  if (!eglMakeCurrent(g_display,
                      surface_->egl_surface(),
                      surface_->egl_surface(),
                      context_)) {
    VLOG(1) << "eglMakeCurrent failed with error "
            << GetLastEGLErrorString();
    return false;
  }

  return true;
}

bool NativeViewEGLContext::IsCurrent() {
  DCHECK(context_);
  return context_ == eglGetCurrentContext();
}

bool NativeViewEGLContext::IsOffscreen() {
  return false;
}

bool NativeViewEGLContext::SwapBuffers() {
  if (!eglSwapBuffers(g_display, surface_->egl_surface())) {
    VLOG(1) << "eglSwapBuffers failed with error "
            << GetLastEGLErrorString();
    return false;
  }

  return true;
}

gfx::Size NativeViewEGLContext::GetSize() {
#if defined(OS_WIN)
  RECT rect;
  if (!GetClientRect(static_cast<HWND>(window_), &rect)) {
    DCHECK(false) << "GetClientRect failed.";
    return gfx::Size();
  }

  return gfx::Size(rect.right - rect.left, rect.bottom - rect.top);
#else
  // TODO(piman): This doesn't work correctly on Windows yet, the size doesn't
  // get updated on resize. When it does, we can share the code.
  EGLint width;
  EGLint height;
  if (!eglQuerySurface(
          g_display, surface_->egl_surface(), EGL_WIDTH, &width) ||
      !eglQuerySurface(
          g_display, surface_->egl_surface(), EGL_HEIGHT, &height)) {
    NOTREACHED() << "eglQuerySurface failed with error "
                 << GetLastEGLErrorString();
    return gfx::Size();
  }

  return gfx::Size(width, height);
#endif
}

void* NativeViewEGLContext::GetHandle() {
  return context_;
}

void NativeViewEGLContext::SetSwapInterval(int interval) {
  DCHECK(IsCurrent());
  if (!eglSwapInterval(g_display, interval)) {
    LOG(ERROR) << "eglSwapInterval failed with error "
               << GetLastEGLErrorString();
  }
}

SharedEGLSurface* NativeViewEGLContext::GetSurface() {
  return surface_;
}

SecondaryEGLContext::SecondaryEGLContext()
    : context_(NULL)
{
}

SecondaryEGLContext::~SecondaryEGLContext() {
}

bool SecondaryEGLContext::Initialize(GLContext* shared_context) {
  DCHECK(!context_);

  static const EGLint kContextAttributes[] = {
    EGL_CONTEXT_CLIENT_VERSION, 2,
    EGL_NONE
  };

  if (shared_context) {
    surface_ = static_cast<BaseEGLContext*>(shared_context)->GetSurface();

    // Create a context.
    context_ = eglCreateContext(g_display,
                                g_config,
                                shared_context->GetHandle(),
                                kContextAttributes);
  } else {
#ifdef EGL_HAS_PBUFFERS
    static const EGLint kPbufferAttribs[] = {
      EGL_WIDTH, 1,
      EGL_HEIGHT, 1,
      EGL_NONE
    };

    surface_ = new SharedEGLSurface(eglCreatePbufferSurface(g_display,
                                                            g_config,
                                                            kPbufferAttribs));
    if (!surface_->egl_surface()) {
      LOG(ERROR) << "eglCreatePbufferSurface failed with error "
                 << GetLastEGLErrorString();
      Destroy();
      return false;
    }

    context_ = eglCreateContext(g_display, g_config, NULL, kContextAttributes);
#else
    NOTIMPLEMENTED() << "Offscreen non-shared GLES context";
    return false;
#endif
  }

  if (!context_) {
    LOG(ERROR) << "eglCreateContext failed with error "
               << GetLastEGLErrorString();
    Destroy();
    return false;
  }

  return true;
}

void SecondaryEGLContext::Destroy() {
  if (context_) {
    if (!eglDestroyContext(g_display, context_)) {
      LOG(ERROR) << "eglDestroyContext failed with error "
                 << GetLastEGLErrorString();
    }

    context_ = NULL;
  }

  surface_ = NULL;
}

bool SecondaryEGLContext::MakeCurrent() {
  DCHECK(context_);
  if (!eglMakeCurrent(g_display,
                      surface_->egl_surface(),
                      surface_->egl_surface(),
                      context_)) {
    VLOG(1) << "eglMakeCurrent failed with error "
            << GetLastEGLErrorString();
    return false;
  }

  return true;
}

bool SecondaryEGLContext::IsCurrent() {
  DCHECK(context_);
  return context_ == eglGetCurrentContext();
}

bool SecondaryEGLContext::IsOffscreen() {
  return true;
}

bool SecondaryEGLContext::SwapBuffers() {
  NOTREACHED() << "Attempted to call SwapBuffers on a SecondaryEGLContext.";
  return false;
}

gfx::Size SecondaryEGLContext::GetSize() {
  NOTREACHED() << "Should not be requesting size of this SecondaryEGLContext.";
  return gfx::Size(1, 1);
}

void* SecondaryEGLContext::GetHandle() {
  return context_;
}

void SecondaryEGLContext::SetSwapInterval(int interval) {
  DCHECK(IsCurrent());
  NOTREACHED() << "Attempt to call SetSwapInterval on a SecondaryEGLContext.";
}

SharedEGLSurface* SecondaryEGLContext::GetSurface() {
  return surface_;
}

}  // namespace gfx
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_FUN_AS_COLUMN_VECTOR_OR_SCALAR_HPP
#define STAN_MATH_PRIM_FUN_AS_COLUMN_VECTOR_OR_SCALAR_HPP

#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/meta.hpp>
#include <vector>

namespace stan {
namespace math {
namespace internal {
  template <typename T, typename S, typename Enable>
  class empty_broadcast_array;
}
/**
 * no-op that passes the scalar
 *
 * @tparam T Type of scalar element.
 * @param a Specified scalar.
 * @return the scalar.
 */
template <typename T, require_stan_scalar_t<T>* = nullptr>
inline T as_column_vector_or_scalar(const T& a) {
  return a;
}

/**
 * No-op used when working with operands and partials.
 * This is not implimented so it cannot be invoked and only exists so the
 * compiler can resolve it's output type.
 */
template <typename T, typename S>
internal::empty_broadcast_array<T, S, void>& as_column_vector_or_scalar(internal::empty_broadcast_array<T, S, void>& a);

/**
 * no-op that returns a column vector.
 *
 * @tparam T Type inheriting from `EigenBase` with dynamic compile time rows
 *  and fixed column of 1.
 * @param a Specified vector.
 * @return Same vector.
 */
template <typename T, require_eigen_col_vector_t<T>* = nullptr>
inline T&& as_column_vector_or_scalar(T&& a) {
  return std::forward<T>(a);
}

/**
 * Converts a row vector to an eigen column vector. For row vectors this returns
 *  a `Transpose<Eigen::Matrix<T, 1, -1>>`.
 *
 * @tparam T Type inheriting from `EigenBase` with dynamic compile time columns
 * and fixed row of 1.
 * @param a Specified vector.
 * @return Transposed vector.
 */
template <typename T, require_eigen_row_vector_t<T>* = nullptr,
          require_not_eigen_col_vector_t<T>* = nullptr>
inline auto as_column_vector_or_scalar(T&& a) {
  return make_holder([](auto& x) { return x.transpose(); }, std::forward<T>(a));
}

/**
 * Converts `std::vector` to a column vector.
 *
 * @tparam T `std::vector` type.
 * @param a Specified vector.
 * @return input converted to a column vector.
 */
template <typename T, require_std_vector_t<T>* = nullptr>
inline auto as_column_vector_or_scalar(T&& a) {
  using plain_vector = Eigen::Matrix<value_type_t<T>, Eigen::Dynamic, 1>;
  using optionally_const_vector
      = std::conditional_t<std::is_const<std::remove_reference_t<T>>::value,
                           const plain_vector, plain_vector>;
  using T_map = Eigen::Map<optionally_const_vector>;
  return make_holder([](auto& x) { return T_map(x.data(), x.size()); },
                     std::forward<T>(a));
}

}  // namespace math
}  // namespace stan

#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_PRIM_FUN_AS_COLUMN_VECTOR_OR_SCALAR_HPP
#define STAN_MATH_PRIM_FUN_AS_COLUMN_VECTOR_OR_SCALAR_HPP

#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/meta.hpp>
#include <vector>

namespace stan {
namespace math {
namespace internal {
template <typename T, typename S, typename Enable>
class empty_broadcast_array;
}
/**
 * no-op that passes the scalar
 *
 * @tparam T Type of scalar element.
 * @param a Specified scalar.
 * @return the scalar.
 */
template <typename T, require_stan_scalar_t<T>* = nullptr>
inline T as_column_vector_or_scalar(const T& a) {
  return a;
}

/**
 * No-op used when working with operands and partials.
 * This is not implimented so it cannot be invoked and only exists so the
 * compiler can resolve it's output type.
 */
template <typename T, typename S>
internal::empty_broadcast_array<T, S, void>& as_column_vector_or_scalar(
    internal::empty_broadcast_array<T, S, void>& a);

/**
 * no-op that returns a column vector.
 *
 * @tparam T Type inheriting from `EigenBase` with dynamic compile time rows
 *  and fixed column of 1.
 * @param a Specified vector.
 * @return Same vector.
 */
template <typename T, require_eigen_col_vector_t<T>* = nullptr>
inline T&& as_column_vector_or_scalar(T&& a) {
  return std::forward<T>(a);
}

/**
 * Converts a row vector to an eigen column vector. For row vectors this returns
 *  a `Transpose<Eigen::Matrix<T, 1, -1>>`.
 *
 * @tparam T Type inheriting from `EigenBase` with dynamic compile time columns
 * and fixed row of 1.
 * @param a Specified vector.
 * @return Transposed vector.
 */
template <typename T, require_eigen_row_vector_t<T>* = nullptr,
          require_not_eigen_col_vector_t<T>* = nullptr>
inline auto as_column_vector_or_scalar(T&& a) {
  return make_holder([](auto& x) { return x.transpose(); }, std::forward<T>(a));
}

/**
 * Converts `std::vector` to a column vector.
 *
 * @tparam T `std::vector` type.
 * @param a Specified vector.
 * @return input converted to a column vector.
 */
template <typename T, require_std_vector_t<T>* = nullptr>
inline auto as_column_vector_or_scalar(T&& a) {
  using plain_vector = Eigen::Matrix<value_type_t<T>, Eigen::Dynamic, 1>;
  using optionally_const_vector
      = std::conditional_t<std::is_const<std::remove_reference_t<T>>::value,
                           const plain_vector, plain_vector>;
  using T_map = Eigen::Map<optionally_const_vector>;
  return make_holder([](auto& x) { return T_map(x.data(), x.size()); },
                     std::forward<T>(a));
}

}  // namespace math
}  // namespace stan

#endif
<|endoftext|>